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