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