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