c9756a5251e9cfd239fb73a5b4ede0686802ec89
[linux-2.4.git] / inode.c
1 /*
2  *  linux/fs/ext2/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@dcs.ed.ac.uk), 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 ext2_get_block() by Al Viro, 2000
23  */
24
25 #include <linux/fs.h>
26 #include <linux/ext2_fs.h>
27 #include <linux/locks.h>
28 #include <linux/smp_lock.h>
29 #include <linux/sched.h>
30 #include <linux/highuid.h>
31 #include <linux/quotaops.h>
32 #include <linux/module.h>
33
34 MODULE_AUTHOR("Remy Card and others");
35 MODULE_DESCRIPTION("Second Extended Filesystem");
36 MODULE_LICENSE("GPL");
37
38 /*
39  * Test whether an inode is a fast symlink.
40  */
41 static inline int ext2_inode_is_fast_symlink(struct inode *inode)
42 {
43         int ea_blocks = inode->u.ext2_i.i_file_acl ?
44                 (inode->i_sb->s_blocksize >> 9) : 0;
45
46         return (S_ISLNK(inode->i_mode) &&
47                 inode->i_blocks - ea_blocks == 0);
48 }
49
50 static int ext2_update_inode(struct inode * inode, int do_sync);
51
52 /*
53  * Called at each iput()
54  */
55 void ext2_put_inode (struct inode * inode)
56 {
57         ext2_discard_prealloc (inode);
58 }
59
60 /*
61  * Called at the last iput() if i_nlink is zero.
62  */
63 void ext2_delete_inode (struct inode * inode)
64 {
65         lock_kernel();
66
67         if (is_bad_inode(inode) ||
68             inode->i_ino == EXT2_ACL_IDX_INO ||
69             inode->i_ino == EXT2_ACL_DATA_INO)
70                 goto no_delete;
71         inode->u.ext2_i.i_dtime = CURRENT_TIME;
72         mark_inode_dirty(inode);
73         ext2_update_inode(inode, IS_SYNC(inode));
74         inode->i_size = 0;
75         if (inode->i_blocks)
76                 ext2_truncate (inode);
77         ext2_free_inode (inode);
78
79         unlock_kernel();
80         return;
81 no_delete:
82         unlock_kernel();
83         clear_inode(inode);     /* We must guarantee clearing of inode... */
84 }
85
86 void ext2_discard_prealloc (struct inode * inode)
87 {
88 #ifdef EXT2_PREALLOCATE
89         lock_kernel();
90         /* Writer: ->i_prealloc* */
91         if (inode->u.ext2_i.i_prealloc_count) {
92                 unsigned short total = inode->u.ext2_i.i_prealloc_count;
93                 unsigned long block = inode->u.ext2_i.i_prealloc_block;
94                 inode->u.ext2_i.i_prealloc_count = 0;
95                 inode->u.ext2_i.i_prealloc_block = 0;
96                 /* Writer: end */
97                 ext2_free_blocks (inode, block, total);
98         }
99         unlock_kernel();
100 #endif
101 }
102
103 static int ext2_alloc_block (struct inode * inode, unsigned long goal, int *err)
104 {
105 #ifdef EXT2FS_DEBUG
106         static unsigned long alloc_hits = 0, alloc_attempts = 0;
107 #endif
108         unsigned long result;
109
110
111 #ifdef EXT2_PREALLOCATE
112         /* Writer: ->i_prealloc* */
113         if (inode->u.ext2_i.i_prealloc_count &&
114             (goal == inode->u.ext2_i.i_prealloc_block ||
115              goal + 1 == inode->u.ext2_i.i_prealloc_block))
116         {               
117                 result = inode->u.ext2_i.i_prealloc_block++;
118                 inode->u.ext2_i.i_prealloc_count--;
119                 /* Writer: end */
120                 ext2_debug ("preallocation hit (%lu/%lu).\n",
121                             ++alloc_hits, ++alloc_attempts);
122         } else {
123                 ext2_discard_prealloc (inode);
124                 ext2_debug ("preallocation miss (%lu/%lu).\n",
125                             alloc_hits, ++alloc_attempts);
126                 if (S_ISREG(inode->i_mode))
127                         result = ext2_new_block (inode, goal, 
128                                  &inode->u.ext2_i.i_prealloc_count,
129                                  &inode->u.ext2_i.i_prealloc_block, err);
130                 else
131                         result = ext2_new_block (inode, goal, 0, 0, err);
132         }
133 #else
134         result = ext2_new_block (inode, goal, 0, 0, err);
135 #endif
136         return result;
137 }
138
139 typedef struct {
140         u32     *p;
141         u32     key;
142         struct buffer_head *bh;
143 } Indirect;
144
145 static inline void add_chain(Indirect *p, struct buffer_head *bh, u32 *v)
146 {
147         p->key = *(p->p = v);
148         p->bh = bh;
149 }
150
151 static inline int verify_chain(Indirect *from, Indirect *to)
152 {
153         while (from <= to && from->key == *from->p)
154                 from++;
155         return (from > to);
156 }
157
158 /**
159  *      ext2_block_to_path - parse the block number into array of offsets
160  *      @inode: inode in question (we are only interested in its superblock)
161  *      @i_block: block number to be parsed
162  *      @offsets: array to store the offsets in
163  *
164  *      To store the locations of file's data ext2 uses a data structure common
165  *      for UNIX filesystems - tree of pointers anchored in the inode, with
166  *      data blocks at leaves and indirect blocks in intermediate nodes.
167  *      This function translates the block number into path in that tree -
168  *      return value is the path length and @offsets[n] is the offset of
169  *      pointer to (n+1)th node in the nth one. If @block is out of range
170  *      (negative or too large) warning is printed and zero returned.
171  *
172  *      Note: function doesn't find node addresses, so no IO is needed. All
173  *      we need to know is the capacity of indirect blocks (taken from the
174  *      inode->i_sb).
175  */
176
177 /*
178  * Portability note: the last comparison (check that we fit into triple
179  * indirect block) is spelled differently, because otherwise on an
180  * architecture with 32-bit longs and 8Kb pages we might get into trouble
181  * if our filesystem had 8Kb blocks. We might use long long, but that would
182  * kill us on x86. Oh, well, at least the sign propagation does not matter -
183  * i_block would have to be negative in the very beginning, so we would not
184  * get there at all.
185  */
186
187 static int ext2_block_to_path(struct inode *inode, long i_block, int offsets[4])
188 {
189         int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
190         int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
191         const long direct_blocks = EXT2_NDIR_BLOCKS,
192                 indirect_blocks = ptrs,
193                 double_blocks = (1 << (ptrs_bits * 2));
194         int n = 0;
195
196         if (i_block < 0) {
197                 ext2_warning (inode->i_sb, "ext2_block_to_path", "block < 0");
198         } else if (i_block < direct_blocks) {
199                 offsets[n++] = i_block;
200         } else if ( (i_block -= direct_blocks) < indirect_blocks) {
201                 offsets[n++] = EXT2_IND_BLOCK;
202                 offsets[n++] = i_block;
203         } else if ((i_block -= indirect_blocks) < double_blocks) {
204                 offsets[n++] = EXT2_DIND_BLOCK;
205                 offsets[n++] = i_block >> ptrs_bits;
206                 offsets[n++] = i_block & (ptrs - 1);
207         } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
208                 offsets[n++] = EXT2_TIND_BLOCK;
209                 offsets[n++] = i_block >> (ptrs_bits * 2);
210                 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
211                 offsets[n++] = i_block & (ptrs - 1);
212         } else {
213                 ext2_warning (inode->i_sb, "ext2_block_to_path", "block > big");
214         }
215         return n;
216 }
217
218 /**
219  *      ext2_get_branch - read the chain of indirect blocks leading to data
220  *      @inode: inode in question
221  *      @depth: depth of the chain (1 - direct pointer, etc.)
222  *      @offsets: offsets of pointers in inode/indirect blocks
223  *      @chain: place to store the result
224  *      @err: here we store the error value
225  *
226  *      Function fills the array of triples <key, p, bh> and returns %NULL
227  *      if everything went OK or the pointer to the last filled triple
228  *      (incomplete one) otherwise. Upon the return chain[i].key contains
229  *      the number of (i+1)-th block in the chain (as it is stored in memory,
230  *      i.e. little-endian 32-bit), chain[i].p contains the address of that
231  *      number (it points into struct inode for i==0 and into the bh->b_data
232  *      for i>0) and chain[i].bh points to the buffer_head of i-th indirect
233  *      block for i>0 and NULL for i==0. In other words, it holds the block
234  *      numbers of the chain, addresses they were taken from (and where we can
235  *      verify that chain did not change) and buffer_heads hosting these
236  *      numbers.
237  *
238  *      Function stops when it stumbles upon zero pointer (absent block)
239  *              (pointer to last triple returned, *@err == 0)
240  *      or when it gets an IO error reading an indirect block
241  *              (ditto, *@err == -EIO)
242  *      or when it notices that chain had been changed while it was reading
243  *              (ditto, *@err == -EAGAIN)
244  *      or when it reads all @depth-1 indirect blocks successfully and finds
245  *      the whole chain, all way to the data (returns %NULL, *err == 0).
246  */
247 static Indirect *ext2_get_branch(struct inode *inode,
248                                  int depth,
249                                  int *offsets,
250                                  Indirect chain[4],
251                                  int *err)
252 {
253         struct super_block *sb = inode->i_sb;
254         Indirect *p = chain;
255         struct buffer_head *bh;
256
257         *err = 0;
258         /* i_data is not going away, no lock needed */
259         add_chain (chain, NULL, inode->u.ext2_i.i_data + *offsets);
260         if (!p->key)
261                 goto no_block;
262         while (--depth) {
263                 bh = sb_bread(sb, le32_to_cpu(p->key));
264                 if (!bh)
265                         goto failure;
266                 /* Reader: pointers */
267                 if (!verify_chain(chain, p))
268                         goto changed;
269                 add_chain(++p, bh, (u32*)bh->b_data + *++offsets);
270                 /* Reader: end */
271                 if (!p->key)
272                         goto no_block;
273         }
274         return NULL;
275
276 changed:
277         *err = -EAGAIN;
278         goto no_block;
279 failure:
280         *err = -EIO;
281 no_block:
282         return p;
283 }
284
285 /**
286  *      ext2_find_near - find a place for allocation with sufficient locality
287  *      @inode: owner
288  *      @ind: descriptor of indirect block.
289  *
290  *      This function returns the prefered place for block allocation.
291  *      It is used when heuristic for sequential allocation fails.
292  *      Rules are:
293  *        + if there is a block to the left of our position - allocate near it.
294  *        + if pointer will live in indirect block - allocate near that block.
295  *        + if pointer will live in inode - allocate in the same cylinder group.
296  *      Caller must make sure that @ind is valid and will stay that way.
297  */
298
299 static inline unsigned long ext2_find_near(struct inode *inode, Indirect *ind)
300 {
301         u32 *start = ind->bh ? (u32*) ind->bh->b_data : inode->u.ext2_i.i_data;
302         u32 *p;
303
304         /* Try to find previous block */
305         for (p = ind->p - 1; p >= start; p--)
306                 if (*p)
307                         return le32_to_cpu(*p);
308
309         /* No such thing, so let's try location of indirect block */
310         if (ind->bh)
311                 return ind->bh->b_blocknr;
312
313         /*
314          * It is going to be refered from inode itself? OK, just put it into
315          * the same cylinder group then.
316          */
317         return (inode->u.ext2_i.i_block_group * 
318                 EXT2_BLOCKS_PER_GROUP(inode->i_sb)) +
319                le32_to_cpu(inode->i_sb->u.ext2_sb.s_es->s_first_data_block);
320 }
321
322 /**
323  *      ext2_find_goal - find a prefered place for allocation.
324  *      @inode: owner
325  *      @block:  block we want
326  *      @chain:  chain of indirect blocks
327  *      @partial: pointer to the last triple within a chain
328  *      @goal:  place to store the result.
329  *
330  *      Normally this function find the prefered place for block allocation,
331  *      stores it in *@goal and returns zero. If the branch had been changed
332  *      under us we return -EAGAIN.
333  */
334
335 static inline int ext2_find_goal(struct inode *inode,
336                                  long block,
337                                  Indirect chain[4],
338                                  Indirect *partial,
339                                  unsigned long *goal)
340 {
341         /* Writer: ->i_next_alloc* */
342         if (block == inode->u.ext2_i.i_next_alloc_block + 1) {
343                 inode->u.ext2_i.i_next_alloc_block++;
344                 inode->u.ext2_i.i_next_alloc_goal++;
345         } 
346         /* Writer: end */
347         /* Reader: pointers, ->i_next_alloc* */
348         if (verify_chain(chain, partial)) {
349                 /*
350                  * try the heuristic for sequential allocation,
351                  * failing that at least try to get decent locality.
352                  */
353                 if (block == inode->u.ext2_i.i_next_alloc_block)
354                         *goal = inode->u.ext2_i.i_next_alloc_goal;
355                 if (!*goal)
356                         *goal = ext2_find_near(inode, partial);
357                 return 0;
358         }
359         /* Reader: end */
360         return -EAGAIN;
361 }
362
363 /**
364  *      ext2_alloc_branch - allocate and set up a chain of blocks.
365  *      @inode: owner
366  *      @num: depth of the chain (number of blocks to allocate)
367  *      @offsets: offsets (in the blocks) to store the pointers to next.
368  *      @branch: place to store the chain in.
369  *
370  *      This function allocates @num blocks, zeroes out all but the last one,
371  *      links them into chain and (if we are synchronous) writes them to disk.
372  *      In other words, it prepares a branch that can be spliced onto the
373  *      inode. It stores the information about that chain in the branch[], in
374  *      the same format as ext2_get_branch() would do. We are calling it after
375  *      we had read the existing part of chain and partial points to the last
376  *      triple of that (one with zero ->key). Upon the exit we have the same
377  *      picture as after the successful ext2_get_block(), excpet that in one
378  *      place chain is disconnected - *branch->p is still zero (we did not
379  *      set the last link), but branch->key contains the number that should
380  *      be placed into *branch->p to fill that gap.
381  *
382  *      If allocation fails we free all blocks we've allocated (and forget
383  *      their buffer_heads) and return the error value the from failed
384  *      ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
385  *      as described above and return 0.
386  */
387
388 static int ext2_alloc_branch(struct inode *inode,
389                              int num,
390                              unsigned long goal,
391                              int *offsets,
392                              Indirect *branch)
393 {
394         int blocksize = inode->i_sb->s_blocksize;
395         int n = 0;
396         int err;
397         int i;
398         int parent = ext2_alloc_block(inode, goal, &err);
399
400         branch[0].key = cpu_to_le32(parent);
401         if (parent) for (n = 1; n < num; n++) {
402                 struct buffer_head *bh;
403                 /* Allocate the next block */
404                 int nr = ext2_alloc_block(inode, parent, &err);
405                 if (!nr)
406                         break;
407                 branch[n].key = cpu_to_le32(nr);
408                 /*
409                  * Get buffer_head for parent block, zero it out and set 
410                  * the pointer to new one, then send parent to disk.
411                  */
412                 bh = sb_getblk(inode->i_sb, parent);
413                 lock_buffer(bh);
414                 memset(bh->b_data, 0, blocksize);
415                 branch[n].bh = bh;
416                 branch[n].p = (u32*) bh->b_data + offsets[n];
417                 *branch[n].p = branch[n].key;
418                 mark_buffer_uptodate(bh, 1);
419                 unlock_buffer(bh);
420                 mark_buffer_dirty_inode(bh, inode);
421                 /* We used to sync bh here if IS_SYNC(inode).
422                  * But for S_ISREG files we now rely upon generic_osync_inode()
423                  * and b_inode_buffers
424                  */
425                 if (S_ISDIR(inode->i_mode) && IS_SYNC(inode)) {
426                         ll_rw_block (WRITE, 1, &bh);
427                         wait_on_buffer (bh);
428                 }
429                 parent = nr;
430         }
431         if (n == num)
432                 return 0;
433
434         /* Allocation failed, free what we already allocated */
435         for (i = 1; i < n; i++)
436                 bforget(branch[i].bh);
437         for (i = 0; i < n; i++)
438                 ext2_free_blocks(inode, le32_to_cpu(branch[i].key), 1);
439         return err;
440 }
441
442 /**
443  *      ext2_splice_branch - splice the allocated branch onto inode.
444  *      @inode: owner
445  *      @block: (logical) number of block we are adding
446  *      @chain: chain of indirect blocks (with a missing link - see
447  *              ext2_alloc_branch)
448  *      @where: location of missing link
449  *      @num:   number of blocks we are adding
450  *
451  *      This function verifies that chain (up to the missing link) had not
452  *      changed, fills the missing link and does all housekeeping needed in
453  *      inode (->i_blocks, etc.). In case of success we end up with the full
454  *      chain to new block and return 0. Otherwise (== chain had been changed)
455  *      we free the new blocks (forgetting their buffer_heads, indeed) and
456  *      return -EAGAIN.
457  */
458
459 static inline int ext2_splice_branch(struct inode *inode,
460                                      long block,
461                                      Indirect chain[4],
462                                      Indirect *where,
463                                      int num)
464 {
465         int i;
466
467         /* Verify that place we are splicing to is still there and vacant */
468
469         /* Writer: pointers, ->i_next_alloc* */
470         if (!verify_chain(chain, where-1) || *where->p)
471                 /* Writer: end */
472                 goto changed;
473
474         /* That's it */
475
476         *where->p = where->key;
477         inode->u.ext2_i.i_next_alloc_block = block;
478         inode->u.ext2_i.i_next_alloc_goal = le32_to_cpu(where[num-1].key);
479
480         /* Writer: end */
481
482         /* We are done with atomic stuff, now do the rest of housekeeping */
483
484         inode->i_ctime = CURRENT_TIME;
485
486         /* had we spliced it onto indirect block? */
487         if (where->bh) {
488                 mark_buffer_dirty_inode(where->bh, inode);
489                 if (S_ISDIR(inode->i_mode) && IS_SYNC(inode)) {
490                         ll_rw_block(WRITE, 1, &where->bh);
491                         wait_on_buffer(where->bh);
492                 }
493         }
494
495         mark_inode_dirty(inode);
496         return 0;
497
498 changed:
499         for (i = 1; i < num; i++)
500                 bforget(where[i].bh);
501         for (i = 0; i < num; i++)
502                 ext2_free_blocks(inode, le32_to_cpu(where[i].key), 1);
503         return -EAGAIN;
504 }
505
506 /*
507  * Allocation strategy is simple: if we have to allocate something, we will
508  * have to go the whole way to leaf. So let's do it before attaching anything
509  * to tree, set linkage between the newborn blocks, write them if sync is
510  * required, recheck the path, free and repeat if check fails, otherwise
511  * set the last missing link (that will protect us from any truncate-generated
512  * removals - all blocks on the path are immune now) and possibly force the
513  * write on the parent block.
514  * That has a nice additional property: no special recovery from the failed
515  * allocations is needed - we simply release blocks and do not touch anything
516  * reachable from inode.
517  */
518
519 static int ext2_get_block(struct inode *inode, long iblock, struct buffer_head *bh_result, int create)
520 {
521         int err = -EIO;
522         int offsets[4];
523         Indirect chain[4];
524         Indirect *partial;
525         unsigned long goal;
526         int left;
527         int depth = ext2_block_to_path(inode, iblock, offsets);
528
529         if (depth == 0)
530                 goto out;
531
532         lock_kernel();
533 reread:
534         partial = ext2_get_branch(inode, depth, offsets, chain, &err);
535
536         /* Simplest case - block found, no allocation needed */
537         if (!partial) {
538 got_it:
539                 bh_result->b_dev = inode->i_dev;
540                 bh_result->b_blocknr = le32_to_cpu(chain[depth-1].key);
541                 bh_result->b_state |= (1UL << BH_Mapped);
542                 /* Clean up and exit */
543                 partial = chain+depth-1; /* the whole chain */
544                 goto cleanup;
545         }
546
547         /* Next simple case - plain lookup or failed read of indirect block */
548         if (!create || err == -EIO) {
549 cleanup:
550                 while (partial > chain) {
551                         brelse(partial->bh);
552                         partial--;
553                 }
554                 unlock_kernel();
555 out:
556                 return err;
557         }
558
559         /*
560          * Indirect block might be removed by truncate while we were
561          * reading it. Handling of that case (forget what we've got and
562          * reread) is taken out of the main path.
563          */
564         if (err == -EAGAIN)
565                 goto changed;
566
567         goal = 0;
568         if (ext2_find_goal(inode, iblock, chain, partial, &goal) < 0)
569                 goto changed;
570
571         left = (chain + depth) - partial;
572         err = ext2_alloc_branch(inode, left, goal,
573                                         offsets+(partial-chain), partial);
574         if (err)
575                 goto cleanup;
576
577         if (ext2_splice_branch(inode, iblock, chain, partial, left) < 0)
578                 goto changed;
579
580         bh_result->b_state |= (1UL << BH_New);
581         goto got_it;
582
583 changed:
584         while (partial > chain) {
585                 brelse(partial->bh);
586                 partial--;
587         }
588         goto reread;
589 }
590
591 static int ext2_writepage(struct page *page)
592 {
593         return block_write_full_page(page,ext2_get_block);
594 }
595 static int ext2_readpage(struct file *file, struct page *page)
596 {
597         return block_read_full_page(page,ext2_get_block);
598 }
599 static int ext2_prepare_write(struct file *file, struct page *page, unsigned from, unsigned to)
600 {
601         return block_prepare_write(page,from,to,ext2_get_block);
602 }
603 static int ext2_bmap(struct address_space *mapping, long block)
604 {
605         return generic_block_bmap(mapping,block,ext2_get_block);
606 }
607 static int ext2_direct_IO(int rw, struct inode * inode, struct kiobuf * iobuf, unsigned long blocknr, int blocksize)
608 {
609         return generic_direct_IO(rw, inode, iobuf, blocknr, blocksize, ext2_get_block);
610 }
611 struct address_space_operations ext2_aops = {
612         readpage: ext2_readpage,
613         writepage: ext2_writepage,
614         sync_page: block_sync_page,
615         prepare_write: ext2_prepare_write,
616         commit_write: generic_commit_write,
617         bmap: ext2_bmap,
618         direct_IO: ext2_direct_IO,
619 };
620
621 /*
622  * Probably it should be a library function... search for first non-zero word
623  * or memcmp with zero_page, whatever is better for particular architecture.
624  * Linus?
625  */
626 static inline int all_zeroes(u32 *p, u32 *q)
627 {
628         while (p < q)
629                 if (*p++)
630                         return 0;
631         return 1;
632 }
633
634 /**
635  *      ext2_find_shared - find the indirect blocks for partial truncation.
636  *      @inode:   inode in question
637  *      @depth:   depth of the affected branch
638  *      @offsets: offsets of pointers in that branch (see ext2_block_to_path)
639  *      @chain:   place to store the pointers to partial indirect blocks
640  *      @top:     place to the (detached) top of branch
641  *
642  *      This is a helper function used by ext2_truncate().
643  *
644  *      When we do truncate() we may have to clean the ends of several indirect
645  *      blocks but leave the blocks themselves alive. Block is partially
646  *      truncated if some data below the new i_size is refered from it (and
647  *      it is on the path to the first completely truncated data block, indeed).
648  *      We have to free the top of that path along with everything to the right
649  *      of the path. Since no allocation past the truncation point is possible
650  *      until ext2_truncate() finishes, we may safely do the latter, but top
651  *      of branch may require special attention - pageout below the truncation
652  *      point might try to populate it.
653  *
654  *      We atomically detach the top of branch from the tree, store the block
655  *      number of its root in *@top, pointers to buffer_heads of partially
656  *      truncated blocks - in @chain[].bh and pointers to their last elements
657  *      that should not be removed - in @chain[].p. Return value is the pointer
658  *      to last filled element of @chain.
659  *
660  *      The work left to caller to do the actual freeing of subtrees:
661  *              a) free the subtree starting from *@top
662  *              b) free the subtrees whose roots are stored in
663  *                      (@chain[i].p+1 .. end of @chain[i].bh->b_data)
664  *              c) free the subtrees growing from the inode past the @chain[0].p
665  *                      (no partially truncated stuff there).
666  */
667
668 static Indirect *ext2_find_shared(struct inode *inode,
669                                 int depth,
670                                 int offsets[4],
671                                 Indirect chain[4],
672                                 u32 *top)
673 {
674         Indirect *partial, *p;
675         int k, err;
676
677         *top = 0;
678         for (k = depth; k > 1 && !offsets[k-1]; k--)
679                 ;
680         partial = ext2_get_branch(inode, k, offsets, chain, &err);
681         /* Writer: pointers */
682         if (!partial)
683                 partial = chain + k-1;
684         /*
685          * If the branch acquired continuation since we've looked at it -
686          * fine, it should all survive and (new) top doesn't belong to us.
687          */
688         if (!partial->key && *partial->p)
689                 /* Writer: end */
690                 goto no_top;
691         for (p=partial; p>chain && all_zeroes((u32*)p->bh->b_data,p->p); p--)
692                 ;
693         /*
694          * OK, we've found the last block that must survive. The rest of our
695          * branch should be detached before unlocking. However, if that rest
696          * of branch is all ours and does not grow immediately from the inode
697          * it's easier to cheat and just decrement partial->p.
698          */
699         if (p == chain + k - 1 && p > chain) {
700                 p->p--;
701         } else {
702                 *top = *p->p;
703                 *p->p = 0;
704         }
705         /* Writer: end */
706
707         while(partial > p)
708         {
709                 brelse(partial->bh);
710                 partial--;
711         }
712 no_top:
713         return partial;
714 }
715
716 /**
717  *      ext2_free_data - free a list of data blocks
718  *      @inode: inode we are dealing with
719  *      @p:     array of block numbers
720  *      @q:     points immediately past the end of array
721  *
722  *      We are freeing all blocks refered from that array (numbers are
723  *      stored as little-endian 32-bit) and updating @inode->i_blocks
724  *      appropriately.
725  */
726 static inline void ext2_free_data(struct inode *inode, u32 *p, u32 *q)
727 {
728         unsigned long block_to_free = 0, count = 0;
729         unsigned long nr;
730
731         for ( ; p < q ; p++) {
732                 nr = le32_to_cpu(*p);
733                 if (nr) {
734                         *p = 0;
735                         /* accumulate blocks to free if they're contiguous */
736                         if (count == 0)
737                                 goto free_this;
738                         else if (block_to_free == nr - count)
739                                 count++;
740                         else {
741                                 mark_inode_dirty(inode);
742                                 ext2_free_blocks (inode, block_to_free, count);
743                         free_this:
744                                 block_to_free = nr;
745                                 count = 1;
746                         }
747                 }
748         }
749         if (count > 0) {
750                 mark_inode_dirty(inode);
751                 ext2_free_blocks (inode, block_to_free, count);
752         }
753 }
754
755 /**
756  *      ext2_free_branches - free an array of branches
757  *      @inode: inode we are dealing with
758  *      @p:     array of block numbers
759  *      @q:     pointer immediately past the end of array
760  *      @depth: depth of the branches to free
761  *
762  *      We are freeing all blocks refered from these branches (numbers are
763  *      stored as little-endian 32-bit) and updating @inode->i_blocks
764  *      appropriately.
765  */
766 static void ext2_free_branches(struct inode *inode, u32 *p, u32 *q, int depth)
767 {
768         struct buffer_head * bh;
769         unsigned long nr;
770
771         if (depth--) {
772                 int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
773                 for ( ; p < q ; p++) {
774                         nr = le32_to_cpu(*p);
775                         if (!nr)
776                                 continue;
777                         *p = 0;
778                         bh = sb_bread(inode->i_sb, nr);
779                         /*
780                          * A read failure? Report error and clear slot
781                          * (should be rare).
782                          */ 
783                         if (!bh) {
784                                 ext2_error(inode->i_sb, "ext2_free_branches",
785                                         "Read failure, inode=%ld, block=%ld",
786                                         inode->i_ino, nr);
787                                 continue;
788                         }
789                         ext2_free_branches(inode,
790                                            (u32*)bh->b_data,
791                                            (u32*)bh->b_data + addr_per_block,
792                                            depth);
793                         bforget(bh);
794                         ext2_free_blocks(inode, nr, 1);
795                         mark_inode_dirty(inode);
796                 }
797         } else
798                 ext2_free_data(inode, p, q);
799 }
800
801 void ext2_truncate (struct inode * inode)
802 {
803         u32 *i_data = inode->u.ext2_i.i_data;
804         int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
805         int offsets[4];
806         Indirect chain[4];
807         Indirect *partial;
808         int nr = 0;
809         int n;
810         long iblock;
811         unsigned blocksize;
812
813         if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
814             S_ISLNK(inode->i_mode)))
815                 return;
816         if (ext2_inode_is_fast_symlink(inode))
817                 return;
818         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
819                 return;
820
821         ext2_discard_prealloc(inode);
822
823         blocksize = inode->i_sb->s_blocksize;
824         iblock = (inode->i_size + blocksize-1)
825                                         >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
826
827         block_truncate_page(inode->i_mapping, inode->i_size, ext2_get_block);
828
829         n = ext2_block_to_path(inode, iblock, offsets);
830         if (n == 0)
831                 return;
832
833         if (n == 1) {
834                 ext2_free_data(inode, i_data+offsets[0],
835                                         i_data + EXT2_NDIR_BLOCKS);
836                 goto do_indirects;
837         }
838
839         partial = ext2_find_shared(inode, n, offsets, chain, &nr);
840         /* Kill the top of shared branch (already detached) */
841         if (nr) {
842                 if (partial == chain)
843                         mark_inode_dirty(inode);
844                 else
845                         mark_buffer_dirty_inode(partial->bh, inode);
846                 ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
847         }
848         /* Clear the ends of indirect blocks on the shared branch */
849         while (partial > chain) {
850                 ext2_free_branches(inode,
851                                    partial->p + 1,
852                                    (u32*)partial->bh->b_data + addr_per_block,
853                                    (chain+n-1) - partial);
854                 mark_buffer_dirty_inode(partial->bh, inode);
855                 brelse (partial->bh);
856                 partial--;
857         }
858 do_indirects:
859         /* Kill the remaining (whole) subtrees */
860         switch (offsets[0]) {
861                 default:
862                         nr = i_data[EXT2_IND_BLOCK];
863                         if (nr) {
864                                 i_data[EXT2_IND_BLOCK] = 0;
865                                 mark_inode_dirty(inode);
866                                 ext2_free_branches(inode, &nr, &nr+1, 1);
867                         }
868                 case EXT2_IND_BLOCK:
869                         nr = i_data[EXT2_DIND_BLOCK];
870                         if (nr) {
871                                 i_data[EXT2_DIND_BLOCK] = 0;
872                                 mark_inode_dirty(inode);
873                                 ext2_free_branches(inode, &nr, &nr+1, 2);
874                         }
875                 case EXT2_DIND_BLOCK:
876                         nr = i_data[EXT2_TIND_BLOCK];
877                         if (nr) {
878                                 i_data[EXT2_TIND_BLOCK] = 0;
879                                 mark_inode_dirty(inode);
880                                 ext2_free_branches(inode, &nr, &nr+1, 3);
881                         }
882                 case EXT2_TIND_BLOCK:
883                         ;
884         }
885         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
886         if (IS_SYNC(inode)) {
887                 fsync_inode_buffers(inode);
888                 ext2_sync_inode (inode);
889         } else {
890                 mark_inode_dirty(inode);
891         }
892 }
893
894 void ext2_set_inode_flags(struct inode *inode)
895 {
896         unsigned int flags = inode->u.ext2_i.i_flags;
897
898         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME);
899         if (flags & EXT2_SYNC_FL)
900                 inode->i_flags |= S_SYNC;
901         if (flags & EXT2_APPEND_FL)
902                 inode->i_flags |= S_APPEND;
903         if (flags & EXT2_IMMUTABLE_FL)
904                 inode->i_flags |= S_IMMUTABLE;
905         if (flags & EXT2_NOATIME_FL)
906                 inode->i_flags |= S_NOATIME;
907 }
908
909 void ext2_read_inode (struct inode * inode)
910 {
911         struct buffer_head * bh;
912         struct ext2_inode * raw_inode;
913         unsigned long block_group;
914         unsigned long group_desc;
915         unsigned long desc;
916         unsigned long block;
917         unsigned long offset;
918         struct ext2_group_desc * gdp;
919
920         if ((inode->i_ino != EXT2_ROOT_INO && inode->i_ino != EXT2_ACL_IDX_INO &&
921              inode->i_ino != EXT2_ACL_DATA_INO &&
922              inode->i_ino < EXT2_FIRST_INO(inode->i_sb)) ||
923             inode->i_ino > le32_to_cpu(inode->i_sb->u.ext2_sb.s_es->s_inodes_count)) {
924                 ext2_error (inode->i_sb, "ext2_read_inode",
925                             "bad inode number: %lu", inode->i_ino);
926                 goto bad_inode;
927         }
928         block_group = (inode->i_ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
929         if (block_group >= inode->i_sb->u.ext2_sb.s_groups_count) {
930                 ext2_error (inode->i_sb, "ext2_read_inode",
931                             "group >= groups count");
932                 goto bad_inode;
933         }
934         group_desc = block_group >> EXT2_DESC_PER_BLOCK_BITS(inode->i_sb);
935         desc = block_group & (EXT2_DESC_PER_BLOCK(inode->i_sb) - 1);
936         bh = inode->i_sb->u.ext2_sb.s_group_desc[group_desc];
937         if (!bh) {
938                 ext2_error (inode->i_sb, "ext2_read_inode",
939                             "Descriptor not loaded");
940                 goto bad_inode;
941         }
942
943         gdp = (struct ext2_group_desc *) bh->b_data;
944         /*
945          * Figure out the offset within the block group inode table
946          */
947         offset = ((inode->i_ino - 1) % EXT2_INODES_PER_GROUP(inode->i_sb)) *
948                 EXT2_INODE_SIZE(inode->i_sb);
949         block = le32_to_cpu(gdp[desc].bg_inode_table) +
950                 (offset >> EXT2_BLOCK_SIZE_BITS(inode->i_sb));
951         if (!(bh = sb_bread(inode->i_sb, block))) {
952                 ext2_error (inode->i_sb, "ext2_read_inode",
953                             "unable to read inode block - "
954                             "inode=%lu, block=%lu", inode->i_ino, block);
955                 goto bad_inode;
956         }
957         offset &= (EXT2_BLOCK_SIZE(inode->i_sb) - 1);
958         raw_inode = (struct ext2_inode *) (bh->b_data + offset);
959
960         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
961         inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
962         inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
963         if(!(test_opt (inode->i_sb, NO_UID32))) {
964                 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
965                 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
966         }
967         inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
968         inode->i_size = le32_to_cpu(raw_inode->i_size);
969         inode->i_atime = le32_to_cpu(raw_inode->i_atime);
970         inode->i_ctime = le32_to_cpu(raw_inode->i_ctime);
971         inode->i_mtime = le32_to_cpu(raw_inode->i_mtime);
972         inode->u.ext2_i.i_dtime = le32_to_cpu(raw_inode->i_dtime);
973         /* We now have enough fields to check if the inode was active or not.
974          * This is needed because nfsd might try to access dead inodes
975          * the test is that same one that e2fsck uses
976          * NeilBrown 1999oct15
977          */
978         if (inode->i_nlink == 0 && (inode->i_mode == 0 || inode->u.ext2_i.i_dtime)) {
979                 /* this inode is deleted */
980                 brelse (bh);
981                 goto bad_inode;
982         }
983         inode->i_blksize = PAGE_SIZE;   /* This is the optimal IO size (for stat), not the fs block size */
984         inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
985         inode->i_version = ++event;
986         inode->u.ext2_i.i_flags = le32_to_cpu(raw_inode->i_flags);
987         inode->u.ext2_i.i_faddr = le32_to_cpu(raw_inode->i_faddr);
988         inode->u.ext2_i.i_frag_no = raw_inode->i_frag;
989         inode->u.ext2_i.i_frag_size = raw_inode->i_fsize;
990         inode->u.ext2_i.i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
991         if (S_ISREG(inode->i_mode))
992                 inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
993         else
994                 inode->u.ext2_i.i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
995         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
996         inode->u.ext2_i.i_state = 0;
997         inode->u.ext2_i.i_prealloc_count = 0;
998         inode->u.ext2_i.i_block_group = block_group;
999
1000         /*
1001          * NOTE! The in-memory inode i_data array is in little-endian order
1002          * even on big-endian machines: we do NOT byteswap the block numbers!
1003          */
1004         for (block = 0; block < EXT2_N_BLOCKS; block++)
1005                 inode->u.ext2_i.i_data[block] = raw_inode->i_block[block];
1006
1007         if (inode->i_ino == EXT2_ACL_IDX_INO ||
1008             inode->i_ino == EXT2_ACL_DATA_INO)
1009                 /* Nothing to do */ ;
1010         else if (S_ISREG(inode->i_mode)) {
1011                 inode->i_op = &ext2_file_inode_operations;
1012                 inode->i_fop = &ext2_file_operations;
1013                 inode->i_mapping->a_ops = &ext2_aops;
1014         } else if (S_ISDIR(inode->i_mode)) {
1015                 inode->i_op = &ext2_dir_inode_operations;
1016                 inode->i_fop = &ext2_dir_operations;
1017                 inode->i_mapping->a_ops = &ext2_aops;
1018         } else if (S_ISLNK(inode->i_mode)) {
1019                 if (ext2_inode_is_fast_symlink(inode))
1020                         inode->i_op = &ext2_fast_symlink_inode_operations;
1021                 else {
1022                         inode->i_op = &page_symlink_inode_operations;
1023                         inode->i_mapping->a_ops = &ext2_aops;
1024                 }
1025         } else 
1026                 init_special_inode(inode, inode->i_mode,
1027                                    le32_to_cpu(raw_inode->i_block[0]));
1028         brelse (bh);
1029         inode->i_attr_flags = 0;
1030         ext2_set_inode_flags(inode);
1031         return;
1032         
1033 bad_inode:
1034         make_bad_inode(inode);
1035         return;
1036 }
1037
1038 static int ext2_update_inode(struct inode * inode, int do_sync)
1039 {
1040         struct buffer_head * bh;
1041         struct ext2_inode * raw_inode;
1042         unsigned long block_group;
1043         unsigned long group_desc;
1044         unsigned long desc;
1045         unsigned long block;
1046         unsigned long offset;
1047         int err = 0;
1048         struct ext2_group_desc * gdp;
1049
1050         if ((inode->i_ino != EXT2_ROOT_INO &&
1051              inode->i_ino < EXT2_FIRST_INO(inode->i_sb)) ||
1052             inode->i_ino > le32_to_cpu(inode->i_sb->u.ext2_sb.s_es->s_inodes_count)) {
1053                 ext2_error (inode->i_sb, "ext2_write_inode",
1054                             "bad inode number: %lu", inode->i_ino);
1055                 return -EIO;
1056         }
1057         block_group = (inode->i_ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
1058         if (block_group >= inode->i_sb->u.ext2_sb.s_groups_count) {
1059                 ext2_error (inode->i_sb, "ext2_write_inode",
1060                             "group >= groups count");
1061                 return -EIO;
1062         }
1063         group_desc = block_group >> EXT2_DESC_PER_BLOCK_BITS(inode->i_sb);
1064         desc = block_group & (EXT2_DESC_PER_BLOCK(inode->i_sb) - 1);
1065         bh = inode->i_sb->u.ext2_sb.s_group_desc[group_desc];
1066         if (!bh) {
1067                 ext2_error (inode->i_sb, "ext2_write_inode",
1068                             "Descriptor not loaded");
1069                 return -EIO;
1070         }
1071         gdp = (struct ext2_group_desc *) bh->b_data;
1072         /*
1073          * Figure out the offset within the block group inode table
1074          */
1075         offset = ((inode->i_ino - 1) % EXT2_INODES_PER_GROUP(inode->i_sb)) *
1076                 EXT2_INODE_SIZE(inode->i_sb);
1077         block = le32_to_cpu(gdp[desc].bg_inode_table) +
1078                 (offset >> EXT2_BLOCK_SIZE_BITS(inode->i_sb));
1079         if (!(bh = sb_bread(inode->i_sb, block))) {
1080                 ext2_error (inode->i_sb, "ext2_write_inode",
1081                             "unable to read inode block - "
1082                             "inode=%lu, block=%lu", inode->i_ino, block);
1083                 return -EIO;
1084         }
1085         offset &= EXT2_BLOCK_SIZE(inode->i_sb) - 1;
1086         raw_inode = (struct ext2_inode *) (bh->b_data + offset);
1087
1088         /* For fields not tracked in the in-memory inode,
1089          * initialise them to zero for new inodes. */
1090         if (inode->u.ext2_i.i_state & EXT2_STATE_NEW)
1091                 memset(raw_inode, 0, EXT2_SB(inode->i_sb)->s_inode_size);
1092
1093         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
1094         if(!(test_opt(inode->i_sb, NO_UID32))) {
1095                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
1096                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
1097 /*
1098  * Fix up interoperability with old kernels. Otherwise, old inodes get
1099  * re-used with the upper 16 bits of the uid/gid intact
1100  */
1101                 if(!inode->u.ext2_i.i_dtime) {
1102                         raw_inode->i_uid_high = cpu_to_le16(high_16_bits(inode->i_uid));
1103                         raw_inode->i_gid_high = cpu_to_le16(high_16_bits(inode->i_gid));
1104                 } else {
1105                         raw_inode->i_uid_high = 0;
1106                         raw_inode->i_gid_high = 0;
1107                 }
1108         } else {
1109                 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(inode->i_uid));
1110                 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(inode->i_gid));
1111                 raw_inode->i_uid_high = 0;
1112                 raw_inode->i_gid_high = 0;
1113         }
1114         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
1115         raw_inode->i_size = cpu_to_le32(inode->i_size);
1116         raw_inode->i_atime = cpu_to_le32(inode->i_atime);
1117         raw_inode->i_ctime = cpu_to_le32(inode->i_ctime);
1118         raw_inode->i_mtime = cpu_to_le32(inode->i_mtime);
1119         raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
1120         raw_inode->i_dtime = cpu_to_le32(inode->u.ext2_i.i_dtime);
1121         raw_inode->i_flags = cpu_to_le32(inode->u.ext2_i.i_flags);
1122         raw_inode->i_faddr = cpu_to_le32(inode->u.ext2_i.i_faddr);
1123         raw_inode->i_frag = inode->u.ext2_i.i_frag_no;
1124         raw_inode->i_fsize = inode->u.ext2_i.i_frag_size;
1125         raw_inode->i_file_acl = cpu_to_le32(inode->u.ext2_i.i_file_acl);
1126         if (!S_ISREG(inode->i_mode))
1127                 raw_inode->i_dir_acl = cpu_to_le32(inode->u.ext2_i.i_dir_acl);
1128         else {
1129                 raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
1130                 if (inode->i_size > 0x7fffffffULL) {
1131                         struct super_block *sb = inode->i_sb;
1132                         if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
1133                                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
1134                             EXT2_SB(sb)->s_es->s_rev_level ==
1135                                         cpu_to_le32(EXT2_GOOD_OLD_REV)) {
1136                                /* If this is the first large file
1137                                 * created, add a flag to the superblock.
1138                                 */
1139                                 lock_kernel();
1140                                 ext2_update_dynamic_rev(sb);
1141                                 EXT2_SET_RO_COMPAT_FEATURE(sb,
1142                                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
1143                                 unlock_kernel();
1144                                 ext2_write_super(sb);
1145                         }
1146                 }
1147         }
1148         
1149         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
1150         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
1151                 raw_inode->i_block[0] = cpu_to_le32(kdev_t_to_nr(inode->i_rdev));
1152         else for (block = 0; block < EXT2_N_BLOCKS; block++)
1153                 raw_inode->i_block[block] = inode->u.ext2_i.i_data[block];
1154         mark_buffer_dirty(bh);
1155         if (do_sync) {
1156                 ll_rw_block (WRITE, 1, &bh);
1157                 wait_on_buffer (bh);
1158                 if (buffer_req(bh) && !buffer_uptodate(bh)) {
1159                         printk ("IO error syncing ext2 inode ["
1160                                 "%s:%08lx]\n",
1161                                 bdevname(inode->i_dev), inode->i_ino);
1162                         err = -EIO;
1163                 }
1164         }
1165         inode->u.ext2_i.i_state &= ~EXT2_STATE_NEW;
1166         brelse (bh);
1167         return err;
1168 }
1169
1170 void ext2_write_inode (struct inode * inode, int wait)
1171 {
1172         lock_kernel();
1173         ext2_update_inode (inode, wait);
1174         unlock_kernel();
1175 }
1176
1177 int ext2_sync_inode (struct inode *inode)
1178 {
1179         return ext2_update_inode (inode, 1);
1180 }