ext4: don't let i_reserved_meta_blocks go negative
[firefly-linux-kernel-4.4.55.git] / fs / ext4 / inode.c
1 /*
2  *  linux/fs/ext4/inode.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  from
10  *
11  *  linux/fs/minix/inode.c
12  *
13  *  Copyright (C) 1991, 1992  Linus Torvalds
14  *
15  *  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         while (index <= end) {
2203                 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2204                 if (nr_pages == 0)
2205                         break;
2206                 for (i = 0; i < nr_pages; i++) {
2207                         struct page *page = pvec.pages[i];
2208                         if (page->index > end)
2209                                 break;
2210                         BUG_ON(!PageLocked(page));
2211                         BUG_ON(PageWriteback(page));
2212                         block_invalidatepage(page, 0);
2213                         ClearPageUptodate(page);
2214                         unlock_page(page);
2215                 }
2216                 index = pvec.pages[nr_pages - 1]->index + 1;
2217                 pagevec_release(&pvec);
2218         }
2219         return;
2220 }
2221
2222 static void ext4_print_free_blocks(struct inode *inode)
2223 {
2224         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2225         printk(KERN_CRIT "Total free blocks count %lld\n",
2226                ext4_count_free_blocks(inode->i_sb));
2227         printk(KERN_CRIT "Free/Dirty block details\n");
2228         printk(KERN_CRIT "free_blocks=%lld\n",
2229                (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
2230         printk(KERN_CRIT "dirty_blocks=%lld\n",
2231                (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2232         printk(KERN_CRIT "Block reservation details\n");
2233         printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
2234                EXT4_I(inode)->i_reserved_data_blocks);
2235         printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
2236                EXT4_I(inode)->i_reserved_meta_blocks);
2237         return;
2238 }
2239
2240 /*
2241  * mpage_da_map_and_submit - go through given space, map them
2242  *       if necessary, and then submit them for I/O
2243  *
2244  * @mpd - bh describing space
2245  *
2246  * The function skips space we know is already mapped to disk blocks.
2247  *
2248  */
2249 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
2250 {
2251         int err, blks, get_blocks_flags;
2252         struct ext4_map_blocks map, *mapp = NULL;
2253         sector_t next = mpd->b_blocknr;
2254         unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2255         loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2256         handle_t *handle = NULL;
2257
2258         /*
2259          * If the blocks are mapped already, or we couldn't accumulate
2260          * any blocks, then proceed immediately to the submission stage.
2261          */
2262         if ((mpd->b_size == 0) ||
2263             ((mpd->b_state  & (1 << BH_Mapped)) &&
2264              !(mpd->b_state & (1 << BH_Delay)) &&
2265              !(mpd->b_state & (1 << BH_Unwritten))))
2266                 goto submit_io;
2267
2268         handle = ext4_journal_current_handle();
2269         BUG_ON(!handle);
2270
2271         /*
2272          * Call ext4_map_blocks() to allocate any delayed allocation
2273          * blocks, or to convert an uninitialized extent to be
2274          * initialized (in the case where we have written into
2275          * one or more preallocated blocks).
2276          *
2277          * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2278          * indicate that we are on the delayed allocation path.  This
2279          * affects functions in many different parts of the allocation
2280          * call path.  This flag exists primarily because we don't
2281          * want to change *many* call functions, so ext4_map_blocks()
2282          * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
2283          * inode's allocation semaphore is taken.
2284          *
2285          * If the blocks in questions were delalloc blocks, set
2286          * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2287          * variables are updated after the blocks have been allocated.
2288          */
2289         map.m_lblk = next;
2290         map.m_len = max_blocks;
2291         get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
2292         if (ext4_should_dioread_nolock(mpd->inode))
2293                 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2294         if (mpd->b_state & (1 << BH_Delay))
2295                 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2296
2297         blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
2298         if (blks < 0) {
2299                 struct super_block *sb = mpd->inode->i_sb;
2300
2301                 err = blks;
2302                 /*
2303                  * If get block returns EAGAIN or ENOSPC and there
2304                  * appears to be free blocks we will just let
2305                  * mpage_da_submit_io() unlock all of the pages.
2306                  */
2307                 if (err == -EAGAIN)
2308                         goto submit_io;
2309
2310                 if (err == -ENOSPC &&
2311                     ext4_count_free_blocks(sb)) {
2312                         mpd->retval = err;
2313                         goto submit_io;
2314                 }
2315
2316                 /*
2317                  * get block failure will cause us to loop in
2318                  * writepages, because a_ops->writepage won't be able
2319                  * to make progress. The page will be redirtied by
2320                  * writepage and writepages will again try to write
2321                  * the same.
2322                  */
2323                 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2324                         ext4_msg(sb, KERN_CRIT,
2325                                  "delayed block allocation failed for inode %lu "
2326                                  "at logical offset %llu with max blocks %zd "
2327                                  "with error %d", mpd->inode->i_ino,
2328                                  (unsigned long long) next,
2329                                  mpd->b_size >> mpd->inode->i_blkbits, err);
2330                         ext4_msg(sb, KERN_CRIT,
2331                                 "This should not happen!! Data will be lost\n");
2332                         if (err == -ENOSPC)
2333                                 ext4_print_free_blocks(mpd->inode);
2334                 }
2335                 /* invalidate all the pages */
2336                 ext4_da_block_invalidatepages(mpd);
2337
2338                 /* Mark this page range as having been completed */
2339                 mpd->io_done = 1;
2340                 return;
2341         }
2342         BUG_ON(blks == 0);
2343
2344         mapp = &map;
2345         if (map.m_flags & EXT4_MAP_NEW) {
2346                 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
2347                 int i;
2348
2349                 for (i = 0; i < map.m_len; i++)
2350                         unmap_underlying_metadata(bdev, map.m_pblk + i);
2351         }
2352
2353         if (ext4_should_order_data(mpd->inode)) {
2354                 err = ext4_jbd2_file_inode(handle, mpd->inode);
2355                 if (err)
2356                         /* This only happens if the journal is aborted */
2357                         return;
2358         }
2359
2360         /*
2361          * Update on-disk size along with block allocation.
2362          */
2363         disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2364         if (disksize > i_size_read(mpd->inode))
2365                 disksize = i_size_read(mpd->inode);
2366         if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2367                 ext4_update_i_disksize(mpd->inode, disksize);
2368                 err = ext4_mark_inode_dirty(handle, mpd->inode);
2369                 if (err)
2370                         ext4_error(mpd->inode->i_sb,
2371                                    "Failed to mark inode %lu dirty",
2372                                    mpd->inode->i_ino);
2373         }
2374
2375 submit_io:
2376         mpage_da_submit_io(mpd, mapp);
2377         mpd->io_done = 1;
2378 }
2379
2380 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2381                 (1 << BH_Delay) | (1 << BH_Unwritten))
2382
2383 /*
2384  * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2385  *
2386  * @mpd->lbh - extent of blocks
2387  * @logical - logical number of the block in the file
2388  * @bh - bh of the block (used to access block's state)
2389  *
2390  * the function is used to collect contig. blocks in same state
2391  */
2392 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2393                                    sector_t logical, size_t b_size,
2394                                    unsigned long b_state)
2395 {
2396         sector_t next;
2397         int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2398
2399         /*
2400          * XXX Don't go larger than mballoc is willing to allocate
2401          * This is a stopgap solution.  We eventually need to fold
2402          * mpage_da_submit_io() into this function and then call
2403          * ext4_map_blocks() multiple times in a loop
2404          */
2405         if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
2406                 goto flush_it;
2407
2408         /* check if thereserved journal credits might overflow */
2409         if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
2410                 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2411                         /*
2412                          * With non-extent format we are limited by the journal
2413                          * credit available.  Total credit needed to insert
2414                          * nrblocks contiguous blocks is dependent on the
2415                          * nrblocks.  So limit nrblocks.
2416                          */
2417                         goto flush_it;
2418                 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2419                                 EXT4_MAX_TRANS_DATA) {
2420                         /*
2421                          * Adding the new buffer_head would make it cross the
2422                          * allowed limit for which we have journal credit
2423                          * reserved. So limit the new bh->b_size
2424                          */
2425                         b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2426                                                 mpd->inode->i_blkbits;
2427                         /* we will do mpage_da_submit_io in the next loop */
2428                 }
2429         }
2430         /*
2431          * First block in the extent
2432          */
2433         if (mpd->b_size == 0) {
2434                 mpd->b_blocknr = logical;
2435                 mpd->b_size = b_size;
2436                 mpd->b_state = b_state & BH_FLAGS;
2437                 return;
2438         }
2439
2440         next = mpd->b_blocknr + nrblocks;
2441         /*
2442          * Can we merge the block to our big extent?
2443          */
2444         if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2445                 mpd->b_size += b_size;
2446                 return;
2447         }
2448
2449 flush_it:
2450         /*
2451          * We couldn't merge the block to our extent, so we
2452          * need to flush current  extent and start new one
2453          */
2454         mpage_da_map_and_submit(mpd);
2455         return;
2456 }
2457
2458 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
2459 {
2460         return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
2461 }
2462
2463 /*
2464  * This is a special get_blocks_t callback which is used by
2465  * ext4_da_write_begin().  It will either return mapped block or
2466  * reserve space for a single block.
2467  *
2468  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2469  * We also have b_blocknr = -1 and b_bdev initialized properly
2470  *
2471  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2472  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2473  * initialized properly.
2474  */
2475 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2476                                   struct buffer_head *bh, int create)
2477 {
2478         struct ext4_map_blocks map;
2479         int ret = 0;
2480         sector_t invalid_block = ~((sector_t) 0xffff);
2481
2482         if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2483                 invalid_block = ~0;
2484
2485         BUG_ON(create == 0);
2486         BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2487
2488         map.m_lblk = iblock;
2489         map.m_len = 1;
2490
2491         /*
2492          * first, we need to know whether the block is allocated already
2493          * preallocated blocks are unmapped but should treated
2494          * the same as allocated blocks.
2495          */
2496         ret = ext4_map_blocks(NULL, inode, &map, 0);
2497         if (ret < 0)
2498                 return ret;
2499         if (ret == 0) {
2500                 if (buffer_delay(bh))
2501                         return 0; /* Not sure this could or should happen */
2502                 /*
2503                  * XXX: __block_write_begin() unmaps passed block, is it OK?
2504                  */
2505                 ret = ext4_da_reserve_space(inode, iblock);
2506                 if (ret)
2507                         /* not enough space to reserve */
2508                         return ret;
2509
2510                 map_bh(bh, inode->i_sb, invalid_block);
2511                 set_buffer_new(bh);
2512                 set_buffer_delay(bh);
2513                 return 0;
2514         }
2515
2516         map_bh(bh, inode->i_sb, map.m_pblk);
2517         bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
2518
2519         if (buffer_unwritten(bh)) {
2520                 /* A delayed write to unwritten bh should be marked
2521                  * new and mapped.  Mapped ensures that we don't do
2522                  * get_block multiple times when we write to the same
2523                  * offset and new ensures that we do proper zero out
2524                  * for partial write.
2525                  */
2526                 set_buffer_new(bh);
2527                 set_buffer_mapped(bh);
2528         }
2529         return 0;
2530 }
2531
2532 /*
2533  * This function is used as a standard get_block_t calback function
2534  * when there is no desire to allocate any blocks.  It is used as a
2535  * callback function for block_write_begin() and block_write_full_page().
2536  * These functions should only try to map a single block at a time.
2537  *
2538  * Since this function doesn't do block allocations even if the caller
2539  * requests it by passing in create=1, it is critically important that
2540  * any caller checks to make sure that any buffer heads are returned
2541  * by this function are either all already mapped or marked for
2542  * delayed allocation before calling  block_write_full_page().  Otherwise,
2543  * b_blocknr could be left unitialized, and the page write functions will
2544  * be taken by surprise.
2545  */
2546 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2547                                    struct buffer_head *bh_result, int create)
2548 {
2549         BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2550         return _ext4_get_block(inode, iblock, bh_result, 0);
2551 }
2552
2553 static int bget_one(handle_t *handle, struct buffer_head *bh)
2554 {
2555         get_bh(bh);
2556         return 0;
2557 }
2558
2559 static int bput_one(handle_t *handle, struct buffer_head *bh)
2560 {
2561         put_bh(bh);
2562         return 0;
2563 }
2564
2565 static int __ext4_journalled_writepage(struct page *page,
2566                                        unsigned int len)
2567 {
2568         struct address_space *mapping = page->mapping;
2569         struct inode *inode = mapping->host;
2570         struct buffer_head *page_bufs;
2571         handle_t *handle = NULL;
2572         int ret = 0;
2573         int err;
2574
2575         ClearPageChecked(page);
2576         page_bufs = page_buffers(page);
2577         BUG_ON(!page_bufs);
2578         walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
2579         /* As soon as we unlock the page, it can go away, but we have
2580          * references to buffers so we are safe */
2581         unlock_page(page);
2582
2583         handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2584         if (IS_ERR(handle)) {
2585                 ret = PTR_ERR(handle);
2586                 goto out;
2587         }
2588
2589         BUG_ON(!ext4_handle_valid(handle));
2590
2591         ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2592                                 do_journal_get_write_access);
2593
2594         err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2595                                 write_end_fn);
2596         if (ret == 0)
2597                 ret = err;
2598         err = ext4_journal_stop(handle);
2599         if (!ret)
2600                 ret = err;
2601
2602         walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
2603         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2604 out:
2605         return ret;
2606 }
2607
2608 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
2609 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
2610
2611 /*
2612  * Note that we don't need to start a transaction unless we're journaling data
2613  * because we should have holes filled from ext4_page_mkwrite(). We even don't
2614  * need to file the inode to the transaction's list in ordered mode because if
2615  * we are writing back data added by write(), the inode is already there and if
2616  * we are writing back data modified via mmap(), no one guarantees in which
2617  * transaction the data will hit the disk. In case we are journaling data, we
2618  * cannot start transaction directly because transaction start ranks above page
2619  * lock so we have to do some magic.
2620  *
2621  * This function can get called via...
2622  *   - ext4_da_writepages after taking page lock (have journal handle)
2623  *   - journal_submit_inode_data_buffers (no journal handle)
2624  *   - shrink_page_list via pdflush (no journal handle)
2625  *   - grab_page_cache when doing write_begin (have journal handle)
2626  *
2627  * We don't do any block allocation in this function. If we have page with
2628  * multiple blocks we need to write those buffer_heads that are mapped. This
2629  * is important for mmaped based write. So if we do with blocksize 1K
2630  * truncate(f, 1024);
2631  * a = mmap(f, 0, 4096);
2632  * a[0] = 'a';
2633  * truncate(f, 4096);
2634  * we have in the page first buffer_head mapped via page_mkwrite call back
2635  * but other bufer_heads would be unmapped but dirty(dirty done via the
2636  * do_wp_page). So writepage should write the first block. If we modify
2637  * the mmap area beyond 1024 we will again get a page_fault and the
2638  * page_mkwrite callback will do the block allocation and mark the
2639  * buffer_heads mapped.
2640  *
2641  * We redirty the page if we have any buffer_heads that is either delay or
2642  * unwritten in the page.
2643  *
2644  * We can get recursively called as show below.
2645  *
2646  *      ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2647  *              ext4_writepage()
2648  *
2649  * But since we don't do any block allocation we should not deadlock.
2650  * Page also have the dirty flag cleared so we don't get recurive page_lock.
2651  */
2652 static int ext4_writepage(struct page *page,
2653                           struct writeback_control *wbc)
2654 {
2655         int ret = 0, commit_write = 0;
2656         loff_t size;
2657         unsigned int len;
2658         struct buffer_head *page_bufs = NULL;
2659         struct inode *inode = page->mapping->host;
2660
2661         trace_ext4_writepage(page);
2662         size = i_size_read(inode);
2663         if (page->index == size >> PAGE_CACHE_SHIFT)
2664                 len = size & ~PAGE_CACHE_MASK;
2665         else
2666                 len = PAGE_CACHE_SIZE;
2667
2668         /*
2669          * If the page does not have buffers (for whatever reason),
2670          * try to create them using __block_write_begin.  If this
2671          * fails, redirty the page and move on.
2672          */
2673         if (!page_has_buffers(page)) {
2674                 if (__block_write_begin(page, 0, len,
2675                                         noalloc_get_block_write)) {
2676                 redirty_page:
2677                         redirty_page_for_writepage(wbc, page);
2678                         unlock_page(page);
2679                         return 0;
2680                 }
2681                 commit_write = 1;
2682         }
2683         page_bufs = page_buffers(page);
2684         if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2685                               ext4_bh_delay_or_unwritten)) {
2686                 /*
2687                  * We don't want to do block allocation, so redirty
2688                  * the page and return.  We may reach here when we do
2689                  * a journal commit via journal_submit_inode_data_buffers.
2690                  * We can also reach here via shrink_page_list
2691                  */
2692                 goto redirty_page;
2693         }
2694         if (commit_write)
2695                 /* now mark the buffer_heads as dirty and uptodate */
2696                 block_commit_write(page, 0, len);
2697
2698         if (PageChecked(page) && ext4_should_journal_data(inode))
2699                 /*
2700                  * It's mmapped pagecache.  Add buffers and journal it.  There
2701                  * doesn't seem much point in redirtying the page here.
2702                  */
2703                 return __ext4_journalled_writepage(page, len);
2704
2705         if (buffer_uninit(page_bufs)) {
2706                 ext4_set_bh_endio(page_bufs, inode);
2707                 ret = block_write_full_page_endio(page, noalloc_get_block_write,
2708                                             wbc, ext4_end_io_buffer_write);
2709         } else
2710                 ret = block_write_full_page(page, noalloc_get_block_write,
2711                                             wbc);
2712
2713         return ret;
2714 }
2715
2716 /*
2717  * This is called via ext4_da_writepages() to
2718  * calculate the total number of credits to reserve to fit
2719  * a single extent allocation into a single transaction,
2720  * ext4_da_writpeages() will loop calling this before
2721  * the block allocation.
2722  */
2723
2724 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2725 {
2726         int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2727
2728         /*
2729          * With non-extent format the journal credit needed to
2730          * insert nrblocks contiguous block is dependent on
2731          * number of contiguous block. So we will limit
2732          * number of contiguous block to a sane value
2733          */
2734         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2735             (max_blocks > EXT4_MAX_TRANS_DATA))
2736                 max_blocks = EXT4_MAX_TRANS_DATA;
2737
2738         return ext4_chunk_trans_blocks(inode, max_blocks);
2739 }
2740
2741 /*
2742  * write_cache_pages_da - walk the list of dirty pages of the given
2743  * address space and accumulate pages that need writing, and call
2744  * mpage_da_map_and_submit to map a single contiguous memory region
2745  * and then write them.
2746  */
2747 static int write_cache_pages_da(struct address_space *mapping,
2748                                 struct writeback_control *wbc,
2749                                 struct mpage_da_data *mpd,
2750                                 pgoff_t *done_index)
2751 {
2752         struct buffer_head      *bh, *head;
2753         struct inode            *inode = mapping->host;
2754         struct pagevec          pvec;
2755         unsigned int            nr_pages;
2756         sector_t                logical;
2757         pgoff_t                 index, end;
2758         long                    nr_to_write = wbc->nr_to_write;
2759         int                     i, tag, ret = 0;
2760
2761         memset(mpd, 0, sizeof(struct mpage_da_data));
2762         mpd->wbc = wbc;
2763         mpd->inode = inode;
2764         pagevec_init(&pvec, 0);
2765         index = wbc->range_start >> PAGE_CACHE_SHIFT;
2766         end = wbc->range_end >> PAGE_CACHE_SHIFT;
2767
2768         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2769                 tag = PAGECACHE_TAG_TOWRITE;
2770         else
2771                 tag = PAGECACHE_TAG_DIRTY;
2772
2773         *done_index = index;
2774         while (index <= end) {
2775                 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2776                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2777                 if (nr_pages == 0)
2778                         return 0;
2779
2780                 for (i = 0; i < nr_pages; i++) {
2781                         struct page *page = pvec.pages[i];
2782
2783                         /*
2784                          * At this point, the page may be truncated or
2785                          * invalidated (changing page->mapping to NULL), or
2786                          * even swizzled back from swapper_space to tmpfs file
2787                          * mapping. However, page->index will not change
2788                          * because we have a reference on the page.
2789                          */
2790                         if (page->index > end)
2791                                 goto out;
2792
2793                         *done_index = page->index + 1;
2794
2795                         /*
2796                          * If we can't merge this page, and we have
2797                          * accumulated an contiguous region, write it
2798                          */
2799                         if ((mpd->next_page != page->index) &&
2800                             (mpd->next_page != mpd->first_page)) {
2801                                 mpage_da_map_and_submit(mpd);
2802                                 goto ret_extent_tail;
2803                         }
2804
2805                         lock_page(page);
2806
2807                         /*
2808                          * If the page is no longer dirty, or its
2809                          * mapping no longer corresponds to inode we
2810                          * are writing (which means it has been
2811                          * truncated or invalidated), or the page is
2812                          * already under writeback and we are not
2813                          * doing a data integrity writeback, skip the page
2814                          */
2815                         if (!PageDirty(page) ||
2816                             (PageWriteback(page) &&
2817                              (wbc->sync_mode == WB_SYNC_NONE)) ||
2818                             unlikely(page->mapping != mapping)) {
2819                                 unlock_page(page);
2820                                 continue;
2821                         }
2822
2823                         wait_on_page_writeback(page);
2824                         BUG_ON(PageWriteback(page));
2825
2826                         if (mpd->next_page != page->index)
2827                                 mpd->first_page = page->index;
2828                         mpd->next_page = page->index + 1;
2829                         logical = (sector_t) page->index <<
2830                                 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2831
2832                         if (!page_has_buffers(page)) {
2833                                 mpage_add_bh_to_extent(mpd, logical,
2834                                                        PAGE_CACHE_SIZE,
2835                                                        (1 << BH_Dirty) | (1 << BH_Uptodate));
2836                                 if (mpd->io_done)
2837                                         goto ret_extent_tail;
2838                         } else {
2839                                 /*
2840                                  * Page with regular buffer heads,
2841                                  * just add all dirty ones
2842                                  */
2843                                 head = page_buffers(page);
2844                                 bh = head;
2845                                 do {
2846                                         BUG_ON(buffer_locked(bh));
2847                                         /*
2848                                          * We need to try to allocate
2849                                          * unmapped blocks in the same page.
2850                                          * Otherwise we won't make progress
2851                                          * with the page in ext4_writepage
2852                                          */
2853                                         if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2854                                                 mpage_add_bh_to_extent(mpd, logical,
2855                                                                        bh->b_size,
2856                                                                        bh->b_state);
2857                                                 if (mpd->io_done)
2858                                                         goto ret_extent_tail;
2859                                         } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2860                                                 /*
2861                                                  * mapped dirty buffer. We need
2862                                                  * to update the b_state
2863                                                  * because we look at b_state
2864                                                  * in mpage_da_map_blocks.  We
2865                                                  * don't update b_size because
2866                                                  * if we find an unmapped
2867                                                  * buffer_head later we need to
2868                                                  * use the b_state flag of that
2869                                                  * buffer_head.
2870                                                  */
2871                                                 if (mpd->b_size == 0)
2872                                                         mpd->b_state = bh->b_state & BH_FLAGS;
2873                                         }
2874                                         logical++;
2875                                 } while ((bh = bh->b_this_page) != head);
2876                         }
2877
2878                         if (nr_to_write > 0) {
2879                                 nr_to_write--;
2880                                 if (nr_to_write == 0 &&
2881                                     wbc->sync_mode == WB_SYNC_NONE)
2882                                         /*
2883                                          * We stop writing back only if we are
2884                                          * not doing integrity sync. In case of
2885                                          * integrity sync we have to keep going
2886                                          * because someone may be concurrently
2887                                          * dirtying pages, and we might have
2888                                          * synced a lot of newly appeared dirty
2889                                          * pages, but have not synced all of the
2890                                          * old dirty pages.
2891                                          */
2892                                         goto out;
2893                         }
2894                 }
2895                 pagevec_release(&pvec);
2896                 cond_resched();
2897         }
2898         return 0;
2899 ret_extent_tail:
2900         ret = MPAGE_DA_EXTENT_TAIL;
2901 out:
2902         pagevec_release(&pvec);
2903         cond_resched();
2904         return ret;
2905 }
2906
2907
2908 static int ext4_da_writepages(struct address_space *mapping,
2909                               struct writeback_control *wbc)
2910 {
2911         pgoff_t index;
2912         int range_whole = 0;
2913         handle_t *handle = NULL;
2914         struct mpage_da_data mpd;
2915         struct inode *inode = mapping->host;
2916         int pages_written = 0;
2917         unsigned int max_pages;
2918         int range_cyclic, cycled = 1, io_done = 0;
2919         int needed_blocks, ret = 0;
2920         long desired_nr_to_write, nr_to_writebump = 0;
2921         loff_t range_start = wbc->range_start;
2922         struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2923         pgoff_t done_index = 0;
2924         pgoff_t end;
2925
2926         trace_ext4_da_writepages(inode, wbc);
2927
2928         /*
2929          * No pages to write? This is mainly a kludge to avoid starting
2930          * a transaction for special inodes like journal inode on last iput()
2931          * because that could violate lock ordering on umount
2932          */
2933         if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2934                 return 0;
2935
2936         /*
2937          * If the filesystem has aborted, it is read-only, so return
2938          * right away instead of dumping stack traces later on that
2939          * will obscure the real source of the problem.  We test
2940          * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2941          * the latter could be true if the filesystem is mounted
2942          * read-only, and in that case, ext4_da_writepages should
2943          * *never* be called, so if that ever happens, we would want
2944          * the stack trace.
2945          */
2946         if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2947                 return -EROFS;
2948
2949         if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2950                 range_whole = 1;
2951
2952         range_cyclic = wbc->range_cyclic;
2953         if (wbc->range_cyclic) {
2954                 index = mapping->writeback_index;
2955                 if (index)
2956                         cycled = 0;
2957                 wbc->range_start = index << PAGE_CACHE_SHIFT;
2958                 wbc->range_end  = LLONG_MAX;
2959                 wbc->range_cyclic = 0;
2960                 end = -1;
2961         } else {
2962                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2963                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2964         }
2965
2966         /*
2967          * This works around two forms of stupidity.  The first is in
2968          * the writeback code, which caps the maximum number of pages
2969          * written to be 1024 pages.  This is wrong on multiple
2970          * levels; different architectues have a different page size,
2971          * which changes the maximum amount of data which gets
2972          * written.  Secondly, 4 megabytes is way too small.  XFS
2973          * forces this value to be 16 megabytes by multiplying
2974          * nr_to_write parameter by four, and then relies on its
2975          * allocator to allocate larger extents to make them
2976          * contiguous.  Unfortunately this brings us to the second
2977          * stupidity, which is that ext4's mballoc code only allocates
2978          * at most 2048 blocks.  So we force contiguous writes up to
2979          * the number of dirty blocks in the inode, or
2980          * sbi->max_writeback_mb_bump whichever is smaller.
2981          */
2982         max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2983         if (!range_cyclic && range_whole) {
2984                 if (wbc->nr_to_write == LONG_MAX)
2985                         desired_nr_to_write = wbc->nr_to_write;
2986                 else
2987                         desired_nr_to_write = wbc->nr_to_write * 8;
2988         } else
2989                 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2990                                                            max_pages);
2991         if (desired_nr_to_write > max_pages)
2992                 desired_nr_to_write = max_pages;
2993
2994         if (wbc->nr_to_write < desired_nr_to_write) {
2995                 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2996                 wbc->nr_to_write = desired_nr_to_write;
2997         }
2998
2999 retry:
3000         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3001                 tag_pages_for_writeback(mapping, index, end);
3002
3003         while (!ret && wbc->nr_to_write > 0) {
3004
3005                 /*
3006                  * we  insert one extent at a time. So we need
3007                  * credit needed for single extent allocation.
3008                  * journalled mode is currently not supported
3009                  * by delalloc
3010                  */
3011                 BUG_ON(ext4_should_journal_data(inode));
3012                 needed_blocks = ext4_da_writepages_trans_blocks(inode);
3013
3014                 /* start a new transaction*/
3015                 handle = ext4_journal_start(inode, needed_blocks);
3016                 if (IS_ERR(handle)) {
3017                         ret = PTR_ERR(handle);
3018                         ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
3019                                "%ld pages, ino %lu; err %d", __func__,
3020                                 wbc->nr_to_write, inode->i_ino, ret);
3021                         goto out_writepages;
3022                 }
3023
3024                 /*
3025                  * Now call write_cache_pages_da() to find the next
3026                  * contiguous region of logical blocks that need
3027                  * blocks to be allocated by ext4 and submit them.
3028                  */
3029                 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
3030                 /*
3031                  * If we have a contiguous extent of pages and we
3032                  * haven't done the I/O yet, map the blocks and submit
3033                  * them for I/O.
3034                  */
3035                 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
3036                         mpage_da_map_and_submit(&mpd);
3037                         ret = MPAGE_DA_EXTENT_TAIL;
3038                 }
3039                 trace_ext4_da_write_pages(inode, &mpd);
3040                 wbc->nr_to_write -= mpd.pages_written;
3041
3042                 ext4_journal_stop(handle);
3043
3044                 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
3045                         /* commit the transaction which would
3046                          * free blocks released in the transaction
3047                          * and try again
3048                          */
3049                         jbd2_journal_force_commit_nested(sbi->s_journal);
3050                         ret = 0;
3051                 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
3052                         /*
3053                          * got one extent now try with
3054                          * rest of the pages
3055                          */
3056                         pages_written += mpd.pages_written;
3057                         ret = 0;
3058                         io_done = 1;
3059                 } else if (wbc->nr_to_write)
3060                         /*
3061                          * There is no more writeout needed
3062                          * or we requested for a noblocking writeout
3063                          * and we found the device congested
3064                          */
3065                         break;
3066         }
3067         if (!io_done && !cycled) {
3068                 cycled = 1;
3069                 index = 0;
3070                 wbc->range_start = index << PAGE_CACHE_SHIFT;
3071                 wbc->range_end  = mapping->writeback_index - 1;
3072                 goto retry;
3073         }
3074
3075         /* Update index */
3076         wbc->range_cyclic = range_cyclic;
3077         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3078                 /*
3079                  * set the writeback_index so that range_cyclic
3080                  * mode will write it back later
3081                  */
3082                 mapping->writeback_index = done_index;
3083
3084 out_writepages:
3085         wbc->nr_to_write -= nr_to_writebump;
3086         wbc->range_start = range_start;
3087         trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
3088         return ret;
3089 }
3090
3091 #define FALL_BACK_TO_NONDELALLOC 1
3092 static int ext4_nonda_switch(struct super_block *sb)
3093 {
3094         s64 free_blocks, dirty_blocks;
3095         struct ext4_sb_info *sbi = EXT4_SB(sb);
3096
3097         /*
3098          * switch to non delalloc mode if we are running low
3099          * on free block. The free block accounting via percpu
3100          * counters can get slightly wrong with percpu_counter_batch getting
3101          * accumulated on each CPU without updating global counters
3102          * Delalloc need an accurate free block accounting. So switch
3103          * to non delalloc when we are near to error range.
3104          */
3105         free_blocks  = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
3106         dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
3107         if (2 * free_blocks < 3 * dirty_blocks ||
3108                 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
3109                 /*
3110                  * free block count is less than 150% of dirty blocks
3111                  * or free blocks is less than watermark
3112                  */
3113                 return 1;
3114         }
3115         /*
3116          * Even if we don't switch but are nearing capacity,
3117          * start pushing delalloc when 1/2 of free blocks are dirty.
3118          */
3119         if (free_blocks < 2 * dirty_blocks)
3120                 writeback_inodes_sb_if_idle(sb);
3121
3122         return 0;
3123 }
3124
3125 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3126                                loff_t pos, unsigned len, unsigned flags,
3127                                struct page **pagep, void **fsdata)
3128 {
3129         int ret, retries = 0;
3130         struct page *page;
3131         pgoff_t index;
3132         struct inode *inode = mapping->host;
3133         handle_t *handle;
3134
3135         index = pos >> PAGE_CACHE_SHIFT;
3136
3137         if (ext4_nonda_switch(inode->i_sb)) {
3138                 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3139                 return ext4_write_begin(file, mapping, pos,
3140                                         len, flags, pagep, fsdata);
3141         }
3142         *fsdata = (void *)0;
3143         trace_ext4_da_write_begin(inode, pos, len, flags);
3144 retry:
3145         /*
3146          * With delayed allocation, we don't log the i_disksize update
3147          * if there is delayed block allocation. But we still need
3148          * to journalling the i_disksize update if writes to the end
3149          * of file which has an already mapped buffer.
3150          */
3151         handle = ext4_journal_start(inode, 1);
3152         if (IS_ERR(handle)) {
3153                 ret = PTR_ERR(handle);
3154                 goto out;
3155         }
3156         /* We cannot recurse into the filesystem as the transaction is already
3157          * started */
3158         flags |= AOP_FLAG_NOFS;
3159
3160         page = grab_cache_page_write_begin(mapping, index, flags);
3161         if (!page) {
3162                 ext4_journal_stop(handle);
3163                 ret = -ENOMEM;
3164                 goto out;
3165         }
3166         *pagep = page;
3167
3168         ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3169         if (ret < 0) {
3170                 unlock_page(page);
3171                 ext4_journal_stop(handle);
3172                 page_cache_release(page);
3173                 /*
3174                  * block_write_begin may have instantiated a few blocks
3175                  * outside i_size.  Trim these off again. Don't need
3176                  * i_size_read because we hold i_mutex.
3177                  */
3178                 if (pos + len > inode->i_size)
3179                         ext4_truncate_failed_write(inode);
3180         }
3181
3182         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3183                 goto retry;
3184 out:
3185         return ret;
3186 }
3187
3188 /*
3189  * Check if we should update i_disksize
3190  * when write to the end of file but not require block allocation
3191  */
3192 static int ext4_da_should_update_i_disksize(struct page *page,
3193                                             unsigned long offset)
3194 {
3195         struct buffer_head *bh;
3196         struct inode *inode = page->mapping->host;
3197         unsigned int idx;
3198         int i;
3199
3200         bh = page_buffers(page);
3201         idx = offset >> inode->i_blkbits;
3202
3203         for (i = 0; i < idx; i++)
3204                 bh = bh->b_this_page;
3205
3206         if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3207                 return 0;
3208         return 1;
3209 }
3210
3211 static int ext4_da_write_end(struct file *file,
3212                              struct address_space *mapping,
3213                              loff_t pos, unsigned len, unsigned copied,
3214                              struct page *page, void *fsdata)
3215 {
3216         struct inode *inode = mapping->host;
3217         int ret = 0, ret2;
3218         handle_t *handle = ext4_journal_current_handle();
3219         loff_t new_i_size;
3220         unsigned long start, end;
3221         int write_mode = (int)(unsigned long)fsdata;
3222
3223         if (write_mode == FALL_BACK_TO_NONDELALLOC) {
3224                 switch (ext4_inode_journal_mode(inode)) {
3225                 case EXT4_INODE_ORDERED_DATA_MODE:
3226                         return ext4_ordered_write_end(file, mapping, pos,
3227                                         len, copied, page, fsdata);
3228                 case EXT4_INODE_WRITEBACK_DATA_MODE:
3229                         return ext4_writeback_write_end(file, mapping, pos,
3230                                         len, copied, page, fsdata);
3231                 default:
3232                         BUG();
3233                 }
3234         }
3235
3236         trace_ext4_da_write_end(inode, pos, len, copied);
3237         start = pos & (PAGE_CACHE_SIZE - 1);
3238         end = start + copied - 1;
3239
3240         /*
3241          * generic_write_end() will run mark_inode_dirty() if i_size
3242          * changes.  So let's piggyback the i_disksize mark_inode_dirty
3243          * into that.
3244          */
3245
3246         new_i_size = pos + copied;
3247         if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3248                 if (ext4_da_should_update_i_disksize(page, end)) {
3249                         down_write(&EXT4_I(inode)->i_data_sem);
3250                         if (new_i_size > EXT4_I(inode)->i_disksize) {
3251                                 /*
3252                                  * Updating i_disksize when extending file
3253                                  * without needing block allocation
3254                                  */
3255                                 if (ext4_should_order_data(inode))
3256                                         ret = ext4_jbd2_file_inode(handle,
3257                                                                    inode);
3258
3259                                 EXT4_I(inode)->i_disksize = new_i_size;
3260                         }
3261                         up_write(&EXT4_I(inode)->i_data_sem);
3262                         /* We need to mark inode dirty even if
3263                          * new_i_size is less that inode->i_size
3264                          * bu greater than i_disksize.(hint delalloc)
3265                          */
3266                         ext4_mark_inode_dirty(handle, inode);
3267                 }
3268         }
3269         ret2 = generic_write_end(file, mapping, pos, len, copied,
3270                                                         page, fsdata);
3271         copied = ret2;
3272         if (ret2 < 0)
3273                 ret = ret2;
3274         ret2 = ext4_journal_stop(handle);
3275         if (!ret)
3276                 ret = ret2;
3277
3278         return ret ? ret : copied;
3279 }
3280
3281 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3282 {
3283         /*
3284          * Drop reserved blocks
3285          */
3286         BUG_ON(!PageLocked(page));
3287         if (!page_has_buffers(page))
3288                 goto out;
3289
3290         ext4_da_page_release_reservation(page, offset);
3291
3292 out:
3293         ext4_invalidatepage(page, offset);
3294
3295         return;
3296 }
3297
3298 /*
3299  * Force all delayed allocation blocks to be allocated for a given inode.
3300  */
3301 int ext4_alloc_da_blocks(struct inode *inode)
3302 {
3303         trace_ext4_alloc_da_blocks(inode);
3304
3305         if (!EXT4_I(inode)->i_reserved_data_blocks &&
3306             !EXT4_I(inode)->i_reserved_meta_blocks)
3307                 return 0;
3308
3309         /*
3310          * We do something simple for now.  The filemap_flush() will
3311          * also start triggering a write of the data blocks, which is
3312          * not strictly speaking necessary (and for users of
3313          * laptop_mode, not even desirable).  However, to do otherwise
3314          * would require replicating code paths in:
3315          *
3316          * ext4_da_writepages() ->
3317          *    write_cache_pages() ---> (via passed in callback function)
3318          *        __mpage_da_writepage() -->
3319          *           mpage_add_bh_to_extent()
3320          *           mpage_da_map_blocks()
3321          *
3322          * The problem is that write_cache_pages(), located in
3323          * mm/page-writeback.c, marks pages clean in preparation for
3324          * doing I/O, which is not desirable if we're not planning on
3325          * doing I/O at all.
3326          *
3327          * We could call write_cache_pages(), and then redirty all of
3328          * the pages by calling redirty_page_for_writepage() but that
3329          * would be ugly in the extreme.  So instead we would need to
3330          * replicate parts of the code in the above functions,
3331          * simplifying them because we wouldn't actually intend to
3332          * write out the pages, but rather only collect contiguous
3333          * logical block extents, call the multi-block allocator, and
3334          * then update the buffer heads with the block allocations.
3335          *
3336          * For now, though, we'll cheat by calling filemap_flush(),
3337          * which will map the blocks, and start the I/O, but not
3338          * actually wait for the I/O to complete.
3339          */
3340         return filemap_flush(inode->i_mapping);
3341 }
3342
3343 /*
3344  * bmap() is special.  It gets used by applications such as lilo and by
3345  * the swapper to find the on-disk block of a specific piece of data.
3346  *
3347  * Naturally, this is dangerous if the block concerned is still in the
3348  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3349  * filesystem and enables swap, then they may get a nasty shock when the
3350  * data getting swapped to that swapfile suddenly gets overwritten by
3351  * the original zero's written out previously to the journal and
3352  * awaiting writeback in the kernel's buffer cache.
3353  *
3354  * So, if we see any bmap calls here on a modified, data-journaled file,
3355  * take extra steps to flush any blocks which might be in the cache.
3356  */
3357 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3358 {
3359         struct inode *inode = mapping->host;
3360         journal_t *journal;
3361         int err;
3362
3363         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3364                         test_opt(inode->i_sb, DELALLOC)) {
3365                 /*
3366                  * With delalloc we want to sync the file
3367                  * so that we can make sure we allocate
3368                  * blocks for file
3369                  */
3370                 filemap_write_and_wait(mapping);
3371         }
3372
3373         if (EXT4_JOURNAL(inode) &&
3374             ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3375                 /*
3376                  * This is a REALLY heavyweight approach, but the use of
3377                  * bmap on dirty files is expected to be extremely rare:
3378                  * only if we run lilo or swapon on a freshly made file
3379                  * do we expect this to happen.
3380                  *
3381                  * (bmap requires CAP_SYS_RAWIO so this does not
3382                  * represent an unprivileged user DOS attack --- we'd be
3383                  * in trouble if mortal users could trigger this path at
3384                  * will.)
3385                  *
3386                  * NB. EXT4_STATE_JDATA is not set on files other than
3387                  * regular files.  If somebody wants to bmap a directory
3388                  * or symlink and gets confused because the buffer
3389                  * hasn't yet been flushed to disk, they deserve
3390                  * everything they get.
3391                  */
3392
3393                 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3394                 journal = EXT4_JOURNAL(inode);
3395                 jbd2_journal_lock_updates(journal);
3396                 err = jbd2_journal_flush(journal);
3397                 jbd2_journal_unlock_updates(journal);
3398
3399                 if (err)
3400                         return 0;
3401         }
3402
3403         return generic_block_bmap(mapping, block, ext4_get_block);
3404 }
3405
3406 static int ext4_readpage(struct file *file, struct page *page)
3407 {
3408         trace_ext4_readpage(page);
3409         return mpage_readpage(page, ext4_get_block);
3410 }
3411
3412 static int
3413 ext4_readpages(struct file *file, struct address_space *mapping,
3414                 struct list_head *pages, unsigned nr_pages)
3415 {
3416         return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3417 }
3418
3419 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
3420 {
3421         struct buffer_head *head, *bh;
3422         unsigned int curr_off = 0;
3423
3424         if (!page_has_buffers(page))
3425                 return;
3426         head = bh = page_buffers(page);
3427         do {
3428                 if (offset <= curr_off && test_clear_buffer_uninit(bh)
3429                                         && bh->b_private) {
3430                         ext4_free_io_end(bh->b_private);
3431                         bh->b_private = NULL;
3432                         bh->b_end_io = NULL;
3433                 }
3434                 curr_off = curr_off + bh->b_size;
3435                 bh = bh->b_this_page;
3436         } while (bh != head);
3437 }
3438
3439 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3440 {
3441         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3442
3443         trace_ext4_invalidatepage(page, offset);
3444
3445         /*
3446          * free any io_end structure allocated for buffers to be discarded
3447          */
3448         if (ext4_should_dioread_nolock(page->mapping->host))
3449                 ext4_invalidatepage_free_endio(page, offset);
3450         /*
3451          * If it's a full truncate we just forget about the pending dirtying
3452          */
3453         if (offset == 0)
3454                 ClearPageChecked(page);
3455
3456         if (journal)
3457                 jbd2_journal_invalidatepage(journal, page, offset);
3458         else
3459                 block_invalidatepage(page, offset);
3460 }
3461
3462 static int ext4_releasepage(struct page *page, gfp_t wait)
3463 {
3464         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3465
3466         trace_ext4_releasepage(page);
3467
3468         WARN_ON(PageChecked(page));
3469         if (!page_has_buffers(page))
3470                 return 0;
3471         if (journal)
3472                 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3473         else
3474                 return try_to_free_buffers(page);
3475 }
3476
3477 /*
3478  * O_DIRECT for ext3 (or indirect map) based files
3479  *
3480  * If the O_DIRECT write will extend the file then add this inode to the
3481  * orphan list.  So recovery will truncate it back to the original size
3482  * if the machine crashes during the write.
3483  *
3484  * If the O_DIRECT write is intantiating holes inside i_size and the machine
3485  * crashes then stale disk data _may_ be exposed inside the file. But current
3486  * VFS code falls back into buffered path in that case so we are safe.
3487  */
3488 static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3489                               const struct iovec *iov, loff_t offset,
3490                               unsigned long nr_segs)
3491 {
3492         struct file *file = iocb->ki_filp;
3493         struct inode *inode = file->f_mapping->host;
3494         struct ext4_inode_info *ei = EXT4_I(inode);
3495         handle_t *handle;
3496         ssize_t ret;
3497         int orphan = 0;
3498         size_t count = iov_length(iov, nr_segs);
3499         int retries = 0;
3500
3501         if (rw == WRITE) {
3502                 loff_t final_size = offset + count;
3503
3504                 if (final_size > inode->i_size) {
3505                         /* Credits for sb + inode write */
3506                         handle = ext4_journal_start(inode, 2);
3507                         if (IS_ERR(handle)) {
3508                                 ret = PTR_ERR(handle);
3509                                 goto out;
3510                         }
3511                         ret = ext4_orphan_add(handle, inode);
3512                         if (ret) {
3513                                 ext4_journal_stop(handle);
3514                                 goto out;
3515                         }
3516                         orphan = 1;
3517                         ei->i_disksize = inode->i_size;
3518                         ext4_journal_stop(handle);
3519                 }
3520         }
3521
3522 retry:
3523         if (rw == READ && ext4_should_dioread_nolock(inode)) {
3524                 if (unlikely(!list_empty(&ei->i_completed_io_list))) {
3525                         mutex_lock(&inode->i_mutex);
3526                         ext4_flush_completed_IO(inode);
3527                         mutex_unlock(&inode->i_mutex);
3528                 }
3529                 ret = __blockdev_direct_IO(rw, iocb, inode,
3530                                  inode->i_sb->s_bdev, iov,
3531                                  offset, nr_segs,
3532                                  ext4_get_block, NULL, NULL, 0);
3533         } else {
3534                 ret = blockdev_direct_IO(rw, iocb, inode,
3535                                  inode->i_sb->s_bdev, iov,
3536                                  offset, nr_segs,
3537                                  ext4_get_block, NULL);
3538
3539                 if (unlikely((rw & WRITE) && ret < 0)) {
3540                         loff_t isize = i_size_read(inode);
3541                         loff_t end = offset + iov_length(iov, nr_segs);
3542
3543                         if (end > isize)
3544                                 ext4_truncate_failed_write(inode);
3545                 }
3546         }
3547         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3548                 goto retry;
3549
3550         if (orphan) {
3551                 int err;
3552
3553                 /* Credits for sb + inode write */
3554                 handle = ext4_journal_start(inode, 2);
3555                 if (IS_ERR(handle)) {
3556                         /* This is really bad luck. We've written the data
3557                          * but cannot extend i_size. Bail out and pretend
3558                          * the write failed... */
3559                         ret = PTR_ERR(handle);
3560                         if (inode->i_nlink)
3561                                 ext4_orphan_del(NULL, inode);
3562
3563                         goto out;
3564                 }
3565                 if (inode->i_nlink)
3566                         ext4_orphan_del(handle, inode);
3567                 if (ret > 0) {
3568                         loff_t end = offset + ret;
3569                         if (end > inode->i_size) {
3570                                 ei->i_disksize = end;
3571                                 i_size_write(inode, end);
3572                                 /*
3573                                  * We're going to return a positive `ret'
3574                                  * here due to non-zero-length I/O, so there's
3575                                  * no way of reporting error returns from
3576                                  * ext4_mark_inode_dirty() to userspace.  So
3577                                  * ignore it.
3578                                  */
3579                                 ext4_mark_inode_dirty(handle, inode);
3580                         }
3581                 }
3582                 err = ext4_journal_stop(handle);
3583                 if (ret == 0)
3584                         ret = err;
3585         }
3586 out:
3587         return ret;
3588 }
3589
3590 /*
3591  * ext4_get_block used when preparing for a DIO write or buffer write.
3592  * We allocate an uinitialized extent if blocks haven't been allocated.
3593  * The extent will be converted to initialized after the IO is complete.
3594  */
3595 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
3596                    struct buffer_head *bh_result, int create)
3597 {
3598         ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3599                    inode->i_ino, create);
3600         return _ext4_get_block(inode, iblock, bh_result,
3601                                EXT4_GET_BLOCKS_IO_CREATE_EXT);
3602 }
3603
3604 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3605                             ssize_t size, void *private, int ret,
3606                             bool is_async)
3607 {
3608         ext4_io_end_t *io_end = iocb->private;
3609         struct workqueue_struct *wq;
3610         unsigned long flags;
3611         struct ext4_inode_info *ei;
3612
3613         /* if not async direct IO or dio with 0 bytes write, just return */
3614         if (!io_end || !size)
3615                 goto out;
3616
3617         ext_debug("ext4_end_io_dio(): io_end 0x%p"
3618                   "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
3619                   iocb->private, io_end->inode->i_ino, iocb, offset,
3620                   size);
3621
3622         /* if not aio dio with unwritten extents, just free io and return */
3623         if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3624                 ext4_free_io_end(io_end);
3625                 iocb->private = NULL;
3626 out:
3627                 if (is_async)
3628                         aio_complete(iocb, ret, 0);
3629                 return;
3630         }
3631
3632         io_end->offset = offset;
3633         io_end->size = size;
3634         if (is_async) {
3635                 io_end->iocb = iocb;
3636                 io_end->result = ret;
3637         }
3638         wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
3639
3640         /* Add the io_end to per-inode completed aio dio list*/
3641         ei = EXT4_I(io_end->inode);
3642         spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3643         list_add_tail(&io_end->list, &ei->i_completed_io_list);
3644         spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3645
3646         /* queue the work to convert unwritten extents to written */
3647         queue_work(wq, &io_end->work);
3648         iocb->private = NULL;
3649 }
3650
3651 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
3652 {
3653         ext4_io_end_t *io_end = bh->b_private;
3654         struct workqueue_struct *wq;
3655         struct inode *inode;
3656         unsigned long flags;
3657
3658         if (!test_clear_buffer_uninit(bh) || !io_end)
3659                 goto out;
3660
3661         if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
3662                 printk("sb umounted, discard end_io request for inode %lu\n",
3663                         io_end->inode->i_ino);
3664                 ext4_free_io_end(io_end);
3665                 goto out;
3666         }
3667
3668         /*
3669          * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
3670          * but being more careful is always safe for the future change.
3671          */
3672         inode = io_end->inode;
3673         if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3674                 io_end->flag |= EXT4_IO_END_UNWRITTEN;
3675                 atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3676         }
3677
3678         /* Add the io_end to per-inode completed io list*/
3679         spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3680         list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
3681         spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
3682
3683         wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
3684         /* queue the work to convert unwritten extents to written */
3685         queue_work(wq, &io_end->work);
3686 out:
3687         bh->b_private = NULL;
3688         bh->b_end_io = NULL;
3689         clear_buffer_uninit(bh);
3690         end_buffer_async_write(bh, uptodate);
3691 }
3692
3693 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
3694 {
3695         ext4_io_end_t *io_end;
3696         struct page *page = bh->b_page;
3697         loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
3698         size_t size = bh->b_size;
3699
3700 retry:
3701         io_end = ext4_init_io_end(inode, GFP_ATOMIC);
3702         if (!io_end) {
3703                 pr_warn_ratelimited("%s: allocation fail\n", __func__);
3704                 schedule();
3705                 goto retry;
3706         }
3707         io_end->offset = offset;
3708         io_end->size = size;
3709         /*
3710          * We need to hold a reference to the page to make sure it
3711          * doesn't get evicted before ext4_end_io_work() has a chance
3712          * to convert the extent from written to unwritten.
3713          */
3714         io_end->page = page;
3715         get_page(io_end->page);
3716
3717         bh->b_private = io_end;
3718         bh->b_end_io = ext4_end_io_buffer_write;
3719         return 0;
3720 }
3721
3722 /*
3723  * For ext4 extent files, ext4 will do direct-io write to holes,
3724  * preallocated extents, and those write extend the file, no need to
3725  * fall back to buffered IO.
3726  *
3727  * For holes, we fallocate those blocks, mark them as uninitialized
3728  * If those blocks were preallocated, we mark sure they are splited, but
3729  * still keep the range to write as uninitialized.
3730  *
3731  * The unwrritten extents will be converted to written when DIO is completed.
3732  * For async direct IO, since the IO may still pending when return, we
3733  * set up an end_io call back function, which will do the conversion
3734  * when async direct IO completed.
3735  *
3736  * If the O_DIRECT write will extend the file then add this inode to the
3737  * orphan list.  So recovery will truncate it back to the original size
3738  * if the machine crashes during the write.
3739  *
3740  */
3741 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3742                               const struct iovec *iov, loff_t offset,
3743                               unsigned long nr_segs)
3744 {
3745         struct file *file = iocb->ki_filp;
3746         struct inode *inode = file->f_mapping->host;
3747         ssize_t ret;
3748         size_t count = iov_length(iov, nr_segs);
3749
3750         loff_t final_size = offset + count;
3751         if (rw == WRITE && final_size <= inode->i_size) {
3752                 /*
3753                  * We could direct write to holes and fallocate.
3754                  *
3755                  * Allocated blocks to fill the hole are marked as uninitialized
3756                  * to prevent parallel buffered read to expose the stale data
3757                  * before DIO complete the data IO.
3758                  *
3759                  * As to previously fallocated extents, ext4 get_block
3760                  * will just simply mark the buffer mapped but still
3761                  * keep the extents uninitialized.
3762                  *
3763                  * for non AIO case, we will convert those unwritten extents
3764                  * to written after return back from blockdev_direct_IO.
3765                  *
3766                  * for async DIO, the conversion needs to be defered when
3767                  * the IO is completed. The ext4 end_io callback function
3768                  * will be called to take care of the conversion work.
3769                  * Here for async case, we allocate an io_end structure to
3770                  * hook to the iocb.
3771                  */
3772                 iocb->private = NULL;
3773                 EXT4_I(inode)->cur_aio_dio = NULL;
3774                 if (!is_sync_kiocb(iocb)) {
3775                         iocb->private = ext4_init_io_end(inode, GFP_NOFS);
3776                         if (!iocb->private)
3777                                 return -ENOMEM;
3778                         /*
3779                          * we save the io structure for current async
3780                          * direct IO, so that later ext4_map_blocks()
3781                          * could flag the io structure whether there
3782                          * is a unwritten extents needs to be converted
3783                          * when IO is completed.
3784                          */
3785                         EXT4_I(inode)->cur_aio_dio = iocb->private;
3786                 }
3787
3788                 ret = blockdev_direct_IO(rw, iocb, inode,
3789                                          inode->i_sb->s_bdev, iov,
3790                                          offset, nr_segs,
3791                                          ext4_get_block_write,
3792                                          ext4_end_io_dio);
3793                 if (iocb->private)
3794                         EXT4_I(inode)->cur_aio_dio = NULL;
3795                 /*
3796                  * The io_end structure takes a reference to the inode,
3797                  * that structure needs to be destroyed and the
3798                  * reference to the inode need to be dropped, when IO is
3799                  * complete, even with 0 byte write, or failed.
3800                  *
3801                  * In the successful AIO DIO case, the io_end structure will be
3802                  * desctroyed and the reference to the inode will be dropped
3803                  * after the end_io call back function is called.
3804                  *
3805                  * In the case there is 0 byte write, or error case, since
3806                  * VFS direct IO won't invoke the end_io call back function,
3807                  * we need to free the end_io structure here.
3808                  */
3809                 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3810                         ext4_free_io_end(iocb->private);
3811                         iocb->private = NULL;
3812                 } else if (ret > 0 && ext4_test_inode_state(inode,
3813                                                 EXT4_STATE_DIO_UNWRITTEN)) {
3814                         int err;
3815                         /*
3816                          * for non AIO case, since the IO is already
3817                          * completed, we could do the conversion right here
3818                          */
3819                         err = ext4_convert_unwritten_extents(inode,
3820                                                              offset, ret);
3821                         if (err < 0)
3822                                 ret = err;
3823                         ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3824                 }
3825                 return ret;
3826         }
3827
3828         /* for write the the end of file case, we fall back to old way */
3829         return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3830 }
3831
3832 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3833                               const struct iovec *iov, loff_t offset,
3834                               unsigned long nr_segs)
3835 {
3836         struct file *file = iocb->ki_filp;
3837         struct inode *inode = file->f_mapping->host;
3838         ssize_t ret;
3839
3840         trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3841         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3842                 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3843         else
3844                 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3845         trace_ext4_direct_IO_exit(inode, offset,
3846                                 iov_length(iov, nr_segs), rw, ret);
3847         return ret;
3848 }
3849
3850 /*
3851  * Pages can be marked dirty completely asynchronously from ext4's journalling
3852  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3853  * much here because ->set_page_dirty is called under VFS locks.  The page is
3854  * not necessarily locked.
3855  *
3856  * We cannot just dirty the page and leave attached buffers clean, because the
3857  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3858  * or jbddirty because all the journalling code will explode.
3859  *
3860  * So what we do is to mark the page "pending dirty" and next time writepage
3861  * is called, propagate that into the buffers appropriately.
3862  */
3863 static int ext4_journalled_set_page_dirty(struct page *page)
3864 {
3865         SetPageChecked(page);
3866         return __set_page_dirty_nobuffers(page);
3867 }
3868
3869 static const struct address_space_operations ext4_ordered_aops = {
3870         .readpage               = ext4_readpage,
3871         .readpages              = ext4_readpages,
3872         .writepage              = ext4_writepage,
3873         .write_begin            = ext4_write_begin,
3874         .write_end              = ext4_ordered_write_end,
3875         .bmap                   = ext4_bmap,
3876         .invalidatepage         = ext4_invalidatepage,
3877         .releasepage            = ext4_releasepage,
3878         .direct_IO              = ext4_direct_IO,
3879         .migratepage            = buffer_migrate_page,
3880         .is_partially_uptodate  = block_is_partially_uptodate,
3881         .error_remove_page      = generic_error_remove_page,
3882 };
3883
3884 static const struct address_space_operations ext4_writeback_aops = {
3885         .readpage               = ext4_readpage,
3886         .readpages              = ext4_readpages,
3887         .writepage              = ext4_writepage,
3888         .write_begin            = ext4_write_begin,
3889         .write_end              = ext4_writeback_write_end,
3890         .bmap                   = ext4_bmap,
3891         .invalidatepage         = ext4_invalidatepage,
3892         .releasepage            = ext4_releasepage,
3893         .direct_IO              = ext4_direct_IO,
3894         .migratepage            = buffer_migrate_page,
3895         .is_partially_uptodate  = block_is_partially_uptodate,
3896         .error_remove_page      = generic_error_remove_page,
3897 };
3898
3899 static const struct address_space_operations ext4_journalled_aops = {
3900         .readpage               = ext4_readpage,
3901         .readpages              = ext4_readpages,
3902         .writepage              = ext4_writepage,
3903         .write_begin            = ext4_write_begin,
3904         .write_end              = ext4_journalled_write_end,
3905         .set_page_dirty         = ext4_journalled_set_page_dirty,
3906         .bmap                   = ext4_bmap,
3907         .invalidatepage         = ext4_invalidatepage,
3908         .releasepage            = ext4_releasepage,
3909         .is_partially_uptodate  = block_is_partially_uptodate,
3910         .error_remove_page      = generic_error_remove_page,
3911 };
3912
3913 static const struct address_space_operations ext4_da_aops = {
3914         .readpage               = ext4_readpage,
3915         .readpages              = ext4_readpages,
3916         .writepage              = ext4_writepage,
3917         .writepages             = ext4_da_writepages,
3918         .write_begin            = ext4_da_write_begin,
3919         .write_end              = ext4_da_write_end,
3920         .bmap                   = ext4_bmap,
3921         .invalidatepage         = ext4_da_invalidatepage,
3922         .releasepage            = ext4_releasepage,
3923         .direct_IO              = ext4_direct_IO,
3924         .migratepage            = buffer_migrate_page,
3925         .is_partially_uptodate  = block_is_partially_uptodate,
3926         .error_remove_page      = generic_error_remove_page,
3927 };
3928
3929 void ext4_set_aops(struct inode *inode)
3930 {
3931         switch (ext4_inode_journal_mode(inode)) {
3932         case EXT4_INODE_ORDERED_DATA_MODE:
3933                 if (test_opt(inode->i_sb, DELALLOC))
3934                         inode->i_mapping->a_ops = &ext4_da_aops;
3935                 else
3936                         inode->i_mapping->a_ops = &ext4_ordered_aops;
3937                 break;
3938         case EXT4_INODE_WRITEBACK_DATA_MODE:
3939                 if (test_opt(inode->i_sb, DELALLOC))
3940                         inode->i_mapping->a_ops = &ext4_da_aops;
3941                 else
3942                         inode->i_mapping->a_ops = &ext4_writeback_aops;
3943                 break;
3944         case EXT4_INODE_JOURNAL_DATA_MODE:
3945                 inode->i_mapping->a_ops = &ext4_journalled_aops;
3946                 break;
3947         default:
3948                 BUG();
3949         }
3950 }
3951
3952 /*
3953  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3954  * up to the end of the block which corresponds to `from'.
3955  * This required during truncate. We need to physically zero the tail end
3956  * of that block so it doesn't yield old data if the file is later grown.
3957  */
3958 int ext4_block_truncate_page(handle_t *handle,
3959                 struct address_space *mapping, loff_t from)
3960 {
3961         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3962         unsigned length;
3963         unsigned blocksize;
3964         struct inode *inode = mapping->host;
3965
3966         blocksize = inode->i_sb->s_blocksize;
3967         length = blocksize - (offset & (blocksize - 1));
3968
3969         return ext4_block_zero_page_range(handle, mapping, from, length);
3970 }
3971
3972 /*
3973  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3974  * starting from file offset 'from'.  The range to be zero'd must
3975  * be contained with in one block.  If the specified range exceeds
3976  * the end of the block it will be shortened to end of the block
3977  * that cooresponds to 'from'
3978  */
3979 int ext4_block_zero_page_range(handle_t *handle,
3980                 struct address_space *mapping, loff_t from, loff_t length)
3981 {
3982         ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3983         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3984         unsigned blocksize, max, pos;
3985         ext4_lblk_t iblock;
3986         struct inode *inode = mapping->host;
3987         struct buffer_head *bh;
3988         struct page *page;
3989         int err = 0;
3990
3991         page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3992                                    mapping_gfp_mask(mapping) & ~__GFP_FS);
3993         if (!page)
3994                 return -EINVAL;
3995
3996         blocksize = inode->i_sb->s_blocksize;
3997         max = blocksize - (offset & (blocksize - 1));
3998
3999         /*
4000          * correct length if it does not fall between
4001          * 'from' and the end of the block
4002          */
4003         if (length > max || length < 0)
4004                 length = max;
4005
4006         iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
4007
4008         if (!page_has_buffers(page))
4009                 create_empty_buffers(page, blocksize, 0);
4010
4011         /* Find the buffer that contains "offset" */
4012         bh = page_buffers(page);
4013         pos = blocksize;
4014         while (offset >= pos) {
4015                 bh = bh->b_this_page;
4016                 iblock++;
4017                 pos += blocksize;
4018         }
4019
4020         err = 0;
4021         if (buffer_freed(bh)) {
4022                 BUFFER_TRACE(bh, "freed: skip");
4023                 goto unlock;
4024         }
4025
4026         if (!buffer_mapped(bh)) {
4027                 BUFFER_TRACE(bh, "unmapped");
4028                 ext4_get_block(inode, iblock, bh, 0);
4029                 /* unmapped? It's a hole - nothing to do */
4030                 if (!buffer_mapped(bh)) {
4031                         BUFFER_TRACE(bh, "still unmapped");
4032                         goto unlock;
4033                 }
4034         }
4035
4036         /* Ok, it's mapped. Make sure it's up-to-date */
4037         if (PageUptodate(page))
4038                 set_buffer_uptodate(bh);
4039
4040         if (!buffer_uptodate(bh)) {
4041                 err = -EIO;
4042                 ll_rw_block(READ, 1, &bh);
4043                 wait_on_buffer(bh);
4044                 /* Uhhuh. Read error. Complain and punt. */
4045                 if (!buffer_uptodate(bh))
4046                         goto unlock;
4047         }
4048
4049         if (ext4_should_journal_data(inode)) {
4050                 BUFFER_TRACE(bh, "get write access");
4051                 err = ext4_journal_get_write_access(handle, bh);
4052                 if (err)
4053                         goto unlock;
4054         }
4055
4056         zero_user(page, offset, length);
4057
4058         BUFFER_TRACE(bh, "zeroed end of block");
4059
4060         err = 0;
4061         if (ext4_should_journal_data(inode)) {
4062                 err = ext4_handle_dirty_metadata(handle, inode, bh);
4063         } else {
4064                 if (ext4_should_order_data(inode) && EXT4_I(inode)->jinode)
4065                         err = ext4_jbd2_file_inode(handle, inode);
4066                 mark_buffer_dirty(bh);
4067         }
4068
4069 unlock:
4070         unlock_page(page);
4071         page_cache_release(page);
4072         return err;
4073 }
4074
4075 /*
4076  * Probably it should be a library function... search for first non-zero word
4077  * or memcmp with zero_page, whatever is better for particular architecture.
4078  * Linus?
4079  */
4080 static inline int all_zeroes(__le32 *p, __le32 *q)
4081 {
4082         while (p < q)
4083                 if (*p++)
4084                         return 0;
4085         return 1;
4086 }
4087
4088 /**
4089  *      ext4_find_shared - find the indirect blocks for partial truncation.
4090  *      @inode:   inode in question
4091  *      @depth:   depth of the affected branch
4092  *      @offsets: offsets of pointers in that branch (see ext4_block_to_path)
4093  *      @chain:   place to store the pointers to partial indirect blocks
4094  *      @top:     place to the (detached) top of branch
4095  *
4096  *      This is a helper function used by ext4_truncate().
4097  *
4098  *      When we do truncate() we may have to clean the ends of several
4099  *      indirect blocks but leave the blocks themselves alive. Block is
4100  *      partially truncated if some data below the new i_size is referred
4101  *      from it (and it is on the path to the first completely truncated
4102  *      data block, indeed).  We have to free the top of that path along
4103  *      with everything to the right of the path. Since no allocation
4104  *      past the truncation point is possible until ext4_truncate()
4105  *      finishes, we may safely do the latter, but top of branch may
4106  *      require special attention - pageout below the truncation point
4107  *      might try to populate it.
4108  *
4109  *      We atomically detach the top of branch from the tree, store the
4110  *      block number of its root in *@top, pointers to buffer_heads of
4111  *      partially truncated blocks - in @chain[].bh and pointers to
4112  *      their last elements that should not be removed - in
4113  *      @chain[].p. Return value is the pointer to last filled element
4114  *      of @chain.
4115  *
4116  *      The work left to caller to do the actual freeing of subtrees:
4117  *              a) free the subtree starting from *@top
4118  *              b) free the subtrees whose roots are stored in
4119  *                      (@chain[i].p+1 .. end of @chain[i].bh->b_data)
4120  *              c) free the subtrees growing from the inode past the @chain[0].
4121  *                      (no partially truncated stuff there).  */
4122
4123 static Indirect *ext4_find_shared(struct inode *inode, int depth,
4124                                   ext4_lblk_t offsets[4], Indirect chain[4],
4125                                   __le32 *top)
4126 {
4127         Indirect *partial, *p;
4128         int k, err;
4129
4130         *top = 0;
4131         /* Make k index the deepest non-null offset + 1 */
4132         for (k = depth; k > 1 && !offsets[k-1]; k--)
4133                 ;
4134         partial = ext4_get_branch(inode, k, offsets, chain, &err);
4135         /* Writer: pointers */
4136         if (!partial)
4137                 partial = chain + k-1;
4138         /*
4139          * If the branch acquired continuation since we've looked at it -
4140          * fine, it should all survive and (new) top doesn't belong to us.
4141          */
4142         if (!partial->key && *partial->p)
4143                 /* Writer: end */
4144                 goto no_top;
4145         for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4146                 ;
4147         /*
4148          * OK, we've found the last block that must survive. The rest of our
4149          * branch should be detached before unlocking. However, if that rest
4150          * of branch is all ours and does not grow immediately from the inode
4151          * it's easier to cheat and just decrement partial->p.
4152          */
4153         if (p == chain + k - 1 && p > chain) {
4154                 p->p--;
4155         } else {
4156                 *top = *p->p;
4157                 /* Nope, don't do this in ext4.  Must leave the tree intact */
4158 #if 0
4159                 *p->p = 0;
4160 #endif
4161         }
4162         /* Writer: end */
4163
4164         while (partial > p) {
4165                 brelse(partial->bh);
4166                 partial--;
4167         }
4168 no_top:
4169         return partial;
4170 }
4171
4172 /*
4173  * Zero a number of block pointers in either an inode or an indirect block.
4174  * If we restart the transaction we must again get write access to the
4175  * indirect block for further modification.
4176  *
4177  * We release `count' blocks on disk, but (last - first) may be greater
4178  * than `count' because there can be holes in there.
4179  *
4180  * Return 0 on success, 1 on invalid block range
4181  * and < 0 on fatal error.
4182  */
4183 static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
4184                              struct buffer_head *bh,
4185                              ext4_fsblk_t block_to_free,
4186                              unsigned long count, __le32 *first,
4187                              __le32 *last)
4188 {
4189         __le32 *p;
4190         int     flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
4191         int     err;
4192
4193         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
4194                 flags |= EXT4_FREE_BLOCKS_METADATA;
4195
4196         if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
4197                                    count)) {
4198                 EXT4_ERROR_INODE(inode, "attempt to clear invalid "
4199                                  "blocks %llu len %lu",
4200                                  (unsigned long long) block_to_free, count);
4201                 return 1;
4202         }
4203
4204         if (try_to_extend_transaction(handle, inode)) {
4205                 if (bh) {
4206                         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4207                         err = ext4_handle_dirty_metadata(handle, inode, bh);
4208                         if (unlikely(err))
4209                                 goto out_err;
4210                 }
4211                 err = ext4_mark_inode_dirty(handle, inode);
4212                 if (unlikely(err))
4213                         goto out_err;
4214                 err = ext4_truncate_restart_trans(handle, inode,
4215                                                   blocks_for_truncate(inode));
4216                 if (unlikely(err))
4217                         goto out_err;
4218                 if (bh) {
4219                         BUFFER_TRACE(bh, "retaking write access");
4220                         err = ext4_journal_get_write_access(handle, bh);
4221                         if (unlikely(err))
4222                                 goto out_err;
4223                 }
4224         }
4225
4226         for (p = first; p < last; p++)
4227                 *p = 0;
4228
4229         ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
4230         return 0;
4231 out_err:
4232         ext4_std_error(inode->i_sb, err);
4233         return err;
4234 }
4235
4236 /**
4237  * ext4_free_data - free a list of data blocks
4238  * @handle:     handle for this transaction
4239  * @inode:      inode we are dealing with
4240  * @this_bh:    indirect buffer_head which contains *@first and *@last
4241  * @first:      array of block numbers
4242  * @last:       points immediately past the end of array
4243  *
4244  * We are freeing all blocks referred from that array (numbers are stored as
4245  * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4246  *
4247  * We accumulate contiguous runs of blocks to free.  Conveniently, if these
4248  * blocks are contiguous then releasing them at one time will only affect one
4249  * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4250  * actually use a lot of journal space.
4251  *
4252  * @this_bh will be %NULL if @first and @last point into the inode's direct
4253  * block pointers.
4254  */
4255 static void ext4_free_data(handle_t *handle, struct inode *inode,
4256                            struct buffer_head *this_bh,
4257                            __le32 *first, __le32 *last)
4258 {
4259         ext4_fsblk_t block_to_free = 0;    /* Starting block # of a run */
4260         unsigned long count = 0;            /* Number of blocks in the run */
4261         __le32 *block_to_free_p = NULL;     /* Pointer into inode/ind
4262                                                corresponding to
4263                                                block_to_free */
4264         ext4_fsblk_t nr;                    /* Current block # */
4265         __le32 *p;                          /* Pointer into inode/ind
4266                                                for current block */
4267         int err = 0;
4268
4269         if (this_bh) {                          /* For indirect block */
4270                 BUFFER_TRACE(this_bh, "get_write_access");
4271                 err = ext4_journal_get_write_access(handle, this_bh);
4272                 /* Important: if we can't update the indirect pointers
4273                  * to the blocks, we can't free them. */
4274                 if (err)
4275                         return;
4276         }
4277
4278         for (p = first; p < last; p++) {
4279                 nr = le32_to_cpu(*p);
4280                 if (nr) {
4281                         /* accumulate blocks to free if they're contiguous */
4282                         if (count == 0) {
4283                                 block_to_free = nr;
4284                                 block_to_free_p = p;
4285                                 count = 1;
4286                         } else if (nr == block_to_free + count) {
4287                                 count++;
4288                         } else {
4289                                 err = ext4_clear_blocks(handle, inode, this_bh,
4290                                                         block_to_free, count,
4291                                                         block_to_free_p, p);
4292                                 if (err)
4293                                         break;
4294                                 block_to_free = nr;
4295                                 block_to_free_p = p;
4296                                 count = 1;
4297                         }
4298                 }
4299         }
4300
4301         if (!err && count > 0)
4302                 err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4303                                         count, block_to_free_p, p);
4304         if (err < 0)
4305                 /* fatal error */
4306                 return;
4307
4308         if (this_bh) {
4309                 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
4310
4311                 /*
4312                  * The buffer head should have an attached journal head at this
4313                  * point. However, if the data is corrupted and an indirect
4314                  * block pointed to itself, it would have been detached when
4315                  * the block was cleared. Check for this instead of OOPSing.
4316                  */
4317                 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
4318                         ext4_handle_dirty_metadata(handle, inode, this_bh);
4319                 else
4320                         EXT4_ERROR_INODE(inode,
4321                                          "circular indirect block detected at "
4322                                          "block %llu",
4323                                 (unsigned long long) this_bh->b_blocknr);
4324         }
4325 }
4326
4327 /**
4328  *      ext4_free_branches - free an array of branches
4329  *      @handle: JBD handle for this transaction
4330  *      @inode: inode we are dealing with
4331  *      @parent_bh: the buffer_head which contains *@first and *@last
4332  *      @first: array of block numbers
4333  *      @last:  pointer immediately past the end of array
4334  *      @depth: depth of the branches to free
4335  *
4336  *      We are freeing all blocks referred from these branches (numbers are
4337  *      stored as little-endian 32-bit) and updating @inode->i_blocks
4338  *      appropriately.
4339  */
4340 static void ext4_free_branches(handle_t *handle, struct inode *inode,
4341                                struct buffer_head *parent_bh,
4342                                __le32 *first, __le32 *last, int depth)
4343 {
4344         ext4_fsblk_t nr;
4345         __le32 *p;
4346
4347         if (ext4_handle_is_aborted(handle))
4348                 return;
4349
4350         if (depth--) {
4351                 struct buffer_head *bh;
4352                 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4353                 p = last;
4354                 while (--p >= first) {
4355                         nr = le32_to_cpu(*p);
4356                         if (!nr)
4357                                 continue;               /* A hole */
4358
4359                         if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
4360                                                    nr, 1)) {
4361                                 EXT4_ERROR_INODE(inode,
4362                                                  "invalid indirect mapped "
4363                                                  "block %lu (level %d)",
4364                                                  (unsigned long) nr, depth);
4365                                 break;
4366                         }
4367
4368                         /* Go read the buffer for the next level down */
4369                         bh = sb_bread(inode->i_sb, nr);
4370
4371                         /*
4372                          * A read failure? Report error and clear slot
4373                          * (should be rare).
4374                          */
4375                         if (!bh) {
4376                                 EXT4_ERROR_INODE_BLOCK(inode, nr,
4377                                                        "Read failure");
4378                                 continue;
4379                         }
4380
4381                         /* This zaps the entire block.  Bottom up. */
4382                         BUFFER_TRACE(bh, "free child branches");
4383                         ext4_free_branches(handle, inode, bh,
4384                                         (__le32 *) bh->b_data,
4385                                         (__le32 *) bh->b_data + addr_per_block,
4386                                         depth);
4387                         brelse(bh);
4388
4389                         /*
4390                          * Everything below this this pointer has been
4391                          * released.  Now let this top-of-subtree go.
4392                          *
4393                          * We want the freeing of this indirect block to be
4394                          * atomic in the journal with the updating of the
4395                          * bitmap block which owns it.  So make some room in
4396                          * the journal.
4397                          *
4398                          * We zero the parent pointer *after* freeing its
4399                          * pointee in the bitmaps, so if extend_transaction()
4400                          * for some reason fails to put the bitmap changes and
4401                          * the release into the same transaction, recovery
4402                          * will merely complain about releasing a free block,
4403                          * rather than leaking blocks.
4404                          */
4405                         if (ext4_handle_is_aborted(handle))
4406                                 return;
4407                         if (try_to_extend_transaction(handle, inode)) {
4408                                 ext4_mark_inode_dirty(handle, inode);
4409                                 ext4_truncate_restart_trans(handle, inode,
4410                                             blocks_for_truncate(inode));
4411                         }
4412
4413                         /*
4414                          * The forget flag here is critical because if
4415                          * we are journaling (and not doing data
4416                          * journaling), we have to make sure a revoke
4417                          * record is written to prevent the journal
4418                          * replay from overwriting the (former)
4419                          * indirect block if it gets reallocated as a
4420                          * data block.  This must happen in the same
4421                          * transaction where the data blocks are
4422                          * actually freed.
4423                          */
4424                         ext4_free_blocks(handle, inode, NULL, nr, 1,
4425                                          EXT4_FREE_BLOCKS_METADATA|
4426                                          EXT4_FREE_BLOCKS_FORGET);
4427
4428                         if (parent_bh) {
4429                                 /*
4430                                  * The block which we have just freed is
4431                                  * pointed to by an indirect block: journal it
4432                                  */
4433                                 BUFFER_TRACE(parent_bh, "get_write_access");
4434                                 if (!ext4_journal_get_write_access(handle,
4435                                                                    parent_bh)){
4436                                         *p = 0;
4437                                         BUFFER_TRACE(parent_bh,
4438                                         "call ext4_handle_dirty_metadata");
4439                                         ext4_handle_dirty_metadata(handle,
4440                                                                    inode,
4441                                                                    parent_bh);
4442                                 }
4443                         }
4444                 }
4445         } else {
4446                 /* We have reached the bottom of the tree. */
4447                 BUFFER_TRACE(parent_bh, "free data blocks");
4448                 ext4_free_data(handle, inode, parent_bh, first, last);
4449         }
4450 }
4451
4452 int ext4_can_truncate(struct inode *inode)
4453 {
4454         if (S_ISREG(inode->i_mode))
4455                 return 1;
4456         if (S_ISDIR(inode->i_mode))
4457                 return 1;
4458         if (S_ISLNK(inode->i_mode))
4459                 return !ext4_inode_is_fast_symlink(inode);
4460         return 0;
4461 }
4462
4463 /*
4464  * ext4_punch_hole: punches a hole in a file by releaseing the blocks
4465  * associated with the given offset and length
4466  *
4467  * @inode:  File inode
4468  * @offset: The offset where the hole will begin
4469  * @len:    The length of the hole
4470  *
4471  * Returns: 0 on sucess or negative on failure
4472  */
4473
4474 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4475 {
4476         struct inode *inode = file->f_path.dentry->d_inode;
4477         if (!S_ISREG(inode->i_mode))
4478                 return -ENOTSUPP;
4479
4480         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4481                 /* TODO: Add support for non extent hole punching */
4482                 return -ENOTSUPP;
4483         }
4484
4485         return ext4_ext_punch_hole(file, offset, length);
4486 }
4487
4488 /*
4489  * ext4_truncate()
4490  *
4491  * We block out ext4_get_block() block instantiations across the entire
4492  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4493  * simultaneously on behalf of the same inode.
4494  *
4495  * As we work through the truncate and commmit bits of it to the journal there
4496  * is one core, guiding principle: the file's tree must always be consistent on
4497  * disk.  We must be able to restart the truncate after a crash.
4498  *
4499  * The file's tree may be transiently inconsistent in memory (although it
4500  * probably isn't), but whenever we close off and commit a journal transaction,
4501  * the contents of (the filesystem + the journal) must be consistent and
4502  * restartable.  It's pretty simple, really: bottom up, right to left (although
4503  * left-to-right works OK too).
4504  *
4505  * Note that at recovery time, journal replay occurs *before* the restart of
4506  * truncate against the orphan inode list.
4507  *
4508  * The committed inode has the new, desired i_size (which is the same as
4509  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4510  * that this inode's truncate did not complete and it will again call
4511  * ext4_truncate() to have another go.  So there will be instantiated blocks
4512  * to the right of the truncation point in a crashed ext4 filesystem.  But
4513  * that's fine - as long as they are linked from the inode, the post-crash
4514  * ext4_truncate() run will find them and release them.
4515  */
4516 void ext4_truncate(struct inode *inode)
4517 {
4518         handle_t *handle;
4519         struct ext4_inode_info *ei = EXT4_I(inode);
4520         __le32 *i_data = ei->i_data;
4521         int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4522         struct address_space *mapping = inode->i_mapping;
4523         ext4_lblk_t offsets[4];
4524         Indirect chain[4];
4525         Indirect *partial;
4526         __le32 nr = 0;
4527         int n = 0;
4528         ext4_lblk_t last_block, max_block;
4529         unsigned blocksize = inode->i_sb->s_blocksize;
4530
4531         trace_ext4_truncate_enter(inode);
4532
4533         if (!ext4_can_truncate(inode))
4534                 return;
4535
4536         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4537
4538         if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4539                 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4540
4541         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4542                 ext4_ext_truncate(inode);
4543                 trace_ext4_truncate_exit(inode);
4544                 return;
4545         }
4546
4547         handle = start_transaction(inode);
4548         if (IS_ERR(handle))
4549                 return;         /* AKPM: return what? */
4550
4551         last_block = (inode->i_size + blocksize-1)
4552                                         >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4553         max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
4554                                         >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4555
4556         if (inode->i_size & (blocksize - 1))
4557                 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4558                         goto out_stop;
4559
4560         if (last_block != max_block) {
4561                 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4562                 if (n == 0)
4563                         goto out_stop;  /* error */
4564         }
4565
4566         /*
4567          * OK.  This truncate is going to happen.  We add the inode to the
4568          * orphan list, so that if this truncate spans multiple transactions,
4569          * and we crash, we will resume the truncate when the filesystem
4570          * recovers.  It also marks the inode dirty, to catch the new size.
4571          *
4572          * Implication: the file must always be in a sane, consistent
4573          * truncatable state while each transaction commits.
4574          */
4575         if (ext4_orphan_add(handle, inode))
4576                 goto out_stop;
4577
4578         /*
4579          * From here we block out all ext4_get_block() callers who want to
4580          * modify the block allocation tree.
4581          */
4582         down_write(&ei->i_data_sem);
4583
4584         ext4_discard_preallocations(inode);
4585
4586         /*
4587          * The orphan list entry will now protect us from any crash which
4588          * occurs before the truncate completes, so it is now safe to propagate
4589          * the new, shorter inode size (held for now in i_size) into the
4590          * on-disk inode. We do this via i_disksize, which is the value which
4591          * ext4 *really* writes onto the disk inode.
4592          */
4593         ei->i_disksize = inode->i_size;
4594
4595         if (last_block == max_block) {
4596                 /*
4597                  * It is unnecessary to free any data blocks if last_block is
4598                  * equal to the indirect block limit.
4599                  */
4600                 goto out_unlock;
4601         } else if (n == 1) {            /* direct blocks */
4602                 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4603                                i_data + EXT4_NDIR_BLOCKS);
4604                 goto do_indirects;
4605         }
4606
4607         partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4608         /* Kill the top of shared branch (not detached) */
4609         if (nr) {
4610                 if (partial == chain) {
4611                         /* Shared branch grows from the inode */
4612                         ext4_free_branches(handle, inode, NULL,
4613                                            &nr, &nr+1, (chain+n-1) - partial);
4614                         *partial->p = 0;
4615                         /*
4616                          * We mark the inode dirty prior to restart,
4617                          * and prior to stop.  No need for it here.
4618                          */
4619                 } else {
4620                         /* Shared branch grows from an indirect block */
4621                         BUFFER_TRACE(partial->bh, "get_write_access");
4622                         ext4_free_branches(handle, inode, partial->bh,
4623                                         partial->p,
4624                                         partial->p+1, (chain+n-1) - partial);
4625                 }
4626         }
4627         /* Clear the ends of indirect blocks on the shared branch */
4628         while (partial > chain) {
4629                 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4630                                    (__le32*)partial->bh->b_data+addr_per_block,
4631                                    (chain+n-1) - partial);
4632                 BUFFER_TRACE(partial->bh, "call brelse");
4633                 brelse(partial->bh);
4634                 partial--;
4635         }
4636 do_indirects:
4637         /* Kill the remaining (whole) subtrees */
4638         switch (offsets[0]) {
4639         default:
4640                 nr = i_data[EXT4_IND_BLOCK];
4641                 if (nr) {
4642                         ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4643                         i_data[EXT4_IND_BLOCK] = 0;
4644                 }
4645         case EXT4_IND_BLOCK:
4646                 nr = i_data[EXT4_DIND_BLOCK];
4647                 if (nr) {
4648                         ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4649                         i_data[EXT4_DIND_BLOCK] = 0;
4650                 }
4651         case EXT4_DIND_BLOCK:
4652                 nr = i_data[EXT4_TIND_BLOCK];
4653                 if (nr) {
4654                         ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4655                         i_data[EXT4_TIND_BLOCK] = 0;
4656                 }
4657         case EXT4_TIND_BLOCK:
4658                 ;
4659         }
4660
4661 out_unlock:
4662         up_write(&ei->i_data_sem);
4663         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4664         ext4_mark_inode_dirty(handle, inode);
4665
4666         /*
4667          * In a multi-transaction truncate, we only make the final transaction
4668          * synchronous
4669          */
4670         if (IS_SYNC(inode))
4671                 ext4_handle_sync(handle);
4672 out_stop:
4673         /*
4674          * If this was a simple ftruncate(), and the file will remain alive
4675          * then we need to clear up the orphan record which we created above.
4676          * However, if this was a real unlink then we were called by
4677          * ext4_delete_inode(), and we allow that function to clean up the
4678          * orphan info for us.
4679          */
4680         if (inode->i_nlink)
4681                 ext4_orphan_del(handle, inode);
4682
4683         ext4_journal_stop(handle);
4684         trace_ext4_truncate_exit(inode);
4685 }
4686
4687 /*
4688  * ext4_get_inode_loc returns with an extra refcount against the inode's
4689  * underlying buffer_head on success. If 'in_mem' is true, we have all
4690  * data in memory that is needed to recreate the on-disk version of this
4691  * inode.
4692  */
4693 static int __ext4_get_inode_loc(struct inode *inode,
4694                                 struct ext4_iloc *iloc, int in_mem)
4695 {
4696         struct ext4_group_desc  *gdp;
4697         struct buffer_head      *bh;
4698         struct super_block      *sb = inode->i_sb;
4699         ext4_fsblk_t            block;
4700         int                     inodes_per_block, inode_offset;
4701
4702         iloc->bh = NULL;
4703         if (!ext4_valid_inum(sb, inode->i_ino))
4704                 return -EIO;
4705
4706         iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4707         gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4708         if (!gdp)
4709                 return -EIO;
4710
4711         /*
4712          * Figure out the offset within the block group inode table
4713          */
4714         inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4715         inode_offset = ((inode->i_ino - 1) %
4716                         EXT4_INODES_PER_GROUP(sb));
4717         block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4718         iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4719
4720         bh = sb_getblk(sb, block);
4721         if (!bh) {
4722                 EXT4_ERROR_INODE_BLOCK(inode, block,
4723                                        "unable to read itable block");
4724                 return -EIO;
4725         }
4726         if (!buffer_uptodate(bh)) {
4727                 lock_buffer(bh);
4728
4729                 /*
4730                  * If the buffer has the write error flag, we have failed
4731                  * to write out another inode in the same block.  In this
4732                  * case, we don't have to read the block because we may
4733                  * read the old inode data successfully.
4734                  */
4735                 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4736                         set_buffer_uptodate(bh);
4737
4738                 if (buffer_uptodate(bh)) {
4739                         /* someone brought it uptodate while we waited */
4740                         unlock_buffer(bh);
4741                         goto has_buffer;
4742                 }
4743
4744                 /*
4745                  * If we have all information of the inode in memory and this
4746                  * is the only valid inode in the block, we need not read the
4747                  * block.
4748                  */
4749                 if (in_mem) {
4750                         struct buffer_head *bitmap_bh;
4751                         int i, start;
4752
4753                         start = inode_offset & ~(inodes_per_block - 1);
4754
4755                         /* Is the inode bitmap in cache? */
4756                         bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4757                         if (!bitmap_bh)
4758                                 goto make_io;
4759
4760                         /*
4761                          * If the inode bitmap isn't in cache then the
4762                          * optimisation may end up performing two reads instead
4763                          * of one, so skip it.
4764                          */
4765                         if (!buffer_uptodate(bitmap_bh)) {
4766                                 brelse(bitmap_bh);
4767                                 goto make_io;
4768                         }
4769                         for (i = start; i < start + inodes_per_block; i++) {
4770                                 if (i == inode_offset)
4771                                         continue;
4772                                 if (ext4_test_bit(i, bitmap_bh->b_data))
4773                                         break;
4774                         }
4775                         brelse(bitmap_bh);
4776                         if (i == start + inodes_per_block) {
4777                                 /* all other inodes are free, so skip I/O */
4778                                 memset(bh->b_data, 0, bh->b_size);
4779                                 set_buffer_uptodate(bh);
4780                                 unlock_buffer(bh);
4781                                 goto has_buffer;
4782                         }
4783                 }
4784
4785 make_io:
4786                 /*
4787                  * If we need to do any I/O, try to pre-readahead extra
4788                  * blocks from the inode table.
4789                  */
4790                 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4791                         ext4_fsblk_t b, end, table;
4792                         unsigned num;
4793
4794                         table = ext4_inode_table(sb, gdp);
4795                         /* s_inode_readahead_blks is always a power of 2 */
4796                         b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4797                         if (table > b)
4798                                 b = table;
4799                         end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4800                         num = EXT4_INODES_PER_GROUP(sb);
4801                         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4802                                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4803                                 num -= ext4_itable_unused_count(sb, gdp);
4804                         table += num / inodes_per_block;
4805                         if (end > table)
4806                                 end = table;
4807                         while (b <= end)
4808                                 sb_breadahead(sb, b++);
4809                 }
4810
4811                 /*
4812                  * There are other valid inodes in the buffer, this inode
4813                  * has in-inode xattrs, or we don't have this inode in memory.
4814                  * Read the block from disk.
4815                  */
4816                 trace_ext4_load_inode(inode);
4817                 get_bh(bh);
4818                 bh->b_end_io = end_buffer_read_sync;
4819                 submit_bh(READ_META, bh);
4820                 wait_on_buffer(bh);
4821                 if (!buffer_uptodate(bh)) {
4822                         EXT4_ERROR_INODE_BLOCK(inode, block,
4823                                                "unable to read itable block");
4824                         brelse(bh);
4825                         return -EIO;
4826                 }
4827         }
4828 has_buffer:
4829         iloc->bh = bh;
4830         return 0;
4831 }
4832
4833 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4834 {
4835         /* We have all inode data except xattrs in memory here. */
4836         return __ext4_get_inode_loc(inode, iloc,
4837                 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4838 }
4839
4840 void ext4_set_inode_flags(struct inode *inode)
4841 {
4842         unsigned int flags = EXT4_I(inode)->i_flags;
4843
4844         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4845         if (flags & EXT4_SYNC_FL)
4846                 inode->i_flags |= S_SYNC;
4847         if (flags & EXT4_APPEND_FL)
4848                 inode->i_flags |= S_APPEND;
4849         if (flags & EXT4_IMMUTABLE_FL)
4850                 inode->i_flags |= S_IMMUTABLE;
4851         if (flags & EXT4_NOATIME_FL)
4852                 inode->i_flags |= S_NOATIME;
4853         if (flags & EXT4_DIRSYNC_FL)
4854                 inode->i_flags |= S_DIRSYNC;
4855 }
4856
4857 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4858 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4859 {
4860         unsigned int vfs_fl;
4861         unsigned long old_fl, new_fl;
4862
4863         do {
4864                 vfs_fl = ei->vfs_inode.i_flags;
4865                 old_fl = ei->i_flags;
4866                 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4867                                 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4868                                 EXT4_DIRSYNC_FL);
4869                 if (vfs_fl & S_SYNC)
4870                         new_fl |= EXT4_SYNC_FL;
4871                 if (vfs_fl & S_APPEND)
4872                         new_fl |= EXT4_APPEND_FL;
4873                 if (vfs_fl & S_IMMUTABLE)
4874                         new_fl |= EXT4_IMMUTABLE_FL;
4875                 if (vfs_fl & S_NOATIME)
4876                         new_fl |= EXT4_NOATIME_FL;
4877                 if (vfs_fl & S_DIRSYNC)
4878                         new_fl |= EXT4_DIRSYNC_FL;
4879         } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4880 }
4881
4882 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4883                                   struct ext4_inode_info *ei)
4884 {
4885         blkcnt_t i_blocks ;
4886         struct inode *inode = &(ei->vfs_inode);
4887         struct super_block *sb = inode->i_sb;
4888
4889         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4890                                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4891                 /* we are using combined 48 bit field */
4892                 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4893                                         le32_to_cpu(raw_inode->i_blocks_lo);
4894                 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4895                         /* i_blocks represent file system block size */
4896                         return i_blocks  << (inode->i_blkbits - 9);
4897                 } else {
4898                         return i_blocks;
4899                 }
4900         } else {
4901                 return le32_to_cpu(raw_inode->i_blocks_lo);
4902         }
4903 }
4904
4905 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4906 {
4907         struct ext4_iloc iloc;
4908         struct ext4_inode *raw_inode;
4909         struct ext4_inode_info *ei;
4910         struct inode *inode;
4911         journal_t *journal = EXT4_SB(sb)->s_journal;
4912         long ret;
4913         int block;
4914
4915         inode = iget_locked(sb, ino);
4916         if (!inode)
4917                 return ERR_PTR(-ENOMEM);
4918         if (!(inode->i_state & I_NEW))
4919                 return inode;
4920
4921         ei = EXT4_I(inode);
4922         iloc.bh = NULL;
4923
4924         ret = __ext4_get_inode_loc(inode, &iloc, 0);
4925         if (ret < 0)
4926                 goto bad_inode;
4927         raw_inode = ext4_raw_inode(&iloc);
4928         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4929         inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4930         inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4931         if (!(test_opt(inode->i_sb, NO_UID32))) {
4932                 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4933                 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4934         }
4935         inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4936
4937         ext4_clear_state_flags(ei);     /* Only relevant on 32-bit archs */
4938         ei->i_dir_start_lookup = 0;
4939         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4940         /* We now have enough fields to check if the inode was active or not.
4941          * This is needed because nfsd might try to access dead inodes
4942          * the test is that same one that e2fsck uses
4943          * NeilBrown 1999oct15
4944          */
4945         if (inode->i_nlink == 0) {
4946                 if (inode->i_mode == 0 ||
4947                     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4948                         /* this inode is deleted */
4949                         ret = -ESTALE;
4950                         goto bad_inode;
4951                 }
4952                 /* The only unlinked inodes we let through here have
4953                  * valid i_mode and are being read by the orphan
4954                  * recovery code: that's fine, we're about to complete
4955                  * the process of deleting those. */
4956         }
4957         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4958         inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4959         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4960         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4961                 ei->i_file_acl |=
4962                         ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4963         inode->i_size = ext4_isize(raw_inode);
4964         ei->i_disksize = inode->i_size;
4965 #ifdef CONFIG_QUOTA
4966         ei->i_reserved_quota = 0;
4967 #endif
4968         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4969         ei->i_block_group = iloc.block_group;
4970         ei->i_last_alloc_group = ~0;
4971         /*
4972          * NOTE! The in-memory inode i_data array is in little-endian order
4973          * even on big-endian machines: we do NOT byteswap the block numbers!
4974          */
4975         for (block = 0; block < EXT4_N_BLOCKS; block++)
4976                 ei->i_data[block] = raw_inode->i_block[block];
4977         INIT_LIST_HEAD(&ei->i_orphan);
4978
4979         /*
4980          * Set transaction id's of transactions that have to be committed
4981          * to finish f[data]sync. We set them to currently running transaction
4982          * as we cannot be sure that the inode or some of its metadata isn't
4983          * part of the transaction - the inode could have been reclaimed and
4984          * now it is reread from disk.
4985          */
4986         if (journal) {
4987                 transaction_t *transaction;
4988                 tid_t tid;
4989
4990                 read_lock(&journal->j_state_lock);
4991                 if (journal->j_running_transaction)
4992                         transaction = journal->j_running_transaction;
4993                 else
4994                         transaction = journal->j_committing_transaction;
4995                 if (transaction)
4996                         tid = transaction->t_tid;
4997                 else
4998                         tid = journal->j_commit_sequence;
4999                 read_unlock(&journal->j_state_lock);
5000                 ei->i_sync_tid = tid;
5001                 ei->i_datasync_tid = tid;
5002         }
5003
5004         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5005                 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5006                 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5007                     EXT4_INODE_SIZE(inode->i_sb)) {
5008                         ret = -EIO;
5009                         goto bad_inode;
5010                 }
5011                 if (ei->i_extra_isize == 0) {
5012                         /* The extra space is currently unused. Use it. */
5013                         ei->i_extra_isize = sizeof(struct ext4_inode) -
5014                                             EXT4_GOOD_OLD_INODE_SIZE;
5015                 } else {
5016                         __le32 *magic = (void *)raw_inode +
5017                                         EXT4_GOOD_OLD_INODE_SIZE +
5018                                         ei->i_extra_isize;
5019                         if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
5020                                 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5021                 }
5022         } else
5023                 ei->i_extra_isize = 0;
5024
5025         EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5026         EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5027         EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5028         EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5029
5030         inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
5031         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5032                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5033                         inode->i_version |=
5034                         (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5035         }
5036
5037         ret = 0;
5038         if (ei->i_file_acl &&
5039             !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
5040                 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
5041                                  ei->i_file_acl);
5042                 ret = -EIO;
5043                 goto bad_inode;
5044         } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5045                 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5046                     (S_ISLNK(inode->i_mode) &&
5047                      !ext4_inode_is_fast_symlink(inode)))
5048                         /* Validate extent which is part of inode */
5049                         ret = ext4_ext_check_inode(inode);
5050         } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5051                    (S_ISLNK(inode->i_mode) &&
5052                     !ext4_inode_is_fast_symlink(inode))) {
5053                 /* Validate block references which are part of inode */
5054                 ret = ext4_check_inode_blockref(inode);
5055         }
5056         if (ret)
5057                 goto bad_inode;
5058
5059         if (S_ISREG(inode->i_mode)) {
5060                 inode->i_op = &ext4_file_inode_operations;
5061                 inode->i_fop = &ext4_file_operations;
5062                 ext4_set_aops(inode);
5063         } else if (S_ISDIR(inode->i_mode)) {
5064                 inode->i_op = &ext4_dir_inode_operations;
5065                 inode->i_fop = &ext4_dir_operations;
5066         } else if (S_ISLNK(inode->i_mode)) {
5067                 if (ext4_inode_is_fast_symlink(inode)) {
5068                         inode->i_op = &ext4_fast_symlink_inode_operations;
5069                         nd_terminate_link(ei->i_data, inode->i_size,
5070                                 sizeof(ei->i_data) - 1);
5071                 } else {
5072                         inode->i_op = &ext4_symlink_inode_operations;
5073                         ext4_set_aops(inode);
5074                 }
5075         } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5076               S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5077                 inode->i_op = &ext4_special_inode_operations;
5078                 if (raw_inode->i_block[0])
5079                         init_special_inode(inode, inode->i_mode,
5080                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5081                 else
5082                         init_special_inode(inode, inode->i_mode,
5083                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5084         } else {
5085                 ret = -EIO;
5086                 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
5087                 goto bad_inode;
5088         }
5089         brelse(iloc.bh);
5090         ext4_set_inode_flags(inode);
5091         unlock_new_inode(inode);
5092         return inode;
5093
5094 bad_inode:
5095         brelse(iloc.bh);
5096         iget_failed(inode);
5097         return ERR_PTR(ret);
5098 }
5099
5100 static int ext4_inode_blocks_set(handle_t *handle,
5101                                 struct ext4_inode *raw_inode,
5102                                 struct ext4_inode_info *ei)
5103 {
5104         struct inode *inode = &(ei->vfs_inode);
5105         u64 i_blocks = inode->i_blocks;
5106         struct super_block *sb = inode->i_sb;
5107
5108         if (i_blocks <= ~0U) {
5109                 /*
5110                  * i_blocks can be represnted in a 32 bit variable
5111                  * as multiple of 512 bytes
5112                  */
5113                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
5114                 raw_inode->i_blocks_high = 0;
5115                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5116                 return 0;
5117         }
5118         if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
5119                 return -EFBIG;
5120
5121         if (i_blocks <= 0xffffffffffffULL) {
5122                 /*
5123                  * i_blocks can be represented in a 48 bit variable
5124                  * as multiple of 512 bytes
5125                  */
5126                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
5127                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5128                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5129         } else {
5130                 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5131                 /* i_block is stored in file system block size */
5132                 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5133                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
5134                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5135         }
5136         return 0;
5137 }
5138
5139 /*
5140  * Post the struct inode info into an on-disk inode location in the
5141  * buffer-cache.  This gobbles the caller's reference to the
5142  * buffer_head in the inode location struct.
5143  *
5144  * The caller must have write access to iloc->bh.
5145  */
5146 static int ext4_do_update_inode(handle_t *handle,
5147                                 struct inode *inode,
5148                                 struct ext4_iloc *iloc)
5149 {
5150         struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5151         struct ext4_inode_info *ei = EXT4_I(inode);
5152         struct buffer_head *bh = iloc->bh;
5153         int err = 0, rc, block;
5154
5155         /* For fields not not tracking in the in-memory inode,
5156          * initialise them to zero for new inodes. */
5157         if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5158                 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5159
5160         ext4_get_inode_flags(ei);
5161         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5162         if (!(test_opt(inode->i_sb, NO_UID32))) {
5163                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5164                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5165 /*
5166  * Fix up interoperability with old kernels. Otherwise, old inodes get
5167  * re-used with the upper 16 bits of the uid/gid intact
5168  */
5169                 if (!ei->i_dtime) {
5170                         raw_inode->i_uid_high =
5171                                 cpu_to_le16(high_16_bits(inode->i_uid));
5172                         raw_inode->i_gid_high =
5173                                 cpu_to_le16(high_16_bits(inode->i_gid));
5174                 } else {
5175                         raw_inode->i_uid_high = 0;
5176                         raw_inode->i_gid_high = 0;
5177                 }
5178         } else {
5179                 raw_inode->i_uid_low =
5180                         cpu_to_le16(fs_high2lowuid(inode->i_uid));
5181                 raw_inode->i_gid_low =
5182                         cpu_to_le16(fs_high2lowgid(inode->i_gid));
5183                 raw_inode->i_uid_high = 0;
5184                 raw_inode->i_gid_high = 0;
5185         }
5186         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5187
5188         EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5189         EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5190         EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5191         EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5192
5193         if (ext4_inode_blocks_set(handle, raw_inode, ei))
5194                 goto out_brelse;
5195         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5196         raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5197         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
5198             cpu_to_le32(EXT4_OS_HURD))
5199                 raw_inode->i_file_acl_high =
5200                         cpu_to_le16(ei->i_file_acl >> 32);
5201         raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5202         ext4_isize_set(raw_inode, ei->i_disksize);
5203         if (ei->i_disksize > 0x7fffffffULL) {
5204                 struct super_block *sb = inode->i_sb;
5205                 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5206                                 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5207                                 EXT4_SB(sb)->s_es->s_rev_level ==
5208                                 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5209                         /* If this is the first large file
5210                          * created, add a flag to the superblock.
5211                          */
5212                         err = ext4_journal_get_write_access(handle,
5213                                         EXT4_SB(sb)->s_sbh);
5214                         if (err)
5215                                 goto out_brelse;
5216                         ext4_update_dynamic_rev(sb);
5217                         EXT4_SET_RO_COMPAT_FEATURE(sb,
5218                                         EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5219                         sb->s_dirt = 1;
5220                         ext4_handle_sync(handle);
5221                         err = ext4_handle_dirty_metadata(handle, NULL,
5222                                         EXT4_SB(sb)->s_sbh);
5223                 }
5224         }
5225         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5226         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5227                 if (old_valid_dev(inode->i_rdev)) {
5228                         raw_inode->i_block[0] =
5229                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
5230                         raw_inode->i_block[1] = 0;
5231                 } else {
5232                         raw_inode->i_block[0] = 0;
5233                         raw_inode->i_block[1] =
5234                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
5235                         raw_inode->i_block[2] = 0;
5236                 }
5237         } else
5238                 for (block = 0; block < EXT4_N_BLOCKS; block++)
5239                         raw_inode->i_block[block] = ei->i_data[block];
5240
5241         raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5242         if (ei->i_extra_isize) {
5243                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5244                         raw_inode->i_version_hi =
5245                         cpu_to_le32(inode->i_version >> 32);
5246                 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
5247         }
5248
5249         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5250         rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5251         if (!err)
5252                 err = rc;
5253         ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5254
5255         ext4_update_inode_fsync_trans(handle, inode, 0);
5256 out_brelse:
5257         brelse(bh);
5258         ext4_std_error(inode->i_sb, err);
5259         return err;
5260 }
5261
5262 /*
5263  * ext4_write_inode()
5264  *
5265  * We are called from a few places:
5266  *
5267  * - Within generic_file_write() for O_SYNC files.
5268  *   Here, there will be no transaction running. We wait for any running
5269  *   trasnaction to commit.
5270  *
5271  * - Within sys_sync(), kupdate and such.
5272  *   We wait on commit, if tol to.
5273  *
5274  * - Within prune_icache() (PF_MEMALLOC == true)
5275  *   Here we simply return.  We can't afford to block kswapd on the
5276  *   journal commit.
5277  *
5278  * In all cases it is actually safe for us to return without doing anything,
5279  * because the inode has been copied into a raw inode buffer in
5280  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
5281  * knfsd.
5282  *
5283  * Note that we are absolutely dependent upon all inode dirtiers doing the
5284  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5285  * which we are interested.
5286  *
5287  * It would be a bug for them to not do this.  The code:
5288  *
5289  *      mark_inode_dirty(inode)
5290  *      stuff();
5291  *      inode->i_size = expr;
5292  *
5293  * is in error because a kswapd-driven write_inode() could occur while
5294  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
5295  * will no longer be on the superblock's dirty inode list.
5296  */
5297 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5298 {
5299         int err;
5300
5301         if (current->flags & PF_MEMALLOC)
5302                 return 0;
5303
5304         if (EXT4_SB(inode->i_sb)->s_journal) {
5305                 if (ext4_journal_current_handle()) {
5306                         jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5307                         dump_stack();
5308                         return -EIO;
5309                 }
5310
5311                 if (wbc->sync_mode != WB_SYNC_ALL)
5312                         return 0;
5313
5314                 err = ext4_force_commit(inode->i_sb);
5315         } else {
5316                 struct ext4_iloc iloc;
5317
5318                 err = __ext4_get_inode_loc(inode, &iloc, 0);
5319                 if (err)
5320                         return err;
5321                 if (wbc->sync_mode == WB_SYNC_ALL)
5322                         sync_dirty_buffer(iloc.bh);
5323                 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5324                         EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5325                                          "IO error syncing inode");
5326                         err = -EIO;
5327                 }
5328                 brelse(iloc.bh);
5329         }
5330         return err;
5331 }
5332
5333 /*
5334  * ext4_setattr()
5335  *
5336  * Called from notify_change.
5337  *
5338  * We want to trap VFS attempts to truncate the file as soon as
5339  * possible.  In particular, we want to make sure that when the VFS
5340  * shrinks i_size, we put the inode on the orphan list and modify
5341  * i_disksize immediately, so that during the subsequent flushing of
5342  * dirty pages and freeing of disk blocks, we can guarantee that any
5343  * commit will leave the blocks being flushed in an unused state on
5344  * disk.  (On recovery, the inode will get truncated and the blocks will
5345  * be freed, so we have a strong guarantee that no future commit will
5346  * leave these blocks visible to the user.)
5347  *
5348  * Another thing we have to assure is that if we are in ordered mode
5349  * and inode is still attached to the committing transaction, we must
5350  * we start writeout of all the dirty pages which are being truncated.
5351  * This way we are sure that all the data written in the previous
5352  * transaction are already on disk (truncate waits for pages under
5353  * writeback).
5354  *
5355  * Called with inode->i_mutex down.
5356  */
5357 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5358 {
5359         struct inode *inode = dentry->d_inode;
5360         int error, rc = 0;
5361         int orphan = 0;
5362         const unsigned int ia_valid = attr->ia_valid;
5363
5364         error = inode_change_ok(inode, attr);
5365         if (error)
5366                 return error;
5367
5368         if (is_quota_modification(inode, attr))
5369                 dquot_initialize(inode);
5370         if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5371                 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5372                 handle_t *handle;
5373
5374                 /* (user+group)*(old+new) structure, inode write (sb,
5375                  * inode block, ? - but truncate inode update has it) */
5376                 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5377                                         EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5378                 if (IS_ERR(handle)) {
5379                         error = PTR_ERR(handle);
5380                         goto err_out;
5381                 }
5382                 error = dquot_transfer(inode, attr);
5383                 if (error) {
5384                         ext4_journal_stop(handle);
5385                         return error;
5386                 }
5387                 /* Update corresponding info in inode so that everything is in
5388                  * one transaction */
5389                 if (attr->ia_valid & ATTR_UID)
5390                         inode->i_uid = attr->ia_uid;
5391                 if (attr->ia_valid & ATTR_GID)
5392                         inode->i_gid = attr->ia_gid;
5393                 error = ext4_mark_inode_dirty(handle, inode);
5394                 ext4_journal_stop(handle);
5395         }
5396
5397         if (attr->ia_valid & ATTR_SIZE) {
5398                 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5399                         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5400
5401                         if (attr->ia_size > sbi->s_bitmap_maxbytes)
5402                                 return -EFBIG;
5403                 }
5404         }
5405
5406         if (S_ISREG(inode->i_mode) &&
5407             attr->ia_valid & ATTR_SIZE &&
5408             (attr->ia_size < inode->i_size)) {
5409                 handle_t *handle;
5410
5411                 handle = ext4_journal_start(inode, 3);
5412                 if (IS_ERR(handle)) {
5413                         error = PTR_ERR(handle);
5414                         goto err_out;
5415                 }
5416                 if (ext4_handle_valid(handle)) {
5417                         error = ext4_orphan_add(handle, inode);
5418                         orphan = 1;
5419                 }
5420                 EXT4_I(inode)->i_disksize = attr->ia_size;
5421                 rc = ext4_mark_inode_dirty(handle, inode);
5422                 if (!error)
5423                         error = rc;
5424                 ext4_journal_stop(handle);
5425
5426                 if (ext4_should_order_data(inode)) {
5427                         error = ext4_begin_ordered_truncate(inode,
5428                                                             attr->ia_size);
5429                         if (error) {
5430                                 /* Do as much error cleanup as possible */
5431                                 handle = ext4_journal_start(inode, 3);
5432                                 if (IS_ERR(handle)) {
5433                                         ext4_orphan_del(NULL, inode);
5434                                         goto err_out;
5435                                 }
5436                                 ext4_orphan_del(handle, inode);
5437                                 orphan = 0;
5438                                 ext4_journal_stop(handle);
5439                                 goto err_out;
5440                         }
5441                 }
5442         }
5443
5444         if (attr->ia_valid & ATTR_SIZE) {
5445                 if (attr->ia_size != i_size_read(inode)) {
5446                         truncate_setsize(inode, attr->ia_size);
5447                         ext4_truncate(inode);
5448                 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
5449                         ext4_truncate(inode);
5450         }
5451
5452         if (!rc) {
5453                 setattr_copy(inode, attr);
5454                 mark_inode_dirty(inode);
5455         }
5456
5457         /*
5458          * If the call to ext4_truncate failed to get a transaction handle at
5459          * all, we need to clean up the in-core orphan list manually.
5460          */
5461         if (orphan && inode->i_nlink)
5462                 ext4_orphan_del(NULL, inode);
5463
5464         if (!rc && (ia_valid & ATTR_MODE))
5465                 rc = ext4_acl_chmod(inode);
5466
5467 err_out:
5468         ext4_std_error(inode->i_sb, error);
5469         if (!error)
5470                 error = rc;
5471         return error;
5472 }
5473
5474 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5475                  struct kstat *stat)
5476 {
5477         struct inode *inode;
5478         unsigned long delalloc_blocks;
5479
5480         inode = dentry->d_inode;
5481         generic_fillattr(inode, stat);
5482
5483         /*
5484          * We can't update i_blocks if the block allocation is delayed
5485          * otherwise in the case of system crash before the real block
5486          * allocation is done, we will have i_blocks inconsistent with
5487          * on-disk file blocks.
5488          * We always keep i_blocks updated together with real
5489          * allocation. But to not confuse with user, stat
5490          * will return the blocks that include the delayed allocation
5491          * blocks for this file.
5492          */
5493         delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
5494
5495         stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
5496         return 0;
5497 }
5498
5499 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5500                                       int chunk)
5501 {
5502         int indirects;
5503
5504         /* if nrblocks are contiguous */
5505         if (chunk) {
5506                 /*
5507                  * With N contiguous data blocks, we need at most
5508                  * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
5509                  * 2 dindirect blocks, and 1 tindirect block
5510                  */
5511                 return DIV_ROUND_UP(nrblocks,
5512                                     EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
5513         }
5514         /*
5515          * if nrblocks are not contiguous, worse case, each block touch
5516          * a indirect block, and each indirect block touch a double indirect
5517          * block, plus a triple indirect block
5518          */
5519         indirects = nrblocks * 2 + 1;
5520         return indirects;
5521 }
5522
5523 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5524 {
5525         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5526                 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5527         return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5528 }
5529
5530 /*
5531  * Account for index blocks, block groups bitmaps and block group
5532  * descriptor blocks if modify datablocks and index blocks
5533  * worse case, the indexs blocks spread over different block groups
5534  *
5535  * If datablocks are discontiguous, they are possible to spread over
5536  * different block groups too. If they are contiuguous, with flexbg,
5537  * they could still across block group boundary.
5538  *
5539  * Also account for superblock, inode, quota and xattr blocks
5540  */
5541 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5542 {
5543         ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5544         int gdpblocks;
5545         int idxblocks;
5546         int ret = 0;
5547
5548         /*
5549          * How many index blocks need to touch to modify nrblocks?
5550          * The "Chunk" flag indicating whether the nrblocks is
5551          * physically contiguous on disk
5552          *
5553          * For Direct IO and fallocate, they calls get_block to allocate
5554          * one single extent at a time, so they could set the "Chunk" flag
5555          */
5556         idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5557
5558         ret = idxblocks;
5559
5560         /*
5561          * Now let's see how many group bitmaps and group descriptors need
5562          * to account
5563          */
5564         groups = idxblocks;
5565         if (chunk)
5566                 groups += 1;
5567         else
5568                 groups += nrblocks;
5569
5570         gdpblocks = groups;
5571         if (groups > ngroups)
5572                 groups = ngroups;
5573         if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5574                 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5575
5576         /* bitmaps and block group descriptor blocks */
5577         ret += groups + gdpblocks;
5578
5579         /* Blocks for super block, inode, quota and xattr blocks */
5580         ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5581
5582         return ret;
5583 }
5584
5585 /*
5586  * Calculate the total number of credits to reserve to fit
5587  * the modification of a single pages into a single transaction,
5588  * which may include multiple chunks of block allocations.
5589  *
5590  * This could be called via ext4_write_begin()
5591  *
5592  * We need to consider the worse case, when
5593  * one new block per extent.
5594  */
5595 int ext4_writepage_trans_blocks(struct inode *inode)
5596 {
5597         int bpp = ext4_journal_blocks_per_page(inode);
5598         int ret;
5599
5600         ret = ext4_meta_trans_blocks(inode, bpp, 0);
5601
5602         /* Account for data blocks for journalled mode */
5603         if (ext4_should_journal_data(inode))
5604                 ret += bpp;
5605         return ret;
5606 }
5607
5608 /*
5609  * Calculate the journal credits for a chunk of data modification.
5610  *
5611  * This is called from DIO, fallocate or whoever calling
5612  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5613  *
5614  * journal buffers for data blocks are not included here, as DIO
5615  * and fallocate do no need to journal data buffers.
5616  */
5617 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5618 {
5619         return ext4_meta_trans_blocks(inode, nrblocks, 1);
5620 }
5621
5622 /*
5623  * The caller must have previously called ext4_reserve_inode_write().
5624  * Give this, we know that the caller already has write access to iloc->bh.
5625  */
5626 int ext4_mark_iloc_dirty(handle_t *handle,
5627                          struct inode *inode, struct ext4_iloc *iloc)
5628 {
5629         int err = 0;
5630
5631         if (test_opt(inode->i_sb, I_VERSION))
5632                 inode_inc_iversion(inode);
5633
5634         /* the do_update_inode consumes one bh->b_count */
5635         get_bh(iloc->bh);
5636
5637         /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5638         err = ext4_do_update_inode(handle, inode, iloc);
5639         put_bh(iloc->bh);
5640         return err;
5641 }
5642
5643 /*
5644  * On success, We end up with an outstanding reference count against
5645  * iloc->bh.  This _must_ be cleaned up later.
5646  */
5647
5648 int
5649 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5650                          struct ext4_iloc *iloc)
5651 {
5652         int err;
5653
5654         err = ext4_get_inode_loc(inode, iloc);
5655         if (!err) {
5656                 BUFFER_TRACE(iloc->bh, "get_write_access");
5657                 err = ext4_journal_get_write_access(handle, iloc->bh);
5658                 if (err) {
5659                         brelse(iloc->bh);
5660                         iloc->bh = NULL;
5661                 }
5662         }
5663         ext4_std_error(inode->i_sb, err);
5664         return err;
5665 }
5666
5667 /*
5668  * Expand an inode by new_extra_isize bytes.
5669  * Returns 0 on success or negative error number on failure.
5670  */
5671 static int ext4_expand_extra_isize(struct inode *inode,
5672                                    unsigned int new_extra_isize,
5673                                    struct ext4_iloc iloc,
5674                                    handle_t *handle)
5675 {
5676         struct ext4_inode *raw_inode;
5677         struct ext4_xattr_ibody_header *header;
5678
5679         if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5680                 return 0;
5681
5682         raw_inode = ext4_raw_inode(&iloc);
5683
5684         header = IHDR(inode, raw_inode);
5685
5686         /* No extended attributes present */
5687         if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5688             header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5689                 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5690                         new_extra_isize);
5691                 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5692                 return 0;
5693         }
5694
5695         /* try to expand with EAs present */
5696         return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5697                                           raw_inode, handle);
5698 }
5699
5700 /*
5701  * What we do here is to mark the in-core inode as clean with respect to inode
5702  * dirtiness (it may still be data-dirty).
5703  * This means that the in-core inode may be reaped by prune_icache
5704  * without having to perform any I/O.  This is a very good thing,
5705  * because *any* task may call prune_icache - even ones which
5706  * have a transaction open against a different journal.
5707  *
5708  * Is this cheating?  Not really.  Sure, we haven't written the
5709  * inode out, but prune_icache isn't a user-visible syncing function.
5710  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5711  * we start and wait on commits.
5712  *
5713  * Is this efficient/effective?  Well, we're being nice to the system
5714  * by cleaning up our inodes proactively so they can be reaped
5715  * without I/O.  But we are potentially leaving up to five seconds'
5716  * worth of inodes floating about which prune_icache wants us to
5717  * write out.  One way to fix that would be to get prune_icache()
5718  * to do a write_super() to free up some memory.  It has the desired
5719  * effect.
5720  */
5721 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5722 {
5723         struct ext4_iloc iloc;
5724         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5725         static unsigned int mnt_count;
5726         int err, ret;
5727
5728         might_sleep();
5729         trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5730         err = ext4_reserve_inode_write(handle, inode, &iloc);
5731         if (ext4_handle_valid(handle) &&
5732             EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5733             !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5734                 /*
5735                  * We need extra buffer credits since we may write into EA block
5736                  * with this same handle. If journal_extend fails, then it will
5737                  * only result in a minor loss of functionality for that inode.
5738                  * If this is felt to be critical, then e2fsck should be run to
5739                  * force a large enough s_min_extra_isize.
5740                  */
5741                 if ((jbd2_journal_extend(handle,
5742                              EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5743                         ret = ext4_expand_extra_isize(inode,
5744                                                       sbi->s_want_extra_isize,
5745                                                       iloc, handle);
5746                         if (ret) {
5747                                 ext4_set_inode_state(inode,
5748                                                      EXT4_STATE_NO_EXPAND);
5749                                 if (mnt_count !=
5750                                         le16_to_cpu(sbi->s_es->s_mnt_count)) {
5751                                         ext4_warning(inode->i_sb,
5752                                         "Unable to expand inode %lu. Delete"
5753                                         " some EAs or run e2fsck.",
5754                                         inode->i_ino);
5755                                         mnt_count =
5756                                           le16_to_cpu(sbi->s_es->s_mnt_count);
5757                                 }
5758                         }
5759                 }
5760         }
5761         if (!err)
5762                 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5763         return err;
5764 }
5765
5766 /*
5767  * ext4_dirty_inode() is called from __mark_inode_dirty()
5768  *
5769  * We're really interested in the case where a file is being extended.
5770  * i_size has been changed by generic_commit_write() and we thus need
5771  * to include the updated inode in the current transaction.
5772  *
5773  * Also, dquot_alloc_block() will always dirty the inode when blocks
5774  * are allocated to the file.
5775  *
5776  * If the inode is marked synchronous, we don't honour that here - doing
5777  * so would cause a commit on atime updates, which we don't bother doing.
5778  * We handle synchronous inodes at the highest possible level.
5779  */
5780 void ext4_dirty_inode(struct inode *inode, int flags)
5781 {
5782         handle_t *handle;
5783
5784         handle = ext4_journal_start(inode, 2);
5785         if (IS_ERR(handle))
5786                 goto out;
5787
5788         ext4_mark_inode_dirty(handle, inode);
5789
5790         ext4_journal_stop(handle);
5791 out:
5792         return;
5793 }
5794
5795 #if 0
5796 /*
5797  * Bind an inode's backing buffer_head into this transaction, to prevent
5798  * it from being flushed to disk early.  Unlike
5799  * ext4_reserve_inode_write, this leaves behind no bh reference and
5800  * returns no iloc structure, so the caller needs to repeat the iloc
5801  * lookup to mark the inode dirty later.
5802  */
5803 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5804 {
5805         struct ext4_iloc iloc;
5806
5807         int err = 0;
5808         if (handle) {
5809                 err = ext4_get_inode_loc(inode, &iloc);
5810                 if (!err) {
5811                         BUFFER_TRACE(iloc.bh, "get_write_access");
5812                         err = jbd2_journal_get_write_access(handle, iloc.bh);
5813                         if (!err)
5814                                 err = ext4_handle_dirty_metadata(handle,
5815                                                                  NULL,
5816                                                                  iloc.bh);
5817                         brelse(iloc.bh);
5818                 }
5819         }
5820         ext4_std_error(inode->i_sb, err);
5821         return err;
5822 }
5823 #endif
5824
5825 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5826 {
5827         journal_t *journal;
5828         handle_t *handle;
5829         int err;
5830
5831         /*
5832          * We have to be very careful here: changing a data block's
5833          * journaling status dynamically is dangerous.  If we write a
5834          * data block to the journal, change the status and then delete
5835          * that block, we risk forgetting to revoke the old log record
5836          * from the journal and so a subsequent replay can corrupt data.
5837          * So, first we make sure that the journal is empty and that
5838          * nobody is changing anything.
5839          */
5840
5841         journal = EXT4_JOURNAL(inode);
5842         if (!journal)
5843                 return 0;
5844         if (is_journal_aborted(journal))
5845                 return -EROFS;
5846
5847         jbd2_journal_lock_updates(journal);
5848         jbd2_journal_flush(journal);
5849
5850         /*
5851          * OK, there are no updates running now, and all cached data is
5852          * synced to disk.  We are now in a completely consistent state
5853          * which doesn't have anything in the journal, and we know that
5854          * no filesystem updates are running, so it is safe to modify
5855          * the inode's in-core data-journaling state flag now.
5856          */
5857
5858         if (val)
5859                 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5860         else
5861                 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5862         ext4_set_aops(inode);
5863
5864         jbd2_journal_unlock_updates(journal);
5865
5866         /* Finally we can mark the inode as dirty. */
5867
5868         handle = ext4_journal_start(inode, 1);
5869         if (IS_ERR(handle))
5870                 return PTR_ERR(handle);
5871
5872         err = ext4_mark_inode_dirty(handle, inode);
5873         ext4_handle_sync(handle);
5874         ext4_journal_stop(handle);
5875         ext4_std_error(inode->i_sb, err);
5876
5877         return err;
5878 }
5879
5880 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5881 {
5882         return !buffer_mapped(bh);
5883 }
5884
5885 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5886 {
5887         struct page *page = vmf->page;
5888         loff_t size;
5889         unsigned long len;
5890         int ret = -EINVAL;
5891         void *fsdata;
5892         struct file *file = vma->vm_file;
5893         struct inode *inode = file->f_path.dentry->d_inode;
5894         struct address_space *mapping = inode->i_mapping;
5895
5896         /*
5897          * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5898          * get i_mutex because we are already holding mmap_sem.
5899          */
5900         down_read(&inode->i_alloc_sem);
5901         size = i_size_read(inode);
5902         if (page->mapping != mapping || size <= page_offset(page)
5903             || !PageUptodate(page)) {
5904                 /* page got truncated from under us? */
5905                 goto out_unlock;
5906         }
5907         ret = 0;
5908
5909         lock_page(page);
5910         wait_on_page_writeback(page);
5911         if (PageMappedToDisk(page)) {
5912                 up_read(&inode->i_alloc_sem);
5913                 return VM_FAULT_LOCKED;
5914         }
5915
5916         if (page->index == size >> PAGE_CACHE_SHIFT)
5917                 len = size & ~PAGE_CACHE_MASK;
5918         else
5919                 len = PAGE_CACHE_SIZE;
5920
5921         /*
5922          * return if we have all the buffers mapped. This avoid
5923          * the need to call write_begin/write_end which does a
5924          * journal_start/journal_stop which can block and take
5925          * long time
5926          */
5927         if (page_has_buffers(page)) {
5928                 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5929                                         ext4_bh_unmapped)) {
5930                         up_read(&inode->i_alloc_sem);
5931                         return VM_FAULT_LOCKED;
5932                 }
5933         }
5934         unlock_page(page);
5935         /*
5936          * OK, we need to fill the hole... Do write_begin write_end
5937          * to do block allocation/reservation.We are not holding
5938          * inode.i__mutex here. That allow * parallel write_begin,
5939          * write_end call. lock_page prevent this from happening
5940          * on the same page though
5941          */
5942         ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5943                         len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5944         if (ret < 0)
5945                 goto out_unlock;
5946         ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5947                         len, len, page, fsdata);
5948         if (ret < 0)
5949                 goto out_unlock;
5950         ret = 0;
5951
5952         /*
5953          * write_begin/end might have created a dirty page and someone
5954          * could wander in and start the IO.  Make sure that hasn't
5955          * happened.
5956          */
5957         lock_page(page);
5958         wait_on_page_writeback(page);
5959         up_read(&inode->i_alloc_sem);
5960         return VM_FAULT_LOCKED;
5961 out_unlock:
5962         if (ret)
5963                 ret = VM_FAULT_SIGBUS;
5964         up_read(&inode->i_alloc_sem);
5965         return ret;
5966 }