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