Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/sparc-2.6
[linux-2.6.git] / fs / ext2 / 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/smp_lock.h>
26 #include <linux/time.h>
27 #include <linux/highuid.h>
28 #include <linux/pagemap.h>
29 #include <linux/quotaops.h>
30 #include <linux/module.h>
31 #include <linux/writeback.h>
32 #include <linux/buffer_head.h>
33 #include <linux/mpage.h>
34 #include <linux/fiemap.h>
35 #include <linux/namei.h>
36 #include "ext2.h"
37 #include "acl.h"
38 #include "xip.h"
39
40 MODULE_AUTHOR("Remy Card and others");
41 MODULE_DESCRIPTION("Second Extended Filesystem");
42 MODULE_LICENSE("GPL");
43
44 static int __ext2_write_inode(struct inode *inode, int do_sync);
45
46 /*
47  * Test whether an inode is a fast symlink.
48  */
49 static inline int ext2_inode_is_fast_symlink(struct inode *inode)
50 {
51         int ea_blocks = EXT2_I(inode)->i_file_acl ?
52                 (inode->i_sb->s_blocksize >> 9) : 0;
53
54         return (S_ISLNK(inode->i_mode) &&
55                 inode->i_blocks - ea_blocks == 0);
56 }
57
58 /*
59  * Called at the last iput() if i_nlink is zero.
60  */
61 void ext2_delete_inode (struct inode * inode)
62 {
63         if (!is_bad_inode(inode))
64                 dquot_initialize(inode);
65         truncate_inode_pages(&inode->i_data, 0);
66
67         if (is_bad_inode(inode))
68                 goto no_delete;
69         EXT2_I(inode)->i_dtime  = get_seconds();
70         mark_inode_dirty(inode);
71         __ext2_write_inode(inode, inode_needs_sync(inode));
72
73         inode->i_size = 0;
74         if (inode->i_blocks)
75                 ext2_truncate (inode);
76         ext2_free_inode (inode);
77
78         return;
79 no_delete:
80         clear_inode(inode);     /* We must guarantee clearing of inode... */
81 }
82
83 typedef struct {
84         __le32  *p;
85         __le32  key;
86         struct buffer_head *bh;
87 } Indirect;
88
89 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
90 {
91         p->key = *(p->p = v);
92         p->bh = bh;
93 }
94
95 static inline int verify_chain(Indirect *from, Indirect *to)
96 {
97         while (from <= to && from->key == *from->p)
98                 from++;
99         return (from > to);
100 }
101
102 /**
103  *      ext2_block_to_path - parse the block number into array of offsets
104  *      @inode: inode in question (we are only interested in its superblock)
105  *      @i_block: block number to be parsed
106  *      @offsets: array to store the offsets in
107  *      @boundary: set this non-zero if the referred-to block is likely to be
108  *             followed (on disk) by an indirect block.
109  *      To store the locations of file's data ext2 uses a data structure common
110  *      for UNIX filesystems - tree of pointers anchored in the inode, with
111  *      data blocks at leaves and indirect blocks in intermediate nodes.
112  *      This function translates the block number into path in that tree -
113  *      return value is the path length and @offsets[n] is the offset of
114  *      pointer to (n+1)th node in the nth one. If @block is out of range
115  *      (negative or too large) warning is printed and zero returned.
116  *
117  *      Note: function doesn't find node addresses, so no IO is needed. All
118  *      we need to know is the capacity of indirect blocks (taken from the
119  *      inode->i_sb).
120  */
121
122 /*
123  * Portability note: the last comparison (check that we fit into triple
124  * indirect block) is spelled differently, because otherwise on an
125  * architecture with 32-bit longs and 8Kb pages we might get into trouble
126  * if our filesystem had 8Kb blocks. We might use long long, but that would
127  * kill us on x86. Oh, well, at least the sign propagation does not matter -
128  * i_block would have to be negative in the very beginning, so we would not
129  * get there at all.
130  */
131
132 static int ext2_block_to_path(struct inode *inode,
133                         long i_block, int offsets[4], int *boundary)
134 {
135         int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
136         int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
137         const long direct_blocks = EXT2_NDIR_BLOCKS,
138                 indirect_blocks = ptrs,
139                 double_blocks = (1 << (ptrs_bits * 2));
140         int n = 0;
141         int final = 0;
142
143         if (i_block < 0) {
144                 ext2_msg(inode->i_sb, KERN_WARNING,
145                         "warning: %s: block < 0", __func__);
146         } else if (i_block < direct_blocks) {
147                 offsets[n++] = i_block;
148                 final = direct_blocks;
149         } else if ( (i_block -= direct_blocks) < indirect_blocks) {
150                 offsets[n++] = EXT2_IND_BLOCK;
151                 offsets[n++] = i_block;
152                 final = ptrs;
153         } else if ((i_block -= indirect_blocks) < double_blocks) {
154                 offsets[n++] = EXT2_DIND_BLOCK;
155                 offsets[n++] = i_block >> ptrs_bits;
156                 offsets[n++] = i_block & (ptrs - 1);
157                 final = ptrs;
158         } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
159                 offsets[n++] = EXT2_TIND_BLOCK;
160                 offsets[n++] = i_block >> (ptrs_bits * 2);
161                 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
162                 offsets[n++] = i_block & (ptrs - 1);
163                 final = ptrs;
164         } else {
165                 ext2_msg(inode->i_sb, KERN_WARNING,
166                         "warning: %s: block is too big", __func__);
167         }
168         if (boundary)
169                 *boundary = final - 1 - (i_block & (ptrs - 1));
170
171         return n;
172 }
173
174 /**
175  *      ext2_get_branch - read the chain of indirect blocks leading to data
176  *      @inode: inode in question
177  *      @depth: depth of the chain (1 - direct pointer, etc.)
178  *      @offsets: offsets of pointers in inode/indirect blocks
179  *      @chain: place to store the result
180  *      @err: here we store the error value
181  *
182  *      Function fills the array of triples <key, p, bh> and returns %NULL
183  *      if everything went OK or the pointer to the last filled triple
184  *      (incomplete one) otherwise. Upon the return chain[i].key contains
185  *      the number of (i+1)-th block in the chain (as it is stored in memory,
186  *      i.e. little-endian 32-bit), chain[i].p contains the address of that
187  *      number (it points into struct inode for i==0 and into the bh->b_data
188  *      for i>0) and chain[i].bh points to the buffer_head of i-th indirect
189  *      block for i>0 and NULL for i==0. In other words, it holds the block
190  *      numbers of the chain, addresses they were taken from (and where we can
191  *      verify that chain did not change) and buffer_heads hosting these
192  *      numbers.
193  *
194  *      Function stops when it stumbles upon zero pointer (absent block)
195  *              (pointer to last triple returned, *@err == 0)
196  *      or when it gets an IO error reading an indirect block
197  *              (ditto, *@err == -EIO)
198  *      or when it notices that chain had been changed while it was reading
199  *              (ditto, *@err == -EAGAIN)
200  *      or when it reads all @depth-1 indirect blocks successfully and finds
201  *      the whole chain, all way to the data (returns %NULL, *err == 0).
202  */
203 static Indirect *ext2_get_branch(struct inode *inode,
204                                  int depth,
205                                  int *offsets,
206                                  Indirect chain[4],
207                                  int *err)
208 {
209         struct super_block *sb = inode->i_sb;
210         Indirect *p = chain;
211         struct buffer_head *bh;
212
213         *err = 0;
214         /* i_data is not going away, no lock needed */
215         add_chain (chain, NULL, EXT2_I(inode)->i_data + *offsets);
216         if (!p->key)
217                 goto no_block;
218         while (--depth) {
219                 bh = sb_bread(sb, le32_to_cpu(p->key));
220                 if (!bh)
221                         goto failure;
222                 read_lock(&EXT2_I(inode)->i_meta_lock);
223                 if (!verify_chain(chain, p))
224                         goto changed;
225                 add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
226                 read_unlock(&EXT2_I(inode)->i_meta_lock);
227                 if (!p->key)
228                         goto no_block;
229         }
230         return NULL;
231
232 changed:
233         read_unlock(&EXT2_I(inode)->i_meta_lock);
234         brelse(bh);
235         *err = -EAGAIN;
236         goto no_block;
237 failure:
238         *err = -EIO;
239 no_block:
240         return p;
241 }
242
243 /**
244  *      ext2_find_near - find a place for allocation with sufficient locality
245  *      @inode: owner
246  *      @ind: descriptor of indirect block.
247  *
248  *      This function returns the preferred place for block allocation.
249  *      It is used when heuristic for sequential allocation fails.
250  *      Rules are:
251  *        + if there is a block to the left of our position - allocate near it.
252  *        + if pointer will live in indirect block - allocate near that block.
253  *        + if pointer will live in inode - allocate in the same cylinder group.
254  *
255  * In the latter case we colour the starting block by the callers PID to
256  * prevent it from clashing with concurrent allocations for a different inode
257  * in the same block group.   The PID is used here so that functionally related
258  * files will be close-by on-disk.
259  *
260  *      Caller must make sure that @ind is valid and will stay that way.
261  */
262
263 static ext2_fsblk_t ext2_find_near(struct inode *inode, Indirect *ind)
264 {
265         struct ext2_inode_info *ei = EXT2_I(inode);
266         __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
267         __le32 *p;
268         ext2_fsblk_t bg_start;
269         ext2_fsblk_t colour;
270
271         /* Try to find previous block */
272         for (p = ind->p - 1; p >= start; p--)
273                 if (*p)
274                         return le32_to_cpu(*p);
275
276         /* No such thing, so let's try location of indirect block */
277         if (ind->bh)
278                 return ind->bh->b_blocknr;
279
280         /*
281          * It is going to be refered from inode itself? OK, just put it into
282          * the same cylinder group then.
283          */
284         bg_start = ext2_group_first_block_no(inode->i_sb, ei->i_block_group);
285         colour = (current->pid % 16) *
286                         (EXT2_BLOCKS_PER_GROUP(inode->i_sb) / 16);
287         return bg_start + colour;
288 }
289
290 /**
291  *      ext2_find_goal - find a preferred place for allocation.
292  *      @inode: owner
293  *      @block:  block we want
294  *      @partial: pointer to the last triple within a chain
295  *
296  *      Returns preferred place for a block (the goal).
297  */
298
299 static inline ext2_fsblk_t ext2_find_goal(struct inode *inode, long block,
300                                           Indirect *partial)
301 {
302         struct ext2_block_alloc_info *block_i;
303
304         block_i = EXT2_I(inode)->i_block_alloc_info;
305
306         /*
307          * try the heuristic for sequential allocation,
308          * failing that at least try to get decent locality.
309          */
310         if (block_i && (block == block_i->last_alloc_logical_block + 1)
311                 && (block_i->last_alloc_physical_block != 0)) {
312                 return block_i->last_alloc_physical_block + 1;
313         }
314
315         return ext2_find_near(inode, partial);
316 }
317
318 /**
319  *      ext2_blks_to_allocate: Look up the block map and count the number
320  *      of direct blocks need to be allocated for the given branch.
321  *
322  *      @branch: chain of indirect blocks
323  *      @k: number of blocks need for indirect blocks
324  *      @blks: number of data blocks to be mapped.
325  *      @blocks_to_boundary:  the offset in the indirect block
326  *
327  *      return the total number of blocks to be allocate, including the
328  *      direct and indirect blocks.
329  */
330 static int
331 ext2_blks_to_allocate(Indirect * branch, int k, unsigned long blks,
332                 int blocks_to_boundary)
333 {
334         unsigned long count = 0;
335
336         /*
337          * Simple case, [t,d]Indirect block(s) has not allocated yet
338          * then it's clear blocks on that path have not allocated
339          */
340         if (k > 0) {
341                 /* right now don't hanel cross boundary allocation */
342                 if (blks < blocks_to_boundary + 1)
343                         count += blks;
344                 else
345                         count += blocks_to_boundary + 1;
346                 return count;
347         }
348
349         count++;
350         while (count < blks && count <= blocks_to_boundary
351                 && le32_to_cpu(*(branch[0].p + count)) == 0) {
352                 count++;
353         }
354         return count;
355 }
356
357 /**
358  *      ext2_alloc_blocks: multiple allocate blocks needed for a branch
359  *      @indirect_blks: the number of blocks need to allocate for indirect
360  *                      blocks
361  *
362  *      @new_blocks: on return it will store the new block numbers for
363  *      the indirect blocks(if needed) and the first direct block,
364  *      @blks:  on return it will store the total number of allocated
365  *              direct blocks
366  */
367 static int ext2_alloc_blocks(struct inode *inode,
368                         ext2_fsblk_t goal, int indirect_blks, int blks,
369                         ext2_fsblk_t new_blocks[4], int *err)
370 {
371         int target, i;
372         unsigned long count = 0;
373         int index = 0;
374         ext2_fsblk_t current_block = 0;
375         int ret = 0;
376
377         /*
378          * Here we try to allocate the requested multiple blocks at once,
379          * on a best-effort basis.
380          * To build a branch, we should allocate blocks for
381          * the indirect blocks(if not allocated yet), and at least
382          * the first direct block of this branch.  That's the
383          * minimum number of blocks need to allocate(required)
384          */
385         target = blks + indirect_blks;
386
387         while (1) {
388                 count = target;
389                 /* allocating blocks for indirect blocks and direct blocks */
390                 current_block = ext2_new_blocks(inode,goal,&count,err);
391                 if (*err)
392                         goto failed_out;
393
394                 target -= count;
395                 /* allocate blocks for indirect blocks */
396                 while (index < indirect_blks && count) {
397                         new_blocks[index++] = current_block++;
398                         count--;
399                 }
400
401                 if (count > 0)
402                         break;
403         }
404
405         /* save the new block number for the first direct block */
406         new_blocks[index] = current_block;
407
408         /* total number of blocks allocated for direct blocks */
409         ret = count;
410         *err = 0;
411         return ret;
412 failed_out:
413         for (i = 0; i <index; i++)
414                 ext2_free_blocks(inode, new_blocks[i], 1);
415         return ret;
416 }
417
418 /**
419  *      ext2_alloc_branch - allocate and set up a chain of blocks.
420  *      @inode: owner
421  *      @num: depth of the chain (number of blocks to allocate)
422  *      @offsets: offsets (in the blocks) to store the pointers to next.
423  *      @branch: place to store the chain in.
424  *
425  *      This function allocates @num blocks, zeroes out all but the last one,
426  *      links them into chain and (if we are synchronous) writes them to disk.
427  *      In other words, it prepares a branch that can be spliced onto the
428  *      inode. It stores the information about that chain in the branch[], in
429  *      the same format as ext2_get_branch() would do. We are calling it after
430  *      we had read the existing part of chain and partial points to the last
431  *      triple of that (one with zero ->key). Upon the exit we have the same
432  *      picture as after the successful ext2_get_block(), excpet that in one
433  *      place chain is disconnected - *branch->p is still zero (we did not
434  *      set the last link), but branch->key contains the number that should
435  *      be placed into *branch->p to fill that gap.
436  *
437  *      If allocation fails we free all blocks we've allocated (and forget
438  *      their buffer_heads) and return the error value the from failed
439  *      ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
440  *      as described above and return 0.
441  */
442
443 static int ext2_alloc_branch(struct inode *inode,
444                         int indirect_blks, int *blks, ext2_fsblk_t goal,
445                         int *offsets, Indirect *branch)
446 {
447         int blocksize = inode->i_sb->s_blocksize;
448         int i, n = 0;
449         int err = 0;
450         struct buffer_head *bh;
451         int num;
452         ext2_fsblk_t new_blocks[4];
453         ext2_fsblk_t current_block;
454
455         num = ext2_alloc_blocks(inode, goal, indirect_blks,
456                                 *blks, new_blocks, &err);
457         if (err)
458                 return err;
459
460         branch[0].key = cpu_to_le32(new_blocks[0]);
461         /*
462          * metadata blocks and data blocks are allocated.
463          */
464         for (n = 1; n <= indirect_blks;  n++) {
465                 /*
466                  * Get buffer_head for parent block, zero it out
467                  * and set the pointer to new one, then send
468                  * parent to disk.
469                  */
470                 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
471                 branch[n].bh = bh;
472                 lock_buffer(bh);
473                 memset(bh->b_data, 0, blocksize);
474                 branch[n].p = (__le32 *) bh->b_data + offsets[n];
475                 branch[n].key = cpu_to_le32(new_blocks[n]);
476                 *branch[n].p = branch[n].key;
477                 if ( n == indirect_blks) {
478                         current_block = new_blocks[n];
479                         /*
480                          * End of chain, update the last new metablock of
481                          * the chain to point to the new allocated
482                          * data blocks numbers
483                          */
484                         for (i=1; i < num; i++)
485                                 *(branch[n].p + i) = cpu_to_le32(++current_block);
486                 }
487                 set_buffer_uptodate(bh);
488                 unlock_buffer(bh);
489                 mark_buffer_dirty_inode(bh, inode);
490                 /* We used to sync bh here if IS_SYNC(inode).
491                  * But we now rely upon generic_write_sync()
492                  * and b_inode_buffers.  But not for directories.
493                  */
494                 if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
495                         sync_dirty_buffer(bh);
496         }
497         *blks = num;
498         return err;
499 }
500
501 /**
502  * ext2_splice_branch - splice the allocated branch onto inode.
503  * @inode: owner
504  * @block: (logical) number of block we are adding
505  * @where: location of missing link
506  * @num:   number of indirect blocks we are adding
507  * @blks:  number of direct blocks we are adding
508  *
509  * This function fills the missing link and does all housekeeping needed in
510  * inode (->i_blocks, etc.). In case of success we end up with the full
511  * chain to new block and return 0.
512  */
513 static void ext2_splice_branch(struct inode *inode,
514                         long block, Indirect *where, int num, int blks)
515 {
516         int i;
517         struct ext2_block_alloc_info *block_i;
518         ext2_fsblk_t current_block;
519
520         block_i = EXT2_I(inode)->i_block_alloc_info;
521
522         /* XXX LOCKING probably should have i_meta_lock ?*/
523         /* That's it */
524
525         *where->p = where->key;
526
527         /*
528          * Update the host buffer_head or inode to point to more just allocated
529          * direct blocks blocks
530          */
531         if (num == 0 && blks > 1) {
532                 current_block = le32_to_cpu(where->key) + 1;
533                 for (i = 1; i < blks; i++)
534                         *(where->p + i ) = cpu_to_le32(current_block++);
535         }
536
537         /*
538          * update the most recently allocated logical & physical block
539          * in i_block_alloc_info, to assist find the proper goal block for next
540          * allocation
541          */
542         if (block_i) {
543                 block_i->last_alloc_logical_block = block + blks - 1;
544                 block_i->last_alloc_physical_block =
545                                 le32_to_cpu(where[num].key) + blks - 1;
546         }
547
548         /* We are done with atomic stuff, now do the rest of housekeeping */
549
550         /* had we spliced it onto indirect block? */
551         if (where->bh)
552                 mark_buffer_dirty_inode(where->bh, inode);
553
554         inode->i_ctime = CURRENT_TIME_SEC;
555         mark_inode_dirty(inode);
556 }
557
558 /*
559  * Allocation strategy is simple: if we have to allocate something, we will
560  * have to go the whole way to leaf. So let's do it before attaching anything
561  * to tree, set linkage between the newborn blocks, write them if sync is
562  * required, recheck the path, free and repeat if check fails, otherwise
563  * set the last missing link (that will protect us from any truncate-generated
564  * removals - all blocks on the path are immune now) and possibly force the
565  * write on the parent block.
566  * That has a nice additional property: no special recovery from the failed
567  * allocations is needed - we simply release blocks and do not touch anything
568  * reachable from inode.
569  *
570  * `handle' can be NULL if create == 0.
571  *
572  * return > 0, # of blocks mapped or allocated.
573  * return = 0, if plain lookup failed.
574  * return < 0, error case.
575  */
576 static int ext2_get_blocks(struct inode *inode,
577                            sector_t iblock, unsigned long maxblocks,
578                            struct buffer_head *bh_result,
579                            int create)
580 {
581         int err = -EIO;
582         int offsets[4];
583         Indirect chain[4];
584         Indirect *partial;
585         ext2_fsblk_t goal;
586         int indirect_blks;
587         int blocks_to_boundary = 0;
588         int depth;
589         struct ext2_inode_info *ei = EXT2_I(inode);
590         int count = 0;
591         ext2_fsblk_t first_block = 0;
592
593         depth = ext2_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
594
595         if (depth == 0)
596                 return (err);
597
598         partial = ext2_get_branch(inode, depth, offsets, chain, &err);
599         /* Simplest case - block found, no allocation needed */
600         if (!partial) {
601                 first_block = le32_to_cpu(chain[depth - 1].key);
602                 clear_buffer_new(bh_result); /* What's this do? */
603                 count++;
604                 /*map more blocks*/
605                 while (count < maxblocks && count <= blocks_to_boundary) {
606                         ext2_fsblk_t blk;
607
608                         if (!verify_chain(chain, chain + depth - 1)) {
609                                 /*
610                                  * Indirect block might be removed by
611                                  * truncate while we were reading it.
612                                  * Handling of that case: forget what we've
613                                  * got now, go to reread.
614                                  */
615                                 err = -EAGAIN;
616                                 count = 0;
617                                 break;
618                         }
619                         blk = le32_to_cpu(*(chain[depth-1].p + count));
620                         if (blk == first_block + count)
621                                 count++;
622                         else
623                                 break;
624                 }
625                 if (err != -EAGAIN)
626                         goto got_it;
627         }
628
629         /* Next simple case - plain lookup or failed read of indirect block */
630         if (!create || err == -EIO)
631                 goto cleanup;
632
633         mutex_lock(&ei->truncate_mutex);
634         /*
635          * If the indirect block is missing while we are reading
636          * the chain(ext3_get_branch() returns -EAGAIN err), or
637          * if the chain has been changed after we grab the semaphore,
638          * (either because another process truncated this branch, or
639          * another get_block allocated this branch) re-grab the chain to see if
640          * the request block has been allocated or not.
641          *
642          * Since we already block the truncate/other get_block
643          * at this point, we will have the current copy of the chain when we
644          * splice the branch into the tree.
645          */
646         if (err == -EAGAIN || !verify_chain(chain, partial)) {
647                 while (partial > chain) {
648                         brelse(partial->bh);
649                         partial--;
650                 }
651                 partial = ext2_get_branch(inode, depth, offsets, chain, &err);
652                 if (!partial) {
653                         count++;
654                         mutex_unlock(&ei->truncate_mutex);
655                         if (err)
656                                 goto cleanup;
657                         clear_buffer_new(bh_result);
658                         goto got_it;
659                 }
660         }
661
662         /*
663          * Okay, we need to do block allocation.  Lazily initialize the block
664          * allocation info here if necessary
665         */
666         if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
667                 ext2_init_block_alloc_info(inode);
668
669         goal = ext2_find_goal(inode, iblock, partial);
670
671         /* the number of blocks need to allocate for [d,t]indirect blocks */
672         indirect_blks = (chain + depth) - partial - 1;
673         /*
674          * Next look up the indirect map to count the totoal number of
675          * direct blocks to allocate for this branch.
676          */
677         count = ext2_blks_to_allocate(partial, indirect_blks,
678                                         maxblocks, blocks_to_boundary);
679         /*
680          * XXX ???? Block out ext2_truncate while we alter the tree
681          */
682         err = ext2_alloc_branch(inode, indirect_blks, &count, goal,
683                                 offsets + (partial - chain), partial);
684
685         if (err) {
686                 mutex_unlock(&ei->truncate_mutex);
687                 goto cleanup;
688         }
689
690         if (ext2_use_xip(inode->i_sb)) {
691                 /*
692                  * we need to clear the block
693                  */
694                 err = ext2_clear_xip_target (inode,
695                         le32_to_cpu(chain[depth-1].key));
696                 if (err) {
697                         mutex_unlock(&ei->truncate_mutex);
698                         goto cleanup;
699                 }
700         }
701
702         ext2_splice_branch(inode, iblock, partial, indirect_blks, count);
703         mutex_unlock(&ei->truncate_mutex);
704         set_buffer_new(bh_result);
705 got_it:
706         map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
707         if (count > blocks_to_boundary)
708                 set_buffer_boundary(bh_result);
709         err = count;
710         /* Clean up and exit */
711         partial = chain + depth - 1;    /* the whole chain */
712 cleanup:
713         while (partial > chain) {
714                 brelse(partial->bh);
715                 partial--;
716         }
717         return err;
718 }
719
720 int ext2_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create)
721 {
722         unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
723         int ret = ext2_get_blocks(inode, iblock, max_blocks,
724                               bh_result, create);
725         if (ret > 0) {
726                 bh_result->b_size = (ret << inode->i_blkbits);
727                 ret = 0;
728         }
729         return ret;
730
731 }
732
733 int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
734                 u64 start, u64 len)
735 {
736         return generic_block_fiemap(inode, fieinfo, start, len,
737                                     ext2_get_block);
738 }
739
740 static int ext2_writepage(struct page *page, struct writeback_control *wbc)
741 {
742         return block_write_full_page(page, ext2_get_block, wbc);
743 }
744
745 static int ext2_readpage(struct file *file, struct page *page)
746 {
747         return mpage_readpage(page, ext2_get_block);
748 }
749
750 static int
751 ext2_readpages(struct file *file, struct address_space *mapping,
752                 struct list_head *pages, unsigned nr_pages)
753 {
754         return mpage_readpages(mapping, pages, nr_pages, ext2_get_block);
755 }
756
757 int __ext2_write_begin(struct file *file, struct address_space *mapping,
758                 loff_t pos, unsigned len, unsigned flags,
759                 struct page **pagep, void **fsdata)
760 {
761         return block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
762                                                         ext2_get_block);
763 }
764
765 static int
766 ext2_write_begin(struct file *file, struct address_space *mapping,
767                 loff_t pos, unsigned len, unsigned flags,
768                 struct page **pagep, void **fsdata)
769 {
770         *pagep = NULL;
771         return __ext2_write_begin(file, mapping, pos, len, flags, pagep,fsdata);
772 }
773
774 static int
775 ext2_nobh_write_begin(struct file *file, struct address_space *mapping,
776                 loff_t pos, unsigned len, unsigned flags,
777                 struct page **pagep, void **fsdata)
778 {
779         /*
780          * Dir-in-pagecache still uses ext2_write_begin. Would have to rework
781          * directory handling code to pass around offsets rather than struct
782          * pages in order to make this work easily.
783          */
784         return nobh_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
785                                                         ext2_get_block);
786 }
787
788 static int ext2_nobh_writepage(struct page *page,
789                         struct writeback_control *wbc)
790 {
791         return nobh_writepage(page, ext2_get_block, wbc);
792 }
793
794 static sector_t ext2_bmap(struct address_space *mapping, sector_t block)
795 {
796         return generic_block_bmap(mapping,block,ext2_get_block);
797 }
798
799 static ssize_t
800 ext2_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
801                         loff_t offset, unsigned long nr_segs)
802 {
803         struct file *file = iocb->ki_filp;
804         struct inode *inode = file->f_mapping->host;
805
806         return blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
807                                 offset, nr_segs, ext2_get_block, NULL);
808 }
809
810 static int
811 ext2_writepages(struct address_space *mapping, struct writeback_control *wbc)
812 {
813         return mpage_writepages(mapping, wbc, ext2_get_block);
814 }
815
816 const struct address_space_operations ext2_aops = {
817         .readpage               = ext2_readpage,
818         .readpages              = ext2_readpages,
819         .writepage              = ext2_writepage,
820         .sync_page              = block_sync_page,
821         .write_begin            = ext2_write_begin,
822         .write_end              = generic_write_end,
823         .bmap                   = ext2_bmap,
824         .direct_IO              = ext2_direct_IO,
825         .writepages             = ext2_writepages,
826         .migratepage            = buffer_migrate_page,
827         .is_partially_uptodate  = block_is_partially_uptodate,
828         .error_remove_page      = generic_error_remove_page,
829 };
830
831 const struct address_space_operations ext2_aops_xip = {
832         .bmap                   = ext2_bmap,
833         .get_xip_mem            = ext2_get_xip_mem,
834 };
835
836 const struct address_space_operations ext2_nobh_aops = {
837         .readpage               = ext2_readpage,
838         .readpages              = ext2_readpages,
839         .writepage              = ext2_nobh_writepage,
840         .sync_page              = block_sync_page,
841         .write_begin            = ext2_nobh_write_begin,
842         .write_end              = nobh_write_end,
843         .bmap                   = ext2_bmap,
844         .direct_IO              = ext2_direct_IO,
845         .writepages             = ext2_writepages,
846         .migratepage            = buffer_migrate_page,
847         .error_remove_page      = generic_error_remove_page,
848 };
849
850 /*
851  * Probably it should be a library function... search for first non-zero word
852  * or memcmp with zero_page, whatever is better for particular architecture.
853  * Linus?
854  */
855 static inline int all_zeroes(__le32 *p, __le32 *q)
856 {
857         while (p < q)
858                 if (*p++)
859                         return 0;
860         return 1;
861 }
862
863 /**
864  *      ext2_find_shared - find the indirect blocks for partial truncation.
865  *      @inode:   inode in question
866  *      @depth:   depth of the affected branch
867  *      @offsets: offsets of pointers in that branch (see ext2_block_to_path)
868  *      @chain:   place to store the pointers to partial indirect blocks
869  *      @top:     place to the (detached) top of branch
870  *
871  *      This is a helper function used by ext2_truncate().
872  *
873  *      When we do truncate() we may have to clean the ends of several indirect
874  *      blocks but leave the blocks themselves alive. Block is partially
875  *      truncated if some data below the new i_size is refered from it (and
876  *      it is on the path to the first completely truncated data block, indeed).
877  *      We have to free the top of that path along with everything to the right
878  *      of the path. Since no allocation past the truncation point is possible
879  *      until ext2_truncate() finishes, we may safely do the latter, but top
880  *      of branch may require special attention - pageout below the truncation
881  *      point might try to populate it.
882  *
883  *      We atomically detach the top of branch from the tree, store the block
884  *      number of its root in *@top, pointers to buffer_heads of partially
885  *      truncated blocks - in @chain[].bh and pointers to their last elements
886  *      that should not be removed - in @chain[].p. Return value is the pointer
887  *      to last filled element of @chain.
888  *
889  *      The work left to caller to do the actual freeing of subtrees:
890  *              a) free the subtree starting from *@top
891  *              b) free the subtrees whose roots are stored in
892  *                      (@chain[i].p+1 .. end of @chain[i].bh->b_data)
893  *              c) free the subtrees growing from the inode past the @chain[0].p
894  *                      (no partially truncated stuff there).
895  */
896
897 static Indirect *ext2_find_shared(struct inode *inode,
898                                 int depth,
899                                 int offsets[4],
900                                 Indirect chain[4],
901                                 __le32 *top)
902 {
903         Indirect *partial, *p;
904         int k, err;
905
906         *top = 0;
907         for (k = depth; k > 1 && !offsets[k-1]; k--)
908                 ;
909         partial = ext2_get_branch(inode, k, offsets, chain, &err);
910         if (!partial)
911                 partial = chain + k-1;
912         /*
913          * If the branch acquired continuation since we've looked at it -
914          * fine, it should all survive and (new) top doesn't belong to us.
915          */
916         write_lock(&EXT2_I(inode)->i_meta_lock);
917         if (!partial->key && *partial->p) {
918                 write_unlock(&EXT2_I(inode)->i_meta_lock);
919                 goto no_top;
920         }
921         for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
922                 ;
923         /*
924          * OK, we've found the last block that must survive. The rest of our
925          * branch should be detached before unlocking. However, if that rest
926          * of branch is all ours and does not grow immediately from the inode
927          * it's easier to cheat and just decrement partial->p.
928          */
929         if (p == chain + k - 1 && p > chain) {
930                 p->p--;
931         } else {
932                 *top = *p->p;
933                 *p->p = 0;
934         }
935         write_unlock(&EXT2_I(inode)->i_meta_lock);
936
937         while(partial > p)
938         {
939                 brelse(partial->bh);
940                 partial--;
941         }
942 no_top:
943         return partial;
944 }
945
946 /**
947  *      ext2_free_data - free a list of data blocks
948  *      @inode: inode we are dealing with
949  *      @p:     array of block numbers
950  *      @q:     points immediately past the end of array
951  *
952  *      We are freeing all blocks refered from that array (numbers are
953  *      stored as little-endian 32-bit) and updating @inode->i_blocks
954  *      appropriately.
955  */
956 static inline void ext2_free_data(struct inode *inode, __le32 *p, __le32 *q)
957 {
958         unsigned long block_to_free = 0, count = 0;
959         unsigned long nr;
960
961         for ( ; p < q ; p++) {
962                 nr = le32_to_cpu(*p);
963                 if (nr) {
964                         *p = 0;
965                         /* accumulate blocks to free if they're contiguous */
966                         if (count == 0)
967                                 goto free_this;
968                         else if (block_to_free == nr - count)
969                                 count++;
970                         else {
971                                 mark_inode_dirty(inode);
972                                 ext2_free_blocks (inode, block_to_free, count);
973                         free_this:
974                                 block_to_free = nr;
975                                 count = 1;
976                         }
977                 }
978         }
979         if (count > 0) {
980                 mark_inode_dirty(inode);
981                 ext2_free_blocks (inode, block_to_free, count);
982         }
983 }
984
985 /**
986  *      ext2_free_branches - free an array of branches
987  *      @inode: inode we are dealing with
988  *      @p:     array of block numbers
989  *      @q:     pointer immediately past the end of array
990  *      @depth: depth of the branches to free
991  *
992  *      We are freeing all blocks refered from these branches (numbers are
993  *      stored as little-endian 32-bit) and updating @inode->i_blocks
994  *      appropriately.
995  */
996 static void ext2_free_branches(struct inode *inode, __le32 *p, __le32 *q, int depth)
997 {
998         struct buffer_head * bh;
999         unsigned long nr;
1000
1001         if (depth--) {
1002                 int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
1003                 for ( ; p < q ; p++) {
1004                         nr = le32_to_cpu(*p);
1005                         if (!nr)
1006                                 continue;
1007                         *p = 0;
1008                         bh = sb_bread(inode->i_sb, nr);
1009                         /*
1010                          * A read failure? Report error and clear slot
1011                          * (should be rare).
1012                          */ 
1013                         if (!bh) {
1014                                 ext2_error(inode->i_sb, "ext2_free_branches",
1015                                         "Read failure, inode=%ld, block=%ld",
1016                                         inode->i_ino, nr);
1017                                 continue;
1018                         }
1019                         ext2_free_branches(inode,
1020                                            (__le32*)bh->b_data,
1021                                            (__le32*)bh->b_data + addr_per_block,
1022                                            depth);
1023                         bforget(bh);
1024                         ext2_free_blocks(inode, nr, 1);
1025                         mark_inode_dirty(inode);
1026                 }
1027         } else
1028                 ext2_free_data(inode, p, q);
1029 }
1030
1031 void ext2_truncate(struct inode *inode)
1032 {
1033         __le32 *i_data = EXT2_I(inode)->i_data;
1034         struct ext2_inode_info *ei = EXT2_I(inode);
1035         int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
1036         int offsets[4];
1037         Indirect chain[4];
1038         Indirect *partial;
1039         __le32 nr = 0;
1040         int n;
1041         long iblock;
1042         unsigned blocksize;
1043
1044         if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1045             S_ISLNK(inode->i_mode)))
1046                 return;
1047         if (ext2_inode_is_fast_symlink(inode))
1048                 return;
1049         if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1050                 return;
1051
1052         blocksize = inode->i_sb->s_blocksize;
1053         iblock = (inode->i_size + blocksize-1)
1054                                         >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
1055
1056         if (mapping_is_xip(inode->i_mapping))
1057                 xip_truncate_page(inode->i_mapping, inode->i_size);
1058         else if (test_opt(inode->i_sb, NOBH))
1059                 nobh_truncate_page(inode->i_mapping,
1060                                 inode->i_size, ext2_get_block);
1061         else
1062                 block_truncate_page(inode->i_mapping,
1063                                 inode->i_size, ext2_get_block);
1064
1065         n = ext2_block_to_path(inode, iblock, offsets, NULL);
1066         if (n == 0)
1067                 return;
1068
1069         /*
1070          * From here we block out all ext2_get_block() callers who want to
1071          * modify the block allocation tree.
1072          */
1073         mutex_lock(&ei->truncate_mutex);
1074
1075         if (n == 1) {
1076                 ext2_free_data(inode, i_data+offsets[0],
1077                                         i_data + EXT2_NDIR_BLOCKS);
1078                 goto do_indirects;
1079         }
1080
1081         partial = ext2_find_shared(inode, n, offsets, chain, &nr);
1082         /* Kill the top of shared branch (already detached) */
1083         if (nr) {
1084                 if (partial == chain)
1085                         mark_inode_dirty(inode);
1086                 else
1087                         mark_buffer_dirty_inode(partial->bh, inode);
1088                 ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
1089         }
1090         /* Clear the ends of indirect blocks on the shared branch */
1091         while (partial > chain) {
1092                 ext2_free_branches(inode,
1093                                    partial->p + 1,
1094                                    (__le32*)partial->bh->b_data+addr_per_block,
1095                                    (chain+n-1) - partial);
1096                 mark_buffer_dirty_inode(partial->bh, inode);
1097                 brelse (partial->bh);
1098                 partial--;
1099         }
1100 do_indirects:
1101         /* Kill the remaining (whole) subtrees */
1102         switch (offsets[0]) {
1103                 default:
1104                         nr = i_data[EXT2_IND_BLOCK];
1105                         if (nr) {
1106                                 i_data[EXT2_IND_BLOCK] = 0;
1107                                 mark_inode_dirty(inode);
1108                                 ext2_free_branches(inode, &nr, &nr+1, 1);
1109                         }
1110                 case EXT2_IND_BLOCK:
1111                         nr = i_data[EXT2_DIND_BLOCK];
1112                         if (nr) {
1113                                 i_data[EXT2_DIND_BLOCK] = 0;
1114                                 mark_inode_dirty(inode);
1115                                 ext2_free_branches(inode, &nr, &nr+1, 2);
1116                         }
1117                 case EXT2_DIND_BLOCK:
1118                         nr = i_data[EXT2_TIND_BLOCK];
1119                         if (nr) {
1120                                 i_data[EXT2_TIND_BLOCK] = 0;
1121                                 mark_inode_dirty(inode);
1122                                 ext2_free_branches(inode, &nr, &nr+1, 3);
1123                         }
1124                 case EXT2_TIND_BLOCK:
1125                         ;
1126         }
1127
1128         ext2_discard_reservation(inode);
1129
1130         mutex_unlock(&ei->truncate_mutex);
1131         inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
1132         if (inode_needs_sync(inode)) {
1133                 sync_mapping_buffers(inode->i_mapping);
1134                 ext2_sync_inode (inode);
1135         } else {
1136                 mark_inode_dirty(inode);
1137         }
1138 }
1139
1140 static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino,
1141                                         struct buffer_head **p)
1142 {
1143         struct buffer_head * bh;
1144         unsigned long block_group;
1145         unsigned long block;
1146         unsigned long offset;
1147         struct ext2_group_desc * gdp;
1148
1149         *p = NULL;
1150         if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) ||
1151             ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
1152                 goto Einval;
1153
1154         block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
1155         gdp = ext2_get_group_desc(sb, block_group, NULL);
1156         if (!gdp)
1157                 goto Egdp;
1158         /*
1159          * Figure out the offset within the block group inode table
1160          */
1161         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb);
1162         block = le32_to_cpu(gdp->bg_inode_table) +
1163                 (offset >> EXT2_BLOCK_SIZE_BITS(sb));
1164         if (!(bh = sb_bread(sb, block)))
1165                 goto Eio;
1166
1167         *p = bh;
1168         offset &= (EXT2_BLOCK_SIZE(sb) - 1);
1169         return (struct ext2_inode *) (bh->b_data + offset);
1170
1171 Einval:
1172         ext2_error(sb, "ext2_get_inode", "bad inode number: %lu",
1173                    (unsigned long) ino);
1174         return ERR_PTR(-EINVAL);
1175 Eio:
1176         ext2_error(sb, "ext2_get_inode",
1177                    "unable to read inode block - inode=%lu, block=%lu",
1178                    (unsigned long) ino, block);
1179 Egdp:
1180         return ERR_PTR(-EIO);
1181 }
1182
1183 void ext2_set_inode_flags(struct inode *inode)
1184 {
1185         unsigned int flags = EXT2_I(inode)->i_flags;
1186
1187         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
1188         if (flags & EXT2_SYNC_FL)
1189                 inode->i_flags |= S_SYNC;
1190         if (flags & EXT2_APPEND_FL)
1191                 inode->i_flags |= S_APPEND;
1192         if (flags & EXT2_IMMUTABLE_FL)
1193                 inode->i_flags |= S_IMMUTABLE;
1194         if (flags & EXT2_NOATIME_FL)
1195                 inode->i_flags |= S_NOATIME;
1196         if (flags & EXT2_DIRSYNC_FL)
1197                 inode->i_flags |= S_DIRSYNC;
1198 }
1199
1200 /* Propagate flags from i_flags to EXT2_I(inode)->i_flags */
1201 void ext2_get_inode_flags(struct ext2_inode_info *ei)
1202 {
1203         unsigned int flags = ei->vfs_inode.i_flags;
1204
1205         ei->i_flags &= ~(EXT2_SYNC_FL|EXT2_APPEND_FL|
1206                         EXT2_IMMUTABLE_FL|EXT2_NOATIME_FL|EXT2_DIRSYNC_FL);
1207         if (flags & S_SYNC)
1208                 ei->i_flags |= EXT2_SYNC_FL;
1209         if (flags & S_APPEND)
1210                 ei->i_flags |= EXT2_APPEND_FL;
1211         if (flags & S_IMMUTABLE)
1212                 ei->i_flags |= EXT2_IMMUTABLE_FL;
1213         if (flags & S_NOATIME)
1214                 ei->i_flags |= EXT2_NOATIME_FL;
1215         if (flags & S_DIRSYNC)
1216                 ei->i_flags |= EXT2_DIRSYNC_FL;
1217 }
1218
1219 struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
1220 {
1221         struct ext2_inode_info *ei;
1222         struct buffer_head * bh;
1223         struct ext2_inode *raw_inode;
1224         struct inode *inode;
1225         long ret = -EIO;
1226         int n;
1227
1228         inode = iget_locked(sb, ino);
1229         if (!inode)
1230                 return ERR_PTR(-ENOMEM);
1231         if (!(inode->i_state & I_NEW))
1232                 return inode;
1233
1234         ei = EXT2_I(inode);
1235         ei->i_block_alloc_info = NULL;
1236
1237         raw_inode = ext2_get_inode(inode->i_sb, ino, &bh);
1238         if (IS_ERR(raw_inode)) {
1239                 ret = PTR_ERR(raw_inode);
1240                 goto bad_inode;
1241         }
1242
1243         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
1244         inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
1245         inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
1246         if (!(test_opt (inode->i_sb, NO_UID32))) {
1247                 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
1248                 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
1249         }
1250         inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
1251         inode->i_size = le32_to_cpu(raw_inode->i_size);
1252         inode->i_atime.tv_sec = (signed)le32_to_cpu(raw_inode->i_atime);
1253         inode->i_ctime.tv_sec = (signed)le32_to_cpu(raw_inode->i_ctime);
1254         inode->i_mtime.tv_sec = (signed)le32_to_cpu(raw_inode->i_mtime);
1255         inode->i_atime.tv_nsec = inode->i_mtime.tv_nsec = inode->i_ctime.tv_nsec = 0;
1256         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
1257         /* We now have enough fields to check if the inode was active or not.
1258          * This is needed because nfsd might try to access dead inodes
1259          * the test is that same one that e2fsck uses
1260          * NeilBrown 1999oct15
1261          */
1262         if (inode->i_nlink == 0 && (inode->i_mode == 0 || ei->i_dtime)) {
1263                 /* this inode is deleted */
1264                 brelse (bh);
1265                 ret = -ESTALE;
1266                 goto bad_inode;
1267         }
1268         inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
1269         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
1270         ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
1271         ei->i_frag_no = raw_inode->i_frag;
1272         ei->i_frag_size = raw_inode->i_fsize;
1273         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
1274         ei->i_dir_acl = 0;
1275         if (S_ISREG(inode->i_mode))
1276                 inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
1277         else
1278                 ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
1279         ei->i_dtime = 0;
1280         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
1281         ei->i_state = 0;
1282         ei->i_block_group = (ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
1283         ei->i_dir_start_lookup = 0;
1284
1285         /*
1286          * NOTE! The in-memory inode i_data array is in little-endian order
1287          * even on big-endian machines: we do NOT byteswap the block numbers!
1288          */
1289         for (n = 0; n < EXT2_N_BLOCKS; n++)
1290                 ei->i_data[n] = raw_inode->i_block[n];
1291
1292         if (S_ISREG(inode->i_mode)) {
1293                 inode->i_op = &ext2_file_inode_operations;
1294                 if (ext2_use_xip(inode->i_sb)) {
1295                         inode->i_mapping->a_ops = &ext2_aops_xip;
1296                         inode->i_fop = &ext2_xip_file_operations;
1297                 } else if (test_opt(inode->i_sb, NOBH)) {
1298                         inode->i_mapping->a_ops = &ext2_nobh_aops;
1299                         inode->i_fop = &ext2_file_operations;
1300                 } else {
1301                         inode->i_mapping->a_ops = &ext2_aops;
1302                         inode->i_fop = &ext2_file_operations;
1303                 }
1304         } else if (S_ISDIR(inode->i_mode)) {
1305                 inode->i_op = &ext2_dir_inode_operations;
1306                 inode->i_fop = &ext2_dir_operations;
1307                 if (test_opt(inode->i_sb, NOBH))
1308                         inode->i_mapping->a_ops = &ext2_nobh_aops;
1309                 else
1310                         inode->i_mapping->a_ops = &ext2_aops;
1311         } else if (S_ISLNK(inode->i_mode)) {
1312                 if (ext2_inode_is_fast_symlink(inode)) {
1313                         inode->i_op = &ext2_fast_symlink_inode_operations;
1314                         nd_terminate_link(ei->i_data, inode->i_size,
1315                                 sizeof(ei->i_data) - 1);
1316                 } else {
1317                         inode->i_op = &ext2_symlink_inode_operations;
1318                         if (test_opt(inode->i_sb, NOBH))
1319                                 inode->i_mapping->a_ops = &ext2_nobh_aops;
1320                         else
1321                                 inode->i_mapping->a_ops = &ext2_aops;
1322                 }
1323         } else {
1324                 inode->i_op = &ext2_special_inode_operations;
1325                 if (raw_inode->i_block[0])
1326                         init_special_inode(inode, inode->i_mode,
1327                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
1328                 else 
1329                         init_special_inode(inode, inode->i_mode,
1330                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
1331         }
1332         brelse (bh);
1333         ext2_set_inode_flags(inode);
1334         unlock_new_inode(inode);
1335         return inode;
1336         
1337 bad_inode:
1338         iget_failed(inode);
1339         return ERR_PTR(ret);
1340 }
1341
1342 static int __ext2_write_inode(struct inode *inode, int do_sync)
1343 {
1344         struct ext2_inode_info *ei = EXT2_I(inode);
1345         struct super_block *sb = inode->i_sb;
1346         ino_t ino = inode->i_ino;
1347         uid_t uid = inode->i_uid;
1348         gid_t gid = inode->i_gid;
1349         struct buffer_head * bh;
1350         struct ext2_inode * raw_inode = ext2_get_inode(sb, ino, &bh);
1351         int n;
1352         int err = 0;
1353
1354         if (IS_ERR(raw_inode))
1355                 return -EIO;
1356
1357         /* For fields not not tracking in the in-memory inode,
1358          * initialise them to zero for new inodes. */
1359         if (ei->i_state & EXT2_STATE_NEW)
1360                 memset(raw_inode, 0, EXT2_SB(sb)->s_inode_size);
1361
1362         ext2_get_inode_flags(ei);
1363         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
1364         if (!(test_opt(sb, NO_UID32))) {
1365                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(uid));
1366                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(gid));
1367 /*
1368  * Fix up interoperability with old kernels. Otherwise, old inodes get
1369  * re-used with the upper 16 bits of the uid/gid intact
1370  */
1371                 if (!ei->i_dtime) {
1372                         raw_inode->i_uid_high = cpu_to_le16(high_16_bits(uid));
1373                         raw_inode->i_gid_high = cpu_to_le16(high_16_bits(gid));
1374                 } else {
1375                         raw_inode->i_uid_high = 0;
1376                         raw_inode->i_gid_high = 0;
1377                 }
1378         } else {
1379                 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(uid));
1380                 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(gid));
1381                 raw_inode->i_uid_high = 0;
1382                 raw_inode->i_gid_high = 0;
1383         }
1384         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
1385         raw_inode->i_size = cpu_to_le32(inode->i_size);
1386         raw_inode->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
1387         raw_inode->i_ctime = cpu_to_le32(inode->i_ctime.tv_sec);
1388         raw_inode->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
1389
1390         raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
1391         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
1392         raw_inode->i_flags = cpu_to_le32(ei->i_flags);
1393         raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
1394         raw_inode->i_frag = ei->i_frag_no;
1395         raw_inode->i_fsize = ei->i_frag_size;
1396         raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
1397         if (!S_ISREG(inode->i_mode))
1398                 raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
1399         else {
1400                 raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
1401                 if (inode->i_size > 0x7fffffffULL) {
1402                         if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
1403                                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
1404                             EXT2_SB(sb)->s_es->s_rev_level ==
1405                                         cpu_to_le32(EXT2_GOOD_OLD_REV)) {
1406                                /* If this is the first large file
1407                                 * created, add a flag to the superblock.
1408                                 */
1409                                 lock_kernel();
1410                                 ext2_update_dynamic_rev(sb);
1411                                 EXT2_SET_RO_COMPAT_FEATURE(sb,
1412                                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
1413                                 unlock_kernel();
1414                                 ext2_write_super(sb);
1415                         }
1416                 }
1417         }
1418         
1419         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
1420         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
1421                 if (old_valid_dev(inode->i_rdev)) {
1422                         raw_inode->i_block[0] =
1423                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
1424                         raw_inode->i_block[1] = 0;
1425                 } else {
1426                         raw_inode->i_block[0] = 0;
1427                         raw_inode->i_block[1] =
1428                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
1429                         raw_inode->i_block[2] = 0;
1430                 }
1431         } else for (n = 0; n < EXT2_N_BLOCKS; n++)
1432                 raw_inode->i_block[n] = ei->i_data[n];
1433         mark_buffer_dirty(bh);
1434         if (do_sync) {
1435                 sync_dirty_buffer(bh);
1436                 if (buffer_req(bh) && !buffer_uptodate(bh)) {
1437                         printk ("IO error syncing ext2 inode [%s:%08lx]\n",
1438                                 sb->s_id, (unsigned long) ino);
1439                         err = -EIO;
1440                 }
1441         }
1442         ei->i_state &= ~EXT2_STATE_NEW;
1443         brelse (bh);
1444         return err;
1445 }
1446
1447 int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
1448 {
1449         return __ext2_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
1450 }
1451
1452 int ext2_sync_inode(struct inode *inode)
1453 {
1454         struct writeback_control wbc = {
1455                 .sync_mode = WB_SYNC_ALL,
1456                 .nr_to_write = 0,       /* sys_fsync did this */
1457         };
1458         return sync_inode(inode, &wbc);
1459 }
1460
1461 int ext2_setattr(struct dentry *dentry, struct iattr *iattr)
1462 {
1463         struct inode *inode = dentry->d_inode;
1464         int error;
1465
1466         error = inode_change_ok(inode, iattr);
1467         if (error)
1468                 return error;
1469
1470         if (iattr->ia_valid & ATTR_SIZE)
1471                 dquot_initialize(inode);
1472         if ((iattr->ia_valid & ATTR_UID && iattr->ia_uid != inode->i_uid) ||
1473             (iattr->ia_valid & ATTR_GID && iattr->ia_gid != inode->i_gid)) {
1474                 error = dquot_transfer(inode, iattr);
1475                 if (error)
1476                         return error;
1477         }
1478         error = inode_setattr(inode, iattr);
1479         if (!error && (iattr->ia_valid & ATTR_MODE))
1480                 error = ext2_acl_chmod(inode);
1481         return error;
1482 }