]> Pileus Git - ~andy/linux/blob - fs/ext4/inode.c
38f03dcdc8be37478be15b3dbaf253bc2632a902
[~andy/linux] / fs / ext4 / inode.c
1 /*
2  *  linux/fs/ext4/inode.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  from
10  *
11  *  linux/fs/minix/inode.c
12  *
13  *  Copyright (C) 1991, 1992  Linus Torvalds
14  *
15  *  64-bit file support on 64-bit platforms by Jakub Jelinek
16  *      (jj@sunsite.ms.mff.cuni.cz)
17  *
18  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
19  */
20
21 #include <linux/fs.h>
22 #include <linux/time.h>
23 #include <linux/jbd2.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/aio.h>
41
42 #include "ext4_jbd2.h"
43 #include "xattr.h"
44 #include "acl.h"
45 #include "truncate.h"
46
47 #include <trace/events/ext4.h>
48
49 #define MPAGE_DA_EXTENT_TAIL 0x01
50
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52                               struct ext4_inode_info *ei)
53 {
54         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
55         __u16 csum_lo;
56         __u16 csum_hi = 0;
57         __u32 csum;
58
59         csum_lo = le16_to_cpu(raw->i_checksum_lo);
60         raw->i_checksum_lo = 0;
61         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
62             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
63                 csum_hi = le16_to_cpu(raw->i_checksum_hi);
64                 raw->i_checksum_hi = 0;
65         }
66
67         csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
68                            EXT4_INODE_SIZE(inode->i_sb));
69
70         raw->i_checksum_lo = cpu_to_le16(csum_lo);
71         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
72             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
73                 raw->i_checksum_hi = cpu_to_le16(csum_hi);
74
75         return csum;
76 }
77
78 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
79                                   struct ext4_inode_info *ei)
80 {
81         __u32 provided, calculated;
82
83         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
84             cpu_to_le32(EXT4_OS_LINUX) ||
85             !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
86                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
87                 return 1;
88
89         provided = le16_to_cpu(raw->i_checksum_lo);
90         calculated = ext4_inode_csum(inode, raw, ei);
91         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
92             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
93                 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
94         else
95                 calculated &= 0xFFFF;
96
97         return provided == calculated;
98 }
99
100 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
101                                 struct ext4_inode_info *ei)
102 {
103         __u32 csum;
104
105         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
106             cpu_to_le32(EXT4_OS_LINUX) ||
107             !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
108                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
109                 return;
110
111         csum = ext4_inode_csum(inode, raw, ei);
112         raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
113         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
114             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
115                 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
116 }
117
118 static inline int ext4_begin_ordered_truncate(struct inode *inode,
119                                               loff_t new_size)
120 {
121         trace_ext4_begin_ordered_truncate(inode, new_size);
122         /*
123          * If jinode is zero, then we never opened the file for
124          * writing, so there's no need to call
125          * jbd2_journal_begin_ordered_truncate() since there's no
126          * outstanding writes we need to flush.
127          */
128         if (!EXT4_I(inode)->jinode)
129                 return 0;
130         return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
131                                                    EXT4_I(inode)->jinode,
132                                                    new_size);
133 }
134
135 static void ext4_invalidatepage(struct page *page, unsigned int offset,
136                                 unsigned int length);
137 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
138 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
139
140 /*
141  * Test whether an inode is a fast symlink.
142  */
143 static int ext4_inode_is_fast_symlink(struct inode *inode)
144 {
145         int ea_blocks = EXT4_I(inode)->i_file_acl ?
146                 (inode->i_sb->s_blocksize >> 9) : 0;
147
148         return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
149 }
150
151 /*
152  * Restart the transaction associated with *handle.  This does a commit,
153  * so before we call here everything must be consistently dirtied against
154  * this transaction.
155  */
156 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
157                                  int nblocks)
158 {
159         int ret;
160
161         /*
162          * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
163          * moment, get_block can be called only for blocks inside i_size since
164          * page cache has been already dropped and writes are blocked by
165          * i_mutex. So we can safely drop the i_data_sem here.
166          */
167         BUG_ON(EXT4_JOURNAL(inode) == NULL);
168         jbd_debug(2, "restarting handle %p\n", handle);
169         up_write(&EXT4_I(inode)->i_data_sem);
170         ret = ext4_journal_restart(handle, nblocks);
171         down_write(&EXT4_I(inode)->i_data_sem);
172         ext4_discard_preallocations(inode);
173
174         return ret;
175 }
176
177 /*
178  * Called at the last iput() if i_nlink is zero.
179  */
180 void ext4_evict_inode(struct inode *inode)
181 {
182         handle_t *handle;
183         int err;
184
185         trace_ext4_evict_inode(inode);
186
187         if (inode->i_nlink) {
188                 /*
189                  * When journalling data dirty buffers are tracked only in the
190                  * journal. So although mm thinks everything is clean and
191                  * ready for reaping the inode might still have some pages to
192                  * write in the running transaction or waiting to be
193                  * checkpointed. Thus calling jbd2_journal_invalidatepage()
194                  * (via truncate_inode_pages()) to discard these buffers can
195                  * cause data loss. Also even if we did not discard these
196                  * buffers, we would have no way to find them after the inode
197                  * is reaped and thus user could see stale data if he tries to
198                  * read them before the transaction is checkpointed. So be
199                  * careful and force everything to disk here... We use
200                  * ei->i_datasync_tid to store the newest transaction
201                  * containing inode's data.
202                  *
203                  * Note that directories do not have this problem because they
204                  * don't use page cache.
205                  */
206                 if (ext4_should_journal_data(inode) &&
207                     (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
208                     inode->i_ino != EXT4_JOURNAL_INO) {
209                         journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
210                         tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
211
212                         jbd2_complete_transaction(journal, commit_tid);
213                         filemap_write_and_wait(&inode->i_data);
214                 }
215                 truncate_inode_pages(&inode->i_data, 0);
216                 ext4_ioend_shutdown(inode);
217                 goto no_delete;
218         }
219
220         if (!is_bad_inode(inode))
221                 dquot_initialize(inode);
222
223         if (ext4_should_order_data(inode))
224                 ext4_begin_ordered_truncate(inode, 0);
225         truncate_inode_pages(&inode->i_data, 0);
226         ext4_ioend_shutdown(inode);
227
228         if (is_bad_inode(inode))
229                 goto no_delete;
230
231         /*
232          * Protect us against freezing - iput() caller didn't have to have any
233          * protection against it
234          */
235         sb_start_intwrite(inode->i_sb);
236         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
237                                     ext4_blocks_for_truncate(inode)+3);
238         if (IS_ERR(handle)) {
239                 ext4_std_error(inode->i_sb, PTR_ERR(handle));
240                 /*
241                  * If we're going to skip the normal cleanup, we still need to
242                  * make sure that the in-core orphan linked list is properly
243                  * cleaned up.
244                  */
245                 ext4_orphan_del(NULL, inode);
246                 sb_end_intwrite(inode->i_sb);
247                 goto no_delete;
248         }
249
250         if (IS_SYNC(inode))
251                 ext4_handle_sync(handle);
252         inode->i_size = 0;
253         err = ext4_mark_inode_dirty(handle, inode);
254         if (err) {
255                 ext4_warning(inode->i_sb,
256                              "couldn't mark inode dirty (err %d)", err);
257                 goto stop_handle;
258         }
259         if (inode->i_blocks)
260                 ext4_truncate(inode);
261
262         /*
263          * ext4_ext_truncate() doesn't reserve any slop when it
264          * restarts journal transactions; therefore there may not be
265          * enough credits left in the handle to remove the inode from
266          * the orphan list and set the dtime field.
267          */
268         if (!ext4_handle_has_enough_credits(handle, 3)) {
269                 err = ext4_journal_extend(handle, 3);
270                 if (err > 0)
271                         err = ext4_journal_restart(handle, 3);
272                 if (err != 0) {
273                         ext4_warning(inode->i_sb,
274                                      "couldn't extend journal (err %d)", err);
275                 stop_handle:
276                         ext4_journal_stop(handle);
277                         ext4_orphan_del(NULL, inode);
278                         sb_end_intwrite(inode->i_sb);
279                         goto no_delete;
280                 }
281         }
282
283         /*
284          * Kill off the orphan record which ext4_truncate created.
285          * AKPM: I think this can be inside the above `if'.
286          * Note that ext4_orphan_del() has to be able to cope with the
287          * deletion of a non-existent orphan - this is because we don't
288          * know if ext4_truncate() actually created an orphan record.
289          * (Well, we could do this if we need to, but heck - it works)
290          */
291         ext4_orphan_del(handle, inode);
292         EXT4_I(inode)->i_dtime  = get_seconds();
293
294         /*
295          * One subtle ordering requirement: if anything has gone wrong
296          * (transaction abort, IO errors, whatever), then we can still
297          * do these next steps (the fs will already have been marked as
298          * having errors), but we can't free the inode if the mark_dirty
299          * fails.
300          */
301         if (ext4_mark_inode_dirty(handle, inode))
302                 /* If that failed, just do the required in-core inode clear. */
303                 ext4_clear_inode(inode);
304         else
305                 ext4_free_inode(handle, inode);
306         ext4_journal_stop(handle);
307         sb_end_intwrite(inode->i_sb);
308         return;
309 no_delete:
310         ext4_clear_inode(inode);        /* We must guarantee clearing of inode... */
311 }
312
313 #ifdef CONFIG_QUOTA
314 qsize_t *ext4_get_reserved_space(struct inode *inode)
315 {
316         return &EXT4_I(inode)->i_reserved_quota;
317 }
318 #endif
319
320 /*
321  * Calculate the number of metadata blocks need to reserve
322  * to allocate a block located at @lblock
323  */
324 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
325 {
326         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
327                 return ext4_ext_calc_metadata_amount(inode, lblock);
328
329         return ext4_ind_calc_metadata_amount(inode, lblock);
330 }
331
332 /*
333  * Called with i_data_sem down, which is important since we can call
334  * ext4_discard_preallocations() from here.
335  */
336 void ext4_da_update_reserve_space(struct inode *inode,
337                                         int used, int quota_claim)
338 {
339         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
340         struct ext4_inode_info *ei = EXT4_I(inode);
341
342         spin_lock(&ei->i_block_reservation_lock);
343         trace_ext4_da_update_reserve_space(inode, used, quota_claim);
344         if (unlikely(used > ei->i_reserved_data_blocks)) {
345                 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
346                          "with only %d reserved data blocks",
347                          __func__, inode->i_ino, used,
348                          ei->i_reserved_data_blocks);
349                 WARN_ON(1);
350                 used = ei->i_reserved_data_blocks;
351         }
352
353         if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
354                 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
355                         "with only %d reserved metadata blocks "
356                         "(releasing %d blocks with reserved %d data blocks)",
357                         inode->i_ino, ei->i_allocated_meta_blocks,
358                              ei->i_reserved_meta_blocks, used,
359                              ei->i_reserved_data_blocks);
360                 WARN_ON(1);
361                 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
362         }
363
364         /* Update per-inode reservations */
365         ei->i_reserved_data_blocks -= used;
366         ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
367         percpu_counter_sub(&sbi->s_dirtyclusters_counter,
368                            used + ei->i_allocated_meta_blocks);
369         ei->i_allocated_meta_blocks = 0;
370
371         if (ei->i_reserved_data_blocks == 0) {
372                 /*
373                  * We can release all of the reserved metadata blocks
374                  * only when we have written all of the delayed
375                  * allocation blocks.
376                  */
377                 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
378                                    ei->i_reserved_meta_blocks);
379                 ei->i_reserved_meta_blocks = 0;
380                 ei->i_da_metadata_calc_len = 0;
381         }
382         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
383
384         /* Update quota subsystem for data blocks */
385         if (quota_claim)
386                 dquot_claim_block(inode, EXT4_C2B(sbi, used));
387         else {
388                 /*
389                  * We did fallocate with an offset that is already delayed
390                  * allocated. So on delayed allocated writeback we should
391                  * not re-claim the quota for fallocated blocks.
392                  */
393                 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
394         }
395
396         /*
397          * If we have done all the pending block allocations and if
398          * there aren't any writers on the inode, we can discard the
399          * inode's preallocations.
400          */
401         if ((ei->i_reserved_data_blocks == 0) &&
402             (atomic_read(&inode->i_writecount) == 0))
403                 ext4_discard_preallocations(inode);
404 }
405
406 static int __check_block_validity(struct inode *inode, const char *func,
407                                 unsigned int line,
408                                 struct ext4_map_blocks *map)
409 {
410         if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
411                                    map->m_len)) {
412                 ext4_error_inode(inode, func, line, map->m_pblk,
413                                  "lblock %lu mapped to illegal pblock "
414                                  "(length %d)", (unsigned long) map->m_lblk,
415                                  map->m_len);
416                 return -EIO;
417         }
418         return 0;
419 }
420
421 #define check_block_validity(inode, map)        \
422         __check_block_validity((inode), __func__, __LINE__, (map))
423
424 /*
425  * Return the number of contiguous dirty pages in a given inode
426  * starting at page frame idx.
427  */
428 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
429                                     unsigned int max_pages)
430 {
431         struct address_space *mapping = inode->i_mapping;
432         pgoff_t index;
433         struct pagevec pvec;
434         pgoff_t num = 0;
435         int i, nr_pages, done = 0;
436
437         if (max_pages == 0)
438                 return 0;
439         pagevec_init(&pvec, 0);
440         while (!done) {
441                 index = idx;
442                 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
443                                               PAGECACHE_TAG_DIRTY,
444                                               (pgoff_t)PAGEVEC_SIZE);
445                 if (nr_pages == 0)
446                         break;
447                 for (i = 0; i < nr_pages; i++) {
448                         struct page *page = pvec.pages[i];
449                         struct buffer_head *bh, *head;
450
451                         lock_page(page);
452                         if (unlikely(page->mapping != mapping) ||
453                             !PageDirty(page) ||
454                             PageWriteback(page) ||
455                             page->index != idx) {
456                                 done = 1;
457                                 unlock_page(page);
458                                 break;
459                         }
460                         if (page_has_buffers(page)) {
461                                 bh = head = page_buffers(page);
462                                 do {
463                                         if (!buffer_delay(bh) &&
464                                             !buffer_unwritten(bh))
465                                                 done = 1;
466                                         bh = bh->b_this_page;
467                                 } while (!done && (bh != head));
468                         }
469                         unlock_page(page);
470                         if (done)
471                                 break;
472                         idx++;
473                         num++;
474                         if (num >= max_pages) {
475                                 done = 1;
476                                 break;
477                         }
478                 }
479                 pagevec_release(&pvec);
480         }
481         return num;
482 }
483
484 #ifdef ES_AGGRESSIVE_TEST
485 static void ext4_map_blocks_es_recheck(handle_t *handle,
486                                        struct inode *inode,
487                                        struct ext4_map_blocks *es_map,
488                                        struct ext4_map_blocks *map,
489                                        int flags)
490 {
491         int retval;
492
493         map->m_flags = 0;
494         /*
495          * There is a race window that the result is not the same.
496          * e.g. xfstests #223 when dioread_nolock enables.  The reason
497          * is that we lookup a block mapping in extent status tree with
498          * out taking i_data_sem.  So at the time the unwritten extent
499          * could be converted.
500          */
501         if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
502                 down_read((&EXT4_I(inode)->i_data_sem));
503         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
504                 retval = ext4_ext_map_blocks(handle, inode, map, flags &
505                                              EXT4_GET_BLOCKS_KEEP_SIZE);
506         } else {
507                 retval = ext4_ind_map_blocks(handle, inode, map, flags &
508                                              EXT4_GET_BLOCKS_KEEP_SIZE);
509         }
510         if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
511                 up_read((&EXT4_I(inode)->i_data_sem));
512         /*
513          * Clear EXT4_MAP_FROM_CLUSTER and EXT4_MAP_BOUNDARY flag
514          * because it shouldn't be marked in es_map->m_flags.
515          */
516         map->m_flags &= ~(EXT4_MAP_FROM_CLUSTER | EXT4_MAP_BOUNDARY);
517
518         /*
519          * We don't check m_len because extent will be collpased in status
520          * tree.  So the m_len might not equal.
521          */
522         if (es_map->m_lblk != map->m_lblk ||
523             es_map->m_flags != map->m_flags ||
524             es_map->m_pblk != map->m_pblk) {
525                 printk("ES cache assertation failed for inode: %lu "
526                        "es_cached ex [%d/%d/%llu/%x] != "
527                        "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
528                        inode->i_ino, es_map->m_lblk, es_map->m_len,
529                        es_map->m_pblk, es_map->m_flags, map->m_lblk,
530                        map->m_len, map->m_pblk, map->m_flags,
531                        retval, flags);
532         }
533 }
534 #endif /* ES_AGGRESSIVE_TEST */
535
536 /*
537  * The ext4_map_blocks() function tries to look up the requested blocks,
538  * and returns if the blocks are already mapped.
539  *
540  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
541  * and store the allocated blocks in the result buffer head and mark it
542  * mapped.
543  *
544  * If file type is extents based, it will call ext4_ext_map_blocks(),
545  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
546  * based files
547  *
548  * On success, it returns the number of blocks being mapped or allocate.
549  * if create==0 and the blocks are pre-allocated and uninitialized block,
550  * the result buffer head is unmapped. If the create ==1, it will make sure
551  * the buffer head is mapped.
552  *
553  * It returns 0 if plain look up failed (blocks have not been allocated), in
554  * that case, buffer head is unmapped
555  *
556  * It returns the error in case of allocation failure.
557  */
558 int ext4_map_blocks(handle_t *handle, struct inode *inode,
559                     struct ext4_map_blocks *map, int flags)
560 {
561         struct extent_status es;
562         int retval;
563 #ifdef ES_AGGRESSIVE_TEST
564         struct ext4_map_blocks orig_map;
565
566         memcpy(&orig_map, map, sizeof(*map));
567 #endif
568
569         map->m_flags = 0;
570         ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
571                   "logical block %lu\n", inode->i_ino, flags, map->m_len,
572                   (unsigned long) map->m_lblk);
573
574         /* Lookup extent status tree firstly */
575         if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
576                 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
577                         map->m_pblk = ext4_es_pblock(&es) +
578                                         map->m_lblk - es.es_lblk;
579                         map->m_flags |= ext4_es_is_written(&es) ?
580                                         EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
581                         retval = es.es_len - (map->m_lblk - es.es_lblk);
582                         if (retval > map->m_len)
583                                 retval = map->m_len;
584                         map->m_len = retval;
585                 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
586                         retval = 0;
587                 } else {
588                         BUG_ON(1);
589                 }
590 #ifdef ES_AGGRESSIVE_TEST
591                 ext4_map_blocks_es_recheck(handle, inode, map,
592                                            &orig_map, flags);
593 #endif
594                 goto found;
595         }
596
597         /*
598          * Try to see if we can get the block without requesting a new
599          * file system block.
600          */
601         if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
602                 down_read((&EXT4_I(inode)->i_data_sem));
603         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
604                 retval = ext4_ext_map_blocks(handle, inode, map, flags &
605                                              EXT4_GET_BLOCKS_KEEP_SIZE);
606         } else {
607                 retval = ext4_ind_map_blocks(handle, inode, map, flags &
608                                              EXT4_GET_BLOCKS_KEEP_SIZE);
609         }
610         if (retval > 0) {
611                 int ret;
612                 unsigned long long status;
613
614 #ifdef ES_AGGRESSIVE_TEST
615                 if (retval != map->m_len) {
616                         printk("ES len assertation failed for inode: %lu "
617                                "retval %d != map->m_len %d "
618                                "in %s (lookup)\n", inode->i_ino, retval,
619                                map->m_len, __func__);
620                 }
621 #endif
622
623                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
624                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
625                 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
626                     ext4_find_delalloc_range(inode, map->m_lblk,
627                                              map->m_lblk + map->m_len - 1))
628                         status |= EXTENT_STATUS_DELAYED;
629                 ret = ext4_es_insert_extent(inode, map->m_lblk,
630                                             map->m_len, map->m_pblk, status);
631                 if (ret < 0)
632                         retval = ret;
633         }
634         if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
635                 up_read((&EXT4_I(inode)->i_data_sem));
636
637 found:
638         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
639                 int ret = check_block_validity(inode, map);
640                 if (ret != 0)
641                         return ret;
642         }
643
644         /* If it is only a block(s) look up */
645         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
646                 return retval;
647
648         /*
649          * Returns if the blocks have already allocated
650          *
651          * Note that if blocks have been preallocated
652          * ext4_ext_get_block() returns the create = 0
653          * with buffer head unmapped.
654          */
655         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
656                 return retval;
657
658         /*
659          * Here we clear m_flags because after allocating an new extent,
660          * it will be set again.
661          */
662         map->m_flags &= ~EXT4_MAP_FLAGS;
663
664         /*
665          * New blocks allocate and/or writing to uninitialized extent
666          * will possibly result in updating i_data, so we take
667          * the write lock of i_data_sem, and call get_blocks()
668          * with create == 1 flag.
669          */
670         down_write((&EXT4_I(inode)->i_data_sem));
671
672         /*
673          * if the caller is from delayed allocation writeout path
674          * we have already reserved fs blocks for allocation
675          * let the underlying get_block() function know to
676          * avoid double accounting
677          */
678         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
679                 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
680         /*
681          * We need to check for EXT4 here because migrate
682          * could have changed the inode type in between
683          */
684         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
685                 retval = ext4_ext_map_blocks(handle, inode, map, flags);
686         } else {
687                 retval = ext4_ind_map_blocks(handle, inode, map, flags);
688
689                 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
690                         /*
691                          * We allocated new blocks which will result in
692                          * i_data's format changing.  Force the migrate
693                          * to fail by clearing migrate flags
694                          */
695                         ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
696                 }
697
698                 /*
699                  * Update reserved blocks/metadata blocks after successful
700                  * block allocation which had been deferred till now. We don't
701                  * support fallocate for non extent files. So we can update
702                  * reserve space here.
703                  */
704                 if ((retval > 0) &&
705                         (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
706                         ext4_da_update_reserve_space(inode, retval, 1);
707         }
708         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
709                 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
710
711         if (retval > 0) {
712                 int ret;
713                 unsigned long long status;
714
715 #ifdef ES_AGGRESSIVE_TEST
716                 if (retval != map->m_len) {
717                         printk("ES len assertation failed for inode: %lu "
718                                "retval %d != map->m_len %d "
719                                "in %s (allocation)\n", inode->i_ino, retval,
720                                map->m_len, __func__);
721                 }
722 #endif
723
724                 /*
725                  * If the extent has been zeroed out, we don't need to update
726                  * extent status tree.
727                  */
728                 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
729                     ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
730                         if (ext4_es_is_written(&es))
731                                 goto has_zeroout;
732                 }
733                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
734                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
735                 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
736                     ext4_find_delalloc_range(inode, map->m_lblk,
737                                              map->m_lblk + map->m_len - 1))
738                         status |= EXTENT_STATUS_DELAYED;
739                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
740                                             map->m_pblk, status);
741                 if (ret < 0)
742                         retval = ret;
743         }
744
745 has_zeroout:
746         up_write((&EXT4_I(inode)->i_data_sem));
747         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
748                 int ret = check_block_validity(inode, map);
749                 if (ret != 0)
750                         return ret;
751         }
752         return retval;
753 }
754
755 /* Maximum number of blocks we map for direct IO at once. */
756 #define DIO_MAX_BLOCKS 4096
757
758 static int _ext4_get_block(struct inode *inode, sector_t iblock,
759                            struct buffer_head *bh, int flags)
760 {
761         handle_t *handle = ext4_journal_current_handle();
762         struct ext4_map_blocks map;
763         int ret = 0, started = 0;
764         int dio_credits;
765
766         if (ext4_has_inline_data(inode))
767                 return -ERANGE;
768
769         map.m_lblk = iblock;
770         map.m_len = bh->b_size >> inode->i_blkbits;
771
772         if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
773                 /* Direct IO write... */
774                 if (map.m_len > DIO_MAX_BLOCKS)
775                         map.m_len = DIO_MAX_BLOCKS;
776                 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
777                 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
778                                             dio_credits);
779                 if (IS_ERR(handle)) {
780                         ret = PTR_ERR(handle);
781                         return ret;
782                 }
783                 started = 1;
784         }
785
786         ret = ext4_map_blocks(handle, inode, &map, flags);
787         if (ret > 0) {
788                 map_bh(bh, inode->i_sb, map.m_pblk);
789                 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
790                 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
791                 ret = 0;
792         }
793         if (started)
794                 ext4_journal_stop(handle);
795         return ret;
796 }
797
798 int ext4_get_block(struct inode *inode, sector_t iblock,
799                    struct buffer_head *bh, int create)
800 {
801         return _ext4_get_block(inode, iblock, bh,
802                                create ? EXT4_GET_BLOCKS_CREATE : 0);
803 }
804
805 /*
806  * `handle' can be NULL if create is zero
807  */
808 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
809                                 ext4_lblk_t block, int create, int *errp)
810 {
811         struct ext4_map_blocks map;
812         struct buffer_head *bh;
813         int fatal = 0, err;
814
815         J_ASSERT(handle != NULL || create == 0);
816
817         map.m_lblk = block;
818         map.m_len = 1;
819         err = ext4_map_blocks(handle, inode, &map,
820                               create ? EXT4_GET_BLOCKS_CREATE : 0);
821
822         /* ensure we send some value back into *errp */
823         *errp = 0;
824
825         if (create && err == 0)
826                 err = -ENOSPC;  /* should never happen */
827         if (err < 0)
828                 *errp = err;
829         if (err <= 0)
830                 return NULL;
831
832         bh = sb_getblk(inode->i_sb, map.m_pblk);
833         if (unlikely(!bh)) {
834                 *errp = -ENOMEM;
835                 return NULL;
836         }
837         if (map.m_flags & EXT4_MAP_NEW) {
838                 J_ASSERT(create != 0);
839                 J_ASSERT(handle != NULL);
840
841                 /*
842                  * Now that we do not always journal data, we should
843                  * keep in mind whether this should always journal the
844                  * new buffer as metadata.  For now, regular file
845                  * writes use ext4_get_block instead, so it's not a
846                  * problem.
847                  */
848                 lock_buffer(bh);
849                 BUFFER_TRACE(bh, "call get_create_access");
850                 fatal = ext4_journal_get_create_access(handle, bh);
851                 if (!fatal && !buffer_uptodate(bh)) {
852                         memset(bh->b_data, 0, inode->i_sb->s_blocksize);
853                         set_buffer_uptodate(bh);
854                 }
855                 unlock_buffer(bh);
856                 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
857                 err = ext4_handle_dirty_metadata(handle, inode, bh);
858                 if (!fatal)
859                         fatal = err;
860         } else {
861                 BUFFER_TRACE(bh, "not a new buffer");
862         }
863         if (fatal) {
864                 *errp = fatal;
865                 brelse(bh);
866                 bh = NULL;
867         }
868         return bh;
869 }
870
871 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
872                                ext4_lblk_t block, int create, int *err)
873 {
874         struct buffer_head *bh;
875
876         bh = ext4_getblk(handle, inode, block, create, err);
877         if (!bh)
878                 return bh;
879         if (buffer_uptodate(bh))
880                 return bh;
881         ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
882         wait_on_buffer(bh);
883         if (buffer_uptodate(bh))
884                 return bh;
885         put_bh(bh);
886         *err = -EIO;
887         return NULL;
888 }
889
890 int ext4_walk_page_buffers(handle_t *handle,
891                            struct buffer_head *head,
892                            unsigned from,
893                            unsigned to,
894                            int *partial,
895                            int (*fn)(handle_t *handle,
896                                      struct buffer_head *bh))
897 {
898         struct buffer_head *bh;
899         unsigned block_start, block_end;
900         unsigned blocksize = head->b_size;
901         int err, ret = 0;
902         struct buffer_head *next;
903
904         for (bh = head, block_start = 0;
905              ret == 0 && (bh != head || !block_start);
906              block_start = block_end, bh = next) {
907                 next = bh->b_this_page;
908                 block_end = block_start + blocksize;
909                 if (block_end <= from || block_start >= to) {
910                         if (partial && !buffer_uptodate(bh))
911                                 *partial = 1;
912                         continue;
913                 }
914                 err = (*fn)(handle, bh);
915                 if (!ret)
916                         ret = err;
917         }
918         return ret;
919 }
920
921 /*
922  * To preserve ordering, it is essential that the hole instantiation and
923  * the data write be encapsulated in a single transaction.  We cannot
924  * close off a transaction and start a new one between the ext4_get_block()
925  * and the commit_write().  So doing the jbd2_journal_start at the start of
926  * prepare_write() is the right place.
927  *
928  * Also, this function can nest inside ext4_writepage().  In that case, we
929  * *know* that ext4_writepage() has generated enough buffer credits to do the
930  * whole page.  So we won't block on the journal in that case, which is good,
931  * because the caller may be PF_MEMALLOC.
932  *
933  * By accident, ext4 can be reentered when a transaction is open via
934  * quota file writes.  If we were to commit the transaction while thus
935  * reentered, there can be a deadlock - we would be holding a quota
936  * lock, and the commit would never complete if another thread had a
937  * transaction open and was blocking on the quota lock - a ranking
938  * violation.
939  *
940  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
941  * will _not_ run commit under these circumstances because handle->h_ref
942  * is elevated.  We'll still have enough credits for the tiny quotafile
943  * write.
944  */
945 int do_journal_get_write_access(handle_t *handle,
946                                 struct buffer_head *bh)
947 {
948         int dirty = buffer_dirty(bh);
949         int ret;
950
951         if (!buffer_mapped(bh) || buffer_freed(bh))
952                 return 0;
953         /*
954          * __block_write_begin() could have dirtied some buffers. Clean
955          * the dirty bit as jbd2_journal_get_write_access() could complain
956          * otherwise about fs integrity issues. Setting of the dirty bit
957          * by __block_write_begin() isn't a real problem here as we clear
958          * the bit before releasing a page lock and thus writeback cannot
959          * ever write the buffer.
960          */
961         if (dirty)
962                 clear_buffer_dirty(bh);
963         ret = ext4_journal_get_write_access(handle, bh);
964         if (!ret && dirty)
965                 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
966         return ret;
967 }
968
969 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
970                    struct buffer_head *bh_result, int create);
971 static int ext4_write_begin(struct file *file, struct address_space *mapping,
972                             loff_t pos, unsigned len, unsigned flags,
973                             struct page **pagep, void **fsdata)
974 {
975         struct inode *inode = mapping->host;
976         int ret, needed_blocks;
977         handle_t *handle;
978         int retries = 0;
979         struct page *page;
980         pgoff_t index;
981         unsigned from, to;
982
983         trace_ext4_write_begin(inode, pos, len, flags);
984         /*
985          * Reserve one block more for addition to orphan list in case
986          * we allocate blocks but write fails for some reason
987          */
988         needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
989         index = pos >> PAGE_CACHE_SHIFT;
990         from = pos & (PAGE_CACHE_SIZE - 1);
991         to = from + len;
992
993         if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
994                 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
995                                                     flags, pagep);
996                 if (ret < 0)
997                         return ret;
998                 if (ret == 1)
999                         return 0;
1000         }
1001
1002         /*
1003          * grab_cache_page_write_begin() can take a long time if the
1004          * system is thrashing due to memory pressure, or if the page
1005          * is being written back.  So grab it first before we start
1006          * the transaction handle.  This also allows us to allocate
1007          * the page (if needed) without using GFP_NOFS.
1008          */
1009 retry_grab:
1010         page = grab_cache_page_write_begin(mapping, index, flags);
1011         if (!page)
1012                 return -ENOMEM;
1013         unlock_page(page);
1014
1015 retry_journal:
1016         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1017         if (IS_ERR(handle)) {
1018                 page_cache_release(page);
1019                 return PTR_ERR(handle);
1020         }
1021
1022         lock_page(page);
1023         if (page->mapping != mapping) {
1024                 /* The page got truncated from under us */
1025                 unlock_page(page);
1026                 page_cache_release(page);
1027                 ext4_journal_stop(handle);
1028                 goto retry_grab;
1029         }
1030         wait_on_page_writeback(page);
1031
1032         if (ext4_should_dioread_nolock(inode))
1033                 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1034         else
1035                 ret = __block_write_begin(page, pos, len, ext4_get_block);
1036
1037         if (!ret && ext4_should_journal_data(inode)) {
1038                 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1039                                              from, to, NULL,
1040                                              do_journal_get_write_access);
1041         }
1042
1043         if (ret) {
1044                 unlock_page(page);
1045                 /*
1046                  * __block_write_begin may have instantiated a few blocks
1047                  * outside i_size.  Trim these off again. Don't need
1048                  * i_size_read because we hold i_mutex.
1049                  *
1050                  * Add inode to orphan list in case we crash before
1051                  * truncate finishes
1052                  */
1053                 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1054                         ext4_orphan_add(handle, inode);
1055
1056                 ext4_journal_stop(handle);
1057                 if (pos + len > inode->i_size) {
1058                         ext4_truncate_failed_write(inode);
1059                         /*
1060                          * If truncate failed early the inode might
1061                          * still be on the orphan list; we need to
1062                          * make sure the inode is removed from the
1063                          * orphan list in that case.
1064                          */
1065                         if (inode->i_nlink)
1066                                 ext4_orphan_del(NULL, inode);
1067                 }
1068
1069                 if (ret == -ENOSPC &&
1070                     ext4_should_retry_alloc(inode->i_sb, &retries))
1071                         goto retry_journal;
1072                 page_cache_release(page);
1073                 return ret;
1074         }
1075         *pagep = page;
1076         return ret;
1077 }
1078
1079 /* For write_end() in data=journal mode */
1080 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1081 {
1082         int ret;
1083         if (!buffer_mapped(bh) || buffer_freed(bh))
1084                 return 0;
1085         set_buffer_uptodate(bh);
1086         ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1087         clear_buffer_meta(bh);
1088         clear_buffer_prio(bh);
1089         return ret;
1090 }
1091
1092 /*
1093  * We need to pick up the new inode size which generic_commit_write gave us
1094  * `file' can be NULL - eg, when called from page_symlink().
1095  *
1096  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1097  * buffers are managed internally.
1098  */
1099 static int ext4_write_end(struct file *file,
1100                           struct address_space *mapping,
1101                           loff_t pos, unsigned len, unsigned copied,
1102                           struct page *page, void *fsdata)
1103 {
1104         handle_t *handle = ext4_journal_current_handle();
1105         struct inode *inode = mapping->host;
1106         int ret = 0, ret2;
1107         int i_size_changed = 0;
1108
1109         trace_ext4_write_end(inode, pos, len, copied);
1110         if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1111                 ret = ext4_jbd2_file_inode(handle, inode);
1112                 if (ret) {
1113                         unlock_page(page);
1114                         page_cache_release(page);
1115                         goto errout;
1116                 }
1117         }
1118
1119         if (ext4_has_inline_data(inode))
1120                 copied = ext4_write_inline_data_end(inode, pos, len,
1121                                                     copied, page);
1122         else
1123                 copied = block_write_end(file, mapping, pos,
1124                                          len, copied, page, fsdata);
1125
1126         /*
1127          * No need to use i_size_read() here, the i_size
1128          * cannot change under us because we hole i_mutex.
1129          *
1130          * But it's important to update i_size while still holding page lock:
1131          * page writeout could otherwise come in and zero beyond i_size.
1132          */
1133         if (pos + copied > inode->i_size) {
1134                 i_size_write(inode, pos + copied);
1135                 i_size_changed = 1;
1136         }
1137
1138         if (pos + copied > EXT4_I(inode)->i_disksize) {
1139                 /* We need to mark inode dirty even if
1140                  * new_i_size is less that inode->i_size
1141                  * but greater than i_disksize. (hint delalloc)
1142                  */
1143                 ext4_update_i_disksize(inode, (pos + copied));
1144                 i_size_changed = 1;
1145         }
1146         unlock_page(page);
1147         page_cache_release(page);
1148
1149         /*
1150          * Don't mark the inode dirty under page lock. First, it unnecessarily
1151          * makes the holding time of page lock longer. Second, it forces lock
1152          * ordering of page lock and transaction start for journaling
1153          * filesystems.
1154          */
1155         if (i_size_changed)
1156                 ext4_mark_inode_dirty(handle, inode);
1157
1158         if (copied < 0)
1159                 ret = copied;
1160         if (pos + len > inode->i_size && ext4_can_truncate(inode))
1161                 /* if we have allocated more blocks and copied
1162                  * less. We will have blocks allocated outside
1163                  * inode->i_size. So truncate them
1164                  */
1165                 ext4_orphan_add(handle, inode);
1166 errout:
1167         ret2 = ext4_journal_stop(handle);
1168         if (!ret)
1169                 ret = ret2;
1170
1171         if (pos + len > inode->i_size) {
1172                 ext4_truncate_failed_write(inode);
1173                 /*
1174                  * If truncate failed early the inode might still be
1175                  * on the orphan list; we need to make sure the inode
1176                  * is removed from the orphan list in that case.
1177                  */
1178                 if (inode->i_nlink)
1179                         ext4_orphan_del(NULL, inode);
1180         }
1181
1182         return ret ? ret : copied;
1183 }
1184
1185 static int ext4_journalled_write_end(struct file *file,
1186                                      struct address_space *mapping,
1187                                      loff_t pos, unsigned len, unsigned copied,
1188                                      struct page *page, void *fsdata)
1189 {
1190         handle_t *handle = ext4_journal_current_handle();
1191         struct inode *inode = mapping->host;
1192         int ret = 0, ret2;
1193         int partial = 0;
1194         unsigned from, to;
1195         loff_t new_i_size;
1196
1197         trace_ext4_journalled_write_end(inode, pos, len, copied);
1198         from = pos & (PAGE_CACHE_SIZE - 1);
1199         to = from + len;
1200
1201         BUG_ON(!ext4_handle_valid(handle));
1202
1203         if (ext4_has_inline_data(inode))
1204                 copied = ext4_write_inline_data_end(inode, pos, len,
1205                                                     copied, page);
1206         else {
1207                 if (copied < len) {
1208                         if (!PageUptodate(page))
1209                                 copied = 0;
1210                         page_zero_new_buffers(page, from+copied, to);
1211                 }
1212
1213                 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1214                                              to, &partial, write_end_fn);
1215                 if (!partial)
1216                         SetPageUptodate(page);
1217         }
1218         new_i_size = pos + copied;
1219         if (new_i_size > inode->i_size)
1220                 i_size_write(inode, pos+copied);
1221         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1222         EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1223         if (new_i_size > EXT4_I(inode)->i_disksize) {
1224                 ext4_update_i_disksize(inode, new_i_size);
1225                 ret2 = ext4_mark_inode_dirty(handle, inode);
1226                 if (!ret)
1227                         ret = ret2;
1228         }
1229
1230         unlock_page(page);
1231         page_cache_release(page);
1232         if (pos + len > inode->i_size && ext4_can_truncate(inode))
1233                 /* if we have allocated more blocks and copied
1234                  * less. We will have blocks allocated outside
1235                  * inode->i_size. So truncate them
1236                  */
1237                 ext4_orphan_add(handle, inode);
1238
1239         ret2 = ext4_journal_stop(handle);
1240         if (!ret)
1241                 ret = ret2;
1242         if (pos + len > inode->i_size) {
1243                 ext4_truncate_failed_write(inode);
1244                 /*
1245                  * If truncate failed early the inode might still be
1246                  * on the orphan list; we need to make sure the inode
1247                  * is removed from the orphan list in that case.
1248                  */
1249                 if (inode->i_nlink)
1250                         ext4_orphan_del(NULL, inode);
1251         }
1252
1253         return ret ? ret : copied;
1254 }
1255
1256 /*
1257  * Reserve a metadata for a single block located at lblock
1258  */
1259 static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1260 {
1261         int retries = 0;
1262         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1263         struct ext4_inode_info *ei = EXT4_I(inode);
1264         unsigned int md_needed;
1265         ext4_lblk_t save_last_lblock;
1266         int save_len;
1267
1268         /*
1269          * recalculate the amount of metadata blocks to reserve
1270          * in order to allocate nrblocks
1271          * worse case is one extent per block
1272          */
1273 repeat:
1274         spin_lock(&ei->i_block_reservation_lock);
1275         /*
1276          * ext4_calc_metadata_amount() has side effects, which we have
1277          * to be prepared undo if we fail to claim space.
1278          */
1279         save_len = ei->i_da_metadata_calc_len;
1280         save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1281         md_needed = EXT4_NUM_B2C(sbi,
1282                                  ext4_calc_metadata_amount(inode, lblock));
1283         trace_ext4_da_reserve_space(inode, md_needed);
1284
1285         /*
1286          * We do still charge estimated metadata to the sb though;
1287          * we cannot afford to run out of free blocks.
1288          */
1289         if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1290                 ei->i_da_metadata_calc_len = save_len;
1291                 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1292                 spin_unlock(&ei->i_block_reservation_lock);
1293                 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1294                         cond_resched();
1295                         goto repeat;
1296                 }
1297                 return -ENOSPC;
1298         }
1299         ei->i_reserved_meta_blocks += md_needed;
1300         spin_unlock(&ei->i_block_reservation_lock);
1301
1302         return 0;       /* success */
1303 }
1304
1305 /*
1306  * Reserve a single cluster located at lblock
1307  */
1308 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1309 {
1310         int retries = 0;
1311         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1312         struct ext4_inode_info *ei = EXT4_I(inode);
1313         unsigned int md_needed;
1314         int ret;
1315         ext4_lblk_t save_last_lblock;
1316         int save_len;
1317
1318         /*
1319          * We will charge metadata quota at writeout time; this saves
1320          * us from metadata over-estimation, though we may go over by
1321          * a small amount in the end.  Here we just reserve for data.
1322          */
1323         ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1324         if (ret)
1325                 return ret;
1326
1327         /*
1328          * recalculate the amount of metadata blocks to reserve
1329          * in order to allocate nrblocks
1330          * worse case is one extent per block
1331          */
1332 repeat:
1333         spin_lock(&ei->i_block_reservation_lock);
1334         /*
1335          * ext4_calc_metadata_amount() has side effects, which we have
1336          * to be prepared undo if we fail to claim space.
1337          */
1338         save_len = ei->i_da_metadata_calc_len;
1339         save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1340         md_needed = EXT4_NUM_B2C(sbi,
1341                                  ext4_calc_metadata_amount(inode, lblock));
1342         trace_ext4_da_reserve_space(inode, md_needed);
1343
1344         /*
1345          * We do still charge estimated metadata to the sb though;
1346          * we cannot afford to run out of free blocks.
1347          */
1348         if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1349                 ei->i_da_metadata_calc_len = save_len;
1350                 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1351                 spin_unlock(&ei->i_block_reservation_lock);
1352                 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1353                         cond_resched();
1354                         goto repeat;
1355                 }
1356                 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1357                 return -ENOSPC;
1358         }
1359         ei->i_reserved_data_blocks++;
1360         ei->i_reserved_meta_blocks += md_needed;
1361         spin_unlock(&ei->i_block_reservation_lock);
1362
1363         return 0;       /* success */
1364 }
1365
1366 static void ext4_da_release_space(struct inode *inode, int to_free)
1367 {
1368         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1369         struct ext4_inode_info *ei = EXT4_I(inode);
1370
1371         if (!to_free)
1372                 return;         /* Nothing to release, exit */
1373
1374         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1375
1376         trace_ext4_da_release_space(inode, to_free);
1377         if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1378                 /*
1379                  * if there aren't enough reserved blocks, then the
1380                  * counter is messed up somewhere.  Since this
1381                  * function is called from invalidate page, it's
1382                  * harmless to return without any action.
1383                  */
1384                 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1385                          "ino %lu, to_free %d with only %d reserved "
1386                          "data blocks", inode->i_ino, to_free,
1387                          ei->i_reserved_data_blocks);
1388                 WARN_ON(1);
1389                 to_free = ei->i_reserved_data_blocks;
1390         }
1391         ei->i_reserved_data_blocks -= to_free;
1392
1393         if (ei->i_reserved_data_blocks == 0) {
1394                 /*
1395                  * We can release all of the reserved metadata blocks
1396                  * only when we have written all of the delayed
1397                  * allocation blocks.
1398                  * Note that in case of bigalloc, i_reserved_meta_blocks,
1399                  * i_reserved_data_blocks, etc. refer to number of clusters.
1400                  */
1401                 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1402                                    ei->i_reserved_meta_blocks);
1403                 ei->i_reserved_meta_blocks = 0;
1404                 ei->i_da_metadata_calc_len = 0;
1405         }
1406
1407         /* update fs dirty data blocks counter */
1408         percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1409
1410         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1411
1412         dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1413 }
1414
1415 static void ext4_da_page_release_reservation(struct page *page,
1416                                              unsigned int offset,
1417                                              unsigned int length)
1418 {
1419         int to_release = 0;
1420         struct buffer_head *head, *bh;
1421         unsigned int curr_off = 0;
1422         struct inode *inode = page->mapping->host;
1423         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1424         unsigned int stop = offset + length;
1425         int num_clusters;
1426         ext4_fsblk_t lblk;
1427
1428         BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1429
1430         head = page_buffers(page);
1431         bh = head;
1432         do {
1433                 unsigned int next_off = curr_off + bh->b_size;
1434
1435                 if (next_off > stop)
1436                         break;
1437
1438                 if ((offset <= curr_off) && (buffer_delay(bh))) {
1439                         to_release++;
1440                         clear_buffer_delay(bh);
1441                 }
1442                 curr_off = next_off;
1443         } while ((bh = bh->b_this_page) != head);
1444
1445         if (to_release) {
1446                 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1447                 ext4_es_remove_extent(inode, lblk, to_release);
1448         }
1449
1450         /* If we have released all the blocks belonging to a cluster, then we
1451          * need to release the reserved space for that cluster. */
1452         num_clusters = EXT4_NUM_B2C(sbi, to_release);
1453         while (num_clusters > 0) {
1454                 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1455                         ((num_clusters - 1) << sbi->s_cluster_bits);
1456                 if (sbi->s_cluster_ratio == 1 ||
1457                     !ext4_find_delalloc_cluster(inode, lblk))
1458                         ext4_da_release_space(inode, 1);
1459
1460                 num_clusters--;
1461         }
1462 }
1463
1464 /*
1465  * Delayed allocation stuff
1466  */
1467
1468 /*
1469  * mpage_da_submit_io - walks through extent of pages and try to write
1470  * them with writepage() call back
1471  *
1472  * @mpd->inode: inode
1473  * @mpd->first_page: first page of the extent
1474  * @mpd->next_page: page after the last page of the extent
1475  *
1476  * By the time mpage_da_submit_io() is called we expect all blocks
1477  * to be allocated. this may be wrong if allocation failed.
1478  *
1479  * As pages are already locked by write_cache_pages(), we can't use it
1480  */
1481 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1482                               struct ext4_map_blocks *map)
1483 {
1484         struct pagevec pvec;
1485         unsigned long index, end;
1486         int ret = 0, err, nr_pages, i;
1487         struct inode *inode = mpd->inode;
1488         struct address_space *mapping = inode->i_mapping;
1489         loff_t size = i_size_read(inode);
1490         unsigned int len, block_start;
1491         struct buffer_head *bh, *page_bufs = NULL;
1492         sector_t pblock = 0, cur_logical = 0;
1493         struct ext4_io_submit io_submit;
1494
1495         BUG_ON(mpd->next_page <= mpd->first_page);
1496         memset(&io_submit, 0, sizeof(io_submit));
1497         /*
1498          * We need to start from the first_page to the next_page - 1
1499          * to make sure we also write the mapped dirty buffer_heads.
1500          * If we look at mpd->b_blocknr we would only be looking
1501          * at the currently mapped buffer_heads.
1502          */
1503         index = mpd->first_page;
1504         end = mpd->next_page - 1;
1505
1506         pagevec_init(&pvec, 0);
1507         while (index <= end) {
1508                 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1509                 if (nr_pages == 0)
1510                         break;
1511                 for (i = 0; i < nr_pages; i++) {
1512                         int skip_page = 0;
1513                         struct page *page = pvec.pages[i];
1514
1515                         index = page->index;
1516                         if (index > end)
1517                                 break;
1518
1519                         if (index == size >> PAGE_CACHE_SHIFT)
1520                                 len = size & ~PAGE_CACHE_MASK;
1521                         else
1522                                 len = PAGE_CACHE_SIZE;
1523                         if (map) {
1524                                 cur_logical = index << (PAGE_CACHE_SHIFT -
1525                                                         inode->i_blkbits);
1526                                 pblock = map->m_pblk + (cur_logical -
1527                                                         map->m_lblk);
1528                         }
1529                         index++;
1530
1531                         BUG_ON(!PageLocked(page));
1532                         BUG_ON(PageWriteback(page));
1533
1534                         bh = page_bufs = page_buffers(page);
1535                         block_start = 0;
1536                         do {
1537                                 if (map && (cur_logical >= map->m_lblk) &&
1538                                     (cur_logical <= (map->m_lblk +
1539                                                      (map->m_len - 1)))) {
1540                                         if (buffer_delay(bh)) {
1541                                                 clear_buffer_delay(bh);
1542                                                 bh->b_blocknr = pblock;
1543                                         }
1544                                         if (buffer_unwritten(bh) ||
1545                                             buffer_mapped(bh))
1546                                                 BUG_ON(bh->b_blocknr != pblock);
1547                                         if (map->m_flags & EXT4_MAP_UNINIT)
1548                                                 set_buffer_uninit(bh);
1549                                         clear_buffer_unwritten(bh);
1550                                 }
1551
1552                                 /*
1553                                  * skip page if block allocation undone and
1554                                  * block is dirty
1555                                  */
1556                                 if (ext4_bh_delay_or_unwritten(NULL, bh))
1557                                         skip_page = 1;
1558                                 bh = bh->b_this_page;
1559                                 block_start += bh->b_size;
1560                                 cur_logical++;
1561                                 pblock++;
1562                         } while (bh != page_bufs);
1563
1564                         if (skip_page) {
1565                                 unlock_page(page);
1566                                 continue;
1567                         }
1568
1569                         clear_page_dirty_for_io(page);
1570                         err = ext4_bio_write_page(&io_submit, page, len,
1571                                                   mpd->wbc);
1572                         if (!err)
1573                                 mpd->pages_written++;
1574                         /*
1575                          * In error case, we have to continue because
1576                          * remaining pages are still locked
1577                          */
1578                         if (ret == 0)
1579                                 ret = err;
1580                 }
1581                 pagevec_release(&pvec);
1582         }
1583         ext4_io_submit(&io_submit);
1584         return ret;
1585 }
1586
1587 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1588 {
1589         int nr_pages, i;
1590         pgoff_t index, end;
1591         struct pagevec pvec;
1592         struct inode *inode = mpd->inode;
1593         struct address_space *mapping = inode->i_mapping;
1594         ext4_lblk_t start, last;
1595
1596         index = mpd->first_page;
1597         end   = mpd->next_page - 1;
1598
1599         start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1600         last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1601         ext4_es_remove_extent(inode, start, last - start + 1);
1602
1603         pagevec_init(&pvec, 0);
1604         while (index <= end) {
1605                 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1606                 if (nr_pages == 0)
1607                         break;
1608                 for (i = 0; i < nr_pages; i++) {
1609                         struct page *page = pvec.pages[i];
1610                         if (page->index > end)
1611                                 break;
1612                         BUG_ON(!PageLocked(page));
1613                         BUG_ON(PageWriteback(page));
1614                         block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1615                         ClearPageUptodate(page);
1616                         unlock_page(page);
1617                 }
1618                 index = pvec.pages[nr_pages - 1]->index + 1;
1619                 pagevec_release(&pvec);
1620         }
1621         return;
1622 }
1623
1624 static void ext4_print_free_blocks(struct inode *inode)
1625 {
1626         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1627         struct super_block *sb = inode->i_sb;
1628         struct ext4_inode_info *ei = EXT4_I(inode);
1629
1630         ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1631                EXT4_C2B(EXT4_SB(inode->i_sb),
1632                         ext4_count_free_clusters(sb)));
1633         ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1634         ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1635                (long long) EXT4_C2B(EXT4_SB(sb),
1636                 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1637         ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1638                (long long) EXT4_C2B(EXT4_SB(sb),
1639                 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1640         ext4_msg(sb, KERN_CRIT, "Block reservation details");
1641         ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1642                  ei->i_reserved_data_blocks);
1643         ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1644                ei->i_reserved_meta_blocks);
1645         ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1646                ei->i_allocated_meta_blocks);
1647         return;
1648 }
1649
1650 /*
1651  * mpage_da_map_and_submit - go through given space, map them
1652  *       if necessary, and then submit them for I/O
1653  *
1654  * @mpd - bh describing space
1655  *
1656  * The function skips space we know is already mapped to disk blocks.
1657  *
1658  */
1659 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1660 {
1661         int err, blks, get_blocks_flags;
1662         struct ext4_map_blocks map, *mapp = NULL;
1663         sector_t next = mpd->b_blocknr;
1664         unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1665         loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1666         handle_t *handle = NULL;
1667
1668         /*
1669          * If the blocks are mapped already, or we couldn't accumulate
1670          * any blocks, then proceed immediately to the submission stage.
1671          */
1672         if ((mpd->b_size == 0) ||
1673             ((mpd->b_state  & (1 << BH_Mapped)) &&
1674              !(mpd->b_state & (1 << BH_Delay)) &&
1675              !(mpd->b_state & (1 << BH_Unwritten))))
1676                 goto submit_io;
1677
1678         handle = ext4_journal_current_handle();
1679         BUG_ON(!handle);
1680
1681         /*
1682          * Call ext4_map_blocks() to allocate any delayed allocation
1683          * blocks, or to convert an uninitialized extent to be
1684          * initialized (in the case where we have written into
1685          * one or more preallocated blocks).
1686          *
1687          * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1688          * indicate that we are on the delayed allocation path.  This
1689          * affects functions in many different parts of the allocation
1690          * call path.  This flag exists primarily because we don't
1691          * want to change *many* call functions, so ext4_map_blocks()
1692          * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1693          * inode's allocation semaphore is taken.
1694          *
1695          * If the blocks in questions were delalloc blocks, set
1696          * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1697          * variables are updated after the blocks have been allocated.
1698          */
1699         map.m_lblk = next;
1700         map.m_len = max_blocks;
1701         /*
1702          * We're in delalloc path and it is possible that we're going to
1703          * need more metadata blocks than previously reserved. However
1704          * we must not fail because we're in writeback and there is
1705          * nothing we can do about it so it might result in data loss.
1706          * So use reserved blocks to allocate metadata if possible.
1707          */
1708         get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
1709                            EXT4_GET_BLOCKS_METADATA_NOFAIL;
1710         if (ext4_should_dioread_nolock(mpd->inode))
1711                 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1712         if (mpd->b_state & (1 << BH_Delay))
1713                 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1714
1715
1716         blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1717         if (blks < 0) {
1718                 struct super_block *sb = mpd->inode->i_sb;
1719
1720                 err = blks;
1721                 /*
1722                  * If get block returns EAGAIN or ENOSPC and there
1723                  * appears to be free blocks we will just let
1724                  * mpage_da_submit_io() unlock all of the pages.
1725                  */
1726                 if (err == -EAGAIN)
1727                         goto submit_io;
1728
1729                 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1730                         mpd->retval = err;
1731                         goto submit_io;
1732                 }
1733
1734                 /*
1735                  * get block failure will cause us to loop in
1736                  * writepages, because a_ops->writepage won't be able
1737                  * to make progress. The page will be redirtied by
1738                  * writepage and writepages will again try to write
1739                  * the same.
1740                  */
1741                 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1742                         ext4_msg(sb, KERN_CRIT,
1743                                  "delayed block allocation failed for inode %lu "
1744                                  "at logical offset %llu with max blocks %zd "
1745                                  "with error %d", mpd->inode->i_ino,
1746                                  (unsigned long long) next,
1747                                  mpd->b_size >> mpd->inode->i_blkbits, err);
1748                         ext4_msg(sb, KERN_CRIT,
1749                                 "This should not happen!! Data will be lost");
1750                         if (err == -ENOSPC)
1751                                 ext4_print_free_blocks(mpd->inode);
1752                 }
1753                 /* invalidate all the pages */
1754                 ext4_da_block_invalidatepages(mpd);
1755
1756                 /* Mark this page range as having been completed */
1757                 mpd->io_done = 1;
1758                 return;
1759         }
1760         BUG_ON(blks == 0);
1761
1762         mapp = &map;
1763         if (map.m_flags & EXT4_MAP_NEW) {
1764                 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1765                 int i;
1766
1767                 for (i = 0; i < map.m_len; i++)
1768                         unmap_underlying_metadata(bdev, map.m_pblk + i);
1769         }
1770
1771         /*
1772          * Update on-disk size along with block allocation.
1773          */
1774         disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1775         if (disksize > i_size_read(mpd->inode))
1776                 disksize = i_size_read(mpd->inode);
1777         if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1778                 ext4_update_i_disksize(mpd->inode, disksize);
1779                 err = ext4_mark_inode_dirty(handle, mpd->inode);
1780                 if (err)
1781                         ext4_error(mpd->inode->i_sb,
1782                                    "Failed to mark inode %lu dirty",
1783                                    mpd->inode->i_ino);
1784         }
1785
1786 submit_io:
1787         mpage_da_submit_io(mpd, mapp);
1788         mpd->io_done = 1;
1789 }
1790
1791 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1792                 (1 << BH_Delay) | (1 << BH_Unwritten))
1793
1794 /*
1795  * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1796  *
1797  * @mpd->lbh - extent of blocks
1798  * @logical - logical number of the block in the file
1799  * @b_state - b_state of the buffer head added
1800  *
1801  * the function is used to collect contig. blocks in same state
1802  */
1803 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd, sector_t logical,
1804                                    unsigned long b_state)
1805 {
1806         sector_t next;
1807         int blkbits = mpd->inode->i_blkbits;
1808         int nrblocks = mpd->b_size >> blkbits;
1809
1810         /*
1811          * XXX Don't go larger than mballoc is willing to allocate
1812          * This is a stopgap solution.  We eventually need to fold
1813          * mpage_da_submit_io() into this function and then call
1814          * ext4_map_blocks() multiple times in a loop
1815          */
1816         if (nrblocks >= (8*1024*1024 >> blkbits))
1817                 goto flush_it;
1818
1819         /* check if the reserved journal credits might overflow */
1820         if (!ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS)) {
1821                 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1822                         /*
1823                          * With non-extent format we are limited by the journal
1824                          * credit available.  Total credit needed to insert
1825                          * nrblocks contiguous blocks is dependent on the
1826                          * nrblocks.  So limit nrblocks.
1827                          */
1828                         goto flush_it;
1829                 }
1830         }
1831         /*
1832          * First block in the extent
1833          */
1834         if (mpd->b_size == 0) {
1835                 mpd->b_blocknr = logical;
1836                 mpd->b_size = 1 << blkbits;
1837                 mpd->b_state = b_state & BH_FLAGS;
1838                 return;
1839         }
1840
1841         next = mpd->b_blocknr + nrblocks;
1842         /*
1843          * Can we merge the block to our big extent?
1844          */
1845         if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1846                 mpd->b_size += 1 << blkbits;
1847                 return;
1848         }
1849
1850 flush_it:
1851         /*
1852          * We couldn't merge the block to our extent, so we
1853          * need to flush current  extent and start new one
1854          */
1855         mpage_da_map_and_submit(mpd);
1856         return;
1857 }
1858
1859 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1860 {
1861         return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1862 }
1863
1864 /*
1865  * This function is grabs code from the very beginning of
1866  * ext4_map_blocks, but assumes that the caller is from delayed write
1867  * time. This function looks up the requested blocks and sets the
1868  * buffer delay bit under the protection of i_data_sem.
1869  */
1870 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1871                               struct ext4_map_blocks *map,
1872                               struct buffer_head *bh)
1873 {
1874         struct extent_status es;
1875         int retval;
1876         sector_t invalid_block = ~((sector_t) 0xffff);
1877 #ifdef ES_AGGRESSIVE_TEST
1878         struct ext4_map_blocks orig_map;
1879
1880         memcpy(&orig_map, map, sizeof(*map));
1881 #endif
1882
1883         if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1884                 invalid_block = ~0;
1885
1886         map->m_flags = 0;
1887         ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1888                   "logical block %lu\n", inode->i_ino, map->m_len,
1889                   (unsigned long) map->m_lblk);
1890
1891         /* Lookup extent status tree firstly */
1892         if (ext4_es_lookup_extent(inode, iblock, &es)) {
1893
1894                 if (ext4_es_is_hole(&es)) {
1895                         retval = 0;
1896                         down_read((&EXT4_I(inode)->i_data_sem));
1897                         goto add_delayed;
1898                 }
1899
1900                 /*
1901                  * Delayed extent could be allocated by fallocate.
1902                  * So we need to check it.
1903                  */
1904                 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1905                         map_bh(bh, inode->i_sb, invalid_block);
1906                         set_buffer_new(bh);
1907                         set_buffer_delay(bh);
1908                         return 0;
1909                 }
1910
1911                 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1912                 retval = es.es_len - (iblock - es.es_lblk);
1913                 if (retval > map->m_len)
1914                         retval = map->m_len;
1915                 map->m_len = retval;
1916                 if (ext4_es_is_written(&es))
1917                         map->m_flags |= EXT4_MAP_MAPPED;
1918                 else if (ext4_es_is_unwritten(&es))
1919                         map->m_flags |= EXT4_MAP_UNWRITTEN;
1920                 else
1921                         BUG_ON(1);
1922
1923 #ifdef ES_AGGRESSIVE_TEST
1924                 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1925 #endif
1926                 return retval;
1927         }
1928
1929         /*
1930          * Try to see if we can get the block without requesting a new
1931          * file system block.
1932          */
1933         down_read((&EXT4_I(inode)->i_data_sem));
1934         if (ext4_has_inline_data(inode)) {
1935                 /*
1936                  * We will soon create blocks for this page, and let
1937                  * us pretend as if the blocks aren't allocated yet.
1938                  * In case of clusters, we have to handle the work
1939                  * of mapping from cluster so that the reserved space
1940                  * is calculated properly.
1941                  */
1942                 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1943                     ext4_find_delalloc_cluster(inode, map->m_lblk))
1944                         map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1945                 retval = 0;
1946         } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1947                 retval = ext4_ext_map_blocks(NULL, inode, map,
1948                                              EXT4_GET_BLOCKS_NO_PUT_HOLE);
1949         else
1950                 retval = ext4_ind_map_blocks(NULL, inode, map,
1951                                              EXT4_GET_BLOCKS_NO_PUT_HOLE);
1952
1953 add_delayed:
1954         if (retval == 0) {
1955                 int ret;
1956                 /*
1957                  * XXX: __block_prepare_write() unmaps passed block,
1958                  * is it OK?
1959                  */
1960                 /*
1961                  * If the block was allocated from previously allocated cluster,
1962                  * then we don't need to reserve it again. However we still need
1963                  * to reserve metadata for every block we're going to write.
1964                  */
1965                 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1966                         ret = ext4_da_reserve_space(inode, iblock);
1967                         if (ret) {
1968                                 /* not enough space to reserve */
1969                                 retval = ret;
1970                                 goto out_unlock;
1971                         }
1972                 } else {
1973                         ret = ext4_da_reserve_metadata(inode, iblock);
1974                         if (ret) {
1975                                 /* not enough space to reserve */
1976                                 retval = ret;
1977                                 goto out_unlock;
1978                         }
1979                 }
1980
1981                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1982                                             ~0, EXTENT_STATUS_DELAYED);
1983                 if (ret) {
1984                         retval = ret;
1985                         goto out_unlock;
1986                 }
1987
1988                 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1989                  * and it should not appear on the bh->b_state.
1990                  */
1991                 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1992
1993                 map_bh(bh, inode->i_sb, invalid_block);
1994                 set_buffer_new(bh);
1995                 set_buffer_delay(bh);
1996         } else if (retval > 0) {
1997                 int ret;
1998                 unsigned long long status;
1999
2000 #ifdef ES_AGGRESSIVE_TEST
2001                 if (retval != map->m_len) {
2002                         printk("ES len assertation failed for inode: %lu "
2003                                "retval %d != map->m_len %d "
2004                                "in %s (lookup)\n", inode->i_ino, retval,
2005                                map->m_len, __func__);
2006                 }
2007 #endif
2008
2009                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
2010                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
2011                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
2012                                             map->m_pblk, status);
2013                 if (ret != 0)
2014                         retval = ret;
2015         }
2016
2017 out_unlock:
2018         up_read((&EXT4_I(inode)->i_data_sem));
2019
2020         return retval;
2021 }
2022
2023 /*
2024  * This is a special get_blocks_t callback which is used by
2025  * ext4_da_write_begin().  It will either return mapped block or
2026  * reserve space for a single block.
2027  *
2028  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2029  * We also have b_blocknr = -1 and b_bdev initialized properly
2030  *
2031  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2032  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2033  * initialized properly.
2034  */
2035 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2036                            struct buffer_head *bh, int create)
2037 {
2038         struct ext4_map_blocks map;
2039         int ret = 0;
2040
2041         BUG_ON(create == 0);
2042         BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2043
2044         map.m_lblk = iblock;
2045         map.m_len = 1;
2046
2047         /*
2048          * first, we need to know whether the block is allocated already
2049          * preallocated blocks are unmapped but should treated
2050          * the same as allocated blocks.
2051          */
2052         ret = ext4_da_map_blocks(inode, iblock, &map, bh);
2053         if (ret <= 0)
2054                 return ret;
2055
2056         map_bh(bh, inode->i_sb, map.m_pblk);
2057         bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
2058
2059         if (buffer_unwritten(bh)) {
2060                 /* A delayed write to unwritten bh should be marked
2061                  * new and mapped.  Mapped ensures that we don't do
2062                  * get_block multiple times when we write to the same
2063                  * offset and new ensures that we do proper zero out
2064                  * for partial write.
2065                  */
2066                 set_buffer_new(bh);
2067                 set_buffer_mapped(bh);
2068         }
2069         return 0;
2070 }
2071
2072 static int bget_one(handle_t *handle, struct buffer_head *bh)
2073 {
2074         get_bh(bh);
2075         return 0;
2076 }
2077
2078 static int bput_one(handle_t *handle, struct buffer_head *bh)
2079 {
2080         put_bh(bh);
2081         return 0;
2082 }
2083
2084 static int __ext4_journalled_writepage(struct page *page,
2085                                        unsigned int len)
2086 {
2087         struct address_space *mapping = page->mapping;
2088         struct inode *inode = mapping->host;
2089         struct buffer_head *page_bufs = NULL;
2090         handle_t *handle = NULL;
2091         int ret = 0, err = 0;
2092         int inline_data = ext4_has_inline_data(inode);
2093         struct buffer_head *inode_bh = NULL;
2094
2095         ClearPageChecked(page);
2096
2097         if (inline_data) {
2098                 BUG_ON(page->index != 0);
2099                 BUG_ON(len > ext4_get_max_inline_size(inode));
2100                 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2101                 if (inode_bh == NULL)
2102                         goto out;
2103         } else {
2104                 page_bufs = page_buffers(page);
2105                 if (!page_bufs) {
2106                         BUG();
2107                         goto out;
2108                 }
2109                 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2110                                        NULL, bget_one);
2111         }
2112         /* As soon as we unlock the page, it can go away, but we have
2113          * references to buffers so we are safe */
2114         unlock_page(page);
2115
2116         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2117                                     ext4_writepage_trans_blocks(inode));
2118         if (IS_ERR(handle)) {
2119                 ret = PTR_ERR(handle);
2120                 goto out;
2121         }
2122
2123         BUG_ON(!ext4_handle_valid(handle));
2124
2125         if (inline_data) {
2126                 ret = ext4_journal_get_write_access(handle, inode_bh);
2127
2128                 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
2129
2130         } else {
2131                 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2132                                              do_journal_get_write_access);
2133
2134                 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2135                                              write_end_fn);
2136         }
2137         if (ret == 0)
2138                 ret = err;
2139         EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2140         err = ext4_journal_stop(handle);
2141         if (!ret)
2142                 ret = err;
2143
2144         if (!ext4_has_inline_data(inode))
2145                 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2146                                        NULL, bput_one);
2147         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2148 out:
2149         brelse(inode_bh);
2150         return ret;
2151 }
2152
2153 /*
2154  * Note that we don't need to start a transaction unless we're journaling data
2155  * because we should have holes filled from ext4_page_mkwrite(). We even don't
2156  * need to file the inode to the transaction's list in ordered mode because if
2157  * we are writing back data added by write(), the inode is already there and if
2158  * we are writing back data modified via mmap(), no one guarantees in which
2159  * transaction the data will hit the disk. In case we are journaling data, we
2160  * cannot start transaction directly because transaction start ranks above page
2161  * lock so we have to do some magic.
2162  *
2163  * This function can get called via...
2164  *   - ext4_da_writepages after taking page lock (have journal handle)
2165  *   - journal_submit_inode_data_buffers (no journal handle)
2166  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2167  *   - grab_page_cache when doing write_begin (have journal handle)
2168  *
2169  * We don't do any block allocation in this function. If we have page with
2170  * multiple blocks we need to write those buffer_heads that are mapped. This
2171  * is important for mmaped based write. So if we do with blocksize 1K
2172  * truncate(f, 1024);
2173  * a = mmap(f, 0, 4096);
2174  * a[0] = 'a';
2175  * truncate(f, 4096);
2176  * we have in the page first buffer_head mapped via page_mkwrite call back
2177  * but other buffer_heads would be unmapped but dirty (dirty done via the
2178  * do_wp_page). So writepage should write the first block. If we modify
2179  * the mmap area beyond 1024 we will again get a page_fault and the
2180  * page_mkwrite callback will do the block allocation and mark the
2181  * buffer_heads mapped.
2182  *
2183  * We redirty the page if we have any buffer_heads that is either delay or
2184  * unwritten in the page.
2185  *
2186  * We can get recursively called as show below.
2187  *
2188  *      ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2189  *              ext4_writepage()
2190  *
2191  * But since we don't do any block allocation we should not deadlock.
2192  * Page also have the dirty flag cleared so we don't get recurive page_lock.
2193  */
2194 static int ext4_writepage(struct page *page,
2195                           struct writeback_control *wbc)
2196 {
2197         int ret = 0;
2198         loff_t size;
2199         unsigned int len;
2200         struct buffer_head *page_bufs = NULL;
2201         struct inode *inode = page->mapping->host;
2202         struct ext4_io_submit io_submit;
2203
2204         trace_ext4_writepage(page);
2205         size = i_size_read(inode);
2206         if (page->index == size >> PAGE_CACHE_SHIFT)
2207                 len = size & ~PAGE_CACHE_MASK;
2208         else
2209                 len = PAGE_CACHE_SIZE;
2210
2211         page_bufs = page_buffers(page);
2212         /*
2213          * We cannot do block allocation or other extent handling in this
2214          * function. If there are buffers needing that, we have to redirty
2215          * the page. But we may reach here when we do a journal commit via
2216          * journal_submit_inode_data_buffers() and in that case we must write
2217          * allocated buffers to achieve data=ordered mode guarantees.
2218          */
2219         if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2220                                    ext4_bh_delay_or_unwritten)) {
2221                 redirty_page_for_writepage(wbc, page);
2222                 if (current->flags & PF_MEMALLOC) {
2223                         /*
2224                          * For memory cleaning there's no point in writing only
2225                          * some buffers. So just bail out. Warn if we came here
2226                          * from direct reclaim.
2227                          */
2228                         WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2229                                                         == PF_MEMALLOC);
2230                         unlock_page(page);
2231                         return 0;
2232                 }
2233         }
2234
2235         if (PageChecked(page) && ext4_should_journal_data(inode))
2236                 /*
2237                  * It's mmapped pagecache.  Add buffers and journal it.  There
2238                  * doesn't seem much point in redirtying the page here.
2239                  */
2240                 return __ext4_journalled_writepage(page, len);
2241
2242         memset(&io_submit, 0, sizeof(io_submit));
2243         ret = ext4_bio_write_page(&io_submit, page, len, wbc);
2244         ext4_io_submit(&io_submit);
2245         return ret;
2246 }
2247
2248 /*
2249  * This is called via ext4_da_writepages() to
2250  * calculate the total number of credits to reserve to fit
2251  * a single extent allocation into a single transaction,
2252  * ext4_da_writpeages() will loop calling this before
2253  * the block allocation.
2254  */
2255
2256 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2257 {
2258         int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2259
2260         /*
2261          * With non-extent format the journal credit needed to
2262          * insert nrblocks contiguous block is dependent on
2263          * number of contiguous block. So we will limit
2264          * number of contiguous block to a sane value
2265          */
2266         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2267             (max_blocks > EXT4_MAX_TRANS_DATA))
2268                 max_blocks = EXT4_MAX_TRANS_DATA;
2269
2270         return ext4_chunk_trans_blocks(inode, max_blocks);
2271 }
2272
2273 /*
2274  * write_cache_pages_da - walk the list of dirty pages of the given
2275  * address space and accumulate pages that need writing, and call
2276  * mpage_da_map_and_submit to map a single contiguous memory region
2277  * and then write them.
2278  */
2279 static int write_cache_pages_da(handle_t *handle,
2280                                 struct address_space *mapping,
2281                                 struct writeback_control *wbc,
2282                                 struct mpage_da_data *mpd,
2283                                 pgoff_t *done_index)
2284 {
2285         struct buffer_head      *bh, *head;
2286         struct inode            *inode = mapping->host;
2287         struct pagevec          pvec;
2288         unsigned int            nr_pages;
2289         sector_t                logical;
2290         pgoff_t                 index, end;
2291         long                    nr_to_write = wbc->nr_to_write;
2292         int                     i, tag, ret = 0;
2293
2294         memset(mpd, 0, sizeof(struct mpage_da_data));
2295         mpd->wbc = wbc;
2296         mpd->inode = inode;
2297         pagevec_init(&pvec, 0);
2298         index = wbc->range_start >> PAGE_CACHE_SHIFT;
2299         end = wbc->range_end >> PAGE_CACHE_SHIFT;
2300
2301         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2302                 tag = PAGECACHE_TAG_TOWRITE;
2303         else
2304                 tag = PAGECACHE_TAG_DIRTY;
2305
2306         *done_index = index;
2307         while (index <= end) {
2308                 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2309                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2310                 if (nr_pages == 0)
2311                         return 0;
2312
2313                 for (i = 0; i < nr_pages; i++) {
2314                         struct page *page = pvec.pages[i];
2315
2316                         /*
2317                          * At this point, the page may be truncated or
2318                          * invalidated (changing page->mapping to NULL), or
2319                          * even swizzled back from swapper_space to tmpfs file
2320                          * mapping. However, page->index will not change
2321                          * because we have a reference on the page.
2322                          */
2323                         if (page->index > end)
2324                                 goto out;
2325
2326                         *done_index = page->index + 1;
2327
2328                         /*
2329                          * If we can't merge this page, and we have
2330                          * accumulated an contiguous region, write it
2331                          */
2332                         if ((mpd->next_page != page->index) &&
2333                             (mpd->next_page != mpd->first_page)) {
2334                                 mpage_da_map_and_submit(mpd);
2335                                 goto ret_extent_tail;
2336                         }
2337
2338                         lock_page(page);
2339
2340                         /*
2341                          * If the page is no longer dirty, or its
2342                          * mapping no longer corresponds to inode we
2343                          * are writing (which means it has been
2344                          * truncated or invalidated), or the page is
2345                          * already under writeback and we are not
2346                          * doing a data integrity writeback, skip the page
2347                          */
2348                         if (!PageDirty(page) ||
2349                             (PageWriteback(page) &&
2350                              (wbc->sync_mode == WB_SYNC_NONE)) ||
2351                             unlikely(page->mapping != mapping)) {
2352                                 unlock_page(page);
2353                                 continue;
2354                         }
2355
2356                         wait_on_page_writeback(page);
2357                         BUG_ON(PageWriteback(page));
2358
2359                         /*
2360                          * If we have inline data and arrive here, it means that
2361                          * we will soon create the block for the 1st page, so
2362                          * we'd better clear the inline data here.
2363                          */
2364                         if (ext4_has_inline_data(inode)) {
2365                                 BUG_ON(ext4_test_inode_state(inode,
2366                                                 EXT4_STATE_MAY_INLINE_DATA));
2367                                 ext4_destroy_inline_data(handle, inode);
2368                         }
2369
2370                         if (mpd->next_page != page->index)
2371                                 mpd->first_page = page->index;
2372                         mpd->next_page = page->index + 1;
2373                         logical = (sector_t) page->index <<
2374                                 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2375
2376                         /* Add all dirty buffers to mpd */
2377                         head = page_buffers(page);
2378                         bh = head;
2379                         do {
2380                                 BUG_ON(buffer_locked(bh));
2381                                 /*
2382                                  * We need to try to allocate unmapped blocks
2383                                  * in the same page.  Otherwise we won't make
2384                                  * progress with the page in ext4_writepage
2385                                  */
2386                                 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2387                                         mpage_add_bh_to_extent(mpd, logical,
2388                                                                bh->b_state);
2389                                         if (mpd->io_done)
2390                                                 goto ret_extent_tail;
2391                                 } else if (buffer_dirty(bh) &&
2392                                            buffer_mapped(bh)) {
2393                                         /*
2394                                          * mapped dirty buffer. We need to
2395                                          * update the b_state because we look
2396                                          * at b_state in mpage_da_map_blocks.
2397                                          * We don't update b_size because if we
2398                                          * find an unmapped buffer_head later
2399                                          * we need to use the b_state flag of
2400                                          * that buffer_head.
2401                                          */
2402                                         if (mpd->b_size == 0)
2403                                                 mpd->b_state =
2404                                                         bh->b_state & BH_FLAGS;
2405                                 }
2406                                 logical++;
2407                         } while ((bh = bh->b_this_page) != head);
2408
2409                         if (nr_to_write > 0) {
2410                                 nr_to_write--;
2411                                 if (nr_to_write == 0 &&
2412                                     wbc->sync_mode == WB_SYNC_NONE)
2413                                         /*
2414                                          * We stop writing back only if we are
2415                                          * not doing integrity sync. In case of
2416                                          * integrity sync we have to keep going
2417                                          * because someone may be concurrently
2418                                          * dirtying pages, and we might have
2419                                          * synced a lot of newly appeared dirty
2420                                          * pages, but have not synced all of the
2421                                          * old dirty pages.
2422                                          */
2423                                         goto out;
2424                         }
2425                 }
2426                 pagevec_release(&pvec);
2427                 cond_resched();
2428         }
2429         return 0;
2430 ret_extent_tail:
2431         ret = MPAGE_DA_EXTENT_TAIL;
2432 out:
2433         pagevec_release(&pvec);
2434         cond_resched();
2435         return ret;
2436 }
2437
2438
2439 static int ext4_da_writepages(struct address_space *mapping,
2440                               struct writeback_control *wbc)
2441 {
2442         pgoff_t index;
2443         int range_whole = 0;
2444         handle_t *handle = NULL;
2445         struct mpage_da_data mpd;
2446         struct inode *inode = mapping->host;
2447         int pages_written = 0;
2448         unsigned int max_pages;
2449         int range_cyclic, cycled = 1, io_done = 0;
2450         int needed_blocks, ret = 0;
2451         long desired_nr_to_write, nr_to_writebump = 0;
2452         loff_t range_start = wbc->range_start;
2453         struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2454         pgoff_t done_index = 0;
2455         pgoff_t end;
2456         struct blk_plug plug;
2457
2458         trace_ext4_da_writepages(inode, wbc);
2459
2460         /*
2461          * No pages to write? This is mainly a kludge to avoid starting
2462          * a transaction for special inodes like journal inode on last iput()
2463          * because that could violate lock ordering on umount
2464          */
2465         if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2466                 return 0;
2467
2468         /*
2469          * If the filesystem has aborted, it is read-only, so return
2470          * right away instead of dumping stack traces later on that
2471          * will obscure the real source of the problem.  We test
2472          * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2473          * the latter could be true if the filesystem is mounted
2474          * read-only, and in that case, ext4_da_writepages should
2475          * *never* be called, so if that ever happens, we would want
2476          * the stack trace.
2477          */
2478         if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2479                 return -EROFS;
2480
2481         if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2482                 range_whole = 1;
2483
2484         range_cyclic = wbc->range_cyclic;
2485         if (wbc->range_cyclic) {
2486                 index = mapping->writeback_index;
2487                 if (index)
2488                         cycled = 0;
2489                 wbc->range_start = index << PAGE_CACHE_SHIFT;
2490                 wbc->range_end  = LLONG_MAX;
2491                 wbc->range_cyclic = 0;
2492                 end = -1;
2493         } else {
2494                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2495                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2496         }
2497
2498         /*
2499          * This works around two forms of stupidity.  The first is in
2500          * the writeback code, which caps the maximum number of pages
2501          * written to be 1024 pages.  This is wrong on multiple
2502          * levels; different architectues have a different page size,
2503          * which changes the maximum amount of data which gets
2504          * written.  Secondly, 4 megabytes is way too small.  XFS
2505          * forces this value to be 16 megabytes by multiplying
2506          * nr_to_write parameter by four, and then relies on its
2507          * allocator to allocate larger extents to make them
2508          * contiguous.  Unfortunately this brings us to the second
2509          * stupidity, which is that ext4's mballoc code only allocates
2510          * at most 2048 blocks.  So we force contiguous writes up to
2511          * the number of dirty blocks in the inode, or
2512          * sbi->max_writeback_mb_bump whichever is smaller.
2513          */
2514         max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2515         if (!range_cyclic && range_whole) {
2516                 if (wbc->nr_to_write == LONG_MAX)
2517                         desired_nr_to_write = wbc->nr_to_write;
2518                 else
2519                         desired_nr_to_write = wbc->nr_to_write * 8;
2520         } else
2521                 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2522                                                            max_pages);
2523         if (desired_nr_to_write > max_pages)
2524                 desired_nr_to_write = max_pages;
2525
2526         if (wbc->nr_to_write < desired_nr_to_write) {
2527                 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2528                 wbc->nr_to_write = desired_nr_to_write;
2529         }
2530
2531 retry:
2532         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2533                 tag_pages_for_writeback(mapping, index, end);
2534
2535         blk_start_plug(&plug);
2536         while (!ret && wbc->nr_to_write > 0) {
2537
2538                 /*
2539                  * we  insert one extent at a time. So we need
2540                  * credit needed for single extent allocation.
2541                  * journalled mode is currently not supported
2542                  * by delalloc
2543                  */
2544                 BUG_ON(ext4_should_journal_data(inode));
2545                 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2546
2547                 /* start a new transaction*/
2548                 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2549                                             needed_blocks);
2550                 if (IS_ERR(handle)) {
2551                         ret = PTR_ERR(handle);
2552                         ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2553                                "%ld pages, ino %lu; err %d", __func__,
2554                                 wbc->nr_to_write, inode->i_ino, ret);
2555                         blk_finish_plug(&plug);
2556                         goto out_writepages;
2557                 }
2558
2559                 /*
2560                  * Now call write_cache_pages_da() to find the next
2561                  * contiguous region of logical blocks that need
2562                  * blocks to be allocated by ext4 and submit them.
2563                  */
2564                 ret = write_cache_pages_da(handle, mapping,
2565                                            wbc, &mpd, &done_index);
2566                 /*
2567                  * If we have a contiguous extent of pages and we
2568                  * haven't done the I/O yet, map the blocks and submit
2569                  * them for I/O.
2570                  */
2571                 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2572                         mpage_da_map_and_submit(&mpd);
2573                         ret = MPAGE_DA_EXTENT_TAIL;
2574                 }
2575                 trace_ext4_da_write_pages(inode, &mpd);
2576                 wbc->nr_to_write -= mpd.pages_written;
2577
2578                 ext4_journal_stop(handle);
2579
2580                 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2581                         /* commit the transaction which would
2582                          * free blocks released in the transaction
2583                          * and try again
2584                          */
2585                         jbd2_journal_force_commit_nested(sbi->s_journal);
2586                         ret = 0;
2587                 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2588                         /*
2589                          * Got one extent now try with rest of the pages.
2590                          * If mpd.retval is set -EIO, journal is aborted.
2591                          * So we don't need to write any more.
2592                          */
2593                         pages_written += mpd.pages_written;
2594                         ret = mpd.retval;
2595                         io_done = 1;
2596                 } else if (wbc->nr_to_write)
2597                         /*
2598                          * There is no more writeout needed
2599                          * or we requested for a noblocking writeout
2600                          * and we found the device congested
2601                          */
2602                         break;
2603         }
2604         blk_finish_plug(&plug);
2605         if (!io_done && !cycled) {
2606                 cycled = 1;
2607                 index = 0;
2608                 wbc->range_start = index << PAGE_CACHE_SHIFT;
2609                 wbc->range_end  = mapping->writeback_index - 1;
2610                 goto retry;
2611         }
2612
2613         /* Update index */
2614         wbc->range_cyclic = range_cyclic;
2615         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2616                 /*
2617                  * set the writeback_index so that range_cyclic
2618                  * mode will write it back later
2619                  */
2620                 mapping->writeback_index = done_index;
2621
2622 out_writepages:
2623         wbc->nr_to_write -= nr_to_writebump;
2624         wbc->range_start = range_start;
2625         trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2626         return ret;
2627 }
2628
2629 static int ext4_nonda_switch(struct super_block *sb)
2630 {
2631         s64 free_clusters, dirty_clusters;
2632         struct ext4_sb_info *sbi = EXT4_SB(sb);
2633
2634         /*
2635          * switch to non delalloc mode if we are running low
2636          * on free block. The free block accounting via percpu
2637          * counters can get slightly wrong with percpu_counter_batch getting
2638          * accumulated on each CPU without updating global counters
2639          * Delalloc need an accurate free block accounting. So switch
2640          * to non delalloc when we are near to error range.
2641          */
2642         free_clusters =
2643                 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2644         dirty_clusters =
2645                 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2646         /*
2647          * Start pushing delalloc when 1/2 of free blocks are dirty.
2648          */
2649         if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2650                 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2651
2652         if (2 * free_clusters < 3 * dirty_clusters ||
2653             free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2654                 /*
2655                  * free block count is less than 150% of dirty blocks
2656                  * or free blocks is less than watermark
2657                  */
2658                 return 1;
2659         }
2660         return 0;
2661 }
2662
2663 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2664                                loff_t pos, unsigned len, unsigned flags,
2665                                struct page **pagep, void **fsdata)
2666 {
2667         int ret, retries = 0;
2668         struct page *page;
2669         pgoff_t index;
2670         struct inode *inode = mapping->host;
2671         handle_t *handle;
2672
2673         index = pos >> PAGE_CACHE_SHIFT;
2674
2675         if (ext4_nonda_switch(inode->i_sb)) {
2676                 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2677                 return ext4_write_begin(file, mapping, pos,
2678                                         len, flags, pagep, fsdata);
2679         }
2680         *fsdata = (void *)0;
2681         trace_ext4_da_write_begin(inode, pos, len, flags);
2682
2683         if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2684                 ret = ext4_da_write_inline_data_begin(mapping, inode,
2685                                                       pos, len, flags,
2686                                                       pagep, fsdata);
2687                 if (ret < 0)
2688                         return ret;
2689                 if (ret == 1)
2690                         return 0;
2691         }
2692
2693         /*
2694          * grab_cache_page_write_begin() can take a long time if the
2695          * system is thrashing due to memory pressure, or if the page
2696          * is being written back.  So grab it first before we start
2697          * the transaction handle.  This also allows us to allocate
2698          * the page (if needed) without using GFP_NOFS.
2699          */
2700 retry_grab:
2701         page = grab_cache_page_write_begin(mapping, index, flags);
2702         if (!page)
2703                 return -ENOMEM;
2704         unlock_page(page);
2705
2706         /*
2707          * With delayed allocation, we don't log the i_disksize update
2708          * if there is delayed block allocation. But we still need
2709          * to journalling the i_disksize update if writes to the end
2710          * of file which has an already mapped buffer.
2711          */
2712 retry_journal:
2713         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2714         if (IS_ERR(handle)) {
2715                 page_cache_release(page);
2716                 return PTR_ERR(handle);
2717         }
2718
2719         lock_page(page);
2720         if (page->mapping != mapping) {
2721                 /* The page got truncated from under us */
2722                 unlock_page(page);
2723                 page_cache_release(page);
2724                 ext4_journal_stop(handle);
2725                 goto retry_grab;
2726         }
2727         /* In case writeback began while the page was unlocked */
2728         wait_on_page_writeback(page);
2729
2730         ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2731         if (ret < 0) {
2732                 unlock_page(page);
2733                 ext4_journal_stop(handle);
2734                 /*
2735                  * block_write_begin may have instantiated a few blocks
2736                  * outside i_size.  Trim these off again. Don't need
2737                  * i_size_read because we hold i_mutex.
2738                  */
2739                 if (pos + len > inode->i_size)
2740                         ext4_truncate_failed_write(inode);
2741
2742                 if (ret == -ENOSPC &&
2743                     ext4_should_retry_alloc(inode->i_sb, &retries))
2744                         goto retry_journal;
2745
2746                 page_cache_release(page);
2747                 return ret;
2748         }
2749
2750         *pagep = page;
2751         return ret;
2752 }
2753
2754 /*
2755  * Check if we should update i_disksize
2756  * when write to the end of file but not require block allocation
2757  */
2758 static int ext4_da_should_update_i_disksize(struct page *page,
2759                                             unsigned long offset)
2760 {
2761         struct buffer_head *bh;
2762         struct inode *inode = page->mapping->host;
2763         unsigned int idx;
2764         int i;
2765
2766         bh = page_buffers(page);
2767         idx = offset >> inode->i_blkbits;
2768
2769         for (i = 0; i < idx; i++)
2770                 bh = bh->b_this_page;
2771
2772         if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2773                 return 0;
2774         return 1;
2775 }
2776
2777 static int ext4_da_write_end(struct file *file,
2778                              struct address_space *mapping,
2779                              loff_t pos, unsigned len, unsigned copied,
2780                              struct page *page, void *fsdata)
2781 {
2782         struct inode *inode = mapping->host;
2783         int ret = 0, ret2;
2784         handle_t *handle = ext4_journal_current_handle();
2785         loff_t new_i_size;
2786         unsigned long start, end;
2787         int write_mode = (int)(unsigned long)fsdata;
2788
2789         if (write_mode == FALL_BACK_TO_NONDELALLOC)
2790                 return ext4_write_end(file, mapping, pos,
2791                                       len, copied, page, fsdata);
2792
2793         trace_ext4_da_write_end(inode, pos, len, copied);
2794         start = pos & (PAGE_CACHE_SIZE - 1);
2795         end = start + copied - 1;
2796
2797         /*
2798          * generic_write_end() will run mark_inode_dirty() if i_size
2799          * changes.  So let's piggyback the i_disksize mark_inode_dirty
2800          * into that.
2801          */
2802         new_i_size = pos + copied;
2803         if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2804                 if (ext4_has_inline_data(inode) ||
2805                     ext4_da_should_update_i_disksize(page, end)) {
2806                         down_write(&EXT4_I(inode)->i_data_sem);
2807                         if (new_i_size > EXT4_I(inode)->i_disksize)
2808                                 EXT4_I(inode)->i_disksize = new_i_size;
2809                         up_write(&EXT4_I(inode)->i_data_sem);
2810                         /* We need to mark inode dirty even if
2811                          * new_i_size is less that inode->i_size
2812                          * bu greater than i_disksize.(hint delalloc)
2813                          */
2814                         ext4_mark_inode_dirty(handle, inode);
2815                 }
2816         }
2817
2818         if (write_mode != CONVERT_INLINE_DATA &&
2819             ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2820             ext4_has_inline_data(inode))
2821                 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2822                                                      page);
2823         else
2824                 ret2 = generic_write_end(file, mapping, pos, len, copied,
2825                                                         page, fsdata);
2826
2827         copied = ret2;
2828         if (ret2 < 0)
2829                 ret = ret2;
2830         ret2 = ext4_journal_stop(handle);
2831         if (!ret)
2832                 ret = ret2;
2833
2834         return ret ? ret : copied;
2835 }
2836
2837 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2838                                    unsigned int length)
2839 {
2840         /*
2841          * Drop reserved blocks
2842          */
2843         BUG_ON(!PageLocked(page));
2844         if (!page_has_buffers(page))
2845                 goto out;
2846
2847         ext4_da_page_release_reservation(page, offset, length);
2848
2849 out:
2850         ext4_invalidatepage(page, offset, length);
2851
2852         return;
2853 }
2854
2855 /*
2856  * Force all delayed allocation blocks to be allocated for a given inode.
2857  */
2858 int ext4_alloc_da_blocks(struct inode *inode)
2859 {
2860         trace_ext4_alloc_da_blocks(inode);
2861
2862         if (!EXT4_I(inode)->i_reserved_data_blocks &&
2863             !EXT4_I(inode)->i_reserved_meta_blocks)
2864                 return 0;
2865
2866         /*
2867          * We do something simple for now.  The filemap_flush() will
2868          * also start triggering a write of the data blocks, which is
2869          * not strictly speaking necessary (and for users of
2870          * laptop_mode, not even desirable).  However, to do otherwise
2871          * would require replicating code paths in:
2872          *
2873          * ext4_da_writepages() ->
2874          *    write_cache_pages() ---> (via passed in callback function)
2875          *        __mpage_da_writepage() -->
2876          *           mpage_add_bh_to_extent()
2877          *           mpage_da_map_blocks()
2878          *
2879          * The problem is that write_cache_pages(), located in
2880          * mm/page-writeback.c, marks pages clean in preparation for
2881          * doing I/O, which is not desirable if we're not planning on
2882          * doing I/O at all.
2883          *
2884          * We could call write_cache_pages(), and then redirty all of
2885          * the pages by calling redirty_page_for_writepage() but that
2886          * would be ugly in the extreme.  So instead we would need to
2887          * replicate parts of the code in the above functions,
2888          * simplifying them because we wouldn't actually intend to
2889          * write out the pages, but rather only collect contiguous
2890          * logical block extents, call the multi-block allocator, and
2891          * then update the buffer heads with the block allocations.
2892          *
2893          * For now, though, we'll cheat by calling filemap_flush(),
2894          * which will map the blocks, and start the I/O, but not
2895          * actually wait for the I/O to complete.
2896          */
2897         return filemap_flush(inode->i_mapping);
2898 }
2899
2900 /*
2901  * bmap() is special.  It gets used by applications such as lilo and by
2902  * the swapper to find the on-disk block of a specific piece of data.
2903  *
2904  * Naturally, this is dangerous if the block concerned is still in the
2905  * journal.  If somebody makes a swapfile on an ext4 data-journaling
2906  * filesystem and enables swap, then they may get a nasty shock when the
2907  * data getting swapped to that swapfile suddenly gets overwritten by
2908  * the original zero's written out previously to the journal and
2909  * awaiting writeback in the kernel's buffer cache.
2910  *
2911  * So, if we see any bmap calls here on a modified, data-journaled file,
2912  * take extra steps to flush any blocks which might be in the cache.
2913  */
2914 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2915 {
2916         struct inode *inode = mapping->host;
2917         journal_t *journal;
2918         int err;
2919
2920         /*
2921          * We can get here for an inline file via the FIBMAP ioctl
2922          */
2923         if (ext4_has_inline_data(inode))
2924                 return 0;
2925
2926         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2927                         test_opt(inode->i_sb, DELALLOC)) {
2928                 /*
2929                  * With delalloc we want to sync the file
2930                  * so that we can make sure we allocate
2931                  * blocks for file
2932                  */
2933                 filemap_write_and_wait(mapping);
2934         }
2935
2936         if (EXT4_JOURNAL(inode) &&
2937             ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2938                 /*
2939                  * This is a REALLY heavyweight approach, but the use of
2940                  * bmap on dirty files is expected to be extremely rare:
2941                  * only if we run lilo or swapon on a freshly made file
2942                  * do we expect this to happen.
2943                  *
2944                  * (bmap requires CAP_SYS_RAWIO so this does not
2945                  * represent an unprivileged user DOS attack --- we'd be
2946                  * in trouble if mortal users could trigger this path at
2947                  * will.)
2948                  *
2949                  * NB. EXT4_STATE_JDATA is not set on files other than
2950                  * regular files.  If somebody wants to bmap a directory
2951                  * or symlink and gets confused because the buffer
2952                  * hasn't yet been flushed to disk, they deserve
2953                  * everything they get.
2954                  */
2955
2956                 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2957                 journal = EXT4_JOURNAL(inode);
2958                 jbd2_journal_lock_updates(journal);
2959                 err = jbd2_journal_flush(journal);
2960                 jbd2_journal_unlock_updates(journal);
2961
2962                 if (err)
2963                         return 0;
2964         }
2965
2966         return generic_block_bmap(mapping, block, ext4_get_block);
2967 }
2968
2969 static int ext4_readpage(struct file *file, struct page *page)
2970 {
2971         int ret = -EAGAIN;
2972         struct inode *inode = page->mapping->host;
2973
2974         trace_ext4_readpage(page);
2975
2976         if (ext4_has_inline_data(inode))
2977                 ret = ext4_readpage_inline(inode, page);
2978
2979         if (ret == -EAGAIN)
2980                 return mpage_readpage(page, ext4_get_block);
2981
2982         return ret;
2983 }
2984
2985 static int
2986 ext4_readpages(struct file *file, struct address_space *mapping,
2987                 struct list_head *pages, unsigned nr_pages)
2988 {
2989         struct inode *inode = mapping->host;
2990
2991         /* If the file has inline data, no need to do readpages. */
2992         if (ext4_has_inline_data(inode))
2993                 return 0;
2994
2995         return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2996 }
2997
2998 static void ext4_invalidatepage(struct page *page, unsigned int offset,
2999                                 unsigned int length)
3000 {
3001         trace_ext4_invalidatepage(page, offset, length);
3002
3003         /* No journalling happens on data buffers when this function is used */
3004         WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3005
3006         block_invalidatepage(page, offset, length);
3007 }
3008
3009 static int __ext4_journalled_invalidatepage(struct page *page,
3010                                             unsigned int offset,
3011                                             unsigned int length)
3012 {
3013         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3014
3015         trace_ext4_journalled_invalidatepage(page, offset, length);
3016
3017         /*
3018          * If it's a full truncate we just forget about the pending dirtying
3019          */
3020         if (offset == 0 && length == PAGE_CACHE_SIZE)
3021                 ClearPageChecked(page);
3022
3023         return jbd2_journal_invalidatepage(journal, page, offset, length);
3024 }
3025
3026 /* Wrapper for aops... */
3027 static void ext4_journalled_invalidatepage(struct page *page,
3028                                            unsigned int offset,
3029                                            unsigned int length)
3030 {
3031         WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3032 }
3033
3034 static int ext4_releasepage(struct page *page, gfp_t wait)
3035 {
3036         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3037
3038         trace_ext4_releasepage(page);
3039
3040         /* Page has dirty journalled data -> cannot release */
3041         if (PageChecked(page))
3042                 return 0;
3043         if (journal)
3044                 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3045         else
3046                 return try_to_free_buffers(page);
3047 }
3048
3049 /*
3050  * ext4_get_block used when preparing for a DIO write or buffer write.
3051  * We allocate an uinitialized extent if blocks haven't been allocated.
3052  * The extent will be converted to initialized after the IO is complete.
3053  */
3054 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3055                    struct buffer_head *bh_result, int create)
3056 {
3057         ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3058                    inode->i_ino, create);
3059         return _ext4_get_block(inode, iblock, bh_result,
3060                                EXT4_GET_BLOCKS_IO_CREATE_EXT);
3061 }
3062
3063 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3064                    struct buffer_head *bh_result, int create)
3065 {
3066         ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3067                    inode->i_ino, create);
3068         return _ext4_get_block(inode, iblock, bh_result,
3069                                EXT4_GET_BLOCKS_NO_LOCK);
3070 }
3071
3072 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3073                             ssize_t size, void *private, int ret,
3074                             bool is_async)
3075 {
3076         struct inode *inode = file_inode(iocb->ki_filp);
3077         ext4_io_end_t *io_end = iocb->private;
3078
3079         /* if not async direct IO or dio with 0 bytes write, just return */
3080         if (!io_end || !size)
3081                 goto out;
3082
3083         ext_debug("ext4_end_io_dio(): io_end 0x%p "
3084                   "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3085                   iocb->private, io_end->inode->i_ino, iocb, offset,
3086                   size);
3087
3088         iocb->private = NULL;
3089
3090         /* if not aio dio with unwritten extents, just free io and return */
3091         if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3092                 ext4_free_io_end(io_end);
3093 out:
3094                 inode_dio_done(inode);
3095                 if (is_async)
3096                         aio_complete(iocb, ret, 0);
3097                 return;
3098         }
3099
3100         io_end->offset = offset;
3101         io_end->size = size;
3102         if (is_async) {
3103                 io_end->iocb = iocb;
3104                 io_end->result = ret;
3105         }
3106
3107         ext4_add_complete_io(io_end);
3108 }
3109
3110 /*
3111  * For ext4 extent files, ext4 will do direct-io write to holes,
3112  * preallocated extents, and those write extend the file, no need to
3113  * fall back to buffered IO.
3114  *
3115  * For holes, we fallocate those blocks, mark them as uninitialized
3116  * If those blocks were preallocated, we mark sure they are split, but
3117  * still keep the range to write as uninitialized.
3118  *
3119  * The unwritten extents will be converted to written when DIO is completed.
3120  * For async direct IO, since the IO may still pending when return, we
3121  * set up an end_io call back function, which will do the conversion
3122  * when async direct IO completed.
3123  *
3124  * If the O_DIRECT write will extend the file then add this inode to the
3125  * orphan list.  So recovery will truncate it back to the original size
3126  * if the machine crashes during the write.
3127  *
3128  */
3129 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3130                               const struct iovec *iov, loff_t offset,
3131                               unsigned long nr_segs)
3132 {
3133         struct file *file = iocb->ki_filp;
3134         struct inode *inode = file->f_mapping->host;
3135         ssize_t ret;
3136         size_t count = iov_length(iov, nr_segs);
3137         int overwrite = 0;
3138         get_block_t *get_block_func = NULL;
3139         int dio_flags = 0;
3140         loff_t final_size = offset + count;
3141
3142         /* Use the old path for reads and writes beyond i_size. */
3143         if (rw != WRITE || final_size > inode->i_size)
3144                 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3145
3146         BUG_ON(iocb->private == NULL);
3147
3148         /* If we do a overwrite dio, i_mutex locking can be released */
3149         overwrite = *((int *)iocb->private);
3150
3151         if (overwrite) {
3152                 atomic_inc(&inode->i_dio_count);
3153                 down_read(&EXT4_I(inode)->i_data_sem);
3154                 mutex_unlock(&inode->i_mutex);
3155         }
3156
3157         /*
3158          * We could direct write to holes and fallocate.
3159          *
3160          * Allocated blocks to fill the hole are marked as
3161          * uninitialized to prevent parallel buffered read to expose
3162          * the stale data before DIO complete the data IO.
3163          *
3164          * As to previously fallocated extents, ext4 get_block will
3165          * just simply mark the buffer mapped but still keep the
3166          * extents uninitialized.
3167          *
3168          * For non AIO case, we will convert those unwritten extents
3169          * to written after return back from blockdev_direct_IO.
3170          *
3171          * For async DIO, the conversion needs to be deferred when the
3172          * IO is completed. The ext4 end_io callback function will be
3173          * called to take care of the conversion work.  Here for async
3174          * case, we allocate an io_end structure to hook to the iocb.
3175          */
3176         iocb->private = NULL;
3177         ext4_inode_aio_set(inode, NULL);
3178         if (!is_sync_kiocb(iocb)) {
3179                 ext4_io_end_t *io_end = ext4_init_io_end(inode, GFP_NOFS);
3180                 if (!io_end) {
3181                         ret = -ENOMEM;
3182                         goto retake_lock;
3183                 }
3184                 io_end->flag |= EXT4_IO_END_DIRECT;
3185                 iocb->private = io_end;
3186                 /*
3187                  * we save the io structure for current async direct
3188                  * IO, so that later ext4_map_blocks() could flag the
3189                  * io structure whether there is a unwritten extents
3190                  * needs to be converted when IO is completed.
3191                  */
3192                 ext4_inode_aio_set(inode, io_end);
3193         }
3194
3195         if (overwrite) {
3196                 get_block_func = ext4_get_block_write_nolock;
3197         } else {
3198                 get_block_func = ext4_get_block_write;
3199                 dio_flags = DIO_LOCKING;
3200         }
3201         ret = __blockdev_direct_IO(rw, iocb, inode,
3202                                    inode->i_sb->s_bdev, iov,
3203                                    offset, nr_segs,
3204                                    get_block_func,
3205                                    ext4_end_io_dio,
3206                                    NULL,
3207                                    dio_flags);
3208
3209         if (iocb->private)
3210                 ext4_inode_aio_set(inode, NULL);
3211         /*
3212          * The io_end structure takes a reference to the inode, that
3213          * structure needs to be destroyed and the reference to the
3214          * inode need to be dropped, when IO is complete, even with 0
3215          * byte write, or failed.
3216          *
3217          * In the successful AIO DIO case, the io_end structure will
3218          * be destroyed and the reference to the inode will be dropped
3219          * after the end_io call back function is called.
3220          *
3221          * In the case there is 0 byte write, or error case, since VFS
3222          * direct IO won't invoke the end_io call back function, we
3223          * need to free the end_io structure here.
3224          */
3225         if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3226                 ext4_free_io_end(iocb->private);
3227                 iocb->private = NULL;
3228         } else if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3229                                                 EXT4_STATE_DIO_UNWRITTEN)) {
3230                 int err;
3231                 /*
3232                  * for non AIO case, since the IO is already
3233                  * completed, we could do the conversion right here
3234                  */
3235                 err = ext4_convert_unwritten_extents(inode,
3236                                                      offset, ret);
3237                 if (err < 0)
3238                         ret = err;
3239                 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3240         }
3241
3242 retake_lock:
3243         /* take i_mutex locking again if we do a ovewrite dio */
3244         if (overwrite) {
3245                 inode_dio_done(inode);
3246                 up_read(&EXT4_I(inode)->i_data_sem);
3247                 mutex_lock(&inode->i_mutex);
3248         }
3249
3250         return ret;
3251 }
3252
3253 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3254                               const struct iovec *iov, loff_t offset,
3255                               unsigned long nr_segs)
3256 {
3257         struct file *file = iocb->ki_filp;
3258         struct inode *inode = file->f_mapping->host;
3259         ssize_t ret;
3260
3261         /*
3262          * If we are doing data journalling we don't support O_DIRECT
3263          */
3264         if (ext4_should_journal_data(inode))
3265                 return 0;
3266
3267         /* Let buffer I/O handle the inline data case. */
3268         if (ext4_has_inline_data(inode))
3269                 return 0;
3270
3271         trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3272         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3273                 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3274         else
3275                 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3276         trace_ext4_direct_IO_exit(inode, offset,
3277                                 iov_length(iov, nr_segs), rw, ret);
3278         return ret;
3279 }
3280
3281 /*
3282  * Pages can be marked dirty completely asynchronously from ext4's journalling
3283  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3284  * much here because ->set_page_dirty is called under VFS locks.  The page is
3285  * not necessarily locked.
3286  *
3287  * We cannot just dirty the page and leave attached buffers clean, because the
3288  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3289  * or jbddirty because all the journalling code will explode.
3290  *
3291  * So what we do is to mark the page "pending dirty" and next time writepage
3292  * is called, propagate that into the buffers appropriately.
3293  */
3294 static int ext4_journalled_set_page_dirty(struct page *page)
3295 {
3296         SetPageChecked(page);
3297         return __set_page_dirty_nobuffers(page);
3298 }
3299
3300 static const struct address_space_operations ext4_aops = {
3301         .readpage               = ext4_readpage,
3302         .readpages              = ext4_readpages,
3303         .writepage              = ext4_writepage,
3304         .write_begin            = ext4_write_begin,
3305         .write_end              = ext4_write_end,
3306         .bmap                   = ext4_bmap,
3307         .invalidatepage         = ext4_invalidatepage,
3308         .releasepage            = ext4_releasepage,
3309         .direct_IO              = ext4_direct_IO,
3310         .migratepage            = buffer_migrate_page,
3311         .is_partially_uptodate  = block_is_partially_uptodate,
3312         .error_remove_page      = generic_error_remove_page,
3313 };
3314
3315 static const struct address_space_operations ext4_journalled_aops = {
3316         .readpage               = ext4_readpage,
3317         .readpages              = ext4_readpages,
3318         .writepage              = ext4_writepage,
3319         .write_begin            = ext4_write_begin,
3320         .write_end              = ext4_journalled_write_end,
3321         .set_page_dirty         = ext4_journalled_set_page_dirty,
3322         .bmap                   = ext4_bmap,
3323         .invalidatepage         = ext4_journalled_invalidatepage,
3324         .releasepage            = ext4_releasepage,
3325         .direct_IO              = ext4_direct_IO,
3326         .is_partially_uptodate  = block_is_partially_uptodate,
3327         .error_remove_page      = generic_error_remove_page,
3328 };
3329
3330 static const struct address_space_operations ext4_da_aops = {
3331         .readpage               = ext4_readpage,
3332         .readpages              = ext4_readpages,
3333         .writepage              = ext4_writepage,
3334         .writepages             = ext4_da_writepages,
3335         .write_begin            = ext4_da_write_begin,
3336         .write_end              = ext4_da_write_end,
3337         .bmap                   = ext4_bmap,
3338         .invalidatepage         = ext4_da_invalidatepage,
3339         .releasepage            = ext4_releasepage,
3340         .direct_IO              = ext4_direct_IO,
3341         .migratepage            = buffer_migrate_page,
3342         .is_partially_uptodate  = block_is_partially_uptodate,
3343         .error_remove_page      = generic_error_remove_page,
3344 };
3345
3346 void ext4_set_aops(struct inode *inode)
3347 {
3348         switch (ext4_inode_journal_mode(inode)) {
3349         case EXT4_INODE_ORDERED_DATA_MODE:
3350                 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3351                 break;
3352         case EXT4_INODE_WRITEBACK_DATA_MODE:
3353                 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3354                 break;
3355         case EXT4_INODE_JOURNAL_DATA_MODE:
3356                 inode->i_mapping->a_ops = &ext4_journalled_aops;
3357                 return;
3358         default:
3359                 BUG();
3360         }
3361         if (test_opt(inode->i_sb, DELALLOC))
3362                 inode->i_mapping->a_ops = &ext4_da_aops;
3363         else
3364                 inode->i_mapping->a_ops = &ext4_aops;
3365 }
3366
3367 /*
3368  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3369  * up to the end of the block which corresponds to `from'.
3370  * This required during truncate. We need to physically zero the tail end
3371  * of that block so it doesn't yield old data if the file is later grown.
3372  */
3373 int ext4_block_truncate_page(handle_t *handle,
3374                 struct address_space *mapping, loff_t from)
3375 {
3376         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3377         unsigned length;
3378         unsigned blocksize;
3379         struct inode *inode = mapping->host;
3380
3381         blocksize = inode->i_sb->s_blocksize;
3382         length = blocksize - (offset & (blocksize - 1));
3383
3384         return ext4_block_zero_page_range(handle, mapping, from, length);
3385 }
3386
3387 /*
3388  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3389  * starting from file offset 'from'.  The range to be zero'd must
3390  * be contained with in one block.  If the specified range exceeds
3391  * the end of the block it will be shortened to end of the block
3392  * that cooresponds to 'from'
3393  */
3394 int ext4_block_zero_page_range(handle_t *handle,
3395                 struct address_space *mapping, loff_t from, loff_t length)
3396 {
3397         ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3398         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3399         unsigned blocksize, max, pos;
3400         ext4_lblk_t iblock;
3401         struct inode *inode = mapping->host;
3402         struct buffer_head *bh;
3403         struct page *page;
3404         int err = 0;
3405
3406         page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3407                                    mapping_gfp_mask(mapping) & ~__GFP_FS);
3408         if (!page)
3409                 return -ENOMEM;
3410
3411         blocksize = inode->i_sb->s_blocksize;
3412         max = blocksize - (offset & (blocksize - 1));
3413
3414         /*
3415          * correct length if it does not fall between
3416          * 'from' and the end of the block
3417          */
3418         if (length > max || length < 0)
3419                 length = max;
3420
3421         iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3422
3423         if (!page_has_buffers(page))
3424                 create_empty_buffers(page, blocksize, 0);
3425
3426         /* Find the buffer that contains "offset" */
3427         bh = page_buffers(page);
3428         pos = blocksize;
3429         while (offset >= pos) {
3430                 bh = bh->b_this_page;
3431                 iblock++;
3432                 pos += blocksize;
3433         }
3434
3435         err = 0;
3436         if (buffer_freed(bh)) {
3437                 BUFFER_TRACE(bh, "freed: skip");
3438                 goto unlock;
3439         }
3440
3441         if (!buffer_mapped(bh)) {
3442                 BUFFER_TRACE(bh, "unmapped");
3443                 ext4_get_block(inode, iblock, bh, 0);
3444                 /* unmapped? It's a hole - nothing to do */
3445                 if (!buffer_mapped(bh)) {
3446                         BUFFER_TRACE(bh, "still unmapped");
3447                         goto unlock;
3448                 }
3449         }
3450
3451         /* Ok, it's mapped. Make sure it's up-to-date */
3452         if (PageUptodate(page))
3453                 set_buffer_uptodate(bh);
3454
3455         if (!buffer_uptodate(bh)) {
3456                 err = -EIO;
3457                 ll_rw_block(READ, 1, &bh);
3458                 wait_on_buffer(bh);
3459                 /* Uhhuh. Read error. Complain and punt. */
3460                 if (!buffer_uptodate(bh))
3461                         goto unlock;
3462         }
3463
3464         if (ext4_should_journal_data(inode)) {
3465                 BUFFER_TRACE(bh, "get write access");
3466                 err = ext4_journal_get_write_access(handle, bh);
3467                 if (err)
3468                         goto unlock;
3469         }
3470
3471         zero_user(page, offset, length);
3472
3473         BUFFER_TRACE(bh, "zeroed end of block");
3474
3475         err = 0;
3476         if (ext4_should_journal_data(inode)) {
3477                 err = ext4_handle_dirty_metadata(handle, inode, bh);
3478         } else {
3479                 mark_buffer_dirty(bh);
3480                 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3481                         err = ext4_jbd2_file_inode(handle, inode);
3482         }
3483
3484 unlock:
3485         unlock_page(page);
3486         page_cache_release(page);
3487         return err;
3488 }
3489
3490 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3491                              loff_t lstart, loff_t length)
3492 {
3493         struct super_block *sb = inode->i_sb;
3494         struct address_space *mapping = inode->i_mapping;
3495         unsigned partial = lstart & (sb->s_blocksize - 1);
3496         ext4_fsblk_t start, end;
3497         loff_t byte_end = (lstart + length - 1);
3498         int err = 0;
3499
3500         start = lstart >> sb->s_blocksize_bits;
3501         end = byte_end >> sb->s_blocksize_bits;
3502
3503         /* Handle partial zero within the single block */
3504         if (start == end) {
3505                 err = ext4_block_zero_page_range(handle, mapping,
3506                                                  lstart, length);
3507                 return err;
3508         }
3509         /* Handle partial zero out on the start of the range */
3510         if (partial) {
3511                 err = ext4_block_zero_page_range(handle, mapping,
3512                                                  lstart, sb->s_blocksize);
3513                 if (err)
3514                         return err;
3515         }
3516         /* Handle partial zero out on the end of the range */
3517         partial = byte_end & (sb->s_blocksize - 1);
3518         if (partial != sb->s_blocksize - 1)
3519                 err = ext4_block_zero_page_range(handle, mapping,
3520                                                  byte_end - partial,
3521                                                  partial + 1);
3522         return err;
3523 }
3524
3525 int ext4_can_truncate(struct inode *inode)
3526 {
3527         if (S_ISREG(inode->i_mode))
3528                 return 1;
3529         if (S_ISDIR(inode->i_mode))
3530                 return 1;
3531         if (S_ISLNK(inode->i_mode))
3532                 return !ext4_inode_is_fast_symlink(inode);
3533         return 0;
3534 }
3535
3536 /*
3537  * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3538  * associated with the given offset and length
3539  *
3540  * @inode:  File inode
3541  * @offset: The offset where the hole will begin
3542  * @len:    The length of the hole
3543  *
3544  * Returns: 0 on success or negative on failure
3545  */
3546
3547 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3548 {
3549         struct inode *inode = file_inode(file);
3550         struct super_block *sb = inode->i_sb;
3551         ext4_lblk_t first_block, stop_block;
3552         struct address_space *mapping = inode->i_mapping;
3553         loff_t first_block_offset, last_block_offset;
3554         handle_t *handle;
3555         unsigned int credits;
3556         int ret = 0;
3557
3558         if (!S_ISREG(inode->i_mode))
3559                 return -EOPNOTSUPP;
3560
3561         if (EXT4_SB(sb)->s_cluster_ratio > 1) {
3562                 /* TODO: Add support for bigalloc file systems */
3563                 return -EOPNOTSUPP;
3564         }
3565
3566         trace_ext4_punch_hole(inode, offset, length);
3567
3568         /*
3569          * Write out all dirty pages to avoid race conditions
3570          * Then release them.
3571          */
3572         if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3573                 ret = filemap_write_and_wait_range(mapping, offset,
3574                                                    offset + length - 1);
3575                 if (ret)
3576                         return ret;
3577         }
3578
3579         mutex_lock(&inode->i_mutex);
3580         /* It's not possible punch hole on append only file */
3581         if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
3582                 ret = -EPERM;
3583                 goto out_mutex;
3584         }
3585         if (IS_SWAPFILE(inode)) {
3586                 ret = -ETXTBSY;
3587                 goto out_mutex;
3588         }
3589
3590         /* No need to punch hole beyond i_size */
3591         if (offset >= inode->i_size)
3592                 goto out_mutex;
3593
3594         /*
3595          * If the hole extends beyond i_size, set the hole
3596          * to end after the page that contains i_size
3597          */
3598         if (offset + length > inode->i_size) {
3599                 length = inode->i_size +
3600                    PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3601                    offset;
3602         }
3603
3604         first_block_offset = round_up(offset, sb->s_blocksize);
3605         last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3606
3607         /* Now release the pages and zero block aligned part of pages*/
3608         if (last_block_offset > first_block_offset)
3609                 truncate_pagecache_range(inode, first_block_offset,
3610                                          last_block_offset);
3611
3612         /* Wait all existing dio workers, newcomers will block on i_mutex */
3613         ext4_inode_block_unlocked_dio(inode);
3614         ret = ext4_flush_unwritten_io(inode);
3615         if (ret)
3616                 goto out_dio;
3617         inode_dio_wait(inode);
3618
3619         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3620                 credits = ext4_writepage_trans_blocks(inode);
3621         else
3622                 credits = ext4_blocks_for_truncate(inode);
3623         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3624         if (IS_ERR(handle)) {
3625                 ret = PTR_ERR(handle);
3626                 ext4_std_error(sb, ret);
3627                 goto out_dio;
3628         }
3629
3630         ret = ext4_zero_partial_blocks(handle, inode, offset,
3631                                        length);
3632         if (ret)
3633                 goto out_stop;
3634
3635         first_block = (offset + sb->s_blocksize - 1) >>
3636                 EXT4_BLOCK_SIZE_BITS(sb);
3637         stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3638
3639         /* If there are no blocks to remove, return now */
3640         if (first_block >= stop_block)
3641                 goto out_stop;
3642
3643         down_write(&EXT4_I(inode)->i_data_sem);
3644         ext4_discard_preallocations(inode);
3645
3646         ret = ext4_es_remove_extent(inode, first_block,
3647                                     stop_block - first_block);
3648         if (ret) {
3649                 up_write(&EXT4_I(inode)->i_data_sem);
3650                 goto out_stop;
3651         }
3652
3653         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3654                 ret = ext4_ext_remove_space(inode, first_block,
3655                                             stop_block - 1);
3656         else
3657                 ret = ext4_free_hole_blocks(handle, inode, first_block,
3658                                             stop_block);
3659
3660         ext4_discard_preallocations(inode);
3661         up_write(&EXT4_I(inode)->i_data_sem);
3662         if (IS_SYNC(inode))
3663                 ext4_handle_sync(handle);
3664         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3665         ext4_mark_inode_dirty(handle, inode);
3666 out_stop:
3667         ext4_journal_stop(handle);
3668 out_dio:
3669         ext4_inode_resume_unlocked_dio(inode);
3670 out_mutex:
3671         mutex_unlock(&inode->i_mutex);
3672         return ret;
3673 }
3674
3675 /*
3676  * ext4_truncate()
3677  *
3678  * We block out ext4_get_block() block instantiations across the entire
3679  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3680  * simultaneously on behalf of the same inode.
3681  *
3682  * As we work through the truncate and commit bits of it to the journal there
3683  * is one core, guiding principle: the file's tree must always be consistent on
3684  * disk.  We must be able to restart the truncate after a crash.
3685  *
3686  * The file's tree may be transiently inconsistent in memory (although it
3687  * probably isn't), but whenever we close off and commit a journal transaction,
3688  * the contents of (the filesystem + the journal) must be consistent and
3689  * restartable.  It's pretty simple, really: bottom up, right to left (although
3690  * left-to-right works OK too).
3691  *
3692  * Note that at recovery time, journal replay occurs *before* the restart of
3693  * truncate against the orphan inode list.
3694  *
3695  * The committed inode has the new, desired i_size (which is the same as
3696  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
3697  * that this inode's truncate did not complete and it will again call
3698  * ext4_truncate() to have another go.  So there will be instantiated blocks
3699  * to the right of the truncation point in a crashed ext4 filesystem.  But
3700  * that's fine - as long as they are linked from the inode, the post-crash
3701  * ext4_truncate() run will find them and release them.
3702  */
3703 void ext4_truncate(struct inode *inode)
3704 {
3705         struct ext4_inode_info *ei = EXT4_I(inode);
3706         unsigned int credits;
3707         handle_t *handle;
3708         struct address_space *mapping = inode->i_mapping;
3709
3710         /*
3711          * There is a possibility that we're either freeing the inode
3712          * or it completely new indode. In those cases we might not
3713          * have i_mutex locked because it's not necessary.
3714          */
3715         if (!(inode->i_state & (I_NEW|I_FREEING)))
3716                 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3717         trace_ext4_truncate_enter(inode);
3718
3719         if (!ext4_can_truncate(inode))
3720                 return;
3721
3722         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3723
3724         if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3725                 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3726
3727         if (ext4_has_inline_data(inode)) {
3728                 int has_inline = 1;
3729
3730                 ext4_inline_data_truncate(inode, &has_inline);
3731                 if (has_inline)
3732                         return;
3733         }
3734
3735         /*
3736          * finish any pending end_io work so we won't run the risk of
3737          * converting any truncated blocks to initialized later
3738          */
3739         ext4_flush_unwritten_io(inode);
3740
3741         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3742                 credits = ext4_writepage_trans_blocks(inode);
3743         else
3744                 credits = ext4_blocks_for_truncate(inode);
3745
3746         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3747         if (IS_ERR(handle)) {
3748                 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3749                 return;
3750         }
3751
3752         if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3753                 ext4_block_truncate_page(handle, mapping, inode->i_size);
3754
3755         /*
3756          * We add the inode to the orphan list, so that if this
3757          * truncate spans multiple transactions, and we crash, we will
3758          * resume the truncate when the filesystem recovers.  It also
3759          * marks the inode dirty, to catch the new size.
3760          *
3761          * Implication: the file must always be in a sane, consistent
3762          * truncatable state while each transaction commits.
3763          */
3764         if (ext4_orphan_add(handle, inode))
3765                 goto out_stop;
3766
3767         down_write(&EXT4_I(inode)->i_data_sem);
3768
3769         ext4_discard_preallocations(inode);
3770
3771         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3772                 ext4_ext_truncate(handle, inode);
3773         else
3774                 ext4_ind_truncate(handle, inode);
3775
3776         up_write(&ei->i_data_sem);
3777
3778         if (IS_SYNC(inode))
3779                 ext4_handle_sync(handle);
3780
3781 out_stop:
3782         /*
3783          * If this was a simple ftruncate() and the file will remain alive,
3784          * then we need to clear up the orphan record which we created above.
3785          * However, if this was a real unlink then we were called by
3786          * ext4_delete_inode(), and we allow that function to clean up the
3787          * orphan info for us.
3788          */
3789         if (inode->i_nlink)
3790                 ext4_orphan_del(handle, inode);
3791
3792         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3793         ext4_mark_inode_dirty(handle, inode);
3794         ext4_journal_stop(handle);
3795
3796         trace_ext4_truncate_exit(inode);
3797 }
3798
3799 /*
3800  * ext4_get_inode_loc returns with an extra refcount against the inode's
3801  * underlying buffer_head on success. If 'in_mem' is true, we have all
3802  * data in memory that is needed to recreate the on-disk version of this
3803  * inode.
3804  */
3805 static int __ext4_get_inode_loc(struct inode *inode,
3806                                 struct ext4_iloc *iloc, int in_mem)
3807 {
3808         struct ext4_group_desc  *gdp;
3809         struct buffer_head      *bh;
3810         struct super_block      *sb = inode->i_sb;
3811         ext4_fsblk_t            block;
3812         int                     inodes_per_block, inode_offset;
3813
3814         iloc->bh = NULL;
3815         if (!ext4_valid_inum(sb, inode->i_ino))
3816                 return -EIO;
3817
3818         iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3819         gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3820         if (!gdp)
3821                 return -EIO;
3822
3823         /*
3824          * Figure out the offset within the block group inode table
3825          */
3826         inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3827         inode_offset = ((inode->i_ino - 1) %
3828                         EXT4_INODES_PER_GROUP(sb));
3829         block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3830         iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3831
3832         bh = sb_getblk(sb, block);
3833         if (unlikely(!bh))
3834                 return -ENOMEM;
3835         if (!buffer_uptodate(bh)) {
3836                 lock_buffer(bh);
3837
3838                 /*
3839                  * If the buffer has the write error flag, we have failed
3840                  * to write out another inode in the same block.  In this
3841                  * case, we don't have to read the block because we may
3842                  * read the old inode data successfully.
3843                  */
3844                 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3845                         set_buffer_uptodate(bh);
3846
3847                 if (buffer_uptodate(bh)) {
3848                         /* someone brought it uptodate while we waited */
3849                         unlock_buffer(bh);
3850                         goto has_buffer;
3851                 }
3852
3853                 /*
3854                  * If we have all information of the inode in memory and this
3855                  * is the only valid inode in the block, we need not read the
3856                  * block.
3857                  */
3858                 if (in_mem) {
3859                         struct buffer_head *bitmap_bh;
3860                         int i, start;
3861
3862                         start = inode_offset & ~(inodes_per_block - 1);
3863
3864                         /* Is the inode bitmap in cache? */
3865                         bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3866                         if (unlikely(!bitmap_bh))
3867                                 goto make_io;
3868
3869                         /*
3870                          * If the inode bitmap isn't in cache then the
3871                          * optimisation may end up performing two reads instead
3872                          * of one, so skip it.
3873                          */
3874                         if (!buffer_uptodate(bitmap_bh)) {
3875                                 brelse(bitmap_bh);
3876                                 goto make_io;
3877                         }
3878                         for (i = start; i < start + inodes_per_block; i++) {
3879                                 if (i == inode_offset)
3880                                         continue;
3881                                 if (ext4_test_bit(i, bitmap_bh->b_data))
3882                                         break;
3883                         }
3884                         brelse(bitmap_bh);
3885                         if (i == start + inodes_per_block) {
3886                                 /* all other inodes are free, so skip I/O */
3887                                 memset(bh->b_data, 0, bh->b_size);
3888                                 set_buffer_uptodate(bh);
3889                                 unlock_buffer(bh);
3890                                 goto has_buffer;
3891                         }
3892                 }
3893
3894 make_io:
3895                 /*
3896                  * If we need to do any I/O, try to pre-readahead extra
3897                  * blocks from the inode table.
3898                  */
3899                 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3900                         ext4_fsblk_t b, end, table;
3901                         unsigned num;
3902                         __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3903
3904                         table = ext4_inode_table(sb, gdp);
3905                         /* s_inode_readahead_blks is always a power of 2 */
3906                         b = block & ~((ext4_fsblk_t) ra_blks - 1);
3907                         if (table > b)
3908                                 b = table;
3909                         end = b + ra_blks;
3910                         num = EXT4_INODES_PER_GROUP(sb);
3911                         if (ext4_has_group_desc_csum(sb))
3912                                 num -= ext4_itable_unused_count(sb, gdp);
3913                         table += num / inodes_per_block;
3914                         if (end > table)
3915                                 end = table;
3916                         while (b <= end)
3917                                 sb_breadahead(sb, b++);
3918                 }
3919
3920                 /*
3921                  * There are other valid inodes in the buffer, this inode
3922                  * has in-inode xattrs, or we don't have this inode in memory.
3923                  * Read the block from disk.
3924                  */
3925                 trace_ext4_load_inode(inode);
3926                 get_bh(bh);
3927                 bh->b_end_io = end_buffer_read_sync;
3928                 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3929                 wait_on_buffer(bh);
3930                 if (!buffer_uptodate(bh)) {
3931                         EXT4_ERROR_INODE_BLOCK(inode, block,
3932                                                "unable to read itable block");
3933                         brelse(bh);
3934                         return -EIO;
3935                 }
3936         }
3937 has_buffer:
3938         iloc->bh = bh;
3939         return 0;
3940 }
3941
3942 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3943 {
3944         /* We have all inode data except xattrs in memory here. */
3945         return __ext4_get_inode_loc(inode, iloc,
3946                 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3947 }
3948
3949 void ext4_set_inode_flags(struct inode *inode)
3950 {
3951         unsigned int flags = EXT4_I(inode)->i_flags;
3952
3953         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3954         if (flags & EXT4_SYNC_FL)
3955                 inode->i_flags |= S_SYNC;
3956         if (flags & EXT4_APPEND_FL)
3957                 inode->i_flags |= S_APPEND;
3958         if (flags & EXT4_IMMUTABLE_FL)
3959                 inode->i_flags |= S_IMMUTABLE;
3960         if (flags & EXT4_NOATIME_FL)
3961                 inode->i_flags |= S_NOATIME;
3962         if (flags & EXT4_DIRSYNC_FL)
3963                 inode->i_flags |= S_DIRSYNC;
3964 }
3965
3966 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3967 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3968 {
3969         unsigned int vfs_fl;
3970         unsigned long old_fl, new_fl;
3971
3972         do {
3973                 vfs_fl = ei->vfs_inode.i_flags;
3974                 old_fl = ei->i_flags;
3975                 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3976                                 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3977                                 EXT4_DIRSYNC_FL);
3978                 if (vfs_fl & S_SYNC)
3979                         new_fl |= EXT4_SYNC_FL;
3980                 if (vfs_fl & S_APPEND)
3981                         new_fl |= EXT4_APPEND_FL;
3982                 if (vfs_fl & S_IMMUTABLE)
3983                         new_fl |= EXT4_IMMUTABLE_FL;
3984                 if (vfs_fl & S_NOATIME)
3985                         new_fl |= EXT4_NOATIME_FL;
3986                 if (vfs_fl & S_DIRSYNC)
3987                         new_fl |= EXT4_DIRSYNC_FL;
3988         } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3989 }
3990
3991 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3992                                   struct ext4_inode_info *ei)
3993 {
3994         blkcnt_t i_blocks ;
3995         struct inode *inode = &(ei->vfs_inode);
3996         struct super_block *sb = inode->i_sb;
3997
3998         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3999                                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4000                 /* we are using combined 48 bit field */
4001                 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4002                                         le32_to_cpu(raw_inode->i_blocks_lo);
4003                 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4004                         /* i_blocks represent file system block size */
4005                         return i_blocks  << (inode->i_blkbits - 9);
4006                 } else {
4007                         return i_blocks;
4008                 }
4009         } else {
4010                 return le32_to_cpu(raw_inode->i_blocks_lo);
4011         }
4012 }
4013
4014 static inline void ext4_iget_extra_inode(struct inode *inode,
4015                                          struct ext4_inode *raw_inode,
4016                                          struct ext4_inode_info *ei)
4017 {
4018         __le32 *magic = (void *)raw_inode +
4019                         EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4020         if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4021                 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4022                 ext4_find_inline_data_nolock(inode);
4023         } else
4024                 EXT4_I(inode)->i_inline_off = 0;
4025 }
4026
4027 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4028 {
4029         struct ext4_iloc iloc;
4030         struct ext4_inode *raw_inode;
4031         struct ext4_inode_info *ei;
4032         struct inode *inode;
4033         journal_t *journal = EXT4_SB(sb)->s_journal;
4034         long ret;
4035         int block;
4036         uid_t i_uid;
4037         gid_t i_gid;
4038
4039         inode = iget_locked(sb, ino);
4040         if (!inode)
4041                 return ERR_PTR(-ENOMEM);
4042         if (!(inode->i_state & I_NEW))
4043                 return inode;
4044
4045         ei = EXT4_I(inode);
4046         iloc.bh = NULL;
4047
4048         ret = __ext4_get_inode_loc(inode, &iloc, 0);
4049         if (ret < 0)
4050                 goto bad_inode;
4051         raw_inode = ext4_raw_inode(&iloc);
4052
4053         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4054                 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4055                 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4056                     EXT4_INODE_SIZE(inode->i_sb)) {
4057                         EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4058                                 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4059                                 EXT4_INODE_SIZE(inode->i_sb));
4060                         ret = -EIO;
4061                         goto bad_inode;
4062                 }
4063         } else
4064                 ei->i_extra_isize = 0;
4065
4066         /* Precompute checksum seed for inode metadata */
4067         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4068                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
4069                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4070                 __u32 csum;
4071                 __le32 inum = cpu_to_le32(inode->i_ino);
4072                 __le32 gen = raw_inode->i_generation;
4073                 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4074                                    sizeof(inum));
4075                 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4076                                               sizeof(gen));
4077         }
4078
4079         if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4080                 EXT4_ERROR_INODE(inode, "checksum invalid");
4081                 ret = -EIO;
4082                 goto bad_inode;
4083         }
4084
4085         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4086         i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4087         i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4088         if (!(test_opt(inode->i_sb, NO_UID32))) {
4089                 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4090                 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4091         }
4092         i_uid_write(inode, i_uid);
4093         i_gid_write(inode, i_gid);
4094         set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4095
4096         ext4_clear_state_flags(ei);     /* Only relevant on 32-bit archs */
4097         ei->i_inline_off = 0;
4098         ei->i_dir_start_lookup = 0;
4099         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4100         /* We now have enough fields to check if the inode was active or not.
4101          * This is needed because nfsd might try to access dead inodes
4102          * the test is that same one that e2fsck uses
4103          * NeilBrown 1999oct15
4104          */
4105         if (inode->i_nlink == 0) {
4106                 if ((inode->i_mode == 0 ||
4107                      !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4108                     ino != EXT4_BOOT_LOADER_INO) {
4109                         /* this inode is deleted */
4110                         ret = -ESTALE;
4111                         goto bad_inode;
4112                 }
4113                 /* The only unlinked inodes we let through here have
4114                  * valid i_mode and are being read by the orphan
4115                  * recovery code: that's fine, we're about to complete
4116                  * the process of deleting those.
4117                  * OR it is the EXT4_BOOT_LOADER_INO which is
4118                  * not initialized on a new filesystem. */
4119         }
4120         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4121         inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4122         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4123         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4124                 ei->i_file_acl |=
4125                         ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4126         inode->i_size = ext4_isize(raw_inode);
4127         ei->i_disksize = inode->i_size;
4128 #ifdef CONFIG_QUOTA
4129         ei->i_reserved_quota = 0;
4130 #endif
4131         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4132         ei->i_block_group = iloc.block_group;
4133         ei->i_last_alloc_group = ~0;
4134         /*
4135          * NOTE! The in-memory inode i_data array is in little-endian order
4136          * even on big-endian machines: we do NOT byteswap the block numbers!
4137          */
4138         for (block = 0; block < EXT4_N_BLOCKS; block++)
4139                 ei->i_data[block] = raw_inode->i_block[block];
4140         INIT_LIST_HEAD(&ei->i_orphan);
4141
4142         /*
4143          * Set transaction id's of transactions that have to be committed
4144          * to finish f[data]sync. We set them to currently running transaction
4145          * as we cannot be sure that the inode or some of its metadata isn't
4146          * part of the transaction - the inode could have been reclaimed and
4147          * now it is reread from disk.
4148          */
4149         if (journal) {
4150                 transaction_t *transaction;
4151                 tid_t tid;
4152
4153                 read_lock(&journal->j_state_lock);
4154                 if (journal->j_running_transaction)
4155                         transaction = journal->j_running_transaction;
4156                 else
4157                         transaction = journal->j_committing_transaction;
4158                 if (transaction)
4159                         tid = transaction->t_tid;
4160                 else
4161                         tid = journal->j_commit_sequence;
4162                 read_unlock(&journal->j_state_lock);
4163                 ei->i_sync_tid = tid;
4164                 ei->i_datasync_tid = tid;
4165         }
4166
4167         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4168                 if (ei->i_extra_isize == 0) {
4169                         /* The extra space is currently unused. Use it. */
4170                         ei->i_extra_isize = sizeof(struct ext4_inode) -
4171                                             EXT4_GOOD_OLD_INODE_SIZE;
4172                 } else {
4173                         ext4_iget_extra_inode(inode, raw_inode, ei);
4174                 }
4175         }
4176
4177         EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4178         EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4179         EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4180         EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4181
4182         inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4183         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4184                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4185                         inode->i_version |=
4186                         (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4187         }
4188
4189         ret = 0;
4190         if (ei->i_file_acl &&
4191             !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4192                 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4193                                  ei->i_file_acl);
4194                 ret = -EIO;
4195                 goto bad_inode;
4196         } else if (!ext4_has_inline_data(inode)) {
4197                 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4198                         if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4199                             (S_ISLNK(inode->i_mode) &&
4200                              !ext4_inode_is_fast_symlink(inode))))
4201                                 /* Validate extent which is part of inode */
4202                                 ret = ext4_ext_check_inode(inode);
4203                 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4204                            (S_ISLNK(inode->i_mode) &&
4205                             !ext4_inode_is_fast_symlink(inode))) {
4206                         /* Validate block references which are part of inode */
4207                         ret = ext4_ind_check_inode(inode);
4208                 }
4209         }
4210         if (ret)
4211                 goto bad_inode;
4212
4213         if (S_ISREG(inode->i_mode)) {
4214                 inode->i_op = &ext4_file_inode_operations;
4215                 inode->i_fop = &ext4_file_operations;
4216                 ext4_set_aops(inode);
4217         } else if (S_ISDIR(inode->i_mode)) {
4218                 inode->i_op = &ext4_dir_inode_operations;
4219                 inode->i_fop = &ext4_dir_operations;
4220         } else if (S_ISLNK(inode->i_mode)) {
4221                 if (ext4_inode_is_fast_symlink(inode)) {
4222                         inode->i_op = &ext4_fast_symlink_inode_operations;
4223                         nd_terminate_link(ei->i_data, inode->i_size,
4224                                 sizeof(ei->i_data) - 1);
4225                 } else {
4226                         inode->i_op = &ext4_symlink_inode_operations;
4227                         ext4_set_aops(inode);
4228                 }
4229         } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4230               S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4231                 inode->i_op = &ext4_special_inode_operations;
4232                 if (raw_inode->i_block[0])
4233                         init_special_inode(inode, inode->i_mode,
4234                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4235                 else
4236                         init_special_inode(inode, inode->i_mode,
4237                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4238         } else if (ino == EXT4_BOOT_LOADER_INO) {
4239                 make_bad_inode(inode);
4240         } else {
4241                 ret = -EIO;
4242                 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4243                 goto bad_inode;
4244         }
4245         brelse(iloc.bh);
4246         ext4_set_inode_flags(inode);
4247         unlock_new_inode(inode);
4248         return inode;
4249
4250 bad_inode:
4251         brelse(iloc.bh);
4252         iget_failed(inode);
4253         return ERR_PTR(ret);
4254 }
4255
4256 static int ext4_inode_blocks_set(handle_t *handle,
4257                                 struct ext4_inode *raw_inode,
4258                                 struct ext4_inode_info *ei)
4259 {
4260         struct inode *inode = &(ei->vfs_inode);
4261         u64 i_blocks = inode->i_blocks;
4262         struct super_block *sb = inode->i_sb;
4263
4264         if (i_blocks <= ~0U) {
4265                 /*
4266                  * i_blocks can be represented in a 32 bit variable
4267                  * as multiple of 512 bytes
4268                  */
4269                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4270                 raw_inode->i_blocks_high = 0;
4271                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4272                 return 0;
4273         }
4274         if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4275                 return -EFBIG;
4276
4277         if (i_blocks <= 0xffffffffffffULL) {
4278                 /*
4279                  * i_blocks can be represented in a 48 bit variable
4280                  * as multiple of 512 bytes
4281                  */
4282                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4283                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4284                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4285         } else {
4286                 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4287                 /* i_block is stored in file system block size */
4288                 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4289                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4290                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4291         }
4292         return 0;
4293 }
4294
4295 /*
4296  * Post the struct inode info into an on-disk inode location in the
4297  * buffer-cache.  This gobbles the caller's reference to the
4298  * buffer_head in the inode location struct.
4299  *
4300  * The caller must have write access to iloc->bh.
4301  */
4302 static int ext4_do_update_inode(handle_t *handle,
4303                                 struct inode *inode,
4304                                 struct ext4_iloc *iloc)
4305 {
4306         struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4307         struct ext4_inode_info *ei = EXT4_I(inode);
4308         struct buffer_head *bh = iloc->bh;
4309         int err = 0, rc, block;
4310         int need_datasync = 0;
4311         uid_t i_uid;
4312         gid_t i_gid;
4313
4314         /* For fields not not tracking in the in-memory inode,
4315          * initialise them to zero for new inodes. */
4316         if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4317                 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4318
4319         ext4_get_inode_flags(ei);
4320         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4321         i_uid = i_uid_read(inode);
4322         i_gid = i_gid_read(inode);
4323         if (!(test_opt(inode->i_sb, NO_UID32))) {
4324                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4325                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4326 /*
4327  * Fix up interoperability with old kernels. Otherwise, old inodes get
4328  * re-used with the upper 16 bits of the uid/gid intact
4329  */
4330                 if (!ei->i_dtime) {
4331                         raw_inode->i_uid_high =
4332                                 cpu_to_le16(high_16_bits(i_uid));
4333                         raw_inode->i_gid_high =
4334                                 cpu_to_le16(high_16_bits(i_gid));
4335                 } else {
4336                         raw_inode->i_uid_high = 0;
4337                         raw_inode->i_gid_high = 0;
4338                 }
4339         } else {
4340                 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4341                 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4342                 raw_inode->i_uid_high = 0;
4343                 raw_inode->i_gid_high = 0;
4344         }
4345         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4346
4347         EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4348         EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4349         EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4350         EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4351
4352         if (ext4_inode_blocks_set(handle, raw_inode, ei))
4353                 goto out_brelse;
4354         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4355         raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4356         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4357             cpu_to_le32(EXT4_OS_HURD))
4358                 raw_inode->i_file_acl_high =
4359                         cpu_to_le16(ei->i_file_acl >> 32);
4360         raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4361         if (ei->i_disksize != ext4_isize(raw_inode)) {
4362                 ext4_isize_set(raw_inode, ei->i_disksize);
4363                 need_datasync = 1;
4364         }
4365         if (ei->i_disksize > 0x7fffffffULL) {
4366                 struct super_block *sb = inode->i_sb;
4367                 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4368                                 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4369                                 EXT4_SB(sb)->s_es->s_rev_level ==
4370                                 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4371                         /* If this is the first large file
4372                          * created, add a flag to the superblock.
4373                          */
4374                         err = ext4_journal_get_write_access(handle,
4375                                         EXT4_SB(sb)->s_sbh);
4376                         if (err)
4377                                 goto out_brelse;
4378                         ext4_update_dynamic_rev(sb);
4379                         EXT4_SET_RO_COMPAT_FEATURE(sb,
4380                                         EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4381                         ext4_handle_sync(handle);
4382                         err = ext4_handle_dirty_super(handle, sb);
4383                 }
4384         }
4385         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4386         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4387                 if (old_valid_dev(inode->i_rdev)) {
4388                         raw_inode->i_block[0] =
4389                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
4390                         raw_inode->i_block[1] = 0;
4391                 } else {
4392                         raw_inode->i_block[0] = 0;
4393                         raw_inode->i_block[1] =
4394                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
4395                         raw_inode->i_block[2] = 0;
4396                 }
4397         } else if (!ext4_has_inline_data(inode)) {
4398                 for (block = 0; block < EXT4_N_BLOCKS; block++)
4399                         raw_inode->i_block[block] = ei->i_data[block];
4400         }
4401
4402         raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4403         if (ei->i_extra_isize) {
4404                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4405                         raw_inode->i_version_hi =
4406                         cpu_to_le32(inode->i_version >> 32);
4407                 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4408         }
4409
4410         ext4_inode_csum_set(inode, raw_inode, ei);
4411
4412         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4413         rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4414         if (!err)
4415                 err = rc;
4416         ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4417
4418         ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4419 out_brelse:
4420         brelse(bh);
4421         ext4_std_error(inode->i_sb, err);
4422         return err;
4423 }
4424
4425 /*
4426  * ext4_write_inode()
4427  *
4428  * We are called from a few places:
4429  *
4430  * - Within generic_file_write() for O_SYNC files.
4431  *   Here, there will be no transaction running. We wait for any running
4432  *   transaction to commit.
4433  *
4434  * - Within sys_sync(), kupdate and such.
4435  *   We wait on commit, if tol to.
4436  *
4437  * - Within prune_icache() (PF_MEMALLOC == true)
4438  *   Here we simply return.  We can't afford to block kswapd on the
4439  *   journal commit.
4440  *
4441  * In all cases it is actually safe for us to return without doing anything,
4442  * because the inode has been copied into a raw inode buffer in
4443  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
4444  * knfsd.
4445  *
4446  * Note that we are absolutely dependent upon all inode dirtiers doing the
4447  * right thing: they *must* call mark_inode_dirty() after dirtying info in
4448  * which we are interested.
4449  *
4450  * It would be a bug for them to not do this.  The code:
4451  *
4452  *      mark_inode_dirty(inode)
4453  *      stuff();
4454  *      inode->i_size = expr;
4455  *
4456  * is in error because a kswapd-driven write_inode() could occur while
4457  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
4458  * will no longer be on the superblock's dirty inode list.
4459  */
4460 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4461 {
4462         int err;
4463
4464         if (current->flags & PF_MEMALLOC)
4465                 return 0;
4466
4467         if (EXT4_SB(inode->i_sb)->s_journal) {
4468                 if (ext4_journal_current_handle()) {
4469                         jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4470                         dump_stack();
4471                         return -EIO;
4472                 }
4473
4474                 if (wbc->sync_mode != WB_SYNC_ALL)
4475                         return 0;
4476
4477                 err = ext4_force_commit(inode->i_sb);
4478         } else {
4479                 struct ext4_iloc iloc;
4480
4481                 err = __ext4_get_inode_loc(inode, &iloc, 0);
4482                 if (err)
4483                         return err;
4484                 if (wbc->sync_mode == WB_SYNC_ALL)
4485                         sync_dirty_buffer(iloc.bh);
4486                 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4487                         EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4488                                          "IO error syncing inode");
4489                         err = -EIO;
4490                 }
4491                 brelse(iloc.bh);
4492         }
4493         return err;
4494 }
4495
4496 /*
4497  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4498  * buffers that are attached to a page stradding i_size and are undergoing
4499  * commit. In that case we have to wait for commit to finish and try again.
4500  */
4501 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4502 {
4503         struct page *page;
4504         unsigned offset;
4505         journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4506         tid_t commit_tid = 0;
4507         int ret;
4508
4509         offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4510         /*
4511          * All buffers in the last page remain valid? Then there's nothing to
4512          * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4513          * blocksize case
4514          */
4515         if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4516                 return;
4517         while (1) {
4518                 page = find_lock_page(inode->i_mapping,
4519                                       inode->i_size >> PAGE_CACHE_SHIFT);
4520                 if (!page)
4521                         return;
4522                 ret = __ext4_journalled_invalidatepage(page, offset,
4523                                                 PAGE_CACHE_SIZE - offset);
4524                 unlock_page(page);
4525                 page_cache_release(page);
4526                 if (ret != -EBUSY)
4527                         return;
4528                 commit_tid = 0;
4529                 read_lock(&journal->j_state_lock);
4530                 if (journal->j_committing_transaction)
4531                         commit_tid = journal->j_committing_transaction->t_tid;
4532                 read_unlock(&journal->j_state_lock);
4533                 if (commit_tid)
4534                         jbd2_log_wait_commit(journal, commit_tid);
4535         }
4536 }
4537
4538 /*
4539  * ext4_setattr()
4540  *
4541  * Called from notify_change.
4542  *
4543  * We want to trap VFS attempts to truncate the file as soon as
4544  * possible.  In particular, we want to make sure that when the VFS
4545  * shrinks i_size, we put the inode on the orphan list and modify
4546  * i_disksize immediately, so that during the subsequent flushing of
4547  * dirty pages and freeing of disk blocks, we can guarantee that any
4548  * commit will leave the blocks being flushed in an unused state on
4549  * disk.  (On recovery, the inode will get truncated and the blocks will
4550  * be freed, so we have a strong guarantee that no future commit will
4551  * leave these blocks visible to the user.)
4552  *
4553  * Another thing we have to assure is that if we are in ordered mode
4554  * and inode is still attached to the committing transaction, we must
4555  * we start writeout of all the dirty pages which are being truncated.
4556  * This way we are sure that all the data written in the previous
4557  * transaction are already on disk (truncate waits for pages under
4558  * writeback).
4559  *
4560  * Called with inode->i_mutex down.
4561  */
4562 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4563 {
4564         struct inode *inode = dentry->d_inode;
4565         int error, rc = 0;
4566         int orphan = 0;
4567         const unsigned int ia_valid = attr->ia_valid;
4568
4569         error = inode_change_ok(inode, attr);
4570         if (error)
4571                 return error;
4572
4573         if (is_quota_modification(inode, attr))
4574                 dquot_initialize(inode);
4575         if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4576             (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4577                 handle_t *handle;
4578
4579                 /* (user+group)*(old+new) structure, inode write (sb,
4580                  * inode block, ? - but truncate inode update has it) */
4581                 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4582                         (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4583                          EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4584                 if (IS_ERR(handle)) {
4585                         error = PTR_ERR(handle);
4586                         goto err_out;
4587                 }
4588                 error = dquot_transfer(inode, attr);
4589                 if (error) {
4590                         ext4_journal_stop(handle);
4591                         return error;
4592                 }
4593                 /* Update corresponding info in inode so that everything is in
4594                  * one transaction */
4595                 if (attr->ia_valid & ATTR_UID)
4596                         inode->i_uid = attr->ia_uid;
4597                 if (attr->ia_valid & ATTR_GID)
4598                         inode->i_gid = attr->ia_gid;
4599                 error = ext4_mark_inode_dirty(handle, inode);
4600                 ext4_journal_stop(handle);
4601         }
4602
4603         if (attr->ia_valid & ATTR_SIZE) {
4604
4605                 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4606                         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4607
4608                         if (attr->ia_size > sbi->s_bitmap_maxbytes)
4609                                 return -EFBIG;
4610                 }
4611         }
4612
4613         if (S_ISREG(inode->i_mode) &&
4614             attr->ia_valid & ATTR_SIZE &&
4615             (attr->ia_size < inode->i_size)) {
4616                 handle_t *handle;
4617
4618                 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4619                 if (IS_ERR(handle)) {
4620                         error = PTR_ERR(handle);
4621                         goto err_out;
4622                 }
4623                 if (ext4_handle_valid(handle)) {
4624                         error = ext4_orphan_add(handle, inode);
4625                         orphan = 1;
4626                 }
4627                 EXT4_I(inode)->i_disksize = attr->ia_size;
4628                 rc = ext4_mark_inode_dirty(handle, inode);
4629                 if (!error)
4630                         error = rc;
4631                 ext4_journal_stop(handle);
4632
4633                 if (ext4_should_order_data(inode)) {
4634                         error = ext4_begin_ordered_truncate(inode,
4635                                                             attr->ia_size);
4636                         if (error) {
4637                                 /* Do as much error cleanup as possible */
4638                                 handle = ext4_journal_start(inode,
4639                                                             EXT4_HT_INODE, 3);
4640                                 if (IS_ERR(handle)) {
4641                                         ext4_orphan_del(NULL, inode);
4642                                         goto err_out;
4643                                 }
4644                                 ext4_orphan_del(handle, inode);
4645                                 orphan = 0;
4646                                 ext4_journal_stop(handle);
4647                                 goto err_out;
4648                         }
4649                 }
4650         }
4651
4652         if (attr->ia_valid & ATTR_SIZE) {
4653                 if (attr->ia_size != inode->i_size) {
4654                         loff_t oldsize = inode->i_size;
4655
4656                         i_size_write(inode, attr->ia_size);
4657                         /*
4658                          * Blocks are going to be removed from the inode. Wait
4659                          * for dio in flight.  Temporarily disable
4660                          * dioread_nolock to prevent livelock.
4661                          */
4662                         if (orphan) {
4663                                 if (!ext4_should_journal_data(inode)) {
4664                                         ext4_inode_block_unlocked_dio(inode);
4665                                         inode_dio_wait(inode);
4666                                         ext4_inode_resume_unlocked_dio(inode);
4667                                 } else
4668                                         ext4_wait_for_tail_page_commit(inode);
4669                         }
4670                         /*
4671                          * Truncate pagecache after we've waited for commit
4672                          * in data=journal mode to make pages freeable.
4673                          */
4674                         truncate_pagecache(inode, oldsize, inode->i_size);
4675                 }
4676                 ext4_truncate(inode);
4677         }
4678
4679         if (!rc) {
4680                 setattr_copy(inode, attr);
4681                 mark_inode_dirty(inode);
4682         }
4683
4684         /*
4685          * If the call to ext4_truncate failed to get a transaction handle at
4686          * all, we need to clean up the in-core orphan list manually.
4687          */
4688         if (orphan && inode->i_nlink)
4689                 ext4_orphan_del(NULL, inode);
4690
4691         if (!rc && (ia_valid & ATTR_MODE))
4692                 rc = ext4_acl_chmod(inode);
4693
4694 err_out:
4695         ext4_std_error(inode->i_sb, error);
4696         if (!error)
4697                 error = rc;
4698         return error;
4699 }
4700
4701 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4702                  struct kstat *stat)
4703 {
4704         struct inode *inode;
4705         unsigned long long delalloc_blocks;
4706
4707         inode = dentry->d_inode;
4708         generic_fillattr(inode, stat);
4709
4710         /*
4711          * We can't update i_blocks if the block allocation is delayed
4712          * otherwise in the case of system crash before the real block
4713          * allocation is done, we will have i_blocks inconsistent with
4714          * on-disk file blocks.
4715          * We always keep i_blocks updated together with real
4716          * allocation. But to not confuse with user, stat
4717          * will return the blocks that include the delayed allocation
4718          * blocks for this file.
4719          */
4720         delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4721                                 EXT4_I(inode)->i_reserved_data_blocks);
4722
4723         stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
4724         return 0;
4725 }
4726
4727 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4728 {
4729         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4730                 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4731         return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4732 }
4733
4734 /*
4735  * Account for index blocks, block groups bitmaps and block group
4736  * descriptor blocks if modify datablocks and index blocks
4737  * worse case, the indexs blocks spread over different block groups
4738  *
4739  * If datablocks are discontiguous, they are possible to spread over
4740  * different block groups too. If they are contiguous, with flexbg,
4741  * they could still across block group boundary.
4742  *
4743  * Also account for superblock, inode, quota and xattr blocks
4744  */
4745 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4746 {
4747         ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4748         int gdpblocks;
4749         int idxblocks;
4750         int ret = 0;
4751
4752         /*
4753          * How many index blocks need to touch to modify nrblocks?
4754          * The "Chunk" flag indicating whether the nrblocks is
4755          * physically contiguous on disk
4756          *
4757          * For Direct IO and fallocate, they calls get_block to allocate
4758          * one single extent at a time, so they could set the "Chunk" flag
4759          */
4760         idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4761
4762         ret = idxblocks;
4763
4764         /*
4765          * Now let's see how many group bitmaps and group descriptors need
4766          * to account
4767          */
4768         groups = idxblocks;
4769         if (chunk)
4770                 groups += 1;
4771         else
4772                 groups += nrblocks;
4773
4774         gdpblocks = groups;
4775         if (groups > ngroups)
4776                 groups = ngroups;
4777         if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4778                 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4779
4780         /* bitmaps and block group descriptor blocks */
4781         ret += groups + gdpblocks;
4782
4783         /* Blocks for super block, inode, quota and xattr blocks */
4784         ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4785
4786         return ret;
4787 }
4788
4789 /*
4790  * Calculate the total number of credits to reserve to fit
4791  * the modification of a single pages into a single transaction,
4792  * which may include multiple chunks of block allocations.
4793  *
4794  * This could be called via ext4_write_begin()
4795  *
4796  * We need to consider the worse case, when
4797  * one new block per extent.
4798  */
4799 int ext4_writepage_trans_blocks(struct inode *inode)
4800 {
4801         int bpp = ext4_journal_blocks_per_page(inode);
4802         int ret;
4803
4804         ret = ext4_meta_trans_blocks(inode, bpp, 0);
4805
4806         /* Account for data blocks for journalled mode */
4807         if (ext4_should_journal_data(inode))
4808                 ret += bpp;
4809         return ret;
4810 }
4811
4812 /*
4813  * Calculate the journal credits for a chunk of data modification.
4814  *
4815  * This is called from DIO, fallocate or whoever calling
4816  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4817  *
4818  * journal buffers for data blocks are not included here, as DIO
4819  * and fallocate do no need to journal data buffers.
4820  */
4821 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4822 {
4823         return ext4_meta_trans_blocks(inode, nrblocks, 1);
4824 }
4825
4826 /*
4827  * The caller must have previously called ext4_reserve_inode_write().
4828  * Give this, we know that the caller already has write access to iloc->bh.
4829  */
4830 int ext4_mark_iloc_dirty(handle_t *handle,
4831                          struct inode *inode, struct ext4_iloc *iloc)
4832 {
4833         int err = 0;
4834
4835         if (IS_I_VERSION(inode))
4836                 inode_inc_iversion(inode);
4837
4838         /* the do_update_inode consumes one bh->b_count */
4839         get_bh(iloc->bh);
4840
4841         /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4842         err = ext4_do_update_inode(handle, inode, iloc);
4843         put_bh(iloc->bh);
4844         return err;
4845 }
4846
4847 /*
4848  * On success, We end up with an outstanding reference count against
4849  * iloc->bh.  This _must_ be cleaned up later.
4850  */
4851
4852 int
4853 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4854                          struct ext4_iloc *iloc)
4855 {
4856         int err;
4857
4858         err = ext4_get_inode_loc(inode, iloc);
4859         if (!err) {
4860                 BUFFER_TRACE(iloc->bh, "get_write_access");
4861                 err = ext4_journal_get_write_access(handle, iloc->bh);
4862                 if (err) {
4863                         brelse(iloc->bh);
4864                         iloc->bh = NULL;
4865                 }
4866         }
4867         ext4_std_error(inode->i_sb, err);
4868         return err;
4869 }
4870
4871 /*
4872  * Expand an inode by new_extra_isize bytes.
4873  * Returns 0 on success or negative error number on failure.
4874  */
4875 static int ext4_expand_extra_isize(struct inode *inode,
4876                                    unsigned int new_extra_isize,
4877                                    struct ext4_iloc iloc,
4878                                    handle_t *handle)
4879 {
4880         struct ext4_inode *raw_inode;
4881         struct ext4_xattr_ibody_header *header;
4882
4883         if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4884                 return 0;
4885
4886         raw_inode = ext4_raw_inode(&iloc);
4887
4888         header = IHDR(inode, raw_inode);
4889
4890         /* No extended attributes present */
4891         if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4892             header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4893                 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4894                         new_extra_isize);
4895                 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4896                 return 0;
4897         }
4898
4899         /* try to expand with EAs present */
4900         return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4901                                           raw_inode, handle);
4902 }
4903
4904 /*
4905  * What we do here is to mark the in-core inode as clean with respect to inode
4906  * dirtiness (it may still be data-dirty).
4907  * This means that the in-core inode may be reaped by prune_icache
4908  * without having to perform any I/O.  This is a very good thing,
4909  * because *any* task may call prune_icache - even ones which
4910  * have a transaction open against a different journal.
4911  *
4912  * Is this cheating?  Not really.  Sure, we haven't written the
4913  * inode out, but prune_icache isn't a user-visible syncing function.
4914  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4915  * we start and wait on commits.
4916  */
4917 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4918 {
4919         struct ext4_iloc iloc;
4920         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4921         static unsigned int mnt_count;
4922         int err, ret;
4923
4924         might_sleep();
4925         trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4926         err = ext4_reserve_inode_write(handle, inode, &iloc);
4927         if (ext4_handle_valid(handle) &&
4928             EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4929             !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4930                 /*
4931                  * We need extra buffer credits since we may write into EA block
4932                  * with this same handle. If journal_extend fails, then it will
4933                  * only result in a minor loss of functionality for that inode.
4934                  * If this is felt to be critical, then e2fsck should be run to
4935                  * force a large enough s_min_extra_isize.
4936                  */
4937                 if ((jbd2_journal_extend(handle,
4938                              EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4939                         ret = ext4_expand_extra_isize(inode,
4940                                                       sbi->s_want_extra_isize,
4941                                                       iloc, handle);
4942                         if (ret) {
4943                                 ext4_set_inode_state(inode,
4944                                                      EXT4_STATE_NO_EXPAND);
4945                                 if (mnt_count !=
4946                                         le16_to_cpu(sbi->s_es->s_mnt_count)) {
4947                                         ext4_warning(inode->i_sb,
4948                                         "Unable to expand inode %lu. Delete"
4949                                         " some EAs or run e2fsck.",
4950                                         inode->i_ino);
4951                                         mnt_count =
4952                                           le16_to_cpu(sbi->s_es->s_mnt_count);
4953                                 }
4954                         }
4955                 }
4956         }
4957         if (!err)
4958                 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4959         return err;
4960 }
4961
4962 /*
4963  * ext4_dirty_inode() is called from __mark_inode_dirty()
4964  *
4965  * We're really interested in the case where a file is being extended.
4966  * i_size has been changed by generic_commit_write() and we thus need
4967  * to include the updated inode in the current transaction.
4968  *
4969  * Also, dquot_alloc_block() will always dirty the inode when blocks
4970  * are allocated to the file.
4971  *
4972  * If the inode is marked synchronous, we don't honour that here - doing
4973  * so would cause a commit on atime updates, which we don't bother doing.
4974  * We handle synchronous inodes at the highest possible level.
4975  */
4976 void ext4_dirty_inode(struct inode *inode, int flags)
4977 {
4978         handle_t *handle;
4979
4980         handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4981         if (IS_ERR(handle))
4982                 goto out;
4983
4984         ext4_mark_inode_dirty(handle, inode);
4985
4986         ext4_journal_stop(handle);
4987 out:
4988         return;
4989 }
4990
4991 #if 0
4992 /*
4993  * Bind an inode's backing buffer_head into this transaction, to prevent
4994  * it from being flushed to disk early.  Unlike
4995  * ext4_reserve_inode_write, this leaves behind no bh reference and
4996  * returns no iloc structure, so the caller needs to repeat the iloc
4997  * lookup to mark the inode dirty later.
4998  */
4999 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5000 {
5001         struct ext4_iloc iloc;
5002
5003         int err = 0;
5004         if (handle) {
5005                 err = ext4_get_inode_loc(inode, &iloc);
5006                 if (!err) {
5007                         BUFFER_TRACE(iloc.bh, "get_write_access");
5008                         err = jbd2_journal_get_write_access(handle, iloc.bh);
5009                         if (!err)
5010                                 err = ext4_handle_dirty_metadata(handle,
5011                                                                  NULL,
5012                                                                  iloc.bh);
5013                         brelse(iloc.bh);
5014                 }
5015         }
5016         ext4_std_error(inode->i_sb, err);
5017         return err;
5018 }
5019 #endif
5020
5021 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5022 {
5023         journal_t *journal;
5024         handle_t *handle;
5025         int err;
5026
5027         /*
5028          * We have to be very careful here: changing a data block's
5029          * journaling status dynamically is dangerous.  If we write a
5030          * data block to the journal, change the status and then delete
5031          * that block, we risk forgetting to revoke the old log record
5032          * from the journal and so a subsequent replay can corrupt data.
5033          * So, first we make sure that the journal is empty and that
5034          * nobody is changing anything.
5035          */
5036
5037         journal = EXT4_JOURNAL(inode);
5038         if (!journal)
5039                 return 0;
5040         if (is_journal_aborted(journal))
5041                 return -EROFS;
5042         /* We have to allocate physical blocks for delalloc blocks
5043          * before flushing journal. otherwise delalloc blocks can not
5044          * be allocated any more. even more truncate on delalloc blocks
5045          * could trigger BUG by flushing delalloc blocks in journal.
5046          * There is no delalloc block in non-journal data mode.
5047          */
5048         if (val && test_opt(inode->i_sb, DELALLOC)) {
5049                 err = ext4_alloc_da_blocks(inode);
5050                 if (err < 0)
5051                         return err;
5052         }
5053
5054         /* Wait for all existing dio workers */
5055         ext4_inode_block_unlocked_dio(inode);
5056         inode_dio_wait(inode);
5057
5058         jbd2_journal_lock_updates(journal);
5059
5060         /*
5061          * OK, there are no updates running now, and all cached data is
5062          * synced to disk.  We are now in a completely consistent state
5063          * which doesn't have anything in the journal, and we know that
5064          * no filesystem updates are running, so it is safe to modify
5065          * the inode's in-core data-journaling state flag now.
5066          */
5067
5068         if (val)
5069                 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5070         else {
5071                 jbd2_journal_flush(journal);
5072                 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5073         }
5074         ext4_set_aops(inode);
5075
5076         jbd2_journal_unlock_updates(journal);
5077         ext4_inode_resume_unlocked_dio(inode);
5078
5079         /* Finally we can mark the inode as dirty. */
5080
5081         handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5082         if (IS_ERR(handle))
5083                 return PTR_ERR(handle);
5084
5085         err = ext4_mark_inode_dirty(handle, inode);
5086         ext4_handle_sync(handle);
5087         ext4_journal_stop(handle);
5088         ext4_std_error(inode->i_sb, err);
5089
5090         return err;
5091 }
5092
5093 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5094 {
5095         return !buffer_mapped(bh);
5096 }
5097
5098 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5099 {
5100         struct page *page = vmf->page;
5101         loff_t size;
5102         unsigned long len;
5103         int ret;
5104         struct file *file = vma->vm_file;
5105         struct inode *inode = file_inode(file);
5106         struct address_space *mapping = inode->i_mapping;
5107         handle_t *handle;
5108         get_block_t *get_block;
5109         int retries = 0;
5110
5111         sb_start_pagefault(inode->i_sb);
5112         file_update_time(vma->vm_file);
5113         /* Delalloc case is easy... */
5114         if (test_opt(inode->i_sb, DELALLOC) &&
5115             !ext4_should_journal_data(inode) &&
5116             !ext4_nonda_switch(inode->i_sb)) {
5117                 do {
5118                         ret = __block_page_mkwrite(vma, vmf,
5119                                                    ext4_da_get_block_prep);
5120                 } while (ret == -ENOSPC &&
5121                        ext4_should_retry_alloc(inode->i_sb, &retries));
5122                 goto out_ret;
5123         }
5124
5125         lock_page(page);
5126         size = i_size_read(inode);
5127         /* Page got truncated from under us? */
5128         if (page->mapping != mapping || page_offset(page) > size) {
5129                 unlock_page(page);
5130                 ret = VM_FAULT_NOPAGE;
5131                 goto out;
5132         }
5133
5134         if (page->index == size >> PAGE_CACHE_SHIFT)
5135                 len = size & ~PAGE_CACHE_MASK;
5136         else
5137                 len = PAGE_CACHE_SIZE;
5138         /*
5139          * Return if we have all the buffers mapped. This avoids the need to do
5140          * journal_start/journal_stop which can block and take a long time
5141          */
5142         if (page_has_buffers(page)) {
5143                 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5144                                             0, len, NULL,
5145                                             ext4_bh_unmapped)) {
5146                         /* Wait so that we don't change page under IO */
5147                         wait_for_stable_page(page);
5148                         ret = VM_FAULT_LOCKED;
5149                         goto out;
5150                 }
5151         }
5152         unlock_page(page);
5153         /* OK, we need to fill the hole... */
5154         if (ext4_should_dioread_nolock(inode))
5155                 get_block = ext4_get_block_write;
5156         else
5157                 get_block = ext4_get_block;
5158 retry_alloc:
5159         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5160                                     ext4_writepage_trans_blocks(inode));
5161         if (IS_ERR(handle)) {
5162                 ret = VM_FAULT_SIGBUS;
5163                 goto out;
5164         }
5165         ret = __block_page_mkwrite(vma, vmf, get_block);
5166         if (!ret && ext4_should_journal_data(inode)) {
5167                 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5168                           PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5169                         unlock_page(page);
5170                         ret = VM_FAULT_SIGBUS;
5171                         ext4_journal_stop(handle);
5172                         goto out;
5173                 }
5174                 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5175         }
5176         ext4_journal_stop(handle);
5177         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5178                 goto retry_alloc;
5179 out_ret:
5180         ret = block_page_mkwrite_return(ret);
5181 out:
5182         sb_end_pagefault(inode->i_sb);
5183         return ret;
5184 }