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