ext3: add support for extent_map library
[linux-2.6-block.git] / fs / ext3 / inode.c
1 /*
2  *  linux/fs/ext3/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 ext3_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/ext3_jbd.h>
29 #include <linux/jbd.h>
30 #include <linux/highuid.h>
31 #include <linux/pagemap.h>
32 #include <linux/quotaops.h>
33 #include <linux/string.h>
34 #include <linux/buffer_head.h>
35 #include <linux/writeback.h>
36 #include <linux/mpage.h>
37 #include <linux/extent_map.h>
38 #include <linux/uio.h>
39 #include <linux/bio.h>
40 #include <linux/fiemap.h>
41 #include <linux/namei.h>
42 #include "xattr.h"
43 #include "acl.h"
44
45 static int ext3_writepage_trans_blocks(struct inode *inode);
46
47 /*
48  * Test whether an inode is a fast symlink.
49  */
50 static int ext3_inode_is_fast_symlink(struct inode *inode)
51 {
52         int ea_blocks = EXT3_I(inode)->i_file_acl ?
53                 (inode->i_sb->s_blocksize >> 9) : 0;
54
55         return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
56 }
57
58 /*
59  * The ext3 forget function must perform a revoke if we are freeing data
60  * which has been journaled.  Metadata (eg. indirect blocks) must be
61  * revoked in all cases.
62  *
63  * "bh" may be NULL: a metadata block may have been freed from memory
64  * but there may still be a record of it in the journal, and that record
65  * still needs to be revoked.
66  */
67 int ext3_forget(handle_t *handle, int is_metadata, struct inode *inode,
68                         struct buffer_head *bh, ext3_fsblk_t blocknr)
69 {
70         int err;
71
72         might_sleep();
73
74         BUFFER_TRACE(bh, "enter");
75
76         jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
77                   "data mode %lx\n",
78                   bh, is_metadata, inode->i_mode,
79                   test_opt(inode->i_sb, DATA_FLAGS));
80
81         /* Never use the revoke function if we are doing full data
82          * journaling: there is no need to, and a V1 superblock won't
83          * support it.  Otherwise, only skip the revoke on un-journaled
84          * data blocks. */
85
86         if (test_opt(inode->i_sb, DATA_FLAGS) == EXT3_MOUNT_JOURNAL_DATA ||
87             (!is_metadata && !ext3_should_journal_data(inode))) {
88                 if (bh) {
89                         BUFFER_TRACE(bh, "call journal_forget");
90                         return ext3_journal_forget(handle, bh);
91                 }
92                 return 0;
93         }
94
95         /*
96          * data!=journal && (is_metadata || should_journal_data(inode))
97          */
98         BUFFER_TRACE(bh, "call ext3_journal_revoke");
99         err = ext3_journal_revoke(handle, blocknr, bh);
100         if (err)
101                 ext3_abort(inode->i_sb, __func__,
102                            "error %d when attempting revoke", err);
103         BUFFER_TRACE(bh, "exit");
104         return err;
105 }
106
107 /*
108  * Work out how many blocks we need to proceed with the next chunk of a
109  * truncate transaction.
110  */
111 static unsigned long blocks_for_truncate(struct inode *inode)
112 {
113         unsigned long needed;
114
115         needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
116
117         /* Give ourselves just enough room to cope with inodes in which
118          * i_blocks is corrupt: we've seen disk corruptions in the past
119          * which resulted in random data in an inode which looked enough
120          * like a regular file for ext3 to try to delete it.  Things
121          * will go a bit crazy if that happens, but at least we should
122          * try not to panic the whole kernel. */
123         if (needed < 2)
124                 needed = 2;
125
126         /* But we need to bound the transaction so we don't overflow the
127          * journal. */
128         if (needed > EXT3_MAX_TRANS_DATA)
129                 needed = EXT3_MAX_TRANS_DATA;
130
131         return EXT3_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
132 }
133
134 /*
135  * Truncate transactions can be complex and absolutely huge.  So we need to
136  * be able to restart the transaction at a conventient checkpoint to make
137  * sure we don't overflow the journal.
138  *
139  * start_transaction gets us a new handle for a truncate transaction,
140  * and extend_transaction tries to extend the existing one a bit.  If
141  * extend fails, we need to propagate the failure up and restart the
142  * transaction in the top-level truncate loop. --sct
143  */
144 static handle_t *start_transaction(struct inode *inode)
145 {
146         handle_t *result;
147
148         result = ext3_journal_start(inode, blocks_for_truncate(inode));
149         if (!IS_ERR(result))
150                 return result;
151
152         ext3_std_error(inode->i_sb, PTR_ERR(result));
153         return result;
154 }
155
156 /*
157  * Try to extend this transaction for the purposes of truncation.
158  *
159  * Returns 0 if we managed to create more room.  If we can't create more
160  * room, and the transaction must be restarted we return 1.
161  */
162 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
163 {
164         if (handle->h_buffer_credits > EXT3_RESERVE_TRANS_BLOCKS)
165                 return 0;
166         if (!ext3_journal_extend(handle, blocks_for_truncate(inode)))
167                 return 0;
168         return 1;
169 }
170
171 /*
172  * Restart the transaction associated with *handle.  This does a commit,
173  * so before we call here everything must be consistently dirtied against
174  * this transaction.
175  */
176 static int ext3_journal_test_restart(handle_t *handle, struct inode *inode)
177 {
178         jbd_debug(2, "restarting handle %p\n", handle);
179         return ext3_journal_restart(handle, blocks_for_truncate(inode));
180 }
181
182 /*
183  * Called at the last iput() if i_nlink is zero.
184  */
185 void ext3_delete_inode (struct inode * inode)
186 {
187         handle_t *handle;
188
189         truncate_inode_pages(&inode->i_data, 0);
190
191         if (is_bad_inode(inode))
192                 goto no_delete;
193
194         handle = start_transaction(inode);
195         if (IS_ERR(handle)) {
196                 /*
197                  * If we're going to skip the normal cleanup, we still need to
198                  * make sure that the in-core orphan linked list is properly
199                  * cleaned up.
200                  */
201                 ext3_orphan_del(NULL, inode);
202                 goto no_delete;
203         }
204
205         if (IS_SYNC(inode))
206                 handle->h_sync = 1;
207         inode->i_size = 0;
208         if (inode->i_blocks)
209                 ext3_truncate(inode);
210         /*
211          * Kill off the orphan record which ext3_truncate created.
212          * AKPM: I think this can be inside the above `if'.
213          * Note that ext3_orphan_del() has to be able to cope with the
214          * deletion of a non-existent orphan - this is because we don't
215          * know if ext3_truncate() actually created an orphan record.
216          * (Well, we could do this if we need to, but heck - it works)
217          */
218         ext3_orphan_del(handle, inode);
219         EXT3_I(inode)->i_dtime  = get_seconds();
220
221         /*
222          * One subtle ordering requirement: if anything has gone wrong
223          * (transaction abort, IO errors, whatever), then we can still
224          * do these next steps (the fs will already have been marked as
225          * having errors), but we can't free the inode if the mark_dirty
226          * fails.
227          */
228         if (ext3_mark_inode_dirty(handle, inode))
229                 /* If that failed, just do the required in-core inode clear. */
230                 clear_inode(inode);
231         else
232                 ext3_free_inode(handle, inode);
233         remove_extent_mappings(&EXT3_I(inode)->extent_tree, 0, (u64) -1);
234         ext3_journal_stop(handle);
235         return;
236 no_delete:
237         remove_extent_mappings(&EXT3_I(inode)->extent_tree, 0, (u64) -1);
238         clear_inode(inode);     /* We must guarantee clearing of inode... */
239 }
240
241 typedef struct {
242         __le32  *p;
243         __le32  key;
244         struct buffer_head *bh;
245 } Indirect;
246
247 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
248 {
249         p->key = *(p->p = v);
250         p->bh = bh;
251 }
252
253 static int verify_chain(Indirect *from, Indirect *to)
254 {
255         while (from <= to && from->key == *from->p)
256                 from++;
257         return (from > to);
258 }
259
260 /**
261  *      ext3_block_to_path - parse the block number into array of offsets
262  *      @inode: inode in question (we are only interested in its superblock)
263  *      @i_block: block number to be parsed
264  *      @offsets: array to store the offsets in
265  *      @boundary: set this non-zero if the referred-to block is likely to be
266  *             followed (on disk) by an indirect block.
267  *
268  *      To store the locations of file's data ext3 uses a data structure common
269  *      for UNIX filesystems - tree of pointers anchored in the inode, with
270  *      data blocks at leaves and indirect blocks in intermediate nodes.
271  *      This function translates the block number into path in that tree -
272  *      return value is the path length and @offsets[n] is the offset of
273  *      pointer to (n+1)th node in the nth one. If @block is out of range
274  *      (negative or too large) warning is printed and zero returned.
275  *
276  *      Note: function doesn't find node addresses, so no IO is needed. All
277  *      we need to know is the capacity of indirect blocks (taken from the
278  *      inode->i_sb).
279  */
280
281 /*
282  * Portability note: the last comparison (check that we fit into triple
283  * indirect block) is spelled differently, because otherwise on an
284  * architecture with 32-bit longs and 8Kb pages we might get into trouble
285  * if our filesystem had 8Kb blocks. We might use long long, but that would
286  * kill us on x86. Oh, well, at least the sign propagation does not matter -
287  * i_block would have to be negative in the very beginning, so we would not
288  * get there at all.
289  */
290
291 static int ext3_block_to_path(struct inode *inode,
292                         long i_block, int offsets[4], int *boundary)
293 {
294         int ptrs = EXT3_ADDR_PER_BLOCK(inode->i_sb);
295         int ptrs_bits = EXT3_ADDR_PER_BLOCK_BITS(inode->i_sb);
296         const long direct_blocks = EXT3_NDIR_BLOCKS,
297                 indirect_blocks = ptrs,
298                 double_blocks = (1 << (ptrs_bits * 2));
299         int n = 0;
300         int final = 0;
301
302         if (i_block < 0) {
303                 ext3_warning (inode->i_sb, "ext3_block_to_path", "block < 0");
304         } else if (i_block < direct_blocks) {
305                 offsets[n++] = i_block;
306                 final = direct_blocks;
307         } else if ( (i_block -= direct_blocks) < indirect_blocks) {
308                 offsets[n++] = EXT3_IND_BLOCK;
309                 offsets[n++] = i_block;
310                 final = ptrs;
311         } else if ((i_block -= indirect_blocks) < double_blocks) {
312                 offsets[n++] = EXT3_DIND_BLOCK;
313                 offsets[n++] = i_block >> ptrs_bits;
314                 offsets[n++] = i_block & (ptrs - 1);
315                 final = ptrs;
316         } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
317                 offsets[n++] = EXT3_TIND_BLOCK;
318                 offsets[n++] = i_block >> (ptrs_bits * 2);
319                 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
320                 offsets[n++] = i_block & (ptrs - 1);
321                 final = ptrs;
322         } else {
323                 ext3_warning(inode->i_sb, "ext3_block_to_path", "block > big");
324         }
325         if (boundary)
326                 *boundary = final - 1 - (i_block & (ptrs - 1));
327         return n;
328 }
329
330 /**
331  *      ext3_get_branch - read the chain of indirect blocks leading to data
332  *      @inode: inode in question
333  *      @depth: depth of the chain (1 - direct pointer, etc.)
334  *      @offsets: offsets of pointers in inode/indirect blocks
335  *      @chain: place to store the result
336  *      @err: here we store the error value
337  *
338  *      Function fills the array of triples <key, p, bh> and returns %NULL
339  *      if everything went OK or the pointer to the last filled triple
340  *      (incomplete one) otherwise. Upon the return chain[i].key contains
341  *      the number of (i+1)-th block in the chain (as it is stored in memory,
342  *      i.e. little-endian 32-bit), chain[i].p contains the address of that
343  *      number (it points into struct inode for i==0 and into the bh->b_data
344  *      for i>0) and chain[i].bh points to the buffer_head of i-th indirect
345  *      block for i>0 and NULL for i==0. In other words, it holds the block
346  *      numbers of the chain, addresses they were taken from (and where we can
347  *      verify that chain did not change) and buffer_heads hosting these
348  *      numbers.
349  *
350  *      Function stops when it stumbles upon zero pointer (absent block)
351  *              (pointer to last triple returned, *@err == 0)
352  *      or when it gets an IO error reading an indirect block
353  *              (ditto, *@err == -EIO)
354  *      or when it notices that chain had been changed while it was reading
355  *              (ditto, *@err == -EAGAIN)
356  *      or when it reads all @depth-1 indirect blocks successfully and finds
357  *      the whole chain, all way to the data (returns %NULL, *err == 0).
358  */
359 static Indirect *ext3_get_branch(struct inode *inode, int depth, int *offsets,
360                                  Indirect chain[4], int *err)
361 {
362         struct super_block *sb = inode->i_sb;
363         Indirect *p = chain;
364         struct buffer_head *bh;
365
366         *err = 0;
367         /* i_data is not going away, no lock needed */
368         add_chain (chain, NULL, EXT3_I(inode)->i_data + *offsets);
369         if (!p->key)
370                 goto no_block;
371         while (--depth) {
372                 bh = sb_bread(sb, le32_to_cpu(p->key));
373                 if (!bh)
374                         goto failure;
375                 /* Reader: pointers */
376                 if (!verify_chain(chain, p))
377                         goto changed;
378                 add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
379                 /* Reader: end */
380                 if (!p->key)
381                         goto no_block;
382         }
383         return NULL;
384
385 changed:
386         brelse(bh);
387         *err = -EAGAIN;
388         goto no_block;
389 failure:
390         *err = -EIO;
391 no_block:
392         return p;
393 }
394
395 /**
396  *      ext3_find_near - find a place for allocation with sufficient locality
397  *      @inode: owner
398  *      @ind: descriptor of indirect block.
399  *
400  *      This function returns the preferred place for block allocation.
401  *      It is used when heuristic for sequential allocation fails.
402  *      Rules are:
403  *        + if there is a block to the left of our position - allocate near it.
404  *        + if pointer will live in indirect block - allocate near that block.
405  *        + if pointer will live in inode - allocate in the same
406  *          cylinder group.
407  *
408  * In the latter case we colour the starting block by the callers PID to
409  * prevent it from clashing with concurrent allocations for a different inode
410  * in the same block group.   The PID is used here so that functionally related
411  * files will be close-by on-disk.
412  *
413  *      Caller must make sure that @ind is valid and will stay that way.
414  */
415 static ext3_fsblk_t ext3_find_near(struct inode *inode, Indirect *ind)
416 {
417         struct ext3_inode_info *ei = EXT3_I(inode);
418         __le32 *start = ind->bh ? (__le32*) ind->bh->b_data : ei->i_data;
419         __le32 *p;
420         ext3_fsblk_t bg_start;
421         ext3_grpblk_t colour;
422
423         /* Try to find previous block */
424         for (p = ind->p - 1; p >= start; p--) {
425                 if (*p)
426                         return le32_to_cpu(*p);
427         }
428
429         /* No such thing, so let's try location of indirect block */
430         if (ind->bh)
431                 return ind->bh->b_blocknr;
432
433         /*
434          * It is going to be referred to from the inode itself? OK, just put it
435          * into the same cylinder group then.
436          */
437         bg_start = ext3_group_first_block_no(inode->i_sb, ei->i_block_group);
438         colour = (current->pid % 16) *
439                         (EXT3_BLOCKS_PER_GROUP(inode->i_sb) / 16);
440         return bg_start + colour;
441 }
442
443 /**
444  *      ext3_find_goal - find a preferred place for allocation.
445  *      @inode: owner
446  *      @block:  block we want
447  *      @partial: pointer to the last triple within a chain
448  *
449  *      Normally this function find the preferred place for block allocation,
450  *      returns it.
451  */
452
453 static ext3_fsblk_t ext3_find_goal(struct inode *inode, long block,
454                                    Indirect *partial)
455 {
456         struct ext3_block_alloc_info *block_i;
457
458         block_i =  EXT3_I(inode)->i_block_alloc_info;
459
460         /*
461          * try the heuristic for sequential allocation,
462          * failing that at least try to get decent locality.
463          */
464         if (block_i && (block == block_i->last_alloc_logical_block + 1)
465                 && (block_i->last_alloc_physical_block != 0)) {
466                 return block_i->last_alloc_physical_block + 1;
467         }
468
469         return ext3_find_near(inode, partial);
470 }
471
472 /**
473  *      ext3_blks_to_allocate: Look up the block map and count the number
474  *      of direct blocks need to be allocated for the given branch.
475  *
476  *      @branch: chain of indirect blocks
477  *      @k: number of blocks need for indirect blocks
478  *      @blks: number of data blocks to be mapped.
479  *      @blocks_to_boundary:  the offset in the indirect block
480  *
481  *      return the total number of blocks to be allocate, including the
482  *      direct and indirect blocks.
483  */
484 static int ext3_blks_to_allocate(Indirect *branch, int k, unsigned long blks,
485                 int blocks_to_boundary)
486 {
487         unsigned long count = 0;
488
489         /*
490          * Simple case, [t,d]Indirect block(s) has not allocated yet
491          * then it's clear blocks on that path have not allocated
492          */
493         if (k > 0) {
494                 /* right now we don't handle cross boundary allocation */
495                 if (blks < blocks_to_boundary + 1)
496                         count += blks;
497                 else
498                         count += blocks_to_boundary + 1;
499                 return count;
500         }
501
502         count++;
503         while (count < blks && count <= blocks_to_boundary &&
504                 le32_to_cpu(*(branch[0].p + count)) == 0) {
505                 count++;
506         }
507         return count;
508 }
509
510 /**
511  *      ext3_alloc_blocks: multiple allocate blocks needed for a branch
512  *      @indirect_blks: the number of blocks need to allocate for indirect
513  *                      blocks
514  *
515  *      @new_blocks: on return it will store the new block numbers for
516  *      the indirect blocks(if needed) and the first direct block,
517  *      @blks:  on return it will store the total number of allocated
518  *              direct blocks
519  */
520 static int ext3_alloc_blocks(handle_t *handle, struct inode *inode,
521                         ext3_fsblk_t goal, int indirect_blks, int blks,
522                         ext3_fsblk_t new_blocks[4], int *err)
523 {
524         int target, i;
525         unsigned long count = 0;
526         int index = 0;
527         ext3_fsblk_t current_block = 0;
528         int ret = 0;
529
530         /*
531          * Here we try to allocate the requested multiple blocks at once,
532          * on a best-effort basis.
533          * To build a branch, we should allocate blocks for
534          * the indirect blocks(if not allocated yet), and at least
535          * the first direct block of this branch.  That's the
536          * minimum number of blocks need to allocate(required)
537          */
538         target = blks + indirect_blks;
539
540         while (1) {
541                 count = target;
542                 /* allocating blocks for indirect blocks and direct blocks */
543                 current_block = ext3_new_blocks(handle,inode,goal,&count,err);
544                 if (*err)
545                         goto failed_out;
546
547                 target -= count;
548                 /* allocate blocks for indirect blocks */
549                 while (index < indirect_blks && count) {
550                         new_blocks[index++] = current_block++;
551                         count--;
552                 }
553
554                 if (count > 0)
555                         break;
556         }
557
558         /* save the new block number for the first direct block */
559         new_blocks[index] = current_block;
560
561         /* total number of blocks allocated for direct blocks */
562         ret = count;
563         *err = 0;
564         return ret;
565 failed_out:
566         for (i = 0; i <index; i++)
567                 ext3_free_blocks(handle, inode, new_blocks[i], 1);
568         return ret;
569 }
570
571 /**
572  *      ext3_alloc_branch - allocate and set up a chain of blocks.
573  *      @inode: owner
574  *      @indirect_blks: number of allocated indirect blocks
575  *      @blks: number of allocated direct blocks
576  *      @offsets: offsets (in the blocks) to store the pointers to next.
577  *      @branch: place to store the chain in.
578  *
579  *      This function allocates blocks, zeroes out all but the last one,
580  *      links them into chain and (if we are synchronous) writes them to disk.
581  *      In other words, it prepares a branch that can be spliced onto the
582  *      inode. It stores the information about that chain in the branch[], in
583  *      the same format as ext3_get_branch() would do. We are calling it after
584  *      we had read the existing part of chain and partial points to the last
585  *      triple of that (one with zero ->key). Upon the exit we have the same
586  *      picture as after the successful ext3_get_block(), except that in one
587  *      place chain is disconnected - *branch->p is still zero (we did not
588  *      set the last link), but branch->key contains the number that should
589  *      be placed into *branch->p to fill that gap.
590  *
591  *      If allocation fails we free all blocks we've allocated (and forget
592  *      their buffer_heads) and return the error value the from failed
593  *      ext3_alloc_block() (normally -ENOSPC). Otherwise we set the chain
594  *      as described above and return 0.
595  */
596 static int ext3_alloc_branch(handle_t *handle, struct inode *inode,
597                         int indirect_blks, int *blks, ext3_fsblk_t goal,
598                         int *offsets, Indirect *branch)
599 {
600         int blocksize = inode->i_sb->s_blocksize;
601         int i, n = 0;
602         int err = 0;
603         struct buffer_head *bh;
604         int num;
605         ext3_fsblk_t new_blocks[4];
606         ext3_fsblk_t current_block;
607
608         num = ext3_alloc_blocks(handle, inode, goal, indirect_blks,
609                                 *blks, new_blocks, &err);
610         if (err)
611                 return err;
612
613         branch[0].key = cpu_to_le32(new_blocks[0]);
614         /*
615          * metadata blocks and data blocks are allocated.
616          */
617         for (n = 1; n <= indirect_blks;  n++) {
618                 /*
619                  * Get buffer_head for parent block, zero it out
620                  * and set the pointer to new one, then send
621                  * parent to disk.
622                  */
623                 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
624                 branch[n].bh = bh;
625                 lock_buffer(bh);
626                 BUFFER_TRACE(bh, "call get_create_access");
627                 err = ext3_journal_get_create_access(handle, bh);
628                 if (err) {
629                         unlock_buffer(bh);
630                         brelse(bh);
631                         goto failed;
632                 }
633
634                 memset(bh->b_data, 0, blocksize);
635                 branch[n].p = (__le32 *) bh->b_data + offsets[n];
636                 branch[n].key = cpu_to_le32(new_blocks[n]);
637                 *branch[n].p = branch[n].key;
638                 if ( n == indirect_blks) {
639                         current_block = new_blocks[n];
640                         /*
641                          * End of chain, update the last new metablock of
642                          * the chain to point to the new allocated
643                          * data blocks numbers
644                          */
645                         for (i=1; i < num; i++)
646                                 *(branch[n].p + i) = cpu_to_le32(++current_block);
647                 }
648                 BUFFER_TRACE(bh, "marking uptodate");
649                 set_buffer_uptodate(bh);
650                 unlock_buffer(bh);
651
652                 BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
653                 err = ext3_journal_dirty_metadata(handle, bh);
654                 if (err)
655                         goto failed;
656         }
657         *blks = num;
658         return err;
659 failed:
660         /* Allocation failed, free what we already allocated */
661         for (i = 1; i <= n ; i++) {
662                 BUFFER_TRACE(branch[i].bh, "call journal_forget");
663                 ext3_journal_forget(handle, branch[i].bh);
664         }
665         for (i = 0; i <indirect_blks; i++)
666                 ext3_free_blocks(handle, inode, new_blocks[i], 1);
667
668         ext3_free_blocks(handle, inode, new_blocks[i], num);
669
670         return err;
671 }
672
673 /**
674  * ext3_splice_branch - splice the allocated branch onto inode.
675  * @inode: owner
676  * @block: (logical) number of block we are adding
677  * @chain: chain of indirect blocks (with a missing link - see
678  *      ext3_alloc_branch)
679  * @where: location of missing link
680  * @num:   number of indirect blocks we are adding
681  * @blks:  number of direct blocks we are adding
682  *
683  * This function fills the missing link and does all housekeeping needed in
684  * inode (->i_blocks, etc.). In case of success we end up with the full
685  * chain to new block and return 0.
686  */
687 static int ext3_splice_branch(handle_t *handle, struct inode *inode,
688                         long block, Indirect *where, int num, int blks)
689 {
690         int i;
691         int err = 0;
692         struct ext3_block_alloc_info *block_i;
693         ext3_fsblk_t current_block;
694
695         block_i = EXT3_I(inode)->i_block_alloc_info;
696         /*
697          * If we're splicing into a [td]indirect block (as opposed to the
698          * inode) then we need to get write access to the [td]indirect block
699          * before the splice.
700          */
701         if (where->bh) {
702                 BUFFER_TRACE(where->bh, "get_write_access");
703                 err = ext3_journal_get_write_access(handle, where->bh);
704                 if (err)
705                         goto err_out;
706         }
707         /* That's it */
708
709         *where->p = where->key;
710
711         /*
712          * Update the host buffer_head or inode to point to more just allocated
713          * direct blocks blocks
714          */
715         if (num == 0 && blks > 1) {
716                 current_block = le32_to_cpu(where->key) + 1;
717                 for (i = 1; i < blks; i++)
718                         *(where->p + i ) = cpu_to_le32(current_block++);
719         }
720
721         /*
722          * update the most recently allocated logical & physical block
723          * in i_block_alloc_info, to assist find the proper goal block for next
724          * allocation
725          */
726         if (block_i) {
727                 block_i->last_alloc_logical_block = block + blks - 1;
728                 block_i->last_alloc_physical_block =
729                                 le32_to_cpu(where[num].key) + blks - 1;
730         }
731
732         /* We are done with atomic stuff, now do the rest of housekeeping */
733
734         inode->i_ctime = CURRENT_TIME_SEC;
735         ext3_mark_inode_dirty(handle, inode);
736
737         /* had we spliced it onto indirect block? */
738         if (where->bh) {
739                 /*
740                  * If we spliced it onto an indirect block, we haven't
741                  * altered the inode.  Note however that if it is being spliced
742                  * onto an indirect block at the very end of the file (the
743                  * file is growing) then we *will* alter the inode to reflect
744                  * the new i_size.  But that is not done here - it is done in
745                  * generic_commit_write->__mark_inode_dirty->ext3_dirty_inode.
746                  */
747                 jbd_debug(5, "splicing indirect only\n");
748                 BUFFER_TRACE(where->bh, "call ext3_journal_dirty_metadata");
749                 err = ext3_journal_dirty_metadata(handle, where->bh);
750                 if (err)
751                         goto err_out;
752         } else {
753                 /*
754                  * OK, we spliced it into the inode itself on a direct block.
755                  * Inode was dirtied above.
756                  */
757                 jbd_debug(5, "splicing direct\n");
758         }
759         return err;
760
761 err_out:
762         for (i = 1; i <= num; i++) {
763                 BUFFER_TRACE(where[i].bh, "call journal_forget");
764                 ext3_journal_forget(handle, where[i].bh);
765                 ext3_free_blocks(handle,inode,le32_to_cpu(where[i-1].key),1);
766         }
767         ext3_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks);
768
769         return err;
770 }
771
772 /*
773  * Allocation strategy is simple: if we have to allocate something, we will
774  * have to go the whole way to leaf. So let's do it before attaching anything
775  * to tree, set linkage between the newborn blocks, write them if sync is
776  * required, recheck the path, free and repeat if check fails, otherwise
777  * set the last missing link (that will protect us from any truncate-generated
778  * removals - all blocks on the path are immune now) and possibly force the
779  * write on the parent block.
780  * That has a nice additional property: no special recovery from the failed
781  * allocations is needed - we simply release blocks and do not touch anything
782  * reachable from inode.
783  *
784  * `handle' can be NULL if create == 0.
785  *
786  * The BKL may not be held on entry here.  Be sure to take it early.
787  * return > 0, # of blocks mapped or allocated.
788  * return = 0, if plain lookup failed.
789  * return < 0, error case.
790  */
791 int ext3_get_blocks_handle(handle_t *handle, struct inode *inode,
792                 sector_t iblock, unsigned long maxblocks,
793                 struct buffer_head *bh_result,
794                 int create, int extend_disksize)
795 {
796         int err = -EIO;
797         int offsets[4];
798         Indirect chain[4];
799         Indirect *partial;
800         ext3_fsblk_t goal;
801         int indirect_blks;
802         int blocks_to_boundary = 0;
803         int depth;
804         struct ext3_inode_info *ei = EXT3_I(inode);
805         int count = 0;
806         ext3_fsblk_t first_block = 0;
807
808
809         J_ASSERT(handle != NULL || create == 0);
810         depth = ext3_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
811
812         if (depth == 0)
813                 goto out;
814
815         partial = ext3_get_branch(inode, depth, offsets, chain, &err);
816
817         /* Simplest case - block found, no allocation needed */
818         if (!partial) {
819                 first_block = le32_to_cpu(chain[depth - 1].key);
820                 clear_buffer_new(bh_result);
821                 count++;
822                 /*map more blocks*/
823                 while (count < maxblocks && count <= blocks_to_boundary) {
824                         ext3_fsblk_t blk;
825
826                         if (!verify_chain(chain, partial)) {
827                                 /*
828                                  * Indirect block might be removed by
829                                  * truncate while we were reading it.
830                                  * Handling of that case: forget what we've
831                                  * got now. Flag the err as EAGAIN, so it
832                                  * will reread.
833                                  */
834                                 err = -EAGAIN;
835                                 count = 0;
836                                 break;
837                         }
838                         blk = le32_to_cpu(*(chain[depth-1].p + count));
839
840                         if (blk == first_block + count)
841                                 count++;
842                         else
843                                 break;
844                 }
845                 if (err != -EAGAIN)
846                         goto got_it;
847         }
848
849         /* Next simple case - plain lookup or failed read of indirect block */
850         if (!create || err == -EIO)
851                 goto cleanup;
852
853         mutex_lock(&ei->truncate_mutex);
854
855         /*
856          * If the indirect block is missing while we are reading
857          * the chain(ext3_get_branch() returns -EAGAIN err), or
858          * if the chain has been changed after we grab the semaphore,
859          * (either because another process truncated this branch, or
860          * another get_block allocated this branch) re-grab the chain to see if
861          * the request block has been allocated or not.
862          *
863          * Since we already block the truncate/other get_block
864          * at this point, we will have the current copy of the chain when we
865          * splice the branch into the tree.
866          */
867         if (err == -EAGAIN || !verify_chain(chain, partial)) {
868                 while (partial > chain) {
869                         brelse(partial->bh);
870                         partial--;
871                 }
872                 partial = ext3_get_branch(inode, depth, offsets, chain, &err);
873                 if (!partial) {
874                         count++;
875                         mutex_unlock(&ei->truncate_mutex);
876                         if (err)
877                                 goto cleanup;
878                         clear_buffer_new(bh_result);
879                         goto got_it;
880                 }
881         }
882
883         /*
884          * Okay, we need to do block allocation.  Lazily initialize the block
885          * allocation info here if necessary
886         */
887         if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
888                 ext3_init_block_alloc_info(inode);
889
890         goal = ext3_find_goal(inode, iblock, partial);
891
892         /* the number of blocks need to allocate for [d,t]indirect blocks */
893         indirect_blks = (chain + depth) - partial - 1;
894
895         /*
896          * Next look up the indirect map to count the totoal number of
897          * direct blocks to allocate for this branch.
898          */
899         count = ext3_blks_to_allocate(partial, indirect_blks,
900                                         maxblocks, blocks_to_boundary);
901         /*
902          * Block out ext3_truncate while we alter the tree
903          */
904         err = ext3_alloc_branch(handle, inode, indirect_blks, &count, goal,
905                                 offsets + (partial - chain), partial);
906
907         /*
908          * The ext3_splice_branch call will free and forget any buffers
909          * on the new chain if there is a failure, but that risks using
910          * up transaction credits, especially for bitmaps where the
911          * credits cannot be returned.  Can we handle this somehow?  We
912          * may need to return -EAGAIN upwards in the worst case.  --sct
913          */
914         if (!err)
915                 err = ext3_splice_branch(handle, inode, iblock,
916                                         partial, indirect_blks, count);
917         /*
918          * i_disksize growing is protected by truncate_mutex.  Don't forget to
919          * protect it if you're about to implement concurrent
920          * ext3_get_block() -bzzz
921         */
922         if (!err && extend_disksize && inode->i_size > ei->i_disksize)
923                 ei->i_disksize = inode->i_size;
924         mutex_unlock(&ei->truncate_mutex);
925         if (err)
926                 goto cleanup;
927
928         set_buffer_new(bh_result);
929 got_it:
930         map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
931         if (count > blocks_to_boundary)
932                 set_buffer_boundary(bh_result);
933         err = count;
934         /* Clean up and exit */
935         partial = chain + depth - 1;    /* the whole chain */
936 cleanup:
937         while (partial > chain) {
938                 BUFFER_TRACE(partial->bh, "call brelse");
939                 brelse(partial->bh);
940                 partial--;
941         }
942         BUFFER_TRACE(bh_result, "returned");
943 out:
944         return err;
945 }
946
947 /* Maximum number of blocks we map for direct IO at once. */
948 #define DIO_MAX_BLOCKS 4096
949 /*
950  * Number of credits we need for writing DIO_MAX_BLOCKS:
951  * We need sb + group descriptor + bitmap + inode -> 4
952  * For B blocks with A block pointers per block we need:
953  * 1 (triple ind.) + (B/A/A + 2) (doubly ind.) + (B/A + 2) (indirect).
954  * If we plug in 4096 for B and 256 for A (for 1KB block size), we get 25.
955  */
956 #define DIO_CREDITS 25
957
958 static int ext3_get_block(struct inode *inode, sector_t iblock,
959                         struct buffer_head *bh_result, int create)
960 {
961         handle_t *handle = ext3_journal_current_handle();
962         int ret = 0, started = 0;
963         unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
964
965         if (create && !handle) {        /* Direct IO write... */
966                 if (max_blocks > DIO_MAX_BLOCKS)
967                         max_blocks = DIO_MAX_BLOCKS;
968                 handle = ext3_journal_start(inode, DIO_CREDITS +
969                                 2 * EXT3_QUOTA_TRANS_BLOCKS(inode->i_sb));
970                 if (IS_ERR(handle)) {
971                         ret = PTR_ERR(handle);
972                         goto out;
973                 }
974                 started = 1;
975         }
976
977         ret = ext3_get_blocks_handle(handle, inode, iblock,
978                                         max_blocks, bh_result, create, 0);
979         if (ret > 0) {
980                 bh_result->b_size = (ret << inode->i_blkbits);
981                 ret = 0;
982         }
983         if (started)
984                 ext3_journal_stop(handle);
985 out:
986         return ret;
987 }
988
989 int ext3_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
990                 u64 start, u64 len)
991 {
992         return generic_block_fiemap(inode, fieinfo, start, len,
993                                     ext3_get_block);
994 }
995
996 static struct extent_map *ext3_map_extent(struct address_space *mapping,
997                                           struct page *page, size_t page_offset,
998                                           loff_t start, u64 len, int create,
999                                           gfp_t gfp_mask)
1000 {
1001         struct extent_map_tree *tree = &EXT3_I(mapping->host)->extent_tree;
1002         handle_t *handle = NULL;
1003         struct extent_map *ret;
1004
1005         if (create) {
1006                 handle = ext3_journal_start(mapping->host, len >> 9);
1007                 if (IS_ERR(handle))
1008                         return (struct extent_map *) handle;
1009         }
1010
1011         ret = map_extent_get_block(tree, mapping, start, len, create, gfp_mask,
1012                                         ext3_get_block);
1013         if (handle)
1014                 ext3_journal_stop(handle);
1015
1016         return ret;
1017 }
1018
1019 /*
1020  * `handle' can be NULL if create is zero
1021  */
1022 struct buffer_head *ext3_getblk(handle_t *handle, struct inode *inode,
1023                                 long block, int create, int *errp)
1024 {
1025         struct buffer_head dummy;
1026         int fatal = 0, err;
1027
1028         J_ASSERT(handle != NULL || create == 0);
1029
1030         dummy.b_state = 0;
1031         dummy.b_blocknr = -1000;
1032         buffer_trace_init(&dummy.b_history);
1033         err = ext3_get_blocks_handle(handle, inode, block, 1,
1034                                         &dummy, create, 1);
1035         /*
1036          * ext3_get_blocks_handle() returns number of blocks
1037          * mapped. 0 in case of a HOLE.
1038          */
1039         if (err > 0) {
1040                 if (err > 1)
1041                         WARN_ON(1);
1042                 err = 0;
1043         }
1044         *errp = err;
1045         if (!err && buffer_mapped(&dummy)) {
1046                 struct buffer_head *bh;
1047                 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1048                 if (!bh) {
1049                         *errp = -EIO;
1050                         goto err;
1051                 }
1052                 if (buffer_new(&dummy)) {
1053                         J_ASSERT(create != 0);
1054                         J_ASSERT(handle != NULL);
1055
1056                         /*
1057                          * Now that we do not always journal data, we should
1058                          * keep in mind whether this should always journal the
1059                          * new buffer as metadata.  For now, regular file
1060                          * writes use ext3_get_block instead, so it's not a
1061                          * problem.
1062                          */
1063                         lock_buffer(bh);
1064                         BUFFER_TRACE(bh, "call get_create_access");
1065                         fatal = ext3_journal_get_create_access(handle, bh);
1066                         if (!fatal && !buffer_uptodate(bh)) {
1067                                 memset(bh->b_data,0,inode->i_sb->s_blocksize);
1068                                 set_buffer_uptodate(bh);
1069                         }
1070                         unlock_buffer(bh);
1071                         BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
1072                         err = ext3_journal_dirty_metadata(handle, bh);
1073                         if (!fatal)
1074                                 fatal = err;
1075                 } else {
1076                         BUFFER_TRACE(bh, "not a new buffer");
1077                 }
1078                 if (fatal) {
1079                         *errp = fatal;
1080                         brelse(bh);
1081                         bh = NULL;
1082                 }
1083                 return bh;
1084         }
1085 err:
1086         return NULL;
1087 }
1088
1089 struct buffer_head *ext3_bread(handle_t *handle, struct inode *inode,
1090                                int block, int create, int *err)
1091 {
1092         struct buffer_head * bh;
1093
1094         bh = ext3_getblk(handle, inode, block, create, err);
1095         if (!bh)
1096                 return bh;
1097         if (buffer_uptodate(bh))
1098                 return bh;
1099         ll_rw_block(READ_META, 1, &bh);
1100         wait_on_buffer(bh);
1101         if (buffer_uptodate(bh))
1102                 return bh;
1103         put_bh(bh);
1104         *err = -EIO;
1105         return NULL;
1106 }
1107
1108 static int walk_page_buffers(   handle_t *handle,
1109                                 struct buffer_head *head,
1110                                 unsigned from,
1111                                 unsigned to,
1112                                 int *partial,
1113                                 int (*fn)(      handle_t *handle,
1114                                                 struct buffer_head *bh))
1115 {
1116         struct buffer_head *bh;
1117         unsigned block_start, block_end;
1118         unsigned blocksize = head->b_size;
1119         int err, ret = 0;
1120         struct buffer_head *next;
1121
1122         for (   bh = head, block_start = 0;
1123                 ret == 0 && (bh != head || !block_start);
1124                 block_start = block_end, bh = next)
1125         {
1126                 next = bh->b_this_page;
1127                 block_end = block_start + blocksize;
1128                 if (block_end <= from || block_start >= to) {
1129                         if (partial && !buffer_uptodate(bh))
1130                                 *partial = 1;
1131                         continue;
1132                 }
1133                 err = (*fn)(handle, bh);
1134                 if (!ret)
1135                         ret = err;
1136         }
1137         return ret;
1138 }
1139
1140 /*
1141  * To preserve ordering, it is essential that the hole instantiation and
1142  * the data write be encapsulated in a single transaction.  We cannot
1143  * close off a transaction and start a new one between the ext3_get_block()
1144  * and the commit_write().  So doing the journal_start at the start of
1145  * prepare_write() is the right place.
1146  *
1147  * Also, this function can nest inside ext3_writepage() ->
1148  * block_write_full_page(). In that case, we *know* that ext3_writepage()
1149  * has generated enough buffer credits to do the whole page.  So we won't
1150  * block on the journal in that case, which is good, because the caller may
1151  * be PF_MEMALLOC.
1152  *
1153  * By accident, ext3 can be reentered when a transaction is open via
1154  * quota file writes.  If we were to commit the transaction while thus
1155  * reentered, there can be a deadlock - we would be holding a quota
1156  * lock, and the commit would never complete if another thread had a
1157  * transaction open and was blocking on the quota lock - a ranking
1158  * violation.
1159  *
1160  * So what we do is to rely on the fact that journal_stop/journal_start
1161  * will _not_ run commit under these circumstances because handle->h_ref
1162  * is elevated.  We'll still have enough credits for the tiny quotafile
1163  * write.
1164  */
1165 static int do_journal_get_write_access(handle_t *handle,
1166                                         struct buffer_head *bh)
1167 {
1168         if (!buffer_mapped(bh) || buffer_freed(bh))
1169                 return 0;
1170         return ext3_journal_get_write_access(handle, bh);
1171 }
1172
1173 static int ext3_write_begin(struct file *file, struct address_space *mapping,
1174                                 loff_t pos, unsigned len, unsigned flags,
1175                                 struct page **pagep, void **fsdata)
1176 {
1177         struct inode *inode = mapping->host;
1178         int ret, needed_blocks = ext3_writepage_trans_blocks(inode);
1179         handle_t *handle;
1180         int retries = 0;
1181         struct page *page;
1182         pgoff_t index;
1183         unsigned from, to;
1184
1185         index = pos >> PAGE_CACHE_SHIFT;
1186         from = pos & (PAGE_CACHE_SIZE - 1);
1187         to = from + len;
1188
1189 retry:
1190         page = grab_cache_page_write_begin(mapping, index, flags);
1191         if (!page)
1192                 return -ENOMEM;
1193         *pagep = page;
1194
1195         handle = ext3_journal_start(inode, needed_blocks);
1196         if (IS_ERR(handle)) {
1197                 unlock_page(page);
1198                 page_cache_release(page);
1199                 ret = PTR_ERR(handle);
1200                 goto out;
1201         }
1202         ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1203                                                         ext3_get_block);
1204         if (ret)
1205                 goto write_begin_failed;
1206
1207         if (ext3_should_journal_data(inode)) {
1208                 ret = walk_page_buffers(handle, page_buffers(page),
1209                                 from, to, NULL, do_journal_get_write_access);
1210         }
1211 write_begin_failed:
1212         if (ret) {
1213                 ext3_journal_stop(handle);
1214                 unlock_page(page);
1215                 page_cache_release(page);
1216                 /*
1217                  * block_write_begin may have instantiated a few blocks
1218                  * outside i_size.  Trim these off again. Don't need
1219                  * i_size_read because we hold i_mutex.
1220                  */
1221                 if (pos + len > inode->i_size)
1222                         vmtruncate(inode, inode->i_size);
1223         }
1224         if (ret == -ENOSPC && ext3_should_retry_alloc(inode->i_sb, &retries))
1225                 goto retry;
1226 out:
1227         return ret;
1228 }
1229
1230
1231 int ext3_journal_dirty_data(handle_t *handle, struct buffer_head *bh)
1232 {
1233         int err = journal_dirty_data(handle, bh);
1234         if (err)
1235                 ext3_journal_abort_handle(__func__, __func__,
1236                                                 bh, handle, err);
1237         return err;
1238 }
1239
1240 /* For write_end() in data=journal mode */
1241 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1242 {
1243         if (!buffer_mapped(bh) || buffer_freed(bh))
1244                 return 0;
1245         set_buffer_uptodate(bh);
1246         return ext3_journal_dirty_metadata(handle, bh);
1247 }
1248
1249 /*
1250  * Generic write_end handler for ordered and writeback ext3 journal modes.
1251  * We can't use generic_write_end, because that unlocks the page and we need to
1252  * unlock the page after ext3_journal_stop, but ext3_journal_stop must run
1253  * after block_write_end.
1254  */
1255 static int ext3_generic_write_end(struct file *file,
1256                                 struct address_space *mapping,
1257                                 loff_t pos, unsigned len, unsigned copied,
1258                                 struct page *page, void *fsdata)
1259 {
1260         struct inode *inode = file->f_mapping->host;
1261
1262         copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1263
1264         if (pos+copied > inode->i_size) {
1265                 i_size_write(inode, pos+copied);
1266                 mark_inode_dirty(inode);
1267         }
1268
1269         return copied;
1270 }
1271
1272 /*
1273  * We need to pick up the new inode size which generic_commit_write gave us
1274  * `file' can be NULL - eg, when called from page_symlink().
1275  *
1276  * ext3 never places buffers on inode->i_mapping->private_list.  metadata
1277  * buffers are managed internally.
1278  */
1279 static int ext3_ordered_write_end(struct file *file,
1280                                 struct address_space *mapping,
1281                                 loff_t pos, unsigned len, unsigned copied,
1282                                 struct page *page, void *fsdata)
1283 {
1284         handle_t *handle = ext3_journal_current_handle();
1285         struct inode *inode = file->f_mapping->host;
1286         unsigned from, to;
1287         int ret = 0, ret2;
1288
1289         from = pos & (PAGE_CACHE_SIZE - 1);
1290         to = from + len;
1291
1292         ret = walk_page_buffers(handle, page_buffers(page),
1293                 from, to, NULL, ext3_journal_dirty_data);
1294
1295         if (ret == 0) {
1296                 /*
1297                  * generic_write_end() will run mark_inode_dirty() if i_size
1298                  * changes.  So let's piggyback the i_disksize mark_inode_dirty
1299                  * into that.
1300                  */
1301                 loff_t new_i_size;
1302
1303                 new_i_size = pos + copied;
1304                 if (new_i_size > EXT3_I(inode)->i_disksize)
1305                         EXT3_I(inode)->i_disksize = new_i_size;
1306                 ret2 = ext3_generic_write_end(file, mapping, pos, len, copied,
1307                                                         page, fsdata);
1308                 copied = ret2;
1309                 if (ret2 < 0)
1310                         ret = ret2;
1311         }
1312         ret2 = ext3_journal_stop(handle);
1313         if (!ret)
1314                 ret = ret2;
1315         unlock_page(page);
1316         page_cache_release(page);
1317
1318         return ret ? ret : copied;
1319 }
1320
1321 static int ext3_writeback_write_end(struct file *file,
1322                                 struct address_space *mapping,
1323                                 loff_t pos, unsigned len, unsigned copied,
1324                                 struct page *page, void *fsdata)
1325 {
1326         handle_t *handle = ext3_journal_current_handle();
1327         struct inode *inode = file->f_mapping->host;
1328         int ret = 0, ret2;
1329         loff_t new_i_size;
1330
1331         new_i_size = pos + copied;
1332         if (new_i_size > EXT3_I(inode)->i_disksize)
1333                 EXT3_I(inode)->i_disksize = new_i_size;
1334
1335         ret2 = ext3_generic_write_end(file, mapping, pos, len, copied,
1336                                                         page, fsdata);
1337         copied = ret2;
1338         if (ret2 < 0)
1339                 ret = ret2;
1340
1341         ret2 = ext3_journal_stop(handle);
1342         if (!ret)
1343                 ret = ret2;
1344         unlock_page(page);
1345         page_cache_release(page);
1346
1347         return ret ? ret : copied;
1348 }
1349
1350 static int ext3_journalled_write_end(struct file *file,
1351                                 struct address_space *mapping,
1352                                 loff_t pos, unsigned len, unsigned copied,
1353                                 struct page *page, void *fsdata)
1354 {
1355         handle_t *handle = ext3_journal_current_handle();
1356         struct inode *inode = mapping->host;
1357         int ret = 0, ret2;
1358         int partial = 0;
1359         unsigned from, to;
1360
1361         from = pos & (PAGE_CACHE_SIZE - 1);
1362         to = from + len;
1363
1364         if (copied < len) {
1365                 if (!PageUptodate(page))
1366                         copied = 0;
1367                 page_zero_new_buffers(page, from+copied, to);
1368         }
1369
1370         ret = walk_page_buffers(handle, page_buffers(page), from,
1371                                 to, &partial, write_end_fn);
1372         if (!partial)
1373                 SetPageUptodate(page);
1374         if (pos+copied > inode->i_size)
1375                 i_size_write(inode, pos+copied);
1376         EXT3_I(inode)->i_state |= EXT3_STATE_JDATA;
1377         if (inode->i_size > EXT3_I(inode)->i_disksize) {
1378                 EXT3_I(inode)->i_disksize = inode->i_size;
1379                 ret2 = ext3_mark_inode_dirty(handle, inode);
1380                 if (!ret)
1381                         ret = ret2;
1382         }
1383
1384         ret2 = ext3_journal_stop(handle);
1385         if (!ret)
1386                 ret = ret2;
1387         unlock_page(page);
1388         page_cache_release(page);
1389
1390         return ret ? ret : copied;
1391 }
1392
1393 /*
1394  * bmap() is special.  It gets used by applications such as lilo and by
1395  * the swapper to find the on-disk block of a specific piece of data.
1396  *
1397  * Naturally, this is dangerous if the block concerned is still in the
1398  * journal.  If somebody makes a swapfile on an ext3 data-journaling
1399  * filesystem and enables swap, then they may get a nasty shock when the
1400  * data getting swapped to that swapfile suddenly gets overwritten by
1401  * the original zero's written out previously to the journal and
1402  * awaiting writeback in the kernel's buffer cache.
1403  *
1404  * So, if we see any bmap calls here on a modified, data-journaled file,
1405  * take extra steps to flush any blocks which might be in the cache.
1406  */
1407 static sector_t ext3_bmap(struct address_space *mapping, sector_t block)
1408 {
1409         struct inode *inode = mapping->host;
1410         journal_t *journal;
1411         int err;
1412
1413         if (EXT3_I(inode)->i_state & EXT3_STATE_JDATA) {
1414                 /*
1415                  * This is a REALLY heavyweight approach, but the use of
1416                  * bmap on dirty files is expected to be extremely rare:
1417                  * only if we run lilo or swapon on a freshly made file
1418                  * do we expect this to happen.
1419                  *
1420                  * (bmap requires CAP_SYS_RAWIO so this does not
1421                  * represent an unprivileged user DOS attack --- we'd be
1422                  * in trouble if mortal users could trigger this path at
1423                  * will.)
1424                  *
1425                  * NB. EXT3_STATE_JDATA is not set on files other than
1426                  * regular files.  If somebody wants to bmap a directory
1427                  * or symlink and gets confused because the buffer
1428                  * hasn't yet been flushed to disk, they deserve
1429                  * everything they get.
1430                  */
1431
1432                 EXT3_I(inode)->i_state &= ~EXT3_STATE_JDATA;
1433                 journal = EXT3_JOURNAL(inode);
1434                 journal_lock_updates(journal);
1435                 err = journal_flush(journal);
1436                 journal_unlock_updates(journal);
1437
1438                 if (err)
1439                         return 0;
1440         }
1441
1442         return generic_block_bmap(mapping,block,ext3_get_block);
1443 }
1444
1445 static int bget_one(handle_t *handle, struct buffer_head *bh)
1446 {
1447         get_bh(bh);
1448         return 0;
1449 }
1450
1451 static int bput_one(handle_t *handle, struct buffer_head *bh)
1452 {
1453         put_bh(bh);
1454         return 0;
1455 }
1456
1457 static int journal_dirty_data_fn(handle_t *handle, struct buffer_head *bh)
1458 {
1459         if (buffer_mapped(bh))
1460                 return ext3_journal_dirty_data(handle, bh);
1461         return 0;
1462 }
1463
1464 /*
1465  * Note that we always start a transaction even if we're not journalling
1466  * data.  This is to preserve ordering: any hole instantiation within
1467  * __block_write_full_page -> ext3_get_block() should be journalled
1468  * along with the data so we don't crash and then get metadata which
1469  * refers to old data.
1470  *
1471  * In all journalling modes block_write_full_page() will start the I/O.
1472  *
1473  * Problem:
1474  *
1475  *      ext3_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1476  *              ext3_writepage()
1477  *
1478  * Similar for:
1479  *
1480  *      ext3_file_write() -> generic_file_write() -> __alloc_pages() -> ...
1481  *
1482  * Same applies to ext3_get_block().  We will deadlock on various things like
1483  * lock_journal and i_truncate_mutex.
1484  *
1485  * Setting PF_MEMALLOC here doesn't work - too many internal memory
1486  * allocations fail.
1487  *
1488  * 16May01: If we're reentered then journal_current_handle() will be
1489  *          non-zero. We simply *return*.
1490  *
1491  * 1 July 2001: @@@ FIXME:
1492  *   In journalled data mode, a data buffer may be metadata against the
1493  *   current transaction.  But the same file is part of a shared mapping
1494  *   and someone does a writepage() on it.
1495  *
1496  *   We will move the buffer onto the async_data list, but *after* it has
1497  *   been dirtied. So there's a small window where we have dirty data on
1498  *   BJ_Metadata.
1499  *
1500  *   Note that this only applies to the last partial page in the file.  The
1501  *   bit which block_write_full_page() uses prepare/commit for.  (That's
1502  *   broken code anyway: it's wrong for msync()).
1503  *
1504  *   It's a rare case: affects the final partial page, for journalled data
1505  *   where the file is subject to bith write() and writepage() in the same
1506  *   transction.  To fix it we'll need a custom block_write_full_page().
1507  *   We'll probably need that anyway for journalling writepage() output.
1508  *
1509  * We don't honour synchronous mounts for writepage().  That would be
1510  * disastrous.  Any write() or metadata operation will sync the fs for
1511  * us.
1512  *
1513  * AKPM2: if all the page's buffers are mapped to disk and !data=journal,
1514  * we don't need to open a transaction here.
1515  */
1516 static int ext3_ordered_writepage(struct page *page,
1517                                 struct writeback_control *wbc)
1518 {
1519         struct inode *inode = page->mapping->host;
1520         struct buffer_head *page_bufs;
1521         handle_t *handle = NULL;
1522         int ret = 0;
1523         int err;
1524
1525         J_ASSERT(PageLocked(page));
1526
1527         /*
1528          * We give up here if we're reentered, because it might be for a
1529          * different filesystem.
1530          */
1531         if (ext3_journal_current_handle())
1532                 goto out_fail;
1533
1534         handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
1535
1536         if (IS_ERR(handle)) {
1537                 ret = PTR_ERR(handle);
1538                 goto out_fail;
1539         }
1540
1541         if (!page_has_buffers(page)) {
1542                 create_empty_buffers(page, inode->i_sb->s_blocksize,
1543                                 (1 << BH_Dirty)|(1 << BH_Uptodate));
1544         }
1545         page_bufs = page_buffers(page);
1546         walk_page_buffers(handle, page_bufs, 0,
1547                         PAGE_CACHE_SIZE, NULL, bget_one);
1548
1549         ret = block_write_full_page(page, ext3_get_block, wbc);
1550
1551         /*
1552          * The page can become unlocked at any point now, and
1553          * truncate can then come in and change things.  So we
1554          * can't touch *page from now on.  But *page_bufs is
1555          * safe due to elevated refcount.
1556          */
1557
1558         /*
1559          * And attach them to the current transaction.  But only if
1560          * block_write_full_page() succeeded.  Otherwise they are unmapped,
1561          * and generally junk.
1562          */
1563         if (ret == 0) {
1564                 err = walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE,
1565                                         NULL, journal_dirty_data_fn);
1566                 if (!ret)
1567                         ret = err;
1568         }
1569         walk_page_buffers(handle, page_bufs, 0,
1570                         PAGE_CACHE_SIZE, NULL, bput_one);
1571         err = ext3_journal_stop(handle);
1572         if (!ret)
1573                 ret = err;
1574         return ret;
1575
1576 out_fail:
1577         redirty_page_for_writepage(wbc, page);
1578         unlock_page(page);
1579         return ret;
1580 }
1581
1582 static int ext3_writeback_writepage(struct page *page,
1583                                 struct writeback_control *wbc)
1584 {
1585         struct inode *inode = page->mapping->host;
1586         handle_t *handle = NULL;
1587         int ret = 0;
1588         int err;
1589
1590         if (ext3_journal_current_handle())
1591                 goto out_fail;
1592
1593         handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
1594         if (IS_ERR(handle)) {
1595                 ret = PTR_ERR(handle);
1596                 goto out_fail;
1597         }
1598
1599         if (test_opt(inode->i_sb, NOBH) && ext3_should_writeback_data(inode))
1600                 ret = nobh_writepage(page, ext3_get_block, wbc);
1601         else
1602                 ret = block_write_full_page(page, ext3_get_block, wbc);
1603
1604         err = ext3_journal_stop(handle);
1605         if (!ret)
1606                 ret = err;
1607         return ret;
1608
1609 out_fail:
1610         redirty_page_for_writepage(wbc, page);
1611         unlock_page(page);
1612         return ret;
1613 }
1614
1615 static int ext3_journalled_writepage(struct page *page,
1616                                 struct writeback_control *wbc)
1617 {
1618         struct inode *inode = page->mapping->host;
1619         handle_t *handle = NULL;
1620         int ret = 0;
1621         int err;
1622
1623         if (ext3_journal_current_handle())
1624                 goto no_write;
1625
1626         handle = ext3_journal_start(inode, ext3_writepage_trans_blocks(inode));
1627         if (IS_ERR(handle)) {
1628                 ret = PTR_ERR(handle);
1629                 goto no_write;
1630         }
1631
1632         if (!page_has_buffers(page) || PageChecked(page)) {
1633                 /*
1634                  * It's mmapped pagecache.  Add buffers and journal it.  There
1635                  * doesn't seem much point in redirtying the page here.
1636                  */
1637                 ClearPageChecked(page);
1638                 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
1639                                         ext3_get_block);
1640                 if (ret != 0) {
1641                         ext3_journal_stop(handle);
1642                         goto out_unlock;
1643                 }
1644                 ret = walk_page_buffers(handle, page_buffers(page), 0,
1645                         PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
1646
1647                 err = walk_page_buffers(handle, page_buffers(page), 0,
1648                                 PAGE_CACHE_SIZE, NULL, write_end_fn);
1649                 if (ret == 0)
1650                         ret = err;
1651                 EXT3_I(inode)->i_state |= EXT3_STATE_JDATA;
1652                 unlock_page(page);
1653         } else {
1654                 /*
1655                  * It may be a page full of checkpoint-mode buffers.  We don't
1656                  * really know unless we go poke around in the buffer_heads.
1657                  * But block_write_full_page will do the right thing.
1658                  */
1659                 ret = block_write_full_page(page, ext3_get_block, wbc);
1660         }
1661         err = ext3_journal_stop(handle);
1662         if (!ret)
1663                 ret = err;
1664 out:
1665         return ret;
1666
1667 no_write:
1668         redirty_page_for_writepage(wbc, page);
1669 out_unlock:
1670         unlock_page(page);
1671         goto out;
1672 }
1673
1674 static int ext3_readpage(struct file *file, struct page *page)
1675 {
1676         return mpage_readpage(page, ext3_get_block);
1677 }
1678
1679 static int
1680 ext3_readpages(struct file *file, struct address_space *mapping,
1681                 struct list_head *pages, unsigned nr_pages)
1682 {
1683         return mpage_readpages(mapping, pages, nr_pages, ext3_get_block);
1684 }
1685
1686 static void ext3_invalidatepage(struct page *page, unsigned long offset)
1687 {
1688         journal_t *journal = EXT3_JOURNAL(page->mapping->host);
1689
1690         /*
1691          * If it's a full truncate we just forget about the pending dirtying
1692          */
1693         if (offset == 0)
1694                 ClearPageChecked(page);
1695
1696         journal_invalidatepage(journal, page, offset);
1697 }
1698
1699 static int ext3_releasepage(struct page *page, gfp_t wait)
1700 {
1701         journal_t *journal = EXT3_JOURNAL(page->mapping->host);
1702
1703         WARN_ON(PageChecked(page));
1704         if (!page_has_buffers(page))
1705                 return 0;
1706         return journal_try_to_free_buffers(journal, page, wait);
1707 }
1708
1709 /*
1710  * If the O_DIRECT write will extend the file then add this inode to the
1711  * orphan list.  So recovery will truncate it back to the original size
1712  * if the machine crashes during the write.
1713  *
1714  * If the O_DIRECT write is intantiating holes inside i_size and the machine
1715  * crashes then stale disk data _may_ be exposed inside the file. But current
1716  * VFS code falls back into buffered path in that case so we are safe.
1717  */
1718 static ssize_t ext3_direct_IO(int rw, struct kiocb *iocb,
1719                         const struct iovec *iov, loff_t offset,
1720                         unsigned long nr_segs)
1721 {
1722         struct file *file = iocb->ki_filp;
1723         struct inode *inode = file->f_mapping->host;
1724         struct ext3_inode_info *ei = EXT3_I(inode);
1725         handle_t *handle;
1726         ssize_t ret;
1727         int orphan = 0;
1728         size_t count = iov_length(iov, nr_segs);
1729
1730         if (rw == WRITE) {
1731                 loff_t final_size = offset + count;
1732
1733                 if (final_size > inode->i_size) {
1734                         /* Credits for sb + inode write */
1735                         handle = ext3_journal_start(inode, 2);
1736                         if (IS_ERR(handle)) {
1737                                 ret = PTR_ERR(handle);
1738                                 goto out;
1739                         }
1740                         ret = ext3_orphan_add(handle, inode);
1741                         if (ret) {
1742                                 ext3_journal_stop(handle);
1743                                 goto out;
1744                         }
1745                         orphan = 1;
1746                         ei->i_disksize = inode->i_size;
1747                         ext3_journal_stop(handle);
1748                 }
1749         }
1750
1751         ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
1752                                  offset, nr_segs,
1753                                  ext3_get_block, NULL);
1754
1755         if (orphan) {
1756                 int err;
1757
1758                 /* Credits for sb + inode write */
1759                 handle = ext3_journal_start(inode, 2);
1760                 if (IS_ERR(handle)) {
1761                         /* This is really bad luck. We've written the data
1762                          * but cannot extend i_size. Bail out and pretend
1763                          * the write failed... */
1764                         ret = PTR_ERR(handle);
1765                         goto out;
1766                 }
1767                 if (inode->i_nlink)
1768                         ext3_orphan_del(handle, inode);
1769                 if (ret > 0) {
1770                         loff_t end = offset + ret;
1771                         if (end > inode->i_size) {
1772                                 ei->i_disksize = end;
1773                                 i_size_write(inode, end);
1774                                 /*
1775                                  * We're going to return a positive `ret'
1776                                  * here due to non-zero-length I/O, so there's
1777                                  * no way of reporting error returns from
1778                                  * ext3_mark_inode_dirty() to userspace.  So
1779                                  * ignore it.
1780                                  */
1781                                 ext3_mark_inode_dirty(handle, inode);
1782                         }
1783                 }
1784                 err = ext3_journal_stop(handle);
1785                 if (ret == 0)
1786                         ret = err;
1787         }
1788 out:
1789         return ret;
1790 }
1791
1792 /*
1793  * Pages can be marked dirty completely asynchronously from ext3's journalling
1794  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
1795  * much here because ->set_page_dirty is called under VFS locks.  The page is
1796  * not necessarily locked.
1797  *
1798  * We cannot just dirty the page and leave attached buffers clean, because the
1799  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
1800  * or jbddirty because all the journalling code will explode.
1801  *
1802  * So what we do is to mark the page "pending dirty" and next time writepage
1803  * is called, propagate that into the buffers appropriately.
1804  */
1805 static int ext3_journalled_set_page_dirty(struct page *page)
1806 {
1807         SetPageChecked(page);
1808         return __set_page_dirty_nobuffers(page);
1809 }
1810
1811 static const struct address_space_operations ext3_ordered_aops = {
1812         .readpage               = ext3_readpage,
1813         .readpages              = ext3_readpages,
1814         .writepage              = ext3_ordered_writepage,
1815         .sync_page              = block_sync_page,
1816         .write_begin            = ext3_write_begin,
1817         .write_end              = ext3_ordered_write_end,
1818         .bmap                   = ext3_bmap,
1819         .invalidatepage         = ext3_invalidatepage,
1820         .releasepage            = ext3_releasepage,
1821         .direct_IO              = ext3_direct_IO,
1822         .migratepage            = buffer_migrate_page,
1823         .is_partially_uptodate  = block_is_partially_uptodate,
1824         .map_extent             = ext3_map_extent,
1825 };
1826
1827 static const struct address_space_operations ext3_writeback_aops = {
1828         .readpage               = ext3_readpage,
1829         .readpages              = ext3_readpages,
1830         .writepage              = ext3_writeback_writepage,
1831         .sync_page              = block_sync_page,
1832         .write_begin            = ext3_write_begin,
1833         .write_end              = ext3_writeback_write_end,
1834         .bmap                   = ext3_bmap,
1835         .invalidatepage         = ext3_invalidatepage,
1836         .releasepage            = ext3_releasepage,
1837         .direct_IO              = ext3_direct_IO,
1838         .migratepage            = buffer_migrate_page,
1839         .is_partially_uptodate  = block_is_partially_uptodate,
1840         .map_extent             = ext3_map_extent,
1841 };
1842
1843 static const struct address_space_operations ext3_journalled_aops = {
1844         .readpage               = ext3_readpage,
1845         .readpages              = ext3_readpages,
1846         .writepage              = ext3_journalled_writepage,
1847         .sync_page              = block_sync_page,
1848         .write_begin            = ext3_write_begin,
1849         .write_end              = ext3_journalled_write_end,
1850         .set_page_dirty         = ext3_journalled_set_page_dirty,
1851         .bmap                   = ext3_bmap,
1852         .invalidatepage         = ext3_invalidatepage,
1853         .releasepage            = ext3_releasepage,
1854         .is_partially_uptodate  = block_is_partially_uptodate,
1855         .map_extent             = ext3_map_extent,
1856 };
1857
1858 void ext3_set_aops(struct inode *inode)
1859 {
1860         if (ext3_should_order_data(inode))
1861                 inode->i_mapping->a_ops = &ext3_ordered_aops;
1862         else if (ext3_should_writeback_data(inode))
1863                 inode->i_mapping->a_ops = &ext3_writeback_aops;
1864         else
1865                 inode->i_mapping->a_ops = &ext3_journalled_aops;
1866 }
1867
1868 /*
1869  * ext3_block_truncate_page() zeroes out a mapping from file offset `from'
1870  * up to the end of the block which corresponds to `from'.
1871  * This required during truncate. We need to physically zero the tail end
1872  * of that block so it doesn't yield old data if the file is later grown.
1873  */
1874 static int ext3_block_truncate_page(handle_t *handle, struct page *page,
1875                 struct address_space *mapping, loff_t from)
1876 {
1877         ext3_fsblk_t index = from >> PAGE_CACHE_SHIFT;
1878         unsigned offset = from & (PAGE_CACHE_SIZE-1);
1879         unsigned blocksize, iblock, length, pos;
1880         struct inode *inode = mapping->host;
1881         struct buffer_head *bh;
1882         int err = 0;
1883
1884         blocksize = inode->i_sb->s_blocksize;
1885         length = blocksize - (offset & (blocksize - 1));
1886         iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
1887
1888         /*
1889          * For "nobh" option,  we can only work if we don't need to
1890          * read-in the page - otherwise we create buffers to do the IO.
1891          */
1892         if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
1893              ext3_should_writeback_data(inode) && PageUptodate(page)) {
1894                 zero_user(page, offset, length);
1895                 set_page_dirty(page);
1896                 goto unlock;
1897         }
1898
1899         if (!page_has_buffers(page))
1900                 create_empty_buffers(page, blocksize, 0);
1901
1902         /* Find the buffer that contains "offset" */
1903         bh = page_buffers(page);
1904         pos = blocksize;
1905         while (offset >= pos) {
1906                 bh = bh->b_this_page;
1907                 iblock++;
1908                 pos += blocksize;
1909         }
1910
1911         err = 0;
1912         if (buffer_freed(bh)) {
1913                 BUFFER_TRACE(bh, "freed: skip");
1914                 goto unlock;
1915         }
1916
1917         if (!buffer_mapped(bh)) {
1918                 BUFFER_TRACE(bh, "unmapped");
1919                 ext3_get_block(inode, iblock, bh, 0);
1920                 /* unmapped? It's a hole - nothing to do */
1921                 if (!buffer_mapped(bh)) {
1922                         BUFFER_TRACE(bh, "still unmapped");
1923                         goto unlock;
1924                 }
1925         }
1926
1927         /* Ok, it's mapped. Make sure it's up-to-date */
1928         if (PageUptodate(page))
1929                 set_buffer_uptodate(bh);
1930
1931         if (!buffer_uptodate(bh)) {
1932                 err = -EIO;
1933                 ll_rw_block(READ, 1, &bh);
1934                 wait_on_buffer(bh);
1935                 /* Uhhuh. Read error. Complain and punt. */
1936                 if (!buffer_uptodate(bh))
1937                         goto unlock;
1938         }
1939
1940         if (ext3_should_journal_data(inode)) {
1941                 BUFFER_TRACE(bh, "get write access");
1942                 err = ext3_journal_get_write_access(handle, bh);
1943                 if (err)
1944                         goto unlock;
1945         }
1946
1947         zero_user(page, offset, length);
1948         BUFFER_TRACE(bh, "zeroed end of block");
1949
1950         err = 0;
1951         if (ext3_should_journal_data(inode)) {
1952                 err = ext3_journal_dirty_metadata(handle, bh);
1953         } else {
1954                 if (ext3_should_order_data(inode))
1955                         err = ext3_journal_dirty_data(handle, bh);
1956                 mark_buffer_dirty(bh);
1957         }
1958
1959 unlock:
1960         unlock_page(page);
1961         page_cache_release(page);
1962         return err;
1963 }
1964
1965 /*
1966  * Probably it should be a library function... search for first non-zero word
1967  * or memcmp with zero_page, whatever is better for particular architecture.
1968  * Linus?
1969  */
1970 static inline int all_zeroes(__le32 *p, __le32 *q)
1971 {
1972         while (p < q)
1973                 if (*p++)
1974                         return 0;
1975         return 1;
1976 }
1977
1978 /**
1979  *      ext3_find_shared - find the indirect blocks for partial truncation.
1980  *      @inode:   inode in question
1981  *      @depth:   depth of the affected branch
1982  *      @offsets: offsets of pointers in that branch (see ext3_block_to_path)
1983  *      @chain:   place to store the pointers to partial indirect blocks
1984  *      @top:     place to the (detached) top of branch
1985  *
1986  *      This is a helper function used by ext3_truncate().
1987  *
1988  *      When we do truncate() we may have to clean the ends of several
1989  *      indirect blocks but leave the blocks themselves alive. Block is
1990  *      partially truncated if some data below the new i_size is refered
1991  *      from it (and it is on the path to the first completely truncated
1992  *      data block, indeed).  We have to free the top of that path along
1993  *      with everything to the right of the path. Since no allocation
1994  *      past the truncation point is possible until ext3_truncate()
1995  *      finishes, we may safely do the latter, but top of branch may
1996  *      require special attention - pageout below the truncation point
1997  *      might try to populate it.
1998  *
1999  *      We atomically detach the top of branch from the tree, store the
2000  *      block number of its root in *@top, pointers to buffer_heads of
2001  *      partially truncated blocks - in @chain[].bh and pointers to
2002  *      their last elements that should not be removed - in
2003  *      @chain[].p. Return value is the pointer to last filled element
2004  *      of @chain.
2005  *
2006  *      The work left to caller to do the actual freeing of subtrees:
2007  *              a) free the subtree starting from *@top
2008  *              b) free the subtrees whose roots are stored in
2009  *                      (@chain[i].p+1 .. end of @chain[i].bh->b_data)
2010  *              c) free the subtrees growing from the inode past the @chain[0].
2011  *                      (no partially truncated stuff there).  */
2012
2013 static Indirect *ext3_find_shared(struct inode *inode, int depth,
2014                         int offsets[4], Indirect chain[4], __le32 *top)
2015 {
2016         Indirect *partial, *p;
2017         int k, err;
2018
2019         *top = 0;
2020         /* Make k index the deepest non-null offest + 1 */
2021         for (k = depth; k > 1 && !offsets[k-1]; k--)
2022                 ;
2023         partial = ext3_get_branch(inode, k, offsets, chain, &err);
2024         /* Writer: pointers */
2025         if (!partial)
2026                 partial = chain + k-1;
2027         /*
2028          * If the branch acquired continuation since we've looked at it -
2029          * fine, it should all survive and (new) top doesn't belong to us.
2030          */
2031         if (!partial->key && *partial->p)
2032                 /* Writer: end */
2033                 goto no_top;
2034         for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
2035                 ;
2036         /*
2037          * OK, we've found the last block that must survive. The rest of our
2038          * branch should be detached before unlocking. However, if that rest
2039          * of branch is all ours and does not grow immediately from the inode
2040          * it's easier to cheat and just decrement partial->p.
2041          */
2042         if (p == chain + k - 1 && p > chain) {
2043                 p->p--;
2044         } else {
2045                 *top = *p->p;
2046                 /* Nope, don't do this in ext3.  Must leave the tree intact */
2047 #if 0
2048                 *p->p = 0;
2049 #endif
2050         }
2051         /* Writer: end */
2052
2053         while(partial > p) {
2054                 brelse(partial->bh);
2055                 partial--;
2056         }
2057 no_top:
2058         return partial;
2059 }
2060
2061 /*
2062  * Zero a number of block pointers in either an inode or an indirect block.
2063  * If we restart the transaction we must again get write access to the
2064  * indirect block for further modification.
2065  *
2066  * We release `count' blocks on disk, but (last - first) may be greater
2067  * than `count' because there can be holes in there.
2068  */
2069 static void ext3_clear_blocks(handle_t *handle, struct inode *inode,
2070                 struct buffer_head *bh, ext3_fsblk_t block_to_free,
2071                 unsigned long count, __le32 *first, __le32 *last)
2072 {
2073         __le32 *p;
2074         if (try_to_extend_transaction(handle, inode)) {
2075                 if (bh) {
2076                         BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
2077                         ext3_journal_dirty_metadata(handle, bh);
2078                 }
2079                 ext3_mark_inode_dirty(handle, inode);
2080                 ext3_journal_test_restart(handle, inode);
2081                 if (bh) {
2082                         BUFFER_TRACE(bh, "retaking write access");
2083                         ext3_journal_get_write_access(handle, bh);
2084                 }
2085         }
2086
2087         /*
2088          * Any buffers which are on the journal will be in memory. We find
2089          * them on the hash table so journal_revoke() will run journal_forget()
2090          * on them.  We've already detached each block from the file, so
2091          * bforget() in journal_forget() should be safe.
2092          *
2093          * AKPM: turn on bforget in journal_forget()!!!
2094          */
2095         for (p = first; p < last; p++) {
2096                 u32 nr = le32_to_cpu(*p);
2097                 if (nr) {
2098                         struct buffer_head *bh;
2099
2100                         *p = 0;
2101                         bh = sb_find_get_block(inode->i_sb, nr);
2102                         ext3_forget(handle, 0, inode, bh, nr);
2103                 }
2104         }
2105
2106         ext3_free_blocks(handle, inode, block_to_free, count);
2107 }
2108
2109 /**
2110  * ext3_free_data - free a list of data blocks
2111  * @handle:     handle for this transaction
2112  * @inode:      inode we are dealing with
2113  * @this_bh:    indirect buffer_head which contains *@first and *@last
2114  * @first:      array of block numbers
2115  * @last:       points immediately past the end of array
2116  *
2117  * We are freeing all blocks refered from that array (numbers are stored as
2118  * little-endian 32-bit) and updating @inode->i_blocks appropriately.
2119  *
2120  * We accumulate contiguous runs of blocks to free.  Conveniently, if these
2121  * blocks are contiguous then releasing them at one time will only affect one
2122  * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
2123  * actually use a lot of journal space.
2124  *
2125  * @this_bh will be %NULL if @first and @last point into the inode's direct
2126  * block pointers.
2127  */
2128 static void ext3_free_data(handle_t *handle, struct inode *inode,
2129                            struct buffer_head *this_bh,
2130                            __le32 *first, __le32 *last)
2131 {
2132         ext3_fsblk_t block_to_free = 0;    /* Starting block # of a run */
2133         unsigned long count = 0;            /* Number of blocks in the run */
2134         __le32 *block_to_free_p = NULL;     /* Pointer into inode/ind
2135                                                corresponding to
2136                                                block_to_free */
2137         ext3_fsblk_t nr;                    /* Current block # */
2138         __le32 *p;                          /* Pointer into inode/ind
2139                                                for current block */
2140         int err;
2141
2142         if (this_bh) {                          /* For indirect block */
2143                 BUFFER_TRACE(this_bh, "get_write_access");
2144                 err = ext3_journal_get_write_access(handle, this_bh);
2145                 /* Important: if we can't update the indirect pointers
2146                  * to the blocks, we can't free them. */
2147                 if (err)
2148                         return;
2149         }
2150
2151         for (p = first; p < last; p++) {
2152                 nr = le32_to_cpu(*p);
2153                 if (nr) {
2154                         /* accumulate blocks to free if they're contiguous */
2155                         if (count == 0) {
2156                                 block_to_free = nr;
2157                                 block_to_free_p = p;
2158                                 count = 1;
2159                         } else if (nr == block_to_free + count) {
2160                                 count++;
2161                         } else {
2162                                 ext3_clear_blocks(handle, inode, this_bh,
2163                                                   block_to_free,
2164                                                   count, block_to_free_p, p);
2165                                 block_to_free = nr;
2166                                 block_to_free_p = p;
2167                                 count = 1;
2168                         }
2169                 }
2170         }
2171
2172         if (count > 0)
2173                 ext3_clear_blocks(handle, inode, this_bh, block_to_free,
2174                                   count, block_to_free_p, p);
2175
2176         if (this_bh) {
2177                 BUFFER_TRACE(this_bh, "call ext3_journal_dirty_metadata");
2178
2179                 /*
2180                  * The buffer head should have an attached journal head at this
2181                  * point. However, if the data is corrupted and an indirect
2182                  * block pointed to itself, it would have been detached when
2183                  * the block was cleared. Check for this instead of OOPSing.
2184                  */
2185                 if (bh2jh(this_bh))
2186                         ext3_journal_dirty_metadata(handle, this_bh);
2187                 else
2188                         ext3_error(inode->i_sb, "ext3_free_data",
2189                                    "circular indirect block detected, "
2190                                    "inode=%lu, block=%llu",
2191                                    inode->i_ino,
2192                                    (unsigned long long)this_bh->b_blocknr);
2193         }
2194 }
2195
2196 /**
2197  *      ext3_free_branches - free an array of branches
2198  *      @handle: JBD handle for this transaction
2199  *      @inode: inode we are dealing with
2200  *      @parent_bh: the buffer_head which contains *@first and *@last
2201  *      @first: array of block numbers
2202  *      @last:  pointer immediately past the end of array
2203  *      @depth: depth of the branches to free
2204  *
2205  *      We are freeing all blocks refered from these branches (numbers are
2206  *      stored as little-endian 32-bit) and updating @inode->i_blocks
2207  *      appropriately.
2208  */
2209 static void ext3_free_branches(handle_t *handle, struct inode *inode,
2210                                struct buffer_head *parent_bh,
2211                                __le32 *first, __le32 *last, int depth)
2212 {
2213         ext3_fsblk_t nr;
2214         __le32 *p;
2215
2216         if (is_handle_aborted(handle))
2217                 return;
2218
2219         if (depth--) {
2220                 struct buffer_head *bh;
2221                 int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
2222                 p = last;
2223                 while (--p >= first) {
2224                         nr = le32_to_cpu(*p);
2225                         if (!nr)
2226                                 continue;               /* A hole */
2227
2228                         /* Go read the buffer for the next level down */
2229                         bh = sb_bread(inode->i_sb, nr);
2230
2231                         /*
2232                          * A read failure? Report error and clear slot
2233                          * (should be rare).
2234                          */
2235                         if (!bh) {
2236                                 ext3_error(inode->i_sb, "ext3_free_branches",
2237                                            "Read failure, inode=%lu, block="E3FSBLK,
2238                                            inode->i_ino, nr);
2239                                 continue;
2240                         }
2241
2242                         /* This zaps the entire block.  Bottom up. */
2243                         BUFFER_TRACE(bh, "free child branches");
2244                         ext3_free_branches(handle, inode, bh,
2245                                            (__le32*)bh->b_data,
2246                                            (__le32*)bh->b_data + addr_per_block,
2247                                            depth);
2248
2249                         /*
2250                          * We've probably journalled the indirect block several
2251                          * times during the truncate.  But it's no longer
2252                          * needed and we now drop it from the transaction via
2253                          * journal_revoke().
2254                          *
2255                          * That's easy if it's exclusively part of this
2256                          * transaction.  But if it's part of the committing
2257                          * transaction then journal_forget() will simply
2258                          * brelse() it.  That means that if the underlying
2259                          * block is reallocated in ext3_get_block(),
2260                          * unmap_underlying_metadata() will find this block
2261                          * and will try to get rid of it.  damn, damn.
2262                          *
2263                          * If this block has already been committed to the
2264                          * journal, a revoke record will be written.  And
2265                          * revoke records must be emitted *before* clearing
2266                          * this block's bit in the bitmaps.
2267                          */
2268                         ext3_forget(handle, 1, inode, bh, bh->b_blocknr);
2269
2270                         /*
2271                          * Everything below this this pointer has been
2272                          * released.  Now let this top-of-subtree go.
2273                          *
2274                          * We want the freeing of this indirect block to be
2275                          * atomic in the journal with the updating of the
2276                          * bitmap block which owns it.  So make some room in
2277                          * the journal.
2278                          *
2279                          * We zero the parent pointer *after* freeing its
2280                          * pointee in the bitmaps, so if extend_transaction()
2281                          * for some reason fails to put the bitmap changes and
2282                          * the release into the same transaction, recovery
2283                          * will merely complain about releasing a free block,
2284                          * rather than leaking blocks.
2285                          */
2286                         if (is_handle_aborted(handle))
2287                                 return;
2288                         if (try_to_extend_transaction(handle, inode)) {
2289                                 ext3_mark_inode_dirty(handle, inode);
2290                                 ext3_journal_test_restart(handle, inode);
2291                         }
2292
2293                         ext3_free_blocks(handle, inode, nr, 1);
2294
2295                         if (parent_bh) {
2296                                 /*
2297                                  * The block which we have just freed is
2298                                  * pointed to by an indirect block: journal it
2299                                  */
2300                                 BUFFER_TRACE(parent_bh, "get_write_access");
2301                                 if (!ext3_journal_get_write_access(handle,
2302                                                                    parent_bh)){
2303                                         *p = 0;
2304                                         BUFFER_TRACE(parent_bh,
2305                                         "call ext3_journal_dirty_metadata");
2306                                         ext3_journal_dirty_metadata(handle,
2307                                                                     parent_bh);
2308                                 }
2309                         }
2310                 }
2311         } else {
2312                 /* We have reached the bottom of the tree. */
2313                 BUFFER_TRACE(parent_bh, "free data blocks");
2314                 ext3_free_data(handle, inode, parent_bh, first, last);
2315         }
2316 }
2317
2318 int ext3_can_truncate(struct inode *inode)
2319 {
2320         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
2321                 return 0;
2322         if (S_ISREG(inode->i_mode))
2323                 return 1;
2324         if (S_ISDIR(inode->i_mode))
2325                 return 1;
2326         if (S_ISLNK(inode->i_mode))
2327                 return !ext3_inode_is_fast_symlink(inode);
2328         return 0;
2329 }
2330
2331 /*
2332  * ext3_truncate()
2333  *
2334  * We block out ext3_get_block() block instantiations across the entire
2335  * transaction, and VFS/VM ensures that ext3_truncate() cannot run
2336  * simultaneously on behalf of the same inode.
2337  *
2338  * As we work through the truncate and commmit bits of it to the journal there
2339  * is one core, guiding principle: the file's tree must always be consistent on
2340  * disk.  We must be able to restart the truncate after a crash.
2341  *
2342  * The file's tree may be transiently inconsistent in memory (although it
2343  * probably isn't), but whenever we close off and commit a journal transaction,
2344  * the contents of (the filesystem + the journal) must be consistent and
2345  * restartable.  It's pretty simple, really: bottom up, right to left (although
2346  * left-to-right works OK too).
2347  *
2348  * Note that at recovery time, journal replay occurs *before* the restart of
2349  * truncate against the orphan inode list.
2350  *
2351  * The committed inode has the new, desired i_size (which is the same as
2352  * i_disksize in this case).  After a crash, ext3_orphan_cleanup() will see
2353  * that this inode's truncate did not complete and it will again call
2354  * ext3_truncate() to have another go.  So there will be instantiated blocks
2355  * to the right of the truncation point in a crashed ext3 filesystem.  But
2356  * that's fine - as long as they are linked from the inode, the post-crash
2357  * ext3_truncate() run will find them and release them.
2358  */
2359 void ext3_truncate(struct inode *inode)
2360 {
2361         handle_t *handle;
2362         struct ext3_inode_info *ei = EXT3_I(inode);
2363         __le32 *i_data = ei->i_data;
2364         int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
2365         struct address_space *mapping = inode->i_mapping;
2366         int offsets[4];
2367         Indirect chain[4];
2368         Indirect *partial;
2369         __le32 nr = 0;
2370         int n;
2371         long last_block;
2372         unsigned blocksize = inode->i_sb->s_blocksize;
2373         struct page *page;
2374
2375         if (!ext3_can_truncate(inode))
2376                 return;
2377
2378         /*
2379          * We have to lock the EOF page here, because lock_page() nests
2380          * outside journal_start().
2381          */
2382         if ((inode->i_size & (blocksize - 1)) == 0) {
2383                 /* Block boundary? Nothing to do */
2384                 page = NULL;
2385         } else {
2386                 page = grab_cache_page(mapping,
2387                                 inode->i_size >> PAGE_CACHE_SHIFT);
2388                 if (!page)
2389                         return;
2390         }
2391
2392         handle = start_transaction(inode);
2393         if (IS_ERR(handle)) {
2394                 if (page) {
2395                         clear_highpage(page);
2396                         flush_dcache_page(page);
2397                         unlock_page(page);
2398                         page_cache_release(page);
2399                 }
2400                 return;         /* AKPM: return what? */
2401         }
2402
2403         last_block = (inode->i_size + blocksize-1)
2404                                         >> EXT3_BLOCK_SIZE_BITS(inode->i_sb);
2405
2406         if (page)
2407                 ext3_block_truncate_page(handle, page, mapping, inode->i_size);
2408
2409         n = ext3_block_to_path(inode, last_block, offsets, NULL);
2410         if (n == 0)
2411                 goto out_stop;  /* error */
2412
2413         /*
2414          * OK.  This truncate is going to happen.  We add the inode to the
2415          * orphan list, so that if this truncate spans multiple transactions,
2416          * and we crash, we will resume the truncate when the filesystem
2417          * recovers.  It also marks the inode dirty, to catch the new size.
2418          *
2419          * Implication: the file must always be in a sane, consistent
2420          * truncatable state while each transaction commits.
2421          */
2422         if (ext3_orphan_add(handle, inode))
2423                 goto out_stop;
2424
2425         /*
2426          * The orphan list entry will now protect us from any crash which
2427          * occurs before the truncate completes, so it is now safe to propagate
2428          * the new, shorter inode size (held for now in i_size) into the
2429          * on-disk inode. We do this via i_disksize, which is the value which
2430          * ext3 *really* writes onto the disk inode.
2431          */
2432         ei->i_disksize = inode->i_size;
2433
2434         /*
2435          * From here we block out all ext3_get_block() callers who want to
2436          * modify the block allocation tree.
2437          */
2438         mutex_lock(&ei->truncate_mutex);
2439
2440         if (n == 1) {           /* direct blocks */
2441                 ext3_free_data(handle, inode, NULL, i_data+offsets[0],
2442                                i_data + EXT3_NDIR_BLOCKS);
2443                 goto do_indirects;
2444         }
2445
2446         partial = ext3_find_shared(inode, n, offsets, chain, &nr);
2447         /* Kill the top of shared branch (not detached) */
2448         if (nr) {
2449                 if (partial == chain) {
2450                         /* Shared branch grows from the inode */
2451                         ext3_free_branches(handle, inode, NULL,
2452                                            &nr, &nr+1, (chain+n-1) - partial);
2453                         *partial->p = 0;
2454                         /*
2455                          * We mark the inode dirty prior to restart,
2456                          * and prior to stop.  No need for it here.
2457                          */
2458                 } else {
2459                         /* Shared branch grows from an indirect block */
2460                         BUFFER_TRACE(partial->bh, "get_write_access");
2461                         ext3_free_branches(handle, inode, partial->bh,
2462                                         partial->p,
2463                                         partial->p+1, (chain+n-1) - partial);
2464                 }
2465         }
2466         /* Clear the ends of indirect blocks on the shared branch */
2467         while (partial > chain) {
2468                 ext3_free_branches(handle, inode, partial->bh, partial->p + 1,
2469                                    (__le32*)partial->bh->b_data+addr_per_block,
2470                                    (chain+n-1) - partial);
2471                 BUFFER_TRACE(partial->bh, "call brelse");
2472                 brelse (partial->bh);
2473                 partial--;
2474         }
2475 do_indirects:
2476         /* Kill the remaining (whole) subtrees */
2477         switch (offsets[0]) {
2478         default:
2479                 nr = i_data[EXT3_IND_BLOCK];
2480                 if (nr) {
2481                         ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
2482                         i_data[EXT3_IND_BLOCK] = 0;
2483                 }
2484         case EXT3_IND_BLOCK:
2485                 nr = i_data[EXT3_DIND_BLOCK];
2486                 if (nr) {
2487                         ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
2488                         i_data[EXT3_DIND_BLOCK] = 0;
2489                 }
2490         case EXT3_DIND_BLOCK:
2491                 nr = i_data[EXT3_TIND_BLOCK];
2492                 if (nr) {
2493                         ext3_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
2494                         i_data[EXT3_TIND_BLOCK] = 0;
2495                 }
2496         case EXT3_TIND_BLOCK:
2497                 ;
2498         }
2499
2500         ext3_discard_reservation(inode);
2501
2502         mutex_unlock(&ei->truncate_mutex);
2503         inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
2504         ext3_mark_inode_dirty(handle, inode);
2505
2506         /*
2507          * In a multi-transaction truncate, we only make the final transaction
2508          * synchronous
2509          */
2510         if (IS_SYNC(inode))
2511                 handle->h_sync = 1;
2512 out_stop:
2513         /*
2514          * If this was a simple ftruncate(), and the file will remain alive
2515          * then we need to clear up the orphan record which we created above.
2516          * However, if this was a real unlink then we were called by
2517          * ext3_delete_inode(), and we allow that function to clean up the
2518          * orphan info for us.
2519          */
2520         if (inode->i_nlink)
2521                 ext3_orphan_del(handle, inode);
2522
2523         ext3_journal_stop(handle);
2524 }
2525
2526 static ext3_fsblk_t ext3_get_inode_block(struct super_block *sb,
2527                 unsigned long ino, struct ext3_iloc *iloc)
2528 {
2529         unsigned long block_group;
2530         unsigned long offset;
2531         ext3_fsblk_t block;
2532         struct ext3_group_desc *gdp;
2533
2534         if (!ext3_valid_inum(sb, ino)) {
2535                 /*
2536                  * This error is already checked for in namei.c unless we are
2537                  * looking at an NFS filehandle, in which case no error
2538                  * report is needed
2539                  */
2540                 return 0;
2541         }
2542
2543         block_group = (ino - 1) / EXT3_INODES_PER_GROUP(sb);
2544         gdp = ext3_get_group_desc(sb, block_group, NULL);
2545         if (!gdp)
2546                 return 0;
2547         /*
2548          * Figure out the offset within the block group inode table
2549          */
2550         offset = ((ino - 1) % EXT3_INODES_PER_GROUP(sb)) *
2551                 EXT3_INODE_SIZE(sb);
2552         block = le32_to_cpu(gdp->bg_inode_table) +
2553                 (offset >> EXT3_BLOCK_SIZE_BITS(sb));
2554
2555         iloc->block_group = block_group;
2556         iloc->offset = offset & (EXT3_BLOCK_SIZE(sb) - 1);
2557         return block;
2558 }
2559
2560 /*
2561  * ext3_get_inode_loc returns with an extra refcount against the inode's
2562  * underlying buffer_head on success. If 'in_mem' is true, we have all
2563  * data in memory that is needed to recreate the on-disk version of this
2564  * inode.
2565  */
2566 static int __ext3_get_inode_loc(struct inode *inode,
2567                                 struct ext3_iloc *iloc, int in_mem)
2568 {
2569         ext3_fsblk_t block;
2570         struct buffer_head *bh;
2571
2572         block = ext3_get_inode_block(inode->i_sb, inode->i_ino, iloc);
2573         if (!block)
2574                 return -EIO;
2575
2576         bh = sb_getblk(inode->i_sb, block);
2577         if (!bh) {
2578                 ext3_error (inode->i_sb, "ext3_get_inode_loc",
2579                                 "unable to read inode block - "
2580                                 "inode=%lu, block="E3FSBLK,
2581                                  inode->i_ino, block);
2582                 return -EIO;
2583         }
2584         if (!buffer_uptodate(bh)) {
2585                 lock_buffer(bh);
2586
2587                 /*
2588                  * If the buffer has the write error flag, we have failed
2589                  * to write out another inode in the same block.  In this
2590                  * case, we don't have to read the block because we may
2591                  * read the old inode data successfully.
2592                  */
2593                 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
2594                         set_buffer_uptodate(bh);
2595
2596                 if (buffer_uptodate(bh)) {
2597                         /* someone brought it uptodate while we waited */
2598                         unlock_buffer(bh);
2599                         goto has_buffer;
2600                 }
2601
2602                 /*
2603                  * If we have all information of the inode in memory and this
2604                  * is the only valid inode in the block, we need not read the
2605                  * block.
2606                  */
2607                 if (in_mem) {
2608                         struct buffer_head *bitmap_bh;
2609                         struct ext3_group_desc *desc;
2610                         int inodes_per_buffer;
2611                         int inode_offset, i;
2612                         int block_group;
2613                         int start;
2614
2615                         block_group = (inode->i_ino - 1) /
2616                                         EXT3_INODES_PER_GROUP(inode->i_sb);
2617                         inodes_per_buffer = bh->b_size /
2618                                 EXT3_INODE_SIZE(inode->i_sb);
2619                         inode_offset = ((inode->i_ino - 1) %
2620                                         EXT3_INODES_PER_GROUP(inode->i_sb));
2621                         start = inode_offset & ~(inodes_per_buffer - 1);
2622
2623                         /* Is the inode bitmap in cache? */
2624                         desc = ext3_get_group_desc(inode->i_sb,
2625                                                 block_group, NULL);
2626                         if (!desc)
2627                                 goto make_io;
2628
2629                         bitmap_bh = sb_getblk(inode->i_sb,
2630                                         le32_to_cpu(desc->bg_inode_bitmap));
2631                         if (!bitmap_bh)
2632                                 goto make_io;
2633
2634                         /*
2635                          * If the inode bitmap isn't in cache then the
2636                          * optimisation may end up performing two reads instead
2637                          * of one, so skip it.
2638                          */
2639                         if (!buffer_uptodate(bitmap_bh)) {
2640                                 brelse(bitmap_bh);
2641                                 goto make_io;
2642                         }
2643                         for (i = start; i < start + inodes_per_buffer; i++) {
2644                                 if (i == inode_offset)
2645                                         continue;
2646                                 if (ext3_test_bit(i, bitmap_bh->b_data))
2647                                         break;
2648                         }
2649                         brelse(bitmap_bh);
2650                         if (i == start + inodes_per_buffer) {
2651                                 /* all other inodes are free, so skip I/O */
2652                                 memset(bh->b_data, 0, bh->b_size);
2653                                 set_buffer_uptodate(bh);
2654                                 unlock_buffer(bh);
2655                                 goto has_buffer;
2656                         }
2657                 }
2658
2659 make_io:
2660                 /*
2661                  * There are other valid inodes in the buffer, this inode
2662                  * has in-inode xattrs, or we don't have this inode in memory.
2663                  * Read the block from disk.
2664                  */
2665                 get_bh(bh);
2666                 bh->b_end_io = end_buffer_read_sync;
2667                 submit_bh(READ_META, bh);
2668                 wait_on_buffer(bh);
2669                 if (!buffer_uptodate(bh)) {
2670                         ext3_error(inode->i_sb, "ext3_get_inode_loc",
2671                                         "unable to read inode block - "
2672                                         "inode=%lu, block="E3FSBLK,
2673                                         inode->i_ino, block);
2674                         brelse(bh);
2675                         return -EIO;
2676                 }
2677         }
2678 has_buffer:
2679         iloc->bh = bh;
2680         return 0;
2681 }
2682
2683 int ext3_get_inode_loc(struct inode *inode, struct ext3_iloc *iloc)
2684 {
2685         /* We have all inode data except xattrs in memory here. */
2686         return __ext3_get_inode_loc(inode, iloc,
2687                 !(EXT3_I(inode)->i_state & EXT3_STATE_XATTR));
2688 }
2689
2690 void ext3_set_inode_flags(struct inode *inode)
2691 {
2692         unsigned int flags = EXT3_I(inode)->i_flags;
2693
2694         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
2695         if (flags & EXT3_SYNC_FL)
2696                 inode->i_flags |= S_SYNC;
2697         if (flags & EXT3_APPEND_FL)
2698                 inode->i_flags |= S_APPEND;
2699         if (flags & EXT3_IMMUTABLE_FL)
2700                 inode->i_flags |= S_IMMUTABLE;
2701         if (flags & EXT3_NOATIME_FL)
2702                 inode->i_flags |= S_NOATIME;
2703         if (flags & EXT3_DIRSYNC_FL)
2704                 inode->i_flags |= S_DIRSYNC;
2705 }
2706
2707 /* Propagate flags from i_flags to EXT3_I(inode)->i_flags */
2708 void ext3_get_inode_flags(struct ext3_inode_info *ei)
2709 {
2710         unsigned int flags = ei->vfs_inode.i_flags;
2711
2712         ei->i_flags &= ~(EXT3_SYNC_FL|EXT3_APPEND_FL|
2713                         EXT3_IMMUTABLE_FL|EXT3_NOATIME_FL|EXT3_DIRSYNC_FL);
2714         if (flags & S_SYNC)
2715                 ei->i_flags |= EXT3_SYNC_FL;
2716         if (flags & S_APPEND)
2717                 ei->i_flags |= EXT3_APPEND_FL;
2718         if (flags & S_IMMUTABLE)
2719                 ei->i_flags |= EXT3_IMMUTABLE_FL;
2720         if (flags & S_NOATIME)
2721                 ei->i_flags |= EXT3_NOATIME_FL;
2722         if (flags & S_DIRSYNC)
2723                 ei->i_flags |= EXT3_DIRSYNC_FL;
2724 }
2725
2726 struct inode *ext3_iget(struct super_block *sb, unsigned long ino)
2727 {
2728         struct ext3_iloc iloc;
2729         struct ext3_inode *raw_inode;
2730         struct ext3_inode_info *ei;
2731         struct buffer_head *bh;
2732         struct inode *inode;
2733         long ret;
2734         int block;
2735
2736         inode = iget_locked(sb, ino);
2737         if (!inode)
2738                 return ERR_PTR(-ENOMEM);
2739         if (!(inode->i_state & I_NEW))
2740                 return inode;
2741
2742         ei = EXT3_I(inode);
2743 #ifdef CONFIG_EXT3_FS_POSIX_ACL
2744         ei->i_acl = EXT3_ACL_NOT_CACHED;
2745         ei->i_default_acl = EXT3_ACL_NOT_CACHED;
2746 #endif
2747         ei->i_block_alloc_info = NULL;
2748
2749         ret = __ext3_get_inode_loc(inode, &iloc, 0);
2750         if (ret < 0)
2751                 goto bad_inode;
2752         bh = iloc.bh;
2753         raw_inode = ext3_raw_inode(&iloc);
2754         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
2755         inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
2756         inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
2757         if(!(test_opt (inode->i_sb, NO_UID32))) {
2758                 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
2759                 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
2760         }
2761         inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
2762         inode->i_size = le32_to_cpu(raw_inode->i_size);
2763         inode->i_atime.tv_sec = (signed)le32_to_cpu(raw_inode->i_atime);
2764         inode->i_ctime.tv_sec = (signed)le32_to_cpu(raw_inode->i_ctime);
2765         inode->i_mtime.tv_sec = (signed)le32_to_cpu(raw_inode->i_mtime);
2766         inode->i_atime.tv_nsec = inode->i_ctime.tv_nsec = inode->i_mtime.tv_nsec = 0;
2767
2768         ei->i_state = 0;
2769         ei->i_dir_start_lookup = 0;
2770         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
2771         /* We now have enough fields to check if the inode was active or not.
2772          * This is needed because nfsd might try to access dead inodes
2773          * the test is that same one that e2fsck uses
2774          * NeilBrown 1999oct15
2775          */
2776         if (inode->i_nlink == 0) {
2777                 if (inode->i_mode == 0 ||
2778                     !(EXT3_SB(inode->i_sb)->s_mount_state & EXT3_ORPHAN_FS)) {
2779                         /* this inode is deleted */
2780                         brelse (bh);
2781                         ret = -ESTALE;
2782                         goto bad_inode;
2783                 }
2784                 /* The only unlinked inodes we let through here have
2785                  * valid i_mode and are being read by the orphan
2786                  * recovery code: that's fine, we're about to complete
2787                  * the process of deleting those. */
2788         }
2789         inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
2790         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
2791 #ifdef EXT3_FRAGMENTS
2792         ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
2793         ei->i_frag_no = raw_inode->i_frag;
2794         ei->i_frag_size = raw_inode->i_fsize;
2795 #endif
2796         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
2797         if (!S_ISREG(inode->i_mode)) {
2798                 ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
2799         } else {
2800                 inode->i_size |=
2801                         ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
2802         }
2803         ei->i_disksize = inode->i_size;
2804         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
2805         ei->i_block_group = iloc.block_group;
2806         /*
2807          * NOTE! The in-memory inode i_data array is in little-endian order
2808          * even on big-endian machines: we do NOT byteswap the block numbers!
2809          */
2810         for (block = 0; block < EXT3_N_BLOCKS; block++)
2811                 ei->i_data[block] = raw_inode->i_block[block];
2812         INIT_LIST_HEAD(&ei->i_orphan);
2813
2814         if (inode->i_ino >= EXT3_FIRST_INO(inode->i_sb) + 1 &&
2815             EXT3_INODE_SIZE(inode->i_sb) > EXT3_GOOD_OLD_INODE_SIZE) {
2816                 /*
2817                  * When mke2fs creates big inodes it does not zero out
2818                  * the unused bytes above EXT3_GOOD_OLD_INODE_SIZE,
2819                  * so ignore those first few inodes.
2820                  */
2821                 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
2822                 if (EXT3_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
2823                     EXT3_INODE_SIZE(inode->i_sb)) {
2824                         brelse (bh);
2825                         ret = -EIO;
2826                         goto bad_inode;
2827                 }
2828                 if (ei->i_extra_isize == 0) {
2829                         /* The extra space is currently unused. Use it. */
2830                         ei->i_extra_isize = sizeof(struct ext3_inode) -
2831                                             EXT3_GOOD_OLD_INODE_SIZE;
2832                 } else {
2833                         __le32 *magic = (void *)raw_inode +
2834                                         EXT3_GOOD_OLD_INODE_SIZE +
2835                                         ei->i_extra_isize;
2836                         if (*magic == cpu_to_le32(EXT3_XATTR_MAGIC))
2837                                  ei->i_state |= EXT3_STATE_XATTR;
2838                 }
2839         } else
2840                 ei->i_extra_isize = 0;
2841
2842         if (S_ISREG(inode->i_mode)) {
2843                 inode->i_op = &ext3_file_inode_operations;
2844                 inode->i_fop = &ext3_file_operations;
2845                 ext3_set_aops(inode);
2846         } else if (S_ISDIR(inode->i_mode)) {
2847                 inode->i_op = &ext3_dir_inode_operations;
2848                 inode->i_fop = &ext3_dir_operations;
2849         } else if (S_ISLNK(inode->i_mode)) {
2850                 if (ext3_inode_is_fast_symlink(inode)) {
2851                         inode->i_op = &ext3_fast_symlink_inode_operations;
2852                         nd_terminate_link(ei->i_data, inode->i_size,
2853                                 sizeof(ei->i_data) - 1);
2854                 } else {
2855                         inode->i_op = &ext3_symlink_inode_operations;
2856                         ext3_set_aops(inode);
2857                 }
2858         } else {
2859                 inode->i_op = &ext3_special_inode_operations;
2860                 if (raw_inode->i_block[0])
2861                         init_special_inode(inode, inode->i_mode,
2862                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
2863                 else
2864                         init_special_inode(inode, inode->i_mode,
2865                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
2866         }
2867         extent_map_tree_init(&ei->extent_tree);
2868         brelse (iloc.bh);
2869         ext3_set_inode_flags(inode);
2870         unlock_new_inode(inode);
2871         return inode;
2872
2873 bad_inode:
2874         iget_failed(inode);
2875         return ERR_PTR(ret);
2876 }
2877
2878 /*
2879  * Post the struct inode info into an on-disk inode location in the
2880  * buffer-cache.  This gobbles the caller's reference to the
2881  * buffer_head in the inode location struct.
2882  *
2883  * The caller must have write access to iloc->bh.
2884  */
2885 static int ext3_do_update_inode(handle_t *handle,
2886                                 struct inode *inode,
2887                                 struct ext3_iloc *iloc)
2888 {
2889         struct ext3_inode *raw_inode = ext3_raw_inode(iloc);
2890         struct ext3_inode_info *ei = EXT3_I(inode);
2891         struct buffer_head *bh = iloc->bh;
2892         int err = 0, rc, block;
2893
2894         /* For fields not not tracking in the in-memory inode,
2895          * initialise them to zero for new inodes. */
2896         if (ei->i_state & EXT3_STATE_NEW)
2897                 memset(raw_inode, 0, EXT3_SB(inode->i_sb)->s_inode_size);
2898
2899         ext3_get_inode_flags(ei);
2900         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
2901         if(!(test_opt(inode->i_sb, NO_UID32))) {
2902                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
2903                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
2904 /*
2905  * Fix up interoperability with old kernels. Otherwise, old inodes get
2906  * re-used with the upper 16 bits of the uid/gid intact
2907  */
2908                 if(!ei->i_dtime) {
2909                         raw_inode->i_uid_high =
2910                                 cpu_to_le16(high_16_bits(inode->i_uid));
2911                         raw_inode->i_gid_high =
2912                                 cpu_to_le16(high_16_bits(inode->i_gid));
2913                 } else {
2914                         raw_inode->i_uid_high = 0;
2915                         raw_inode->i_gid_high = 0;
2916                 }
2917         } else {
2918                 raw_inode->i_uid_low =
2919                         cpu_to_le16(fs_high2lowuid(inode->i_uid));
2920                 raw_inode->i_gid_low =
2921                         cpu_to_le16(fs_high2lowgid(inode->i_gid));
2922                 raw_inode->i_uid_high = 0;
2923                 raw_inode->i_gid_high = 0;
2924         }
2925         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
2926         raw_inode->i_size = cpu_to_le32(ei->i_disksize);
2927         raw_inode->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
2928         raw_inode->i_ctime = cpu_to_le32(inode->i_ctime.tv_sec);
2929         raw_inode->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
2930         raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
2931         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
2932         raw_inode->i_flags = cpu_to_le32(ei->i_flags);
2933 #ifdef EXT3_FRAGMENTS
2934         raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
2935         raw_inode->i_frag = ei->i_frag_no;
2936         raw_inode->i_fsize = ei->i_frag_size;
2937 #endif
2938         raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
2939         if (!S_ISREG(inode->i_mode)) {
2940                 raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
2941         } else {
2942                 raw_inode->i_size_high =
2943                         cpu_to_le32(ei->i_disksize >> 32);
2944                 if (ei->i_disksize > 0x7fffffffULL) {
2945                         struct super_block *sb = inode->i_sb;
2946                         if (!EXT3_HAS_RO_COMPAT_FEATURE(sb,
2947                                         EXT3_FEATURE_RO_COMPAT_LARGE_FILE) ||
2948                             EXT3_SB(sb)->s_es->s_rev_level ==
2949                                         cpu_to_le32(EXT3_GOOD_OLD_REV)) {
2950                                /* If this is the first large file
2951                                 * created, add a flag to the superblock.
2952                                 */
2953                                 err = ext3_journal_get_write_access(handle,
2954                                                 EXT3_SB(sb)->s_sbh);
2955                                 if (err)
2956                                         goto out_brelse;
2957                                 ext3_update_dynamic_rev(sb);
2958                                 EXT3_SET_RO_COMPAT_FEATURE(sb,
2959                                         EXT3_FEATURE_RO_COMPAT_LARGE_FILE);
2960                                 sb->s_dirt = 1;
2961                                 handle->h_sync = 1;
2962                                 err = ext3_journal_dirty_metadata(handle,
2963                                                 EXT3_SB(sb)->s_sbh);
2964                         }
2965                 }
2966         }
2967         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
2968         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
2969                 if (old_valid_dev(inode->i_rdev)) {
2970                         raw_inode->i_block[0] =
2971                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
2972                         raw_inode->i_block[1] = 0;
2973                 } else {
2974                         raw_inode->i_block[0] = 0;
2975                         raw_inode->i_block[1] =
2976                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
2977                         raw_inode->i_block[2] = 0;
2978                 }
2979         } else for (block = 0; block < EXT3_N_BLOCKS; block++)
2980                 raw_inode->i_block[block] = ei->i_data[block];
2981
2982         if (ei->i_extra_isize)
2983                 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
2984
2985         BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
2986         rc = ext3_journal_dirty_metadata(handle, bh);
2987         if (!err)
2988                 err = rc;
2989         ei->i_state &= ~EXT3_STATE_NEW;
2990
2991 out_brelse:
2992         brelse (bh);
2993         ext3_std_error(inode->i_sb, err);
2994         return err;
2995 }
2996
2997 /*
2998  * ext3_write_inode()
2999  *
3000  * We are called from a few places:
3001  *
3002  * - Within generic_file_write() for O_SYNC files.
3003  *   Here, there will be no transaction running. We wait for any running
3004  *   trasnaction to commit.
3005  *
3006  * - Within sys_sync(), kupdate and such.
3007  *   We wait on commit, if tol to.
3008  *
3009  * - Within prune_icache() (PF_MEMALLOC == true)
3010  *   Here we simply return.  We can't afford to block kswapd on the
3011  *   journal commit.
3012  *
3013  * In all cases it is actually safe for us to return without doing anything,
3014  * because the inode has been copied into a raw inode buffer in
3015  * ext3_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
3016  * knfsd.
3017  *
3018  * Note that we are absolutely dependent upon all inode dirtiers doing the
3019  * right thing: they *must* call mark_inode_dirty() after dirtying info in
3020  * which we are interested.
3021  *
3022  * It would be a bug for them to not do this.  The code:
3023  *
3024  *      mark_inode_dirty(inode)
3025  *      stuff();
3026  *      inode->i_size = expr;
3027  *
3028  * is in error because a kswapd-driven write_inode() could occur while
3029  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
3030  * will no longer be on the superblock's dirty inode list.
3031  */
3032 int ext3_write_inode(struct inode *inode, int wait)
3033 {
3034         if (current->flags & PF_MEMALLOC)
3035                 return 0;
3036
3037         if (ext3_journal_current_handle()) {
3038                 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
3039                 dump_stack();
3040                 return -EIO;
3041         }
3042
3043         if (!wait)
3044                 return 0;
3045
3046         return ext3_force_commit(inode->i_sb);
3047 }
3048
3049 /*
3050  * ext3_setattr()
3051  *
3052  * Called from notify_change.
3053  *
3054  * We want to trap VFS attempts to truncate the file as soon as
3055  * possible.  In particular, we want to make sure that when the VFS
3056  * shrinks i_size, we put the inode on the orphan list and modify
3057  * i_disksize immediately, so that during the subsequent flushing of
3058  * dirty pages and freeing of disk blocks, we can guarantee that any
3059  * commit will leave the blocks being flushed in an unused state on
3060  * disk.  (On recovery, the inode will get truncated and the blocks will
3061  * be freed, so we have a strong guarantee that no future commit will
3062  * leave these blocks visible to the user.)
3063  *
3064  * Called with inode->sem down.
3065  */
3066 int ext3_setattr(struct dentry *dentry, struct iattr *attr)
3067 {
3068         struct inode *inode = dentry->d_inode;
3069         int error, rc = 0;
3070         const unsigned int ia_valid = attr->ia_valid;
3071
3072         error = inode_change_ok(inode, attr);
3073         if (error)
3074                 return error;
3075
3076         if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
3077                 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
3078                 handle_t *handle;
3079
3080                 /* (user+group)*(old+new) structure, inode write (sb,
3081                  * inode block, ? - but truncate inode update has it) */
3082                 handle = ext3_journal_start(inode, 2*(EXT3_QUOTA_INIT_BLOCKS(inode->i_sb)+
3083                                         EXT3_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
3084                 if (IS_ERR(handle)) {
3085                         error = PTR_ERR(handle);
3086                         goto err_out;
3087                 }
3088                 error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
3089                 if (error) {
3090                         ext3_journal_stop(handle);
3091                         return error;
3092                 }
3093                 /* Update corresponding info in inode so that everything is in
3094                  * one transaction */
3095                 if (attr->ia_valid & ATTR_UID)
3096                         inode->i_uid = attr->ia_uid;
3097                 if (attr->ia_valid & ATTR_GID)
3098                         inode->i_gid = attr->ia_gid;
3099                 error = ext3_mark_inode_dirty(handle, inode);
3100                 ext3_journal_stop(handle);
3101         }
3102
3103         if (S_ISREG(inode->i_mode) &&
3104             attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
3105                 handle_t *handle;
3106
3107                 handle = ext3_journal_start(inode, 3);
3108                 if (IS_ERR(handle)) {
3109                         error = PTR_ERR(handle);
3110                         goto err_out;
3111                 }
3112
3113                 error = ext3_orphan_add(handle, inode);
3114                 EXT3_I(inode)->i_disksize = attr->ia_size;
3115                 rc = ext3_mark_inode_dirty(handle, inode);
3116                 if (!error)
3117                         error = rc;
3118                 ext3_journal_stop(handle);
3119         }
3120
3121         rc = inode_setattr(inode, attr);
3122
3123         /* If inode_setattr's call to ext3_truncate failed to get a
3124          * transaction handle at all, we need to clean up the in-core
3125          * orphan list manually. */
3126         if (inode->i_nlink)
3127                 ext3_orphan_del(NULL, inode);
3128
3129         if (!rc && (ia_valid & ATTR_MODE))
3130                 rc = ext3_acl_chmod(inode);
3131
3132 err_out:
3133         ext3_std_error(inode->i_sb, error);
3134         if (!error)
3135                 error = rc;
3136         return error;
3137 }
3138
3139
3140 /*
3141  * How many blocks doth make a writepage()?
3142  *
3143  * With N blocks per page, it may be:
3144  * N data blocks
3145  * 2 indirect block
3146  * 2 dindirect
3147  * 1 tindirect
3148  * N+5 bitmap blocks (from the above)
3149  * N+5 group descriptor summary blocks
3150  * 1 inode block
3151  * 1 superblock.
3152  * 2 * EXT3_SINGLEDATA_TRANS_BLOCKS for the quote files
3153  *
3154  * 3 * (N + 5) + 2 + 2 * EXT3_SINGLEDATA_TRANS_BLOCKS
3155  *
3156  * With ordered or writeback data it's the same, less the N data blocks.
3157  *
3158  * If the inode's direct blocks can hold an integral number of pages then a
3159  * page cannot straddle two indirect blocks, and we can only touch one indirect
3160  * and dindirect block, and the "5" above becomes "3".
3161  *
3162  * This still overestimates under most circumstances.  If we were to pass the
3163  * start and end offsets in here as well we could do block_to_path() on each
3164  * block and work out the exact number of indirects which are touched.  Pah.
3165  */
3166
3167 static int ext3_writepage_trans_blocks(struct inode *inode)
3168 {
3169         int bpp = ext3_journal_blocks_per_page(inode);
3170         int indirects = (EXT3_NDIR_BLOCKS % bpp) ? 5 : 3;
3171         int ret;
3172
3173         if (ext3_should_journal_data(inode))
3174                 ret = 3 * (bpp + indirects) + 2;
3175         else
3176                 ret = 2 * (bpp + indirects) + 2;
3177
3178 #ifdef CONFIG_QUOTA
3179         /* We know that structure was already allocated during DQUOT_INIT so
3180          * we will be updating only the data blocks + inodes */
3181         ret += 2*EXT3_QUOTA_TRANS_BLOCKS(inode->i_sb);
3182 #endif
3183
3184         return ret;
3185 }
3186
3187 /*
3188  * The caller must have previously called ext3_reserve_inode_write().
3189  * Give this, we know that the caller already has write access to iloc->bh.
3190  */
3191 int ext3_mark_iloc_dirty(handle_t *handle,
3192                 struct inode *inode, struct ext3_iloc *iloc)
3193 {
3194         int err = 0;
3195
3196         /* the do_update_inode consumes one bh->b_count */
3197         get_bh(iloc->bh);
3198
3199         /* ext3_do_update_inode() does journal_dirty_metadata */
3200         err = ext3_do_update_inode(handle, inode, iloc);
3201         put_bh(iloc->bh);
3202         return err;
3203 }
3204
3205 /*
3206  * On success, We end up with an outstanding reference count against
3207  * iloc->bh.  This _must_ be cleaned up later.
3208  */
3209
3210 int
3211 ext3_reserve_inode_write(handle_t *handle, struct inode *inode,
3212                          struct ext3_iloc *iloc)
3213 {
3214         int err = 0;
3215         if (handle) {
3216                 err = ext3_get_inode_loc(inode, iloc);
3217                 if (!err) {
3218                         BUFFER_TRACE(iloc->bh, "get_write_access");
3219                         err = ext3_journal_get_write_access(handle, iloc->bh);
3220                         if (err) {
3221                                 brelse(iloc->bh);
3222                                 iloc->bh = NULL;
3223                         }
3224                 }
3225         }
3226         ext3_std_error(inode->i_sb, err);
3227         return err;
3228 }
3229
3230 /*
3231  * What we do here is to mark the in-core inode as clean with respect to inode
3232  * dirtiness (it may still be data-dirty).
3233  * This means that the in-core inode may be reaped by prune_icache
3234  * without having to perform any I/O.  This is a very good thing,
3235  * because *any* task may call prune_icache - even ones which
3236  * have a transaction open against a different journal.
3237  *
3238  * Is this cheating?  Not really.  Sure, we haven't written the
3239  * inode out, but prune_icache isn't a user-visible syncing function.
3240  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
3241  * we start and wait on commits.
3242  *
3243  * Is this efficient/effective?  Well, we're being nice to the system
3244  * by cleaning up our inodes proactively so they can be reaped
3245  * without I/O.  But we are potentially leaving up to five seconds'
3246  * worth of inodes floating about which prune_icache wants us to
3247  * write out.  One way to fix that would be to get prune_icache()
3248  * to do a write_super() to free up some memory.  It has the desired
3249  * effect.
3250  */
3251 int ext3_mark_inode_dirty(handle_t *handle, struct inode *inode)
3252 {
3253         struct ext3_iloc iloc;
3254         int err;
3255
3256         might_sleep();
3257         err = ext3_reserve_inode_write(handle, inode, &iloc);
3258         if (!err)
3259                 err = ext3_mark_iloc_dirty(handle, inode, &iloc);
3260         return err;
3261 }
3262
3263 /*
3264  * ext3_dirty_inode() is called from __mark_inode_dirty()
3265  *
3266  * We're really interested in the case where a file is being extended.
3267  * i_size has been changed by generic_commit_write() and we thus need
3268  * to include the updated inode in the current transaction.
3269  *
3270  * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
3271  * are allocated to the file.
3272  *
3273  * If the inode is marked synchronous, we don't honour that here - doing
3274  * so would cause a commit on atime updates, which we don't bother doing.
3275  * We handle synchronous inodes at the highest possible level.
3276  */
3277 void ext3_dirty_inode(struct inode *inode)
3278 {
3279         handle_t *current_handle = ext3_journal_current_handle();
3280         handle_t *handle;
3281
3282         handle = ext3_journal_start(inode, 2);
3283         if (IS_ERR(handle))
3284                 goto out;
3285         if (current_handle &&
3286                 current_handle->h_transaction != handle->h_transaction) {
3287                 /* This task has a transaction open against a different fs */
3288                 printk(KERN_EMERG "%s: transactions do not match!\n",
3289                        __func__);
3290         } else {
3291                 jbd_debug(5, "marking dirty.  outer handle=%p\n",
3292                                 current_handle);
3293                 ext3_mark_inode_dirty(handle, inode);
3294         }
3295         ext3_journal_stop(handle);
3296 out:
3297         return;
3298 }
3299
3300 #if 0
3301 /*
3302  * Bind an inode's backing buffer_head into this transaction, to prevent
3303  * it from being flushed to disk early.  Unlike
3304  * ext3_reserve_inode_write, this leaves behind no bh reference and
3305  * returns no iloc structure, so the caller needs to repeat the iloc
3306  * lookup to mark the inode dirty later.
3307  */
3308 static int ext3_pin_inode(handle_t *handle, struct inode *inode)
3309 {
3310         struct ext3_iloc iloc;
3311
3312         int err = 0;
3313         if (handle) {
3314                 err = ext3_get_inode_loc(inode, &iloc);
3315                 if (!err) {
3316                         BUFFER_TRACE(iloc.bh, "get_write_access");
3317                         err = journal_get_write_access(handle, iloc.bh);
3318                         if (!err)
3319                                 err = ext3_journal_dirty_metadata(handle,
3320                                                                   iloc.bh);
3321                         brelse(iloc.bh);
3322                 }
3323         }
3324         ext3_std_error(inode->i_sb, err);
3325         return err;
3326 }
3327 #endif
3328
3329 int ext3_change_inode_journal_flag(struct inode *inode, int val)
3330 {
3331         journal_t *journal;
3332         handle_t *handle;
3333         int err;
3334
3335         /*
3336          * We have to be very careful here: changing a data block's
3337          * journaling status dynamically is dangerous.  If we write a
3338          * data block to the journal, change the status and then delete
3339          * that block, we risk forgetting to revoke the old log record
3340          * from the journal and so a subsequent replay can corrupt data.
3341          * So, first we make sure that the journal is empty and that
3342          * nobody is changing anything.
3343          */
3344
3345         journal = EXT3_JOURNAL(inode);
3346         if (is_journal_aborted(journal))
3347                 return -EROFS;
3348
3349         journal_lock_updates(journal);
3350         journal_flush(journal);
3351
3352         /*
3353          * OK, there are no updates running now, and all cached data is
3354          * synced to disk.  We are now in a completely consistent state
3355          * which doesn't have anything in the journal, and we know that
3356          * no filesystem updates are running, so it is safe to modify
3357          * the inode's in-core data-journaling state flag now.
3358          */
3359
3360         if (val)
3361                 EXT3_I(inode)->i_flags |= EXT3_JOURNAL_DATA_FL;
3362         else
3363                 EXT3_I(inode)->i_flags &= ~EXT3_JOURNAL_DATA_FL;
3364         ext3_set_aops(inode);
3365
3366         journal_unlock_updates(journal);
3367
3368         /* Finally we can mark the inode as dirty. */
3369
3370         handle = ext3_journal_start(inode, 1);
3371         if (IS_ERR(handle))
3372                 return PTR_ERR(handle);
3373
3374         err = ext3_mark_inode_dirty(handle, inode);
3375         handle->h_sync = 1;
3376         ext3_journal_stop(handle);
3377         ext3_std_error(inode->i_sb, err);
3378
3379         return err;
3380 }