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