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