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