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