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