pandora: defconfig: update
[pandora-kernel.git] / fs / ext4 / namei.c
1 /*
2  *  linux/fs/ext4/namei.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/namei.c
12  *
13  *  Copyright (C) 1991, 1992  Linus Torvalds
14  *
15  *  Big-endian to little-endian byte-swapping/bitmaps by
16  *        David S. Miller (davem@caip.rutgers.edu), 1995
17  *  Directory entry file type support and forward compatibility hooks
18  *      for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
19  *  Hash Tree Directory indexing (c)
20  *      Daniel Phillips, 2001
21  *  Hash Tree Directory indexing porting
22  *      Christopher Li, 2002
23  *  Hash Tree Directory indexing cleanup
24  *      Theodore Ts'o, 2002
25  */
26
27 #include <linux/fs.h>
28 #include <linux/pagemap.h>
29 #include <linux/jbd2.h>
30 #include <linux/time.h>
31 #include <linux/fcntl.h>
32 #include <linux/stat.h>
33 #include <linux/string.h>
34 #include <linux/quotaops.h>
35 #include <linux/buffer_head.h>
36 #include <linux/bio.h>
37 #include "ext4.h"
38 #include "ext4_jbd2.h"
39
40 #include "xattr.h"
41 #include "acl.h"
42
43 #include <trace/events/ext4.h>
44 /*
45  * define how far ahead to read directories while searching them.
46  */
47 #define NAMEI_RA_CHUNKS  2
48 #define NAMEI_RA_BLOCKS  4
49 #define NAMEI_RA_SIZE        (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
50 #define NAMEI_RA_INDEX(c,b)  (((c) * NAMEI_RA_BLOCKS) + (b))
51
52 static struct buffer_head *ext4_append(handle_t *handle,
53                                         struct inode *inode,
54                                         ext4_lblk_t *block, int *err)
55 {
56         struct buffer_head *bh;
57
58         *block = inode->i_size >> inode->i_sb->s_blocksize_bits;
59
60         bh = ext4_bread(handle, inode, *block, 1, err);
61         if (bh) {
62                 inode->i_size += inode->i_sb->s_blocksize;
63                 EXT4_I(inode)->i_disksize = inode->i_size;
64                 *err = ext4_journal_get_write_access(handle, bh);
65                 if (*err) {
66                         brelse(bh);
67                         bh = NULL;
68                 }
69         }
70         return bh;
71 }
72
73 #ifndef assert
74 #define assert(test) J_ASSERT(test)
75 #endif
76
77 #ifdef DX_DEBUG
78 #define dxtrace(command) command
79 #else
80 #define dxtrace(command)
81 #endif
82
83 struct fake_dirent
84 {
85         __le32 inode;
86         __le16 rec_len;
87         u8 name_len;
88         u8 file_type;
89 };
90
91 struct dx_countlimit
92 {
93         __le16 limit;
94         __le16 count;
95 };
96
97 struct dx_entry
98 {
99         __le32 hash;
100         __le32 block;
101 };
102
103 /*
104  * dx_root_info is laid out so that if it should somehow get overlaid by a
105  * dirent the two low bits of the hash version will be zero.  Therefore, the
106  * hash version mod 4 should never be 0.  Sincerely, the paranoia department.
107  */
108
109 struct dx_root
110 {
111         struct fake_dirent dot;
112         char dot_name[4];
113         struct fake_dirent dotdot;
114         char dotdot_name[4];
115         struct dx_root_info
116         {
117                 __le32 reserved_zero;
118                 u8 hash_version;
119                 u8 info_length; /* 8 */
120                 u8 indirect_levels;
121                 u8 unused_flags;
122         }
123         info;
124         struct dx_entry entries[0];
125 };
126
127 struct dx_node
128 {
129         struct fake_dirent fake;
130         struct dx_entry entries[0];
131 };
132
133
134 struct dx_frame
135 {
136         struct buffer_head *bh;
137         struct dx_entry *entries;
138         struct dx_entry *at;
139 };
140
141 struct dx_map_entry
142 {
143         u32 hash;
144         u16 offs;
145         u16 size;
146 };
147
148 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
149 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
150 static inline unsigned dx_get_hash(struct dx_entry *entry);
151 static void dx_set_hash(struct dx_entry *entry, unsigned value);
152 static unsigned dx_get_count(struct dx_entry *entries);
153 static unsigned dx_get_limit(struct dx_entry *entries);
154 static void dx_set_count(struct dx_entry *entries, unsigned value);
155 static void dx_set_limit(struct dx_entry *entries, unsigned value);
156 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
157 static unsigned dx_node_limit(struct inode *dir);
158 static struct dx_frame *dx_probe(const struct qstr *d_name,
159                                  struct inode *dir,
160                                  struct dx_hash_info *hinfo,
161                                  struct dx_frame *frame,
162                                  int *err);
163 static void dx_release(struct dx_frame *frames);
164 static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize,
165                        struct dx_hash_info *hinfo, struct dx_map_entry map[]);
166 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
167 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
168                 struct dx_map_entry *offsets, int count, unsigned blocksize);
169 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
170 static void dx_insert_block(struct dx_frame *frame,
171                                         u32 hash, ext4_lblk_t block);
172 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
173                                  struct dx_frame *frame,
174                                  struct dx_frame *frames,
175                                  __u32 *start_hash);
176 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
177                 const struct qstr *d_name,
178                 struct ext4_dir_entry_2 **res_dir,
179                 int *err);
180 static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry,
181                              struct inode *inode);
182
183 /*
184  * p is at least 6 bytes before the end of page
185  */
186 static inline struct ext4_dir_entry_2 *
187 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
188 {
189         return (struct ext4_dir_entry_2 *)((char *)p +
190                 ext4_rec_len_from_disk(p->rec_len, blocksize));
191 }
192
193 /*
194  * Future: use high four bits of block for coalesce-on-delete flags
195  * Mask them off for now.
196  */
197
198 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
199 {
200         return le32_to_cpu(entry->block) & 0x00ffffff;
201 }
202
203 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
204 {
205         entry->block = cpu_to_le32(value);
206 }
207
208 static inline unsigned dx_get_hash(struct dx_entry *entry)
209 {
210         return le32_to_cpu(entry->hash);
211 }
212
213 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
214 {
215         entry->hash = cpu_to_le32(value);
216 }
217
218 static inline unsigned dx_get_count(struct dx_entry *entries)
219 {
220         return le16_to_cpu(((struct dx_countlimit *) entries)->count);
221 }
222
223 static inline unsigned dx_get_limit(struct dx_entry *entries)
224 {
225         return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
226 }
227
228 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
229 {
230         ((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
231 }
232
233 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
234 {
235         ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
236 }
237
238 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
239 {
240         unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
241                 EXT4_DIR_REC_LEN(2) - infosize;
242         return entry_space / sizeof(struct dx_entry);
243 }
244
245 static inline unsigned dx_node_limit(struct inode *dir)
246 {
247         unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
248         return entry_space / sizeof(struct dx_entry);
249 }
250
251 /*
252  * Debug
253  */
254 #ifdef DX_DEBUG
255 static void dx_show_index(char * label, struct dx_entry *entries)
256 {
257         int i, n = dx_get_count (entries);
258         printk(KERN_DEBUG "%s index ", label);
259         for (i = 0; i < n; i++) {
260                 printk("%x->%lu ", i ? dx_get_hash(entries + i) :
261                                 0, (unsigned long)dx_get_block(entries + i));
262         }
263         printk("\n");
264 }
265
266 struct stats
267 {
268         unsigned names;
269         unsigned space;
270         unsigned bcount;
271 };
272
273 static struct stats dx_show_leaf(struct dx_hash_info *hinfo, struct ext4_dir_entry_2 *de,
274                                  int size, int show_names)
275 {
276         unsigned names = 0, space = 0;
277         char *base = (char *) de;
278         struct dx_hash_info h = *hinfo;
279
280         printk("names: ");
281         while ((char *) de < base + size)
282         {
283                 if (de->inode)
284                 {
285                         if (show_names)
286                         {
287                                 int len = de->name_len;
288                                 char *name = de->name;
289                                 while (len--) printk("%c", *name++);
290                                 ext4fs_dirhash(de->name, de->name_len, &h);
291                                 printk(":%x.%u ", h.hash,
292                                        (unsigned) ((char *) de - base));
293                         }
294                         space += EXT4_DIR_REC_LEN(de->name_len);
295                         names++;
296                 }
297                 de = ext4_next_entry(de, size);
298         }
299         printk("(%i)\n", names);
300         return (struct stats) { names, space, 1 };
301 }
302
303 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
304                              struct dx_entry *entries, int levels)
305 {
306         unsigned blocksize = dir->i_sb->s_blocksize;
307         unsigned count = dx_get_count(entries), names = 0, space = 0, i;
308         unsigned bcount = 0;
309         struct buffer_head *bh;
310         int err;
311         printk("%i indexed blocks...\n", count);
312         for (i = 0; i < count; i++, entries++)
313         {
314                 ext4_lblk_t block = dx_get_block(entries);
315                 ext4_lblk_t hash  = i ? dx_get_hash(entries): 0;
316                 u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
317                 struct stats stats;
318                 printk("%s%3u:%03u hash %8x/%8x ",levels?"":"   ", i, block, hash, range);
319                 if (!(bh = ext4_bread (NULL,dir, block, 0,&err))) continue;
320                 stats = levels?
321                    dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
322                    dx_show_leaf(hinfo, (struct ext4_dir_entry_2 *) bh->b_data, blocksize, 0);
323                 names += stats.names;
324                 space += stats.space;
325                 bcount += stats.bcount;
326                 brelse(bh);
327         }
328         if (bcount)
329                 printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
330                        levels ? "" : "   ", names, space/bcount,
331                        (space/bcount)*100/blocksize);
332         return (struct stats) { names, space, bcount};
333 }
334 #endif /* DX_DEBUG */
335
336 /*
337  * Probe for a directory leaf block to search.
338  *
339  * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
340  * error in the directory index, and the caller should fall back to
341  * searching the directory normally.  The callers of dx_probe **MUST**
342  * check for this error code, and make sure it never gets reflected
343  * back to userspace.
344  */
345 static struct dx_frame *
346 dx_probe(const struct qstr *d_name, struct inode *dir,
347          struct dx_hash_info *hinfo, struct dx_frame *frame_in, int *err)
348 {
349         unsigned count, indirect;
350         struct dx_entry *at, *entries, *p, *q, *m;
351         struct dx_root *root;
352         struct buffer_head *bh;
353         struct dx_frame *frame = frame_in;
354         u32 hash;
355
356         frame->bh = NULL;
357         if (!(bh = ext4_bread (NULL,dir, 0, 0, err)))
358                 goto fail;
359         root = (struct dx_root *) bh->b_data;
360         if (root->info.hash_version != DX_HASH_TEA &&
361             root->info.hash_version != DX_HASH_HALF_MD4 &&
362             root->info.hash_version != DX_HASH_LEGACY) {
363                 ext4_warning(dir->i_sb, "Unrecognised inode hash code %d",
364                              root->info.hash_version);
365                 brelse(bh);
366                 *err = ERR_BAD_DX_DIR;
367                 goto fail;
368         }
369         hinfo->hash_version = root->info.hash_version;
370         if (hinfo->hash_version <= DX_HASH_TEA)
371                 hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
372         hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
373         if (d_name)
374                 ext4fs_dirhash(d_name->name, d_name->len, hinfo);
375         hash = hinfo->hash;
376
377         if (root->info.unused_flags & 1) {
378                 ext4_warning(dir->i_sb, "Unimplemented inode hash flags: %#06x",
379                              root->info.unused_flags);
380                 brelse(bh);
381                 *err = ERR_BAD_DX_DIR;
382                 goto fail;
383         }
384
385         if ((indirect = root->info.indirect_levels) > 1) {
386                 ext4_warning(dir->i_sb, "Unimplemented inode hash depth: %#06x",
387                              root->info.indirect_levels);
388                 brelse(bh);
389                 *err = ERR_BAD_DX_DIR;
390                 goto fail;
391         }
392
393         entries = (struct dx_entry *) (((char *)&root->info) +
394                                        root->info.info_length);
395
396         if (dx_get_limit(entries) != dx_root_limit(dir,
397                                                    root->info.info_length)) {
398                 ext4_warning(dir->i_sb, "dx entry: limit != root limit");
399                 brelse(bh);
400                 *err = ERR_BAD_DX_DIR;
401                 goto fail;
402         }
403
404         dxtrace(printk("Look up %x", hash));
405         while (1)
406         {
407                 count = dx_get_count(entries);
408                 if (!count || count > dx_get_limit(entries)) {
409                         ext4_warning(dir->i_sb,
410                                      "dx entry: no count or count > limit");
411                         brelse(bh);
412                         *err = ERR_BAD_DX_DIR;
413                         goto fail2;
414                 }
415
416                 p = entries + 1;
417                 q = entries + count - 1;
418                 while (p <= q)
419                 {
420                         m = p + (q - p)/2;
421                         dxtrace(printk("."));
422                         if (dx_get_hash(m) > hash)
423                                 q = m - 1;
424                         else
425                                 p = m + 1;
426                 }
427
428                 if (0) // linear search cross check
429                 {
430                         unsigned n = count - 1;
431                         at = entries;
432                         while (n--)
433                         {
434                                 dxtrace(printk(","));
435                                 if (dx_get_hash(++at) > hash)
436                                 {
437                                         at--;
438                                         break;
439                                 }
440                         }
441                         assert (at == p - 1);
442                 }
443
444                 at = p - 1;
445                 dxtrace(printk(" %x->%u\n", at == entries? 0: dx_get_hash(at), dx_get_block(at)));
446                 frame->bh = bh;
447                 frame->entries = entries;
448                 frame->at = at;
449                 if (!indirect--) return frame;
450                 if (!(bh = ext4_bread (NULL,dir, dx_get_block(at), 0, err)))
451                         goto fail2;
452                 at = entries = ((struct dx_node *) bh->b_data)->entries;
453                 if (dx_get_limit(entries) != dx_node_limit (dir)) {
454                         ext4_warning(dir->i_sb,
455                                      "dx entry: limit != node limit");
456                         brelse(bh);
457                         *err = ERR_BAD_DX_DIR;
458                         goto fail2;
459                 }
460                 frame++;
461                 frame->bh = NULL;
462         }
463 fail2:
464         while (frame >= frame_in) {
465                 brelse(frame->bh);
466                 frame--;
467         }
468 fail:
469         if (*err == ERR_BAD_DX_DIR)
470                 ext4_warning(dir->i_sb,
471                              "Corrupt dir inode %ld, running e2fsck is "
472                              "recommended.", dir->i_ino);
473         return NULL;
474 }
475
476 static void dx_release (struct dx_frame *frames)
477 {
478         if (frames[0].bh == NULL)
479                 return;
480
481         if (((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels)
482                 brelse(frames[1].bh);
483         brelse(frames[0].bh);
484 }
485
486 /*
487  * This function increments the frame pointer to search the next leaf
488  * block, and reads in the necessary intervening nodes if the search
489  * should be necessary.  Whether or not the search is necessary is
490  * controlled by the hash parameter.  If the hash value is even, then
491  * the search is only continued if the next block starts with that
492  * hash value.  This is used if we are searching for a specific file.
493  *
494  * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
495  *
496  * This function returns 1 if the caller should continue to search,
497  * or 0 if it should not.  If there is an error reading one of the
498  * index blocks, it will a negative error code.
499  *
500  * If start_hash is non-null, it will be filled in with the starting
501  * hash of the next page.
502  */
503 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
504                                  struct dx_frame *frame,
505                                  struct dx_frame *frames,
506                                  __u32 *start_hash)
507 {
508         struct dx_frame *p;
509         struct buffer_head *bh;
510         int err, num_frames = 0;
511         __u32 bhash;
512
513         p = frame;
514         /*
515          * Find the next leaf page by incrementing the frame pointer.
516          * If we run out of entries in the interior node, loop around and
517          * increment pointer in the parent node.  When we break out of
518          * this loop, num_frames indicates the number of interior
519          * nodes need to be read.
520          */
521         while (1) {
522                 if (++(p->at) < p->entries + dx_get_count(p->entries))
523                         break;
524                 if (p == frames)
525                         return 0;
526                 num_frames++;
527                 p--;
528         }
529
530         /*
531          * If the hash is 1, then continue only if the next page has a
532          * continuation hash of any value.  This is used for readdir
533          * handling.  Otherwise, check to see if the hash matches the
534          * desired contiuation hash.  If it doesn't, return since
535          * there's no point to read in the successive index pages.
536          */
537         bhash = dx_get_hash(p->at);
538         if (start_hash)
539                 *start_hash = bhash;
540         if ((hash & 1) == 0) {
541                 if ((bhash & ~1) != hash)
542                         return 0;
543         }
544         /*
545          * If the hash is HASH_NB_ALWAYS, we always go to the next
546          * block so no check is necessary
547          */
548         while (num_frames--) {
549                 if (!(bh = ext4_bread(NULL, dir, dx_get_block(p->at),
550                                       0, &err)))
551                         return err; /* Failure */
552                 p++;
553                 brelse(p->bh);
554                 p->bh = bh;
555                 p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
556         }
557         return 1;
558 }
559
560
561 /*
562  * This function fills a red-black tree with information from a
563  * directory block.  It returns the number directory entries loaded
564  * into the tree.  If there is an error it is returned in err.
565  */
566 static int htree_dirblock_to_tree(struct file *dir_file,
567                                   struct inode *dir, ext4_lblk_t block,
568                                   struct dx_hash_info *hinfo,
569                                   __u32 start_hash, __u32 start_minor_hash)
570 {
571         struct buffer_head *bh;
572         struct ext4_dir_entry_2 *de, *top;
573         int err, count = 0;
574
575         dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
576                                                         (unsigned long)block));
577         if (!(bh = ext4_bread (NULL, dir, block, 0, &err)))
578                 return err;
579
580         de = (struct ext4_dir_entry_2 *) bh->b_data;
581         top = (struct ext4_dir_entry_2 *) ((char *) de +
582                                            dir->i_sb->s_blocksize -
583                                            EXT4_DIR_REC_LEN(0));
584         for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
585                 if (ext4_check_dir_entry(dir, NULL, de, bh,
586                                 (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
587                                          + ((char *)de - bh->b_data))) {
588                         /* silently ignore the rest of the block */
589                         break;
590                 }
591                 ext4fs_dirhash(de->name, de->name_len, hinfo);
592                 if ((hinfo->hash < start_hash) ||
593                     ((hinfo->hash == start_hash) &&
594                      (hinfo->minor_hash < start_minor_hash)))
595                         continue;
596                 if (de->inode == 0)
597                         continue;
598                 if ((err = ext4_htree_store_dirent(dir_file,
599                                    hinfo->hash, hinfo->minor_hash, de)) != 0) {
600                         brelse(bh);
601                         return err;
602                 }
603                 count++;
604         }
605         brelse(bh);
606         return count;
607 }
608
609
610 /*
611  * This function fills a red-black tree with information from a
612  * directory.  We start scanning the directory in hash order, starting
613  * at start_hash and start_minor_hash.
614  *
615  * This function returns the number of entries inserted into the tree,
616  * or a negative error code.
617  */
618 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
619                          __u32 start_minor_hash, __u32 *next_hash)
620 {
621         struct dx_hash_info hinfo;
622         struct ext4_dir_entry_2 *de;
623         struct dx_frame frames[2], *frame;
624         struct inode *dir;
625         ext4_lblk_t block;
626         int count = 0;
627         int ret, err;
628         __u32 hashval;
629
630         dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
631                        start_hash, start_minor_hash));
632         dir = dir_file->f_path.dentry->d_inode;
633         if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
634                 hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
635                 if (hinfo.hash_version <= DX_HASH_TEA)
636                         hinfo.hash_version +=
637                                 EXT4_SB(dir->i_sb)->s_hash_unsigned;
638                 hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
639                 count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
640                                                start_hash, start_minor_hash);
641                 *next_hash = ~0;
642                 return count;
643         }
644         hinfo.hash = start_hash;
645         hinfo.minor_hash = 0;
646         frame = dx_probe(NULL, dir, &hinfo, frames, &err);
647         if (!frame)
648                 return err;
649
650         /* Add '.' and '..' from the htree header */
651         if (!start_hash && !start_minor_hash) {
652                 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
653                 if ((err = ext4_htree_store_dirent(dir_file, 0, 0, de)) != 0)
654                         goto errout;
655                 count++;
656         }
657         if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
658                 de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
659                 de = ext4_next_entry(de, dir->i_sb->s_blocksize);
660                 if ((err = ext4_htree_store_dirent(dir_file, 2, 0, de)) != 0)
661                         goto errout;
662                 count++;
663         }
664
665         while (1) {
666                 block = dx_get_block(frame->at);
667                 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
668                                              start_hash, start_minor_hash);
669                 if (ret < 0) {
670                         err = ret;
671                         goto errout;
672                 }
673                 count += ret;
674                 hashval = ~0;
675                 ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
676                                             frame, frames, &hashval);
677                 *next_hash = hashval;
678                 if (ret < 0) {
679                         err = ret;
680                         goto errout;
681                 }
682                 /*
683                  * Stop if:  (a) there are no more entries, or
684                  * (b) we have inserted at least one entry and the
685                  * next hash value is not a continuation
686                  */
687                 if ((ret == 0) ||
688                     (count && ((hashval & 1) == 0)))
689                         break;
690         }
691         dx_release(frames);
692         dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
693                        "next hash: %x\n", count, *next_hash));
694         return count;
695 errout:
696         dx_release(frames);
697         return (err);
698 }
699
700
701 /*
702  * Directory block splitting, compacting
703  */
704
705 /*
706  * Create map of hash values, offsets, and sizes, stored at end of block.
707  * Returns number of entries mapped.
708  */
709 static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize,
710                        struct dx_hash_info *hinfo,
711                        struct dx_map_entry *map_tail)
712 {
713         int count = 0;
714         char *base = (char *) de;
715         struct dx_hash_info h = *hinfo;
716
717         while ((char *) de < base + blocksize) {
718                 if (de->name_len && de->inode) {
719                         ext4fs_dirhash(de->name, de->name_len, &h);
720                         map_tail--;
721                         map_tail->hash = h.hash;
722                         map_tail->offs = ((char *) de - base)>>2;
723                         map_tail->size = le16_to_cpu(de->rec_len);
724                         count++;
725                         cond_resched();
726                 }
727                 /* XXX: do we need to check rec_len == 0 case? -Chris */
728                 de = ext4_next_entry(de, blocksize);
729         }
730         return count;
731 }
732
733 /* Sort map by hash value */
734 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
735 {
736         struct dx_map_entry *p, *q, *top = map + count - 1;
737         int more;
738         /* Combsort until bubble sort doesn't suck */
739         while (count > 2) {
740                 count = count*10/13;
741                 if (count - 9 < 2) /* 9, 10 -> 11 */
742                         count = 11;
743                 for (p = top, q = p - count; q >= map; p--, q--)
744                         if (p->hash < q->hash)
745                                 swap(*p, *q);
746         }
747         /* Garden variety bubble sort */
748         do {
749                 more = 0;
750                 q = top;
751                 while (q-- > map) {
752                         if (q[1].hash >= q[0].hash)
753                                 continue;
754                         swap(*(q+1), *q);
755                         more = 1;
756                 }
757         } while(more);
758 }
759
760 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
761 {
762         struct dx_entry *entries = frame->entries;
763         struct dx_entry *old = frame->at, *new = old + 1;
764         int count = dx_get_count(entries);
765
766         assert(count < dx_get_limit(entries));
767         assert(old < entries + count);
768         memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
769         dx_set_hash(new, hash);
770         dx_set_block(new, block);
771         dx_set_count(entries, count + 1);
772 }
773
774 static void ext4_update_dx_flag(struct inode *inode)
775 {
776         if (!EXT4_HAS_COMPAT_FEATURE(inode->i_sb,
777                                      EXT4_FEATURE_COMPAT_DIR_INDEX))
778                 ext4_clear_inode_flag(inode, EXT4_INODE_INDEX);
779 }
780
781 /*
782  * NOTE! unlike strncmp, ext4_match returns 1 for success, 0 for failure.
783  *
784  * `len <= EXT4_NAME_LEN' is guaranteed by caller.
785  * `de != NULL' is guaranteed by caller.
786  */
787 static inline int ext4_match (int len, const char * const name,
788                               struct ext4_dir_entry_2 * de)
789 {
790         if (len != de->name_len)
791                 return 0;
792         if (!de->inode)
793                 return 0;
794         return !memcmp(name, de->name, len);
795 }
796
797 /*
798  * Returns 0 if not found, -1 on failure, and 1 on success
799  */
800 static inline int search_dirblock(struct buffer_head *bh,
801                                   struct inode *dir,
802                                   const struct qstr *d_name,
803                                   unsigned int offset,
804                                   struct ext4_dir_entry_2 ** res_dir)
805 {
806         struct ext4_dir_entry_2 * de;
807         char * dlimit;
808         int de_len;
809         const char *name = d_name->name;
810         int namelen = d_name->len;
811
812         de = (struct ext4_dir_entry_2 *) bh->b_data;
813         dlimit = bh->b_data + dir->i_sb->s_blocksize;
814         while ((char *) de < dlimit) {
815                 /* this code is executed quadratically often */
816                 /* do minimal checking `by hand' */
817
818                 if ((char *) de + namelen <= dlimit &&
819                     ext4_match (namelen, name, de)) {
820                         /* found a match - just to be sure, do a full check */
821                         if (ext4_check_dir_entry(dir, NULL, de, bh, offset))
822                                 return -1;
823                         *res_dir = de;
824                         return 1;
825                 }
826                 /* prevent looping on a bad block */
827                 de_len = ext4_rec_len_from_disk(de->rec_len,
828                                                 dir->i_sb->s_blocksize);
829                 if (de_len <= 0)
830                         return -1;
831                 offset += de_len;
832                 de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
833         }
834         return 0;
835 }
836
837
838 /*
839  *      ext4_find_entry()
840  *
841  * finds an entry in the specified directory with the wanted name. It
842  * returns the cache buffer in which the entry was found, and the entry
843  * itself (as a parameter - res_dir). It does NOT read the inode of the
844  * entry - you'll have to do that yourself if you want to.
845  *
846  * The returned buffer_head has ->b_count elevated.  The caller is expected
847  * to brelse() it when appropriate.
848  */
849 static struct buffer_head * ext4_find_entry (struct inode *dir,
850                                         const struct qstr *d_name,
851                                         struct ext4_dir_entry_2 ** res_dir)
852 {
853         struct super_block *sb;
854         struct buffer_head *bh_use[NAMEI_RA_SIZE];
855         struct buffer_head *bh, *ret = NULL;
856         ext4_lblk_t start, block, b;
857         const u8 *name = d_name->name;
858         int ra_max = 0;         /* Number of bh's in the readahead
859                                    buffer, bh_use[] */
860         int ra_ptr = 0;         /* Current index into readahead
861                                    buffer */
862         int num = 0;
863         ext4_lblk_t  nblocks;
864         int i, err;
865         int namelen;
866
867         *res_dir = NULL;
868         sb = dir->i_sb;
869         namelen = d_name->len;
870         if (namelen > EXT4_NAME_LEN)
871                 return NULL;
872         if ((namelen <= 2) && (name[0] == '.') &&
873             (name[1] == '.' || name[1] == '\0')) {
874                 /*
875                  * "." or ".." will only be in the first block
876                  * NFS may look up ".."; "." should be handled by the VFS
877                  */
878                 block = start = 0;
879                 nblocks = 1;
880                 goto restart;
881         }
882         if (is_dx(dir)) {
883                 bh = ext4_dx_find_entry(dir, d_name, res_dir, &err);
884                 /*
885                  * On success, or if the error was file not found,
886                  * return.  Otherwise, fall back to doing a search the
887                  * old fashioned way.
888                  */
889                 if (bh || (err != ERR_BAD_DX_DIR))
890                         return bh;
891                 dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
892                                "falling back\n"));
893         }
894         nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
895         if (!nblocks) {
896                 ret = NULL;
897                 goto cleanup_and_exit;
898         }
899         start = EXT4_I(dir)->i_dir_start_lookup;
900         if (start >= nblocks)
901                 start = 0;
902         block = start;
903 restart:
904         do {
905                 /*
906                  * We deal with the read-ahead logic here.
907                  */
908                 if (ra_ptr >= ra_max) {
909                         /* Refill the readahead buffer */
910                         ra_ptr = 0;
911                         b = block;
912                         for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
913                                 /*
914                                  * Terminate if we reach the end of the
915                                  * directory and must wrap, or if our
916                                  * search has finished at this block.
917                                  */
918                                 if (b >= nblocks || (num && block == start)) {
919                                         bh_use[ra_max] = NULL;
920                                         break;
921                                 }
922                                 num++;
923                                 bh = ext4_getblk(NULL, dir, b++, 0, &err);
924                                 bh_use[ra_max] = bh;
925                                 if (bh)
926                                         ll_rw_block(READ | REQ_META | REQ_PRIO,
927                                                     1, &bh);
928                         }
929                 }
930                 if ((bh = bh_use[ra_ptr++]) == NULL)
931                         goto next;
932                 wait_on_buffer(bh);
933                 if (!buffer_uptodate(bh)) {
934                         /* read error, skip block & hope for the best */
935                         EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
936                                          (unsigned long) block);
937                         brelse(bh);
938                         goto next;
939                 }
940                 i = search_dirblock(bh, dir, d_name,
941                             block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
942                 if (i == 1) {
943                         EXT4_I(dir)->i_dir_start_lookup = block;
944                         ret = bh;
945                         goto cleanup_and_exit;
946                 } else {
947                         brelse(bh);
948                         if (i < 0)
949                                 goto cleanup_and_exit;
950                 }
951         next:
952                 if (++block >= nblocks)
953                         block = 0;
954         } while (block != start);
955
956         /*
957          * If the directory has grown while we were searching, then
958          * search the last part of the directory before giving up.
959          */
960         block = nblocks;
961         nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
962         if (block < nblocks) {
963                 start = 0;
964                 goto restart;
965         }
966
967 cleanup_and_exit:
968         /* Clean up the read-ahead blocks */
969         for (; ra_ptr < ra_max; ra_ptr++)
970                 brelse(bh_use[ra_ptr]);
971         return ret;
972 }
973
974 static struct buffer_head * ext4_dx_find_entry(struct inode *dir, const struct qstr *d_name,
975                        struct ext4_dir_entry_2 **res_dir, int *err)
976 {
977         struct super_block * sb = dir->i_sb;
978         struct dx_hash_info     hinfo;
979         struct dx_frame frames[2], *frame;
980         struct buffer_head *bh;
981         ext4_lblk_t block;
982         int retval;
983
984         if (!(frame = dx_probe(d_name, dir, &hinfo, frames, err)))
985                 return NULL;
986         do {
987                 block = dx_get_block(frame->at);
988                 if (!(bh = ext4_bread(NULL, dir, block, 0, err)))
989                         goto errout;
990
991                 retval = search_dirblock(bh, dir, d_name,
992                                          block << EXT4_BLOCK_SIZE_BITS(sb),
993                                          res_dir);
994                 if (retval == 1) {      /* Success! */
995                         dx_release(frames);
996                         return bh;
997                 }
998                 brelse(bh);
999                 if (retval == -1) {
1000                         *err = ERR_BAD_DX_DIR;
1001                         goto errout;
1002                 }
1003
1004                 /* Check to see if we should continue to search */
1005                 retval = ext4_htree_next_block(dir, hinfo.hash, frame,
1006                                                frames, NULL);
1007                 if (retval < 0) {
1008                         ext4_warning(sb,
1009                              "error reading index page in directory #%lu",
1010                              dir->i_ino);
1011                         *err = retval;
1012                         goto errout;
1013                 }
1014         } while (retval == 1);
1015
1016         *err = -ENOENT;
1017 errout:
1018         dxtrace(printk(KERN_DEBUG "%s not found\n", d_name->name));
1019         dx_release (frames);
1020         return NULL;
1021 }
1022
1023 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
1024 {
1025         struct inode *inode;
1026         struct ext4_dir_entry_2 *de;
1027         struct buffer_head *bh;
1028
1029         if (dentry->d_name.len > EXT4_NAME_LEN)
1030                 return ERR_PTR(-ENAMETOOLONG);
1031
1032         bh = ext4_find_entry(dir, &dentry->d_name, &de);
1033         inode = NULL;
1034         if (bh) {
1035                 __u32 ino = le32_to_cpu(de->inode);
1036                 brelse(bh);
1037                 if (!ext4_valid_inum(dir->i_sb, ino)) {
1038                         EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1039                         return ERR_PTR(-EIO);
1040                 }
1041                 if (unlikely(ino == dir->i_ino)) {
1042                         EXT4_ERROR_INODE(dir, "'%.*s' linked to parent dir",
1043                                          dentry->d_name.len,
1044                                          dentry->d_name.name);
1045                         return ERR_PTR(-EIO);
1046                 }
1047                 inode = ext4_iget_normal(dir->i_sb, ino);
1048                 if (inode == ERR_PTR(-ESTALE)) {
1049                         EXT4_ERROR_INODE(dir,
1050                                          "deleted inode referenced: %u",
1051                                          ino);
1052                         return ERR_PTR(-EIO);
1053                 }
1054         }
1055         return d_splice_alias(inode, dentry);
1056 }
1057
1058
1059 struct dentry *ext4_get_parent(struct dentry *child)
1060 {
1061         __u32 ino;
1062         static const struct qstr dotdot = {
1063                 .name = "..",
1064                 .len = 2,
1065         };
1066         struct ext4_dir_entry_2 * de;
1067         struct buffer_head *bh;
1068
1069         bh = ext4_find_entry(child->d_inode, &dotdot, &de);
1070         if (!bh)
1071                 return ERR_PTR(-ENOENT);
1072         ino = le32_to_cpu(de->inode);
1073         brelse(bh);
1074
1075         if (!ext4_valid_inum(child->d_inode->i_sb, ino)) {
1076                 EXT4_ERROR_INODE(child->d_inode,
1077                                  "bad parent inode number: %u", ino);
1078                 return ERR_PTR(-EIO);
1079         }
1080
1081         return d_obtain_alias(ext4_iget_normal(child->d_inode->i_sb, ino));
1082 }
1083
1084 #define S_SHIFT 12
1085 static unsigned char ext4_type_by_mode[S_IFMT >> S_SHIFT] = {
1086         [S_IFREG >> S_SHIFT]    = EXT4_FT_REG_FILE,
1087         [S_IFDIR >> S_SHIFT]    = EXT4_FT_DIR,
1088         [S_IFCHR >> S_SHIFT]    = EXT4_FT_CHRDEV,
1089         [S_IFBLK >> S_SHIFT]    = EXT4_FT_BLKDEV,
1090         [S_IFIFO >> S_SHIFT]    = EXT4_FT_FIFO,
1091         [S_IFSOCK >> S_SHIFT]   = EXT4_FT_SOCK,
1092         [S_IFLNK >> S_SHIFT]    = EXT4_FT_SYMLINK,
1093 };
1094
1095 static inline void ext4_set_de_type(struct super_block *sb,
1096                                 struct ext4_dir_entry_2 *de,
1097                                 umode_t mode) {
1098         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FILETYPE))
1099                 de->file_type = ext4_type_by_mode[(mode & S_IFMT)>>S_SHIFT];
1100 }
1101
1102 /*
1103  * Move count entries from end of map between two memory locations.
1104  * Returns pointer to last entry moved.
1105  */
1106 static struct ext4_dir_entry_2 *
1107 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1108                 unsigned blocksize)
1109 {
1110         unsigned rec_len = 0;
1111
1112         while (count--) {
1113                 struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1114                                                 (from + (map->offs<<2));
1115                 rec_len = EXT4_DIR_REC_LEN(de->name_len);
1116                 memcpy (to, de, rec_len);
1117                 ((struct ext4_dir_entry_2 *) to)->rec_len =
1118                                 ext4_rec_len_to_disk(rec_len, blocksize);
1119                 de->inode = 0;
1120                 map++;
1121                 to += rec_len;
1122         }
1123         return (struct ext4_dir_entry_2 *) (to - rec_len);
1124 }
1125
1126 /*
1127  * Compact each dir entry in the range to the minimal rec_len.
1128  * Returns pointer to last entry in range.
1129  */
1130 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1131 {
1132         struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1133         unsigned rec_len = 0;
1134
1135         prev = to = de;
1136         while ((char*)de < base + blocksize) {
1137                 next = ext4_next_entry(de, blocksize);
1138                 if (de->inode && de->name_len) {
1139                         rec_len = EXT4_DIR_REC_LEN(de->name_len);
1140                         if (de > to)
1141                                 memmove(to, de, rec_len);
1142                         to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1143                         prev = to;
1144                         to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1145                 }
1146                 de = next;
1147         }
1148         return prev;
1149 }
1150
1151 /*
1152  * Split a full leaf block to make room for a new dir entry.
1153  * Allocate a new block, and move entries so that they are approx. equally full.
1154  * Returns pointer to de in block into which the new entry will be inserted.
1155  */
1156 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1157                         struct buffer_head **bh,struct dx_frame *frame,
1158                         struct dx_hash_info *hinfo, int *error)
1159 {
1160         unsigned blocksize = dir->i_sb->s_blocksize;
1161         unsigned count, continued;
1162         struct buffer_head *bh2;
1163         ext4_lblk_t newblock;
1164         u32 hash2;
1165         struct dx_map_entry *map;
1166         char *data1 = (*bh)->b_data, *data2;
1167         unsigned split, move, size;
1168         struct ext4_dir_entry_2 *de = NULL, *de2;
1169         int     err = 0, i;
1170
1171         bh2 = ext4_append (handle, dir, &newblock, &err);
1172         if (!(bh2)) {
1173                 brelse(*bh);
1174                 *bh = NULL;
1175                 goto errout;
1176         }
1177
1178         BUFFER_TRACE(*bh, "get_write_access");
1179         err = ext4_journal_get_write_access(handle, *bh);
1180         if (err)
1181                 goto journal_error;
1182
1183         BUFFER_TRACE(frame->bh, "get_write_access");
1184         err = ext4_journal_get_write_access(handle, frame->bh);
1185         if (err)
1186                 goto journal_error;
1187
1188         data2 = bh2->b_data;
1189
1190         /* create map in the end of data2 block */
1191         map = (struct dx_map_entry *) (data2 + blocksize);
1192         count = dx_make_map((struct ext4_dir_entry_2 *) data1,
1193                              blocksize, hinfo, map);
1194         map -= count;
1195         dx_sort_map(map, count);
1196         /* Split the existing block in the middle, size-wise */
1197         size = 0;
1198         move = 0;
1199         for (i = count-1; i >= 0; i--) {
1200                 /* is more than half of this entry in 2nd half of the block? */
1201                 if (size + map[i].size/2 > blocksize/2)
1202                         break;
1203                 size += map[i].size;
1204                 move++;
1205         }
1206         /* map index at which we will split */
1207         split = count - move;
1208         hash2 = map[split].hash;
1209         continued = hash2 == map[split - 1].hash;
1210         dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1211                         (unsigned long)dx_get_block(frame->at),
1212                                         hash2, split, count-split));
1213
1214         /* Fancy dance to stay within two buffers */
1215         de2 = dx_move_dirents(data1, data2, map + split, count - split, blocksize);
1216         de = dx_pack_dirents(data1, blocksize);
1217         de->rec_len = ext4_rec_len_to_disk(data1 + blocksize - (char *) de,
1218                                            blocksize);
1219         de2->rec_len = ext4_rec_len_to_disk(data2 + blocksize - (char *) de2,
1220                                             blocksize);
1221         dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data1, blocksize, 1));
1222         dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data2, blocksize, 1));
1223
1224         /* Which block gets the new entry? */
1225         if (hinfo->hash >= hash2)
1226         {
1227                 swap(*bh, bh2);
1228                 de = de2;
1229         }
1230         dx_insert_block(frame, hash2 + continued, newblock);
1231         err = ext4_handle_dirty_metadata(handle, dir, bh2);
1232         if (err)
1233                 goto journal_error;
1234         err = ext4_handle_dirty_metadata(handle, dir, frame->bh);
1235         if (err)
1236                 goto journal_error;
1237         brelse(bh2);
1238         dxtrace(dx_show_index("frame", frame->entries));
1239         return de;
1240
1241 journal_error:
1242         brelse(*bh);
1243         brelse(bh2);
1244         *bh = NULL;
1245         ext4_std_error(dir->i_sb, err);
1246 errout:
1247         *error = err;
1248         return NULL;
1249 }
1250
1251 /*
1252  * Add a new entry into a directory (leaf) block.  If de is non-NULL,
1253  * it points to a directory entry which is guaranteed to be large
1254  * enough for new directory entry.  If de is NULL, then
1255  * add_dirent_to_buf will attempt search the directory block for
1256  * space.  It will return -ENOSPC if no space is available, and -EIO
1257  * and -EEXIST if directory entry already exists.
1258  */
1259 static int add_dirent_to_buf(handle_t *handle, struct dentry *dentry,
1260                              struct inode *inode, struct ext4_dir_entry_2 *de,
1261                              struct buffer_head *bh)
1262 {
1263         struct inode    *dir = dentry->d_parent->d_inode;
1264         const char      *name = dentry->d_name.name;
1265         int             namelen = dentry->d_name.len;
1266         unsigned int    offset = 0;
1267         unsigned int    blocksize = dir->i_sb->s_blocksize;
1268         unsigned short  reclen;
1269         int             nlen, rlen, err;
1270         char            *top;
1271
1272         reclen = EXT4_DIR_REC_LEN(namelen);
1273         if (!de) {
1274                 de = (struct ext4_dir_entry_2 *)bh->b_data;
1275                 top = bh->b_data + blocksize - reclen;
1276                 while ((char *) de <= top) {
1277                         if (ext4_check_dir_entry(dir, NULL, de, bh, offset))
1278                                 return -EIO;
1279                         if (ext4_match(namelen, name, de))
1280                                 return -EEXIST;
1281                         nlen = EXT4_DIR_REC_LEN(de->name_len);
1282                         rlen = ext4_rec_len_from_disk(de->rec_len, blocksize);
1283                         if ((de->inode? rlen - nlen: rlen) >= reclen)
1284                                 break;
1285                         de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1286                         offset += rlen;
1287                 }
1288                 if ((char *) de > top)
1289                         return -ENOSPC;
1290         }
1291         BUFFER_TRACE(bh, "get_write_access");
1292         err = ext4_journal_get_write_access(handle, bh);
1293         if (err) {
1294                 ext4_std_error(dir->i_sb, err);
1295                 return err;
1296         }
1297
1298         /* By now the buffer is marked for journaling */
1299         nlen = EXT4_DIR_REC_LEN(de->name_len);
1300         rlen = ext4_rec_len_from_disk(de->rec_len, blocksize);
1301         if (de->inode) {
1302                 struct ext4_dir_entry_2 *de1 = (struct ext4_dir_entry_2 *)((char *)de + nlen);
1303                 de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, blocksize);
1304                 de->rec_len = ext4_rec_len_to_disk(nlen, blocksize);
1305                 de = de1;
1306         }
1307         de->file_type = EXT4_FT_UNKNOWN;
1308         if (inode) {
1309                 de->inode = cpu_to_le32(inode->i_ino);
1310                 ext4_set_de_type(dir->i_sb, de, inode->i_mode);
1311         } else
1312                 de->inode = 0;
1313         de->name_len = namelen;
1314         memcpy(de->name, name, namelen);
1315         /*
1316          * XXX shouldn't update any times until successful
1317          * completion of syscall, but too many callers depend
1318          * on this.
1319          *
1320          * XXX similarly, too many callers depend on
1321          * ext4_new_inode() setting the times, but error
1322          * recovery deletes the inode, so the worst that can
1323          * happen is that the times are slightly out of date
1324          * and/or different from the directory change time.
1325          */
1326         dir->i_mtime = dir->i_ctime = ext4_current_time(dir);
1327         ext4_update_dx_flag(dir);
1328         dir->i_version++;
1329         ext4_mark_inode_dirty(handle, dir);
1330         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1331         err = ext4_handle_dirty_metadata(handle, dir, bh);
1332         if (err)
1333                 ext4_std_error(dir->i_sb, err);
1334         return 0;
1335 }
1336
1337 /*
1338  * This converts a one block unindexed directory to a 3 block indexed
1339  * directory, and adds the dentry to the indexed directory.
1340  */
1341 static int make_indexed_dir(handle_t *handle, struct dentry *dentry,
1342                             struct inode *inode, struct buffer_head *bh)
1343 {
1344         struct inode    *dir = dentry->d_parent->d_inode;
1345         const char      *name = dentry->d_name.name;
1346         int             namelen = dentry->d_name.len;
1347         struct buffer_head *bh2;
1348         struct dx_root  *root;
1349         struct dx_frame frames[2], *frame;
1350         struct dx_entry *entries;
1351         struct ext4_dir_entry_2 *de, *de2;
1352         char            *data1, *top;
1353         unsigned        len;
1354         int             retval;
1355         unsigned        blocksize;
1356         struct dx_hash_info hinfo;
1357         ext4_lblk_t  block;
1358         struct fake_dirent *fde;
1359
1360         blocksize =  dir->i_sb->s_blocksize;
1361         dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
1362         retval = ext4_journal_get_write_access(handle, bh);
1363         if (retval) {
1364                 ext4_std_error(dir->i_sb, retval);
1365                 brelse(bh);
1366                 return retval;
1367         }
1368         root = (struct dx_root *) bh->b_data;
1369
1370         /* The 0th block becomes the root, move the dirents out */
1371         fde = &root->dotdot;
1372         de = (struct ext4_dir_entry_2 *)((char *)fde +
1373                 ext4_rec_len_from_disk(fde->rec_len, blocksize));
1374         if ((char *) de >= (((char *) root) + blocksize)) {
1375                 EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
1376                 brelse(bh);
1377                 return -EIO;
1378         }
1379         len = ((char *) root) + blocksize - (char *) de;
1380
1381         /* Allocate new block for the 0th block's dirents */
1382         bh2 = ext4_append(handle, dir, &block, &retval);
1383         if (!(bh2)) {
1384                 brelse(bh);
1385                 return retval;
1386         }
1387         ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
1388         data1 = bh2->b_data;
1389
1390         memcpy (data1, de, len);
1391         de = (struct ext4_dir_entry_2 *) data1;
1392         top = data1 + len;
1393         while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
1394                 de = de2;
1395         de->rec_len = ext4_rec_len_to_disk(data1 + blocksize - (char *) de,
1396                                            blocksize);
1397         /* Initialize the root; the dot dirents already exist */
1398         de = (struct ext4_dir_entry_2 *) (&root->dotdot);
1399         de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
1400                                            blocksize);
1401         memset (&root->info, 0, sizeof(root->info));
1402         root->info.info_length = sizeof(root->info);
1403         root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1404         entries = root->entries;
1405         dx_set_block(entries, 1);
1406         dx_set_count(entries, 1);
1407         dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
1408
1409         /* Initialize as for dx_probe */
1410         hinfo.hash_version = root->info.hash_version;
1411         if (hinfo.hash_version <= DX_HASH_TEA)
1412                 hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
1413         hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1414         ext4fs_dirhash(name, namelen, &hinfo);
1415         memset(frames, 0, sizeof(frames));
1416         frame = frames;
1417         frame->entries = entries;
1418         frame->at = entries;
1419         frame->bh = bh;
1420
1421         retval = ext4_handle_dirty_metadata(handle, dir, frame->bh);
1422         if (retval)
1423                 goto out_frames;        
1424         retval = ext4_handle_dirty_metadata(handle, dir, bh2);
1425         if (retval)
1426                 goto out_frames;        
1427
1428         de = do_split(handle,dir, &bh2, frame, &hinfo, &retval);
1429         if (!de) {
1430                 goto out_frames;
1431         }
1432
1433         retval = add_dirent_to_buf(handle, dentry, inode, de, bh2);
1434 out_frames:
1435         /*
1436          * Even if the block split failed, we have to properly write
1437          * out all the changes we did so far. Otherwise we can end up
1438          * with corrupted filesystem.
1439          */
1440         if (retval)
1441                 ext4_mark_inode_dirty(handle, dir);
1442         dx_release(frames);
1443         brelse(bh2);
1444         return retval;
1445 }
1446
1447 /*
1448  *      ext4_add_entry()
1449  *
1450  * adds a file entry to the specified directory, using the same
1451  * semantics as ext4_find_entry(). It returns NULL if it failed.
1452  *
1453  * NOTE!! The inode part of 'de' is left at 0 - which means you
1454  * may not sleep between calling this and putting something into
1455  * the entry, as someone else might have used it while you slept.
1456  */
1457 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
1458                           struct inode *inode)
1459 {
1460         struct inode *dir = dentry->d_parent->d_inode;
1461         struct buffer_head *bh = NULL;
1462         struct ext4_dir_entry_2 *de;
1463         struct super_block *sb;
1464         int     retval;
1465         int     dx_fallback=0;
1466         unsigned blocksize;
1467         ext4_lblk_t block, blocks;
1468
1469         sb = dir->i_sb;
1470         blocksize = sb->s_blocksize;
1471         if (!dentry->d_name.len)
1472                 return -EINVAL;
1473         if (is_dx(dir)) {
1474                 retval = ext4_dx_add_entry(handle, dentry, inode);
1475                 if (!retval || (retval != ERR_BAD_DX_DIR))
1476                         goto out;
1477                 ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
1478                 dx_fallback++;
1479                 ext4_mark_inode_dirty(handle, dir);
1480         }
1481         blocks = dir->i_size >> sb->s_blocksize_bits;
1482         for (block = 0; block < blocks; block++) {
1483                 bh = ext4_bread(handle, dir, block, 0, &retval);
1484                 if(!bh)
1485                         return retval;
1486                 retval = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
1487                 if (retval != -ENOSPC)
1488                         goto out;
1489
1490                 if (blocks == 1 && !dx_fallback &&
1491                     EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_DIR_INDEX)) {
1492                         retval = make_indexed_dir(handle, dentry, inode, bh);
1493                         bh = NULL; /* make_indexed_dir releases bh */
1494                         goto out;
1495                 }
1496                 brelse(bh);
1497         }
1498         bh = ext4_append(handle, dir, &block, &retval);
1499         if (!bh)
1500                 return retval;
1501         de = (struct ext4_dir_entry_2 *) bh->b_data;
1502         de->inode = 0;
1503         de->rec_len = ext4_rec_len_to_disk(blocksize, blocksize);
1504         retval = add_dirent_to_buf(handle, dentry, inode, de, bh);
1505 out:
1506         brelse(bh);
1507         if (retval == 0)
1508                 ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
1509         return retval;
1510 }
1511
1512 /*
1513  * Returns 0 for success, or a negative error value
1514  */
1515 static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry,
1516                              struct inode *inode)
1517 {
1518         struct dx_frame frames[2], *frame;
1519         struct dx_entry *entries, *at;
1520         struct dx_hash_info hinfo;
1521         struct buffer_head *bh;
1522         struct inode *dir = dentry->d_parent->d_inode;
1523         struct super_block *sb = dir->i_sb;
1524         struct ext4_dir_entry_2 *de;
1525         int err;
1526
1527         frame = dx_probe(&dentry->d_name, dir, &hinfo, frames, &err);
1528         if (!frame)
1529                 return err;
1530         entries = frame->entries;
1531         at = frame->at;
1532
1533         if (!(bh = ext4_bread(handle,dir, dx_get_block(frame->at), 0, &err)))
1534                 goto cleanup;
1535
1536         BUFFER_TRACE(bh, "get_write_access");
1537         err = ext4_journal_get_write_access(handle, bh);
1538         if (err)
1539                 goto journal_error;
1540
1541         err = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
1542         if (err != -ENOSPC)
1543                 goto cleanup;
1544
1545         /* Block full, should compress but for now just split */
1546         dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
1547                        dx_get_count(entries), dx_get_limit(entries)));
1548         /* Need to split index? */
1549         if (dx_get_count(entries) == dx_get_limit(entries)) {
1550                 ext4_lblk_t newblock;
1551                 unsigned icount = dx_get_count(entries);
1552                 int levels = frame - frames;
1553                 struct dx_entry *entries2;
1554                 struct dx_node *node2;
1555                 struct buffer_head *bh2;
1556
1557                 if (levels && (dx_get_count(frames->entries) ==
1558                                dx_get_limit(frames->entries))) {
1559                         ext4_warning(sb, "Directory index full!");
1560                         err = -ENOSPC;
1561                         goto cleanup;
1562                 }
1563                 bh2 = ext4_append (handle, dir, &newblock, &err);
1564                 if (!(bh2))
1565                         goto cleanup;
1566                 node2 = (struct dx_node *)(bh2->b_data);
1567                 entries2 = node2->entries;
1568                 memset(&node2->fake, 0, sizeof(struct fake_dirent));
1569                 node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
1570                                                            sb->s_blocksize);
1571                 BUFFER_TRACE(frame->bh, "get_write_access");
1572                 err = ext4_journal_get_write_access(handle, frame->bh);
1573                 if (err)
1574                         goto journal_error;
1575                 if (levels) {
1576                         unsigned icount1 = icount/2, icount2 = icount - icount1;
1577                         unsigned hash2 = dx_get_hash(entries + icount1);
1578                         dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
1579                                        icount1, icount2));
1580
1581                         BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
1582                         err = ext4_journal_get_write_access(handle,
1583                                                              frames[0].bh);
1584                         if (err)
1585                                 goto journal_error;
1586
1587                         memcpy((char *) entries2, (char *) (entries + icount1),
1588                                icount2 * sizeof(struct dx_entry));
1589                         dx_set_count(entries, icount1);
1590                         dx_set_count(entries2, icount2);
1591                         dx_set_limit(entries2, dx_node_limit(dir));
1592
1593                         /* Which index block gets the new entry? */
1594                         if (at - entries >= icount1) {
1595                                 frame->at = at = at - entries - icount1 + entries2;
1596                                 frame->entries = entries = entries2;
1597                                 swap(frame->bh, bh2);
1598                         }
1599                         dx_insert_block(frames + 0, hash2, newblock);
1600                         dxtrace(dx_show_index("node", frames[1].entries));
1601                         dxtrace(dx_show_index("node",
1602                                ((struct dx_node *) bh2->b_data)->entries));
1603                         err = ext4_handle_dirty_metadata(handle, dir, bh2);
1604                         if (err)
1605                                 goto journal_error;
1606                         brelse (bh2);
1607                 } else {
1608                         dxtrace(printk(KERN_DEBUG
1609                                        "Creating second level index...\n"));
1610                         memcpy((char *) entries2, (char *) entries,
1611                                icount * sizeof(struct dx_entry));
1612                         dx_set_limit(entries2, dx_node_limit(dir));
1613
1614                         /* Set up root */
1615                         dx_set_count(entries, 1);
1616                         dx_set_block(entries + 0, newblock);
1617                         ((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1;
1618
1619                         /* Add new access path frame */
1620                         frame = frames + 1;
1621                         frame->at = at = at - entries + entries2;
1622                         frame->entries = entries = entries2;
1623                         frame->bh = bh2;
1624                         err = ext4_journal_get_write_access(handle,
1625                                                              frame->bh);
1626                         if (err)
1627                                 goto journal_error;
1628                 }
1629                 err = ext4_handle_dirty_metadata(handle, dir, frames[0].bh);
1630                 if (err) {
1631                         ext4_std_error(inode->i_sb, err);
1632                         goto cleanup;
1633                 }
1634         }
1635         de = do_split(handle, dir, &bh, frame, &hinfo, &err);
1636         if (!de)
1637                 goto cleanup;
1638         err = add_dirent_to_buf(handle, dentry, inode, de, bh);
1639         goto cleanup;
1640
1641 journal_error:
1642         ext4_std_error(dir->i_sb, err);
1643 cleanup:
1644         if (bh)
1645                 brelse(bh);
1646         dx_release(frames);
1647         return err;
1648 }
1649
1650 /*
1651  * ext4_delete_entry deletes a directory entry by merging it with the
1652  * previous entry
1653  */
1654 static int ext4_delete_entry(handle_t *handle,
1655                              struct inode *dir,
1656                              struct ext4_dir_entry_2 *de_del,
1657                              struct buffer_head *bh)
1658 {
1659         struct ext4_dir_entry_2 *de, *pde;
1660         unsigned int blocksize = dir->i_sb->s_blocksize;
1661         int i, err;
1662
1663         i = 0;
1664         pde = NULL;
1665         de = (struct ext4_dir_entry_2 *) bh->b_data;
1666         while (i < bh->b_size) {
1667                 if (ext4_check_dir_entry(dir, NULL, de, bh, i))
1668                         return -EIO;
1669                 if (de == de_del)  {
1670                         BUFFER_TRACE(bh, "get_write_access");
1671                         err = ext4_journal_get_write_access(handle, bh);
1672                         if (unlikely(err)) {
1673                                 ext4_std_error(dir->i_sb, err);
1674                                 return err;
1675                         }
1676                         if (pde)
1677                                 pde->rec_len = ext4_rec_len_to_disk(
1678                                         ext4_rec_len_from_disk(pde->rec_len,
1679                                                                blocksize) +
1680                                         ext4_rec_len_from_disk(de->rec_len,
1681                                                                blocksize),
1682                                         blocksize);
1683                         else
1684                                 de->inode = 0;
1685                         dir->i_version++;
1686                         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1687                         err = ext4_handle_dirty_metadata(handle, dir, bh);
1688                         if (unlikely(err)) {
1689                                 ext4_std_error(dir->i_sb, err);
1690                                 return err;
1691                         }
1692                         return 0;
1693                 }
1694                 i += ext4_rec_len_from_disk(de->rec_len, blocksize);
1695                 pde = de;
1696                 de = ext4_next_entry(de, blocksize);
1697         }
1698         return -ENOENT;
1699 }
1700
1701 /*
1702  * DIR_NLINK feature is set if 1) nlinks > EXT4_LINK_MAX or 2) nlinks == 2,
1703  * since this indicates that nlinks count was previously 1.
1704  */
1705 static void ext4_inc_count(handle_t *handle, struct inode *inode)
1706 {
1707         inc_nlink(inode);
1708         if (is_dx(inode) && inode->i_nlink > 1) {
1709                 /* limit is 16-bit i_links_count */
1710                 if (inode->i_nlink >= EXT4_LINK_MAX || inode->i_nlink == 2) {
1711                         set_nlink(inode, 1);
1712                         EXT4_SET_RO_COMPAT_FEATURE(inode->i_sb,
1713                                               EXT4_FEATURE_RO_COMPAT_DIR_NLINK);
1714                 }
1715         }
1716 }
1717
1718 /*
1719  * If a directory had nlink == 1, then we should let it be 1. This indicates
1720  * directory has >EXT4_LINK_MAX subdirs.
1721  */
1722 static void ext4_dec_count(handle_t *handle, struct inode *inode)
1723 {
1724         if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
1725                 drop_nlink(inode);
1726 }
1727
1728
1729 static int ext4_add_nondir(handle_t *handle,
1730                 struct dentry *dentry, struct inode *inode)
1731 {
1732         int err = ext4_add_entry(handle, dentry, inode);
1733         if (!err) {
1734                 ext4_mark_inode_dirty(handle, inode);
1735                 d_instantiate(dentry, inode);
1736                 unlock_new_inode(inode);
1737                 return 0;
1738         }
1739         drop_nlink(inode);
1740         unlock_new_inode(inode);
1741         iput(inode);
1742         return err;
1743 }
1744
1745 /*
1746  * By the time this is called, we already have created
1747  * the directory cache entry for the new file, but it
1748  * is so far negative - it has no inode.
1749  *
1750  * If the create succeeds, we fill in the inode information
1751  * with d_instantiate().
1752  */
1753 static int ext4_create(struct inode *dir, struct dentry *dentry, int mode,
1754                        struct nameidata *nd)
1755 {
1756         handle_t *handle;
1757         struct inode *inode;
1758         int err, retries = 0;
1759
1760         dquot_initialize(dir);
1761
1762 retry:
1763         handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
1764                                         EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1765                                         EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
1766         if (IS_ERR(handle))
1767                 return PTR_ERR(handle);
1768
1769         if (IS_DIRSYNC(dir))
1770                 ext4_handle_sync(handle);
1771
1772         inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0, NULL);
1773         err = PTR_ERR(inode);
1774         if (!IS_ERR(inode)) {
1775                 inode->i_op = &ext4_file_inode_operations;
1776                 inode->i_fop = &ext4_file_operations;
1777                 ext4_set_aops(inode);
1778                 err = ext4_add_nondir(handle, dentry, inode);
1779         }
1780         ext4_journal_stop(handle);
1781         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
1782                 goto retry;
1783         return err;
1784 }
1785
1786 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
1787                       int mode, dev_t rdev)
1788 {
1789         handle_t *handle;
1790         struct inode *inode;
1791         int err, retries = 0;
1792
1793         if (!new_valid_dev(rdev))
1794                 return -EINVAL;
1795
1796         dquot_initialize(dir);
1797
1798 retry:
1799         handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
1800                                         EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1801                                         EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
1802         if (IS_ERR(handle))
1803                 return PTR_ERR(handle);
1804
1805         if (IS_DIRSYNC(dir))
1806                 ext4_handle_sync(handle);
1807
1808         inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0, NULL);
1809         err = PTR_ERR(inode);
1810         if (!IS_ERR(inode)) {
1811                 init_special_inode(inode, inode->i_mode, rdev);
1812                 inode->i_op = &ext4_special_inode_operations;
1813                 err = ext4_add_nondir(handle, dentry, inode);
1814         }
1815         ext4_journal_stop(handle);
1816         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
1817                 goto retry;
1818         return err;
1819 }
1820
1821 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1822 {
1823         handle_t *handle;
1824         struct inode *inode;
1825         struct buffer_head *dir_block = NULL;
1826         struct ext4_dir_entry_2 *de;
1827         unsigned int blocksize = dir->i_sb->s_blocksize;
1828         int err, retries = 0;
1829
1830         if (EXT4_DIR_LINK_MAX(dir))
1831                 return -EMLINK;
1832
1833         dquot_initialize(dir);
1834
1835 retry:
1836         handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
1837                                         EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1838                                         EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb));
1839         if (IS_ERR(handle))
1840                 return PTR_ERR(handle);
1841
1842         if (IS_DIRSYNC(dir))
1843                 ext4_handle_sync(handle);
1844
1845         inode = ext4_new_inode(handle, dir, S_IFDIR | mode,
1846                                &dentry->d_name, 0, NULL);
1847         err = PTR_ERR(inode);
1848         if (IS_ERR(inode))
1849                 goto out_stop;
1850
1851         inode->i_op = &ext4_dir_inode_operations;
1852         inode->i_fop = &ext4_dir_operations;
1853         inode->i_size = EXT4_I(inode)->i_disksize = inode->i_sb->s_blocksize;
1854         dir_block = ext4_bread(handle, inode, 0, 1, &err);
1855         if (!dir_block)
1856                 goto out_clear_inode;
1857         BUFFER_TRACE(dir_block, "get_write_access");
1858         err = ext4_journal_get_write_access(handle, dir_block);
1859         if (err)
1860                 goto out_clear_inode;
1861         de = (struct ext4_dir_entry_2 *) dir_block->b_data;
1862         de->inode = cpu_to_le32(inode->i_ino);
1863         de->name_len = 1;
1864         de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
1865                                            blocksize);
1866         strcpy(de->name, ".");
1867         ext4_set_de_type(dir->i_sb, de, S_IFDIR);
1868         de = ext4_next_entry(de, blocksize);
1869         de->inode = cpu_to_le32(dir->i_ino);
1870         de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(1),
1871                                            blocksize);
1872         de->name_len = 2;
1873         strcpy(de->name, "..");
1874         ext4_set_de_type(dir->i_sb, de, S_IFDIR);
1875         set_nlink(inode, 2);
1876         BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
1877         err = ext4_handle_dirty_metadata(handle, inode, dir_block);
1878         if (err)
1879                 goto out_clear_inode;
1880         err = ext4_mark_inode_dirty(handle, inode);
1881         if (!err)
1882                 err = ext4_add_entry(handle, dentry, inode);
1883         if (err) {
1884 out_clear_inode:
1885                 clear_nlink(inode);
1886                 unlock_new_inode(inode);
1887                 ext4_mark_inode_dirty(handle, inode);
1888                 iput(inode);
1889                 goto out_stop;
1890         }
1891         ext4_inc_count(handle, dir);
1892         ext4_update_dx_flag(dir);
1893         err = ext4_mark_inode_dirty(handle, dir);
1894         if (err)
1895                 goto out_clear_inode;
1896         d_instantiate(dentry, inode);
1897         unlock_new_inode(inode);
1898 out_stop:
1899         brelse(dir_block);
1900         ext4_journal_stop(handle);
1901         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
1902                 goto retry;
1903         return err;
1904 }
1905
1906 /*
1907  * routine to check that the specified directory is empty (for rmdir)
1908  */
1909 static int empty_dir(struct inode *inode)
1910 {
1911         unsigned int offset;
1912         struct buffer_head *bh;
1913         struct ext4_dir_entry_2 *de, *de1;
1914         struct super_block *sb;
1915         int err = 0;
1916
1917         sb = inode->i_sb;
1918         if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2) ||
1919             !(bh = ext4_bread(NULL, inode, 0, 0, &err))) {
1920                 if (err)
1921                         EXT4_ERROR_INODE(inode,
1922                                 "error %d reading directory lblock 0", err);
1923                 else
1924                         ext4_warning(inode->i_sb,
1925                                      "bad directory (dir #%lu) - no data block",
1926                                      inode->i_ino);
1927                 return 1;
1928         }
1929         de = (struct ext4_dir_entry_2 *) bh->b_data;
1930         de1 = ext4_next_entry(de, sb->s_blocksize);
1931         if (le32_to_cpu(de->inode) != inode->i_ino ||
1932                         !le32_to_cpu(de1->inode) ||
1933                         strcmp(".", de->name) ||
1934                         strcmp("..", de1->name)) {
1935                 ext4_warning(inode->i_sb,
1936                              "bad directory (dir #%lu) - no `.' or `..'",
1937                              inode->i_ino);
1938                 brelse(bh);
1939                 return 1;
1940         }
1941         offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
1942                  ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
1943         de = ext4_next_entry(de1, sb->s_blocksize);
1944         while (offset < inode->i_size) {
1945                 if (!bh ||
1946                     (void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
1947                         unsigned int lblock;
1948                         err = 0;
1949                         brelse(bh);
1950                         lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
1951                         bh = ext4_bread(NULL, inode, lblock, 0, &err);
1952                         if (!bh) {
1953                                 if (err)
1954                                         EXT4_ERROR_INODE(inode,
1955                                                 "error %d reading directory "
1956                                                 "lblock %u", err, lblock);
1957                                 offset += sb->s_blocksize;
1958                                 continue;
1959                         }
1960                         de = (struct ext4_dir_entry_2 *) bh->b_data;
1961                 }
1962                 if (ext4_check_dir_entry(inode, NULL, de, bh, offset)) {
1963                         de = (struct ext4_dir_entry_2 *)(bh->b_data +
1964                                                          sb->s_blocksize);
1965                         offset = (offset | (sb->s_blocksize - 1)) + 1;
1966                         continue;
1967                 }
1968                 if (le32_to_cpu(de->inode)) {
1969                         brelse(bh);
1970                         return 0;
1971                 }
1972                 offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
1973                 de = ext4_next_entry(de, sb->s_blocksize);
1974         }
1975         brelse(bh);
1976         return 1;
1977 }
1978
1979 /* ext4_orphan_add() links an unlinked or truncated inode into a list of
1980  * such inodes, starting at the superblock, in case we crash before the
1981  * file is closed/deleted, or in case the inode truncate spans multiple
1982  * transactions and the last transaction is not recovered after a crash.
1983  *
1984  * At filesystem recovery time, we walk this list deleting unlinked
1985  * inodes and truncating linked inodes in ext4_orphan_cleanup().
1986  */
1987 int ext4_orphan_add(handle_t *handle, struct inode *inode)
1988 {
1989         struct super_block *sb = inode->i_sb;
1990         struct ext4_iloc iloc;
1991         int err = 0, rc;
1992
1993         if (!EXT4_SB(sb)->s_journal || is_bad_inode(inode))
1994                 return 0;
1995
1996         mutex_lock(&EXT4_SB(sb)->s_orphan_lock);
1997         if (!list_empty(&EXT4_I(inode)->i_orphan))
1998                 goto out_unlock;
1999
2000         /*
2001          * Orphan handling is only valid for files with data blocks
2002          * being truncated, or files being unlinked. Note that we either
2003          * hold i_mutex, or the inode can not be referenced from outside,
2004          * so i_nlink should not be bumped due to race
2005          */
2006         J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2007                   S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2008
2009         BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
2010         err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
2011         if (err)
2012                 goto out_unlock;
2013
2014         err = ext4_reserve_inode_write(handle, inode, &iloc);
2015         if (err)
2016                 goto out_unlock;
2017         /*
2018          * Due to previous errors inode may be already a part of on-disk
2019          * orphan list. If so skip on-disk list modification.
2020          */
2021         if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <=
2022                 (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)))
2023                         goto mem_insert;
2024
2025         /* Insert this inode at the head of the on-disk orphan list... */
2026         NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan);
2027         EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2028         err = ext4_handle_dirty_metadata(handle, NULL, EXT4_SB(sb)->s_sbh);
2029         rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2030         if (!err)
2031                 err = rc;
2032
2033         /* Only add to the head of the in-memory list if all the
2034          * previous operations succeeded.  If the orphan_add is going to
2035          * fail (possibly taking the journal offline), we can't risk
2036          * leaving the inode on the orphan list: stray orphan-list
2037          * entries can cause panics at unmount time.
2038          *
2039          * This is safe: on error we're going to ignore the orphan list
2040          * anyway on the next recovery. */
2041 mem_insert:
2042         if (!err)
2043                 list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
2044
2045         jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2046         jbd_debug(4, "orphan inode %lu will point to %d\n",
2047                         inode->i_ino, NEXT_ORPHAN(inode));
2048 out_unlock:
2049         mutex_unlock(&EXT4_SB(sb)->s_orphan_lock);
2050         ext4_std_error(inode->i_sb, err);
2051         return err;
2052 }
2053
2054 /*
2055  * ext4_orphan_del() removes an unlinked or truncated inode from the list
2056  * of such inodes stored on disk, because it is finally being cleaned up.
2057  */
2058 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2059 {
2060         struct list_head *prev;
2061         struct ext4_inode_info *ei = EXT4_I(inode);
2062         struct ext4_sb_info *sbi;
2063         __u32 ino_next;
2064         struct ext4_iloc iloc;
2065         int err = 0;
2066
2067         if (!EXT4_SB(inode->i_sb)->s_journal &&
2068             !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS))
2069                 return 0;
2070
2071         mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
2072         if (list_empty(&ei->i_orphan))
2073                 goto out;
2074
2075         ino_next = NEXT_ORPHAN(inode);
2076         prev = ei->i_orphan.prev;
2077         sbi = EXT4_SB(inode->i_sb);
2078
2079         jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2080
2081         list_del_init(&ei->i_orphan);
2082
2083         /* If we're on an error path, we may not have a valid
2084          * transaction handle with which to update the orphan list on
2085          * disk, but we still need to remove the inode from the linked
2086          * list in memory. */
2087         if (!handle)
2088                 goto out;
2089
2090         err = ext4_reserve_inode_write(handle, inode, &iloc);
2091         if (err)
2092                 goto out_err;
2093
2094         if (prev == &sbi->s_orphan) {
2095                 jbd_debug(4, "superblock will point to %u\n", ino_next);
2096                 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2097                 err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2098                 if (err)
2099                         goto out_brelse;
2100                 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2101                 err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
2102         } else {
2103                 struct ext4_iloc iloc2;
2104                 struct inode *i_prev =
2105                         &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2106
2107                 jbd_debug(4, "orphan inode %lu will point to %u\n",
2108                           i_prev->i_ino, ino_next);
2109                 err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2110                 if (err)
2111                         goto out_brelse;
2112                 NEXT_ORPHAN(i_prev) = ino_next;
2113                 err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2114         }
2115         if (err)
2116                 goto out_brelse;
2117         NEXT_ORPHAN(inode) = 0;
2118         err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2119
2120 out_err:
2121         ext4_std_error(inode->i_sb, err);
2122 out:
2123         mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
2124         return err;
2125
2126 out_brelse:
2127         brelse(iloc.bh);
2128         goto out_err;
2129 }
2130
2131 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
2132 {
2133         int retval;
2134         struct inode *inode;
2135         struct buffer_head *bh;
2136         struct ext4_dir_entry_2 *de;
2137         handle_t *handle;
2138
2139         /* Initialize quotas before so that eventual writes go in
2140          * separate transaction */
2141         dquot_initialize(dir);
2142         dquot_initialize(dentry->d_inode);
2143
2144         handle = ext4_journal_start(dir, EXT4_DELETE_TRANS_BLOCKS(dir->i_sb));
2145         if (IS_ERR(handle))
2146                 return PTR_ERR(handle);
2147
2148         retval = -ENOENT;
2149         bh = ext4_find_entry(dir, &dentry->d_name, &de);
2150         if (!bh)
2151                 goto end_rmdir;
2152
2153         if (IS_DIRSYNC(dir))
2154                 ext4_handle_sync(handle);
2155
2156         inode = dentry->d_inode;
2157
2158         retval = -EIO;
2159         if (le32_to_cpu(de->inode) != inode->i_ino)
2160                 goto end_rmdir;
2161
2162         retval = -ENOTEMPTY;
2163         if (!empty_dir(inode))
2164                 goto end_rmdir;
2165
2166         retval = ext4_delete_entry(handle, dir, de, bh);
2167         if (retval)
2168                 goto end_rmdir;
2169         if (!EXT4_DIR_LINK_EMPTY(inode))
2170                 ext4_warning(inode->i_sb,
2171                              "empty directory has too many links (%d)",
2172                              inode->i_nlink);
2173         inode->i_version++;
2174         clear_nlink(inode);
2175         /* There's no need to set i_disksize: the fact that i_nlink is
2176          * zero will ensure that the right thing happens during any
2177          * recovery. */
2178         inode->i_size = 0;
2179         ext4_orphan_add(handle, inode);
2180         inode->i_ctime = dir->i_ctime = dir->i_mtime = ext4_current_time(inode);
2181         ext4_mark_inode_dirty(handle, inode);
2182         ext4_dec_count(handle, dir);
2183         ext4_update_dx_flag(dir);
2184         ext4_mark_inode_dirty(handle, dir);
2185
2186 end_rmdir:
2187         ext4_journal_stop(handle);
2188         brelse(bh);
2189         return retval;
2190 }
2191
2192 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
2193 {
2194         int retval;
2195         struct inode *inode;
2196         struct buffer_head *bh;
2197         struct ext4_dir_entry_2 *de;
2198         handle_t *handle;
2199
2200         trace_ext4_unlink_enter(dir, dentry);
2201         /* Initialize quotas before so that eventual writes go
2202          * in separate transaction */
2203         dquot_initialize(dir);
2204         dquot_initialize(dentry->d_inode);
2205
2206         handle = ext4_journal_start(dir, EXT4_DELETE_TRANS_BLOCKS(dir->i_sb));
2207         if (IS_ERR(handle))
2208                 return PTR_ERR(handle);
2209
2210         if (IS_DIRSYNC(dir))
2211                 ext4_handle_sync(handle);
2212
2213         retval = -ENOENT;
2214         bh = ext4_find_entry(dir, &dentry->d_name, &de);
2215         if (!bh)
2216                 goto end_unlink;
2217
2218         inode = dentry->d_inode;
2219
2220         retval = -EIO;
2221         if (le32_to_cpu(de->inode) != inode->i_ino)
2222                 goto end_unlink;
2223
2224         if (!inode->i_nlink) {
2225                 ext4_warning(inode->i_sb,
2226                              "Deleting nonexistent file (%lu), %d",
2227                              inode->i_ino, inode->i_nlink);
2228                 set_nlink(inode, 1);
2229         }
2230         retval = ext4_delete_entry(handle, dir, de, bh);
2231         if (retval)
2232                 goto end_unlink;
2233         dir->i_ctime = dir->i_mtime = ext4_current_time(dir);
2234         ext4_update_dx_flag(dir);
2235         ext4_mark_inode_dirty(handle, dir);
2236         drop_nlink(inode);
2237         if (!inode->i_nlink)
2238                 ext4_orphan_add(handle, inode);
2239         inode->i_ctime = ext4_current_time(inode);
2240         ext4_mark_inode_dirty(handle, inode);
2241         retval = 0;
2242
2243 end_unlink:
2244         ext4_journal_stop(handle);
2245         brelse(bh);
2246         trace_ext4_unlink_exit(dentry, retval);
2247         return retval;
2248 }
2249
2250 static int ext4_symlink(struct inode *dir,
2251                         struct dentry *dentry, const char *symname)
2252 {
2253         handle_t *handle;
2254         struct inode *inode;
2255         int l, err, retries = 0;
2256         int credits;
2257
2258         l = strlen(symname)+1;
2259         if (l > dir->i_sb->s_blocksize)
2260                 return -ENAMETOOLONG;
2261
2262         dquot_initialize(dir);
2263
2264         if (l > EXT4_N_BLOCKS * 4) {
2265                 /*
2266                  * For non-fast symlinks, we just allocate inode and put it on
2267                  * orphan list in the first transaction => we need bitmap,
2268                  * group descriptor, sb, inode block, quota blocks, and
2269                  * possibly selinux xattr blocks.
2270                  */
2271                 credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2272                           EXT4_XATTR_TRANS_BLOCKS;
2273         } else {
2274                 /*
2275                  * Fast symlink. We have to add entry to directory
2276                  * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
2277                  * allocate new inode (bitmap, group descriptor, inode block,
2278                  * quota blocks, sb is already counted in previous macros).
2279                  */
2280                 credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2281                           EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 +
2282                           EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb);
2283         }
2284 retry:
2285         handle = ext4_journal_start(dir, credits);
2286         if (IS_ERR(handle))
2287                 return PTR_ERR(handle);
2288
2289         if (IS_DIRSYNC(dir))
2290                 ext4_handle_sync(handle);
2291
2292         inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO,
2293                                &dentry->d_name, 0, NULL);
2294         err = PTR_ERR(inode);
2295         if (IS_ERR(inode))
2296                 goto out_stop;
2297
2298         if (l > EXT4_N_BLOCKS * 4) {
2299                 inode->i_op = &ext4_symlink_inode_operations;
2300                 ext4_set_aops(inode);
2301                 /*
2302                  * We cannot call page_symlink() with transaction started
2303                  * because it calls into ext4_write_begin() which can wait
2304                  * for transaction commit if we are running out of space
2305                  * and thus we deadlock. So we have to stop transaction now
2306                  * and restart it when symlink contents is written.
2307                  * 
2308                  * To keep fs consistent in case of crash, we have to put inode
2309                  * to orphan list in the mean time.
2310                  */
2311                 drop_nlink(inode);
2312                 err = ext4_orphan_add(handle, inode);
2313                 ext4_journal_stop(handle);
2314                 if (err)
2315                         goto err_drop_inode;
2316                 err = __page_symlink(inode, symname, l, 1);
2317                 if (err)
2318                         goto err_drop_inode;
2319                 /*
2320                  * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
2321                  * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
2322                  */
2323                 handle = ext4_journal_start(dir,
2324                                 EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2325                                 EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
2326                 if (IS_ERR(handle)) {
2327                         err = PTR_ERR(handle);
2328                         goto err_drop_inode;
2329                 }
2330                 inc_nlink(inode);
2331                 err = ext4_orphan_del(handle, inode);
2332                 if (err) {
2333                         ext4_journal_stop(handle);
2334                         clear_nlink(inode);
2335                         goto err_drop_inode;
2336                 }
2337         } else {
2338                 /* clear the extent format for fast symlink */
2339                 ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
2340                 inode->i_op = &ext4_fast_symlink_inode_operations;
2341                 memcpy((char *)&EXT4_I(inode)->i_data, symname, l);
2342                 inode->i_size = l-1;
2343         }
2344         EXT4_I(inode)->i_disksize = inode->i_size;
2345         err = ext4_add_nondir(handle, dentry, inode);
2346 out_stop:
2347         ext4_journal_stop(handle);
2348         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2349                 goto retry;
2350         return err;
2351 err_drop_inode:
2352         unlock_new_inode(inode);
2353         iput(inode);
2354         return err;
2355 }
2356
2357 static int ext4_link(struct dentry *old_dentry,
2358                      struct inode *dir, struct dentry *dentry)
2359 {
2360         handle_t *handle;
2361         struct inode *inode = old_dentry->d_inode;
2362         int err, retries = 0;
2363
2364         if (inode->i_nlink >= EXT4_LINK_MAX)
2365                 return -EMLINK;
2366
2367         dquot_initialize(dir);
2368
2369 retry:
2370         handle = ext4_journal_start(dir, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2371                                         EXT4_INDEX_EXTRA_TRANS_BLOCKS);
2372         if (IS_ERR(handle))
2373                 return PTR_ERR(handle);
2374
2375         if (IS_DIRSYNC(dir))
2376                 ext4_handle_sync(handle);
2377
2378         inode->i_ctime = ext4_current_time(inode);
2379         ext4_inc_count(handle, inode);
2380         ihold(inode);
2381
2382         err = ext4_add_entry(handle, dentry, inode);
2383         if (!err) {
2384                 ext4_mark_inode_dirty(handle, inode);
2385                 d_instantiate(dentry, inode);
2386         } else {
2387                 drop_nlink(inode);
2388                 iput(inode);
2389         }
2390         ext4_journal_stop(handle);
2391         if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2392                 goto retry;
2393         return err;
2394 }
2395
2396 #define PARENT_INO(buffer, size) \
2397         (ext4_next_entry((struct ext4_dir_entry_2 *)(buffer), size)->inode)
2398
2399 /*
2400  * Anybody can rename anything with this: the permission checks are left to the
2401  * higher-level routines.
2402  */
2403 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
2404                        struct inode *new_dir, struct dentry *new_dentry)
2405 {
2406         handle_t *handle;
2407         struct inode *old_inode, *new_inode;
2408         struct buffer_head *old_bh, *new_bh, *dir_bh;
2409         struct ext4_dir_entry_2 *old_de, *new_de;
2410         int retval, force_da_alloc = 0;
2411
2412         dquot_initialize(old_dir);
2413         dquot_initialize(new_dir);
2414
2415         old_bh = new_bh = dir_bh = NULL;
2416
2417         /* Initialize quotas before so that eventual writes go
2418          * in separate transaction */
2419         if (new_dentry->d_inode)
2420                 dquot_initialize(new_dentry->d_inode);
2421         handle = ext4_journal_start(old_dir, 2 *
2422                                         EXT4_DATA_TRANS_BLOCKS(old_dir->i_sb) +
2423                                         EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
2424         if (IS_ERR(handle))
2425                 return PTR_ERR(handle);
2426
2427         if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir))
2428                 ext4_handle_sync(handle);
2429
2430         old_bh = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de);
2431         /*
2432          *  Check for inode number is _not_ due to possible IO errors.
2433          *  We might rmdir the source, keep it as pwd of some process
2434          *  and merrily kill the link to whatever was created under the
2435          *  same name. Goodbye sticky bit ;-<
2436          */
2437         old_inode = old_dentry->d_inode;
2438         retval = -ENOENT;
2439         if (!old_bh || le32_to_cpu(old_de->inode) != old_inode->i_ino)
2440                 goto end_rename;
2441
2442         new_inode = new_dentry->d_inode;
2443         new_bh = ext4_find_entry(new_dir, &new_dentry->d_name, &new_de);
2444         if (new_bh) {
2445                 if (!new_inode) {
2446                         brelse(new_bh);
2447                         new_bh = NULL;
2448                 }
2449         }
2450         if (S_ISDIR(old_inode->i_mode)) {
2451                 if (new_inode) {
2452                         retval = -ENOTEMPTY;
2453                         if (!empty_dir(new_inode))
2454                                 goto end_rename;
2455                 }
2456                 retval = -EIO;
2457                 dir_bh = ext4_bread(handle, old_inode, 0, 0, &retval);
2458                 if (!dir_bh)
2459                         goto end_rename;
2460                 if (le32_to_cpu(PARENT_INO(dir_bh->b_data,
2461                                 old_dir->i_sb->s_blocksize)) != old_dir->i_ino)
2462                         goto end_rename;
2463                 retval = -EMLINK;
2464                 if (!new_inode && new_dir != old_dir &&
2465                     EXT4_DIR_LINK_MAX(new_dir))
2466                         goto end_rename;
2467                 BUFFER_TRACE(dir_bh, "get_write_access");
2468                 retval = ext4_journal_get_write_access(handle, dir_bh);
2469                 if (retval)
2470                         goto end_rename;
2471         }
2472         if (!new_bh) {
2473                 retval = ext4_add_entry(handle, new_dentry, old_inode);
2474                 if (retval)
2475                         goto end_rename;
2476         } else {
2477                 BUFFER_TRACE(new_bh, "get write access");
2478                 retval = ext4_journal_get_write_access(handle, new_bh);
2479                 if (retval)
2480                         goto end_rename;
2481                 new_de->inode = cpu_to_le32(old_inode->i_ino);
2482                 if (EXT4_HAS_INCOMPAT_FEATURE(new_dir->i_sb,
2483                                               EXT4_FEATURE_INCOMPAT_FILETYPE))
2484                         new_de->file_type = old_de->file_type;
2485                 new_dir->i_version++;
2486                 new_dir->i_ctime = new_dir->i_mtime =
2487                                         ext4_current_time(new_dir);
2488                 ext4_mark_inode_dirty(handle, new_dir);
2489                 BUFFER_TRACE(new_bh, "call ext4_handle_dirty_metadata");
2490                 retval = ext4_handle_dirty_metadata(handle, new_dir, new_bh);
2491                 if (unlikely(retval)) {
2492                         ext4_std_error(new_dir->i_sb, retval);
2493                         goto end_rename;
2494                 }
2495                 brelse(new_bh);
2496                 new_bh = NULL;
2497         }
2498
2499         /*
2500          * Like most other Unix systems, set the ctime for inodes on a
2501          * rename.
2502          */
2503         old_inode->i_ctime = ext4_current_time(old_inode);
2504         ext4_mark_inode_dirty(handle, old_inode);
2505
2506         /*
2507          * ok, that's it
2508          */
2509         if (le32_to_cpu(old_de->inode) != old_inode->i_ino ||
2510             old_de->name_len != old_dentry->d_name.len ||
2511             strncmp(old_de->name, old_dentry->d_name.name, old_de->name_len) ||
2512             (retval = ext4_delete_entry(handle, old_dir,
2513                                         old_de, old_bh)) == -ENOENT) {
2514                 /* old_de could have moved from under us during htree split, so
2515                  * make sure that we are deleting the right entry.  We might
2516                  * also be pointing to a stale entry in the unused part of
2517                  * old_bh so just checking inum and the name isn't enough. */
2518                 struct buffer_head *old_bh2;
2519                 struct ext4_dir_entry_2 *old_de2;
2520
2521                 old_bh2 = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de2);
2522                 if (old_bh2) {
2523                         retval = ext4_delete_entry(handle, old_dir,
2524                                                    old_de2, old_bh2);
2525                         brelse(old_bh2);
2526                 }
2527         }
2528         if (retval) {
2529                 ext4_warning(old_dir->i_sb,
2530                                 "Deleting old file (%lu), %d, error=%d",
2531                                 old_dir->i_ino, old_dir->i_nlink, retval);
2532         }
2533
2534         if (new_inode) {
2535                 ext4_dec_count(handle, new_inode);
2536                 new_inode->i_ctime = ext4_current_time(new_inode);
2537         }
2538         old_dir->i_ctime = old_dir->i_mtime = ext4_current_time(old_dir);
2539         ext4_update_dx_flag(old_dir);
2540         if (dir_bh) {
2541                 PARENT_INO(dir_bh->b_data, new_dir->i_sb->s_blocksize) =
2542                                                 cpu_to_le32(new_dir->i_ino);
2543                 BUFFER_TRACE(dir_bh, "call ext4_handle_dirty_metadata");
2544                 retval = ext4_handle_dirty_metadata(handle, old_inode, dir_bh);
2545                 if (retval) {
2546                         ext4_std_error(old_dir->i_sb, retval);
2547                         goto end_rename;
2548                 }
2549                 ext4_dec_count(handle, old_dir);
2550                 if (new_inode) {
2551                         /* checked empty_dir above, can't have another parent,
2552                          * ext4_dec_count() won't work for many-linked dirs */
2553                         clear_nlink(new_inode);
2554                 } else {
2555                         ext4_inc_count(handle, new_dir);
2556                         ext4_update_dx_flag(new_dir);
2557                         ext4_mark_inode_dirty(handle, new_dir);
2558                 }
2559         }
2560         ext4_mark_inode_dirty(handle, old_dir);
2561         if (new_inode) {
2562                 ext4_mark_inode_dirty(handle, new_inode);
2563                 if (!new_inode->i_nlink)
2564                         ext4_orphan_add(handle, new_inode);
2565                 if (!test_opt(new_dir->i_sb, NO_AUTO_DA_ALLOC))
2566                         force_da_alloc = 1;
2567         }
2568         retval = 0;
2569
2570 end_rename:
2571         brelse(dir_bh);
2572         brelse(old_bh);
2573         brelse(new_bh);
2574         ext4_journal_stop(handle);
2575         if (retval == 0 && force_da_alloc)
2576                 ext4_alloc_da_blocks(old_inode);
2577         return retval;
2578 }
2579
2580 /*
2581  * directories can handle most operations...
2582  */
2583 const struct inode_operations ext4_dir_inode_operations = {
2584         .create         = ext4_create,
2585         .lookup         = ext4_lookup,
2586         .link           = ext4_link,
2587         .unlink         = ext4_unlink,
2588         .symlink        = ext4_symlink,
2589         .mkdir          = ext4_mkdir,
2590         .rmdir          = ext4_rmdir,
2591         .mknod          = ext4_mknod,
2592         .rename         = ext4_rename,
2593         .setattr        = ext4_setattr,
2594 #ifdef CONFIG_EXT4_FS_XATTR
2595         .setxattr       = generic_setxattr,
2596         .getxattr       = generic_getxattr,
2597         .listxattr      = ext4_listxattr,
2598         .removexattr    = generic_removexattr,
2599 #endif
2600         .get_acl        = ext4_get_acl,
2601         .fiemap         = ext4_fiemap,
2602 };
2603
2604 const struct inode_operations ext4_special_inode_operations = {
2605         .setattr        = ext4_setattr,
2606 #ifdef CONFIG_EXT4_FS_XATTR
2607         .setxattr       = generic_setxattr,
2608         .getxattr       = generic_getxattr,
2609         .listxattr      = ext4_listxattr,
2610         .removexattr    = generic_removexattr,
2611 #endif
2612         .get_acl        = ext4_get_acl,
2613 };