~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/ext4/inode.c

Version: ~ [ linux-5.0-rc6 ] ~ [ linux-4.20.10 ] ~ [ linux-4.19.23 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.101 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.158 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.174 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.134 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.63 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp