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