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