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