vserver 1.9.3
[linux-2.6.git] / 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                 de = ext3_next_entry(de);
614                 if ((err = ext3_htree_store_dirent(dir_file, 0, 0, de)) != 0)
615                         goto errout;
616                 count += 2;
617         }
618
619         while (1) {
620                 block = dx_get_block(frame->at);
621                 ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
622                                              start_hash, start_minor_hash);
623                 if (ret < 0) {
624                         err = ret;
625                         goto errout;
626                 }
627                 count += ret;
628                 hashval = ~0;
629                 ret = ext3_htree_next_block(dir, HASH_NB_ALWAYS, 
630                                             frame, frames, &hashval);
631                 *next_hash = hashval;
632                 if (ret < 0) {
633                         err = ret;
634                         goto errout;
635                 }
636                 /*
637                  * Stop if:  (a) there are no more entries, or
638                  * (b) we have inserted at least one entry and the
639                  * next hash value is not a continuation
640                  */
641                 if ((ret == 0) ||
642                     (count && ((hashval & 1) == 0)))
643                         break;
644         }
645         dx_release(frames);
646         dxtrace(printk("Fill tree: returned %d entries, next hash: %x\n", 
647                        count, *next_hash));
648         return count;
649 errout:
650         dx_release(frames);
651         return (err);
652 }
653
654
655 /*
656  * Directory block splitting, compacting
657  */
658
659 static int dx_make_map (struct ext3_dir_entry_2 *de, int size,
660                         struct dx_hash_info *hinfo, struct dx_map_entry *map_tail)
661 {
662         int count = 0;
663         char *base = (char *) de;
664         struct dx_hash_info h = *hinfo;
665
666         while ((char *) de < base + size)
667         {
668                 if (de->name_len && de->inode) {
669                         ext3fs_dirhash(de->name, de->name_len, &h);
670                         map_tail--;
671                         map_tail->hash = h.hash;
672                         map_tail->offs = (u32) ((char *) de - base);
673                         count++;
674                 }
675                 /* XXX: do we need to check rec_len == 0 case? -Chris */
676                 de = (struct ext3_dir_entry_2 *) ((char *) de + le16_to_cpu(de->rec_len));
677         }
678         return count;
679 }
680
681 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
682 {
683         struct dx_map_entry *p, *q, *top = map + count - 1;
684         int more;
685         /* Combsort until bubble sort doesn't suck */
686         while (count > 2)
687         {
688                 count = count*10/13;
689                 if (count - 9 < 2) /* 9, 10 -> 11 */
690                         count = 11;
691                 for (p = top, q = p - count; q >= map; p--, q--)
692                         if (p->hash < q->hash)
693                                 swap(*p, *q);
694         }
695         /* Garden variety bubble sort */
696         do {
697                 more = 0;
698                 q = top;
699                 while (q-- > map)
700                 {
701                         if (q[1].hash >= q[0].hash)
702                                 continue;
703                         swap(*(q+1), *q);
704                         more = 1;
705                 }
706         } while(more);
707 }
708
709 static void dx_insert_block(struct dx_frame *frame, u32 hash, u32 block)
710 {
711         struct dx_entry *entries = frame->entries;
712         struct dx_entry *old = frame->at, *new = old + 1;
713         int count = dx_get_count(entries);
714
715         assert(count < dx_get_limit(entries));
716         assert(old < entries + count);
717         memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
718         dx_set_hash(new, hash);
719         dx_set_block(new, block);
720         dx_set_count(entries, count + 1);
721 }
722 #endif
723
724
725 static void ext3_update_dx_flag(struct inode *inode)
726 {
727         if (!EXT3_HAS_COMPAT_FEATURE(inode->i_sb,
728                                      EXT3_FEATURE_COMPAT_DIR_INDEX))
729                 EXT3_I(inode)->i_flags &= ~EXT3_INDEX_FL;
730 }
731
732 /*
733  * NOTE! unlike strncmp, ext3_match returns 1 for success, 0 for failure.
734  *
735  * `len <= EXT3_NAME_LEN' is guaranteed by caller.
736  * `de != NULL' is guaranteed by caller.
737  */
738 static inline int ext3_match (int len, const char * const name,
739                               struct ext3_dir_entry_2 * de)
740 {
741         if (len != de->name_len)
742                 return 0;
743         if (!de->inode)
744                 return 0;
745         return !memcmp(name, de->name, len);
746 }
747
748 /*
749  * Returns 0 if not found, -1 on failure, and 1 on success
750  */
751 static inline int search_dirblock(struct buffer_head * bh,
752                                   struct inode *dir,
753                                   struct dentry *dentry,
754                                   unsigned long offset,
755                                   struct ext3_dir_entry_2 ** res_dir)
756 {
757         struct ext3_dir_entry_2 * de;
758         char * dlimit;
759         int de_len;
760         const char *name = dentry->d_name.name;
761         int namelen = dentry->d_name.len;
762
763         de = (struct ext3_dir_entry_2 *) bh->b_data;
764         dlimit = bh->b_data + dir->i_sb->s_blocksize;
765         while ((char *) de < dlimit) {
766                 /* this code is executed quadratically often */
767                 /* do minimal checking `by hand' */
768
769                 if ((char *) de + namelen <= dlimit &&
770                     ext3_match (namelen, name, de)) {
771                         /* found a match - just to be sure, do a full check */
772                         if (!ext3_check_dir_entry("ext3_find_entry",
773                                                   dir, de, bh, offset))
774                                 return -1;
775                         *res_dir = de;
776                         return 1;
777                 }
778                 /* prevent looping on a bad block */
779                 de_len = le16_to_cpu(de->rec_len);
780                 if (de_len <= 0)
781                         return -1;
782                 offset += de_len;
783                 de = (struct ext3_dir_entry_2 *) ((char *) de + de_len);
784         }
785         return 0;
786 }
787
788
789 /*
790  *      ext3_find_entry()
791  *
792  * finds an entry in the specified directory with the wanted name. It
793  * returns the cache buffer in which the entry was found, and the entry
794  * itself (as a parameter - res_dir). It does NOT read the inode of the
795  * entry - you'll have to do that yourself if you want to.
796  *
797  * The returned buffer_head has ->b_count elevated.  The caller is expected
798  * to brelse() it when appropriate.
799  */
800 static struct buffer_head * ext3_find_entry (struct dentry *dentry,
801                                         struct ext3_dir_entry_2 ** res_dir)
802 {
803         struct super_block * sb;
804         struct buffer_head * bh_use[NAMEI_RA_SIZE];
805         struct buffer_head * bh, *ret = NULL;
806         unsigned long start, block, b;
807         int ra_max = 0;         /* Number of bh's in the readahead
808                                    buffer, bh_use[] */
809         int ra_ptr = 0;         /* Current index into readahead
810                                    buffer */
811         int num = 0;
812         int nblocks, i, err;
813         struct inode *dir = dentry->d_parent->d_inode;
814         int namelen;
815         const u8 *name;
816         unsigned blocksize;
817
818         *res_dir = NULL;
819         sb = dir->i_sb;
820         blocksize = sb->s_blocksize;
821         namelen = dentry->d_name.len;
822         name = dentry->d_name.name;
823         if (namelen > EXT3_NAME_LEN)
824                 return NULL;
825 #ifdef CONFIG_EXT3_INDEX
826         if (is_dx(dir)) {
827                 bh = ext3_dx_find_entry(dentry, res_dir, &err);
828                 /*
829                  * On success, or if the error was file not found,
830                  * return.  Otherwise, fall back to doing a search the
831                  * old fashioned way.
832                  */
833                 if (bh || (err != ERR_BAD_DX_DIR))
834                         return bh;
835                 dxtrace(printk("ext3_find_entry: dx failed, falling back\n"));
836         }
837 #endif
838         nblocks = dir->i_size >> EXT3_BLOCK_SIZE_BITS(sb);
839         start = EXT3_I(dir)->i_dir_start_lookup;
840         if (start >= nblocks)
841                 start = 0;
842         block = start;
843 restart:
844         do {
845                 /*
846                  * We deal with the read-ahead logic here.
847                  */
848                 if (ra_ptr >= ra_max) {
849                         /* Refill the readahead buffer */
850                         ra_ptr = 0;
851                         b = block;
852                         for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
853                                 /*
854                                  * Terminate if we reach the end of the
855                                  * directory and must wrap, or if our
856                                  * search has finished at this block.
857                                  */
858                                 if (b >= nblocks || (num && block == start)) {
859                                         bh_use[ra_max] = NULL;
860                                         break;
861                                 }
862                                 num++;
863                                 bh = ext3_getblk(NULL, dir, b++, 0, &err);
864                                 bh_use[ra_max] = bh;
865                                 if (bh)
866                                         ll_rw_block(READ, 1, &bh);
867                         }
868                 }
869                 if ((bh = bh_use[ra_ptr++]) == NULL)
870                         goto next;
871                 wait_on_buffer(bh);
872                 if (!buffer_uptodate(bh)) {
873                         /* read error, skip block & hope for the best */
874                         ext3_error(sb, __FUNCTION__, "reading directory #%lu "
875                                    "offset %lu\n", dir->i_ino, block);
876                         brelse(bh);
877                         goto next;
878                 }
879                 i = search_dirblock(bh, dir, dentry,
880                             block << EXT3_BLOCK_SIZE_BITS(sb), res_dir);
881                 if (i == 1) {
882                         EXT3_I(dir)->i_dir_start_lookup = block;
883                         ret = bh;
884                         goto cleanup_and_exit;
885                 } else {
886                         brelse(bh);
887                         if (i < 0)
888                                 goto cleanup_and_exit;
889                 }
890         next:
891                 if (++block >= nblocks)
892                         block = 0;
893         } while (block != start);
894
895         /*
896          * If the directory has grown while we were searching, then
897          * search the last part of the directory before giving up.
898          */
899         block = nblocks;
900         nblocks = dir->i_size >> EXT3_BLOCK_SIZE_BITS(sb);
901         if (block < nblocks) {
902                 start = 0;
903                 goto restart;
904         }
905
906 cleanup_and_exit:
907         /* Clean up the read-ahead blocks */
908         for (; ra_ptr < ra_max; ra_ptr++)
909                 brelse (bh_use[ra_ptr]);
910         return ret;
911 }
912
913 #ifdef CONFIG_EXT3_INDEX
914 static struct buffer_head * ext3_dx_find_entry(struct dentry *dentry,
915                        struct ext3_dir_entry_2 **res_dir, int *err)
916 {
917         struct super_block * sb;
918         struct dx_hash_info     hinfo;
919         u32 hash;
920         struct dx_frame frames[2], *frame;
921         struct ext3_dir_entry_2 *de, *top;
922         struct buffer_head *bh;
923         unsigned long block;
924         int retval;
925         int namelen = dentry->d_name.len;
926         const u8 *name = dentry->d_name.name;
927         struct inode *dir = dentry->d_parent->d_inode;
928
929         sb = dir->i_sb;
930         if (!(frame = dx_probe(dentry, NULL, &hinfo, frames, err)))
931                 return NULL;
932         hash = hinfo.hash;
933         do {
934                 block = dx_get_block(frame->at);
935                 if (!(bh = ext3_bread (NULL,dir, block, 0, err)))
936                         goto errout;
937                 de = (struct ext3_dir_entry_2 *) bh->b_data;
938                 top = (struct ext3_dir_entry_2 *) ((char *) de + sb->s_blocksize -
939                                        EXT3_DIR_REC_LEN(0));
940                 for (; de < top; de = ext3_next_entry(de))
941                 if (ext3_match (namelen, name, de)) {
942                         if (!ext3_check_dir_entry("ext3_find_entry",
943                                                   dir, de, bh,
944                                   (block<<EXT3_BLOCK_SIZE_BITS(sb))
945                                           +((char *)de - bh->b_data))) {
946                                 brelse (bh);
947                                 goto errout;
948                         }
949                         *res_dir = de;
950                         dx_release (frames);
951                         return bh;
952                 }
953                 brelse (bh);
954                 /* Check to see if we should continue to search */
955                 retval = ext3_htree_next_block(dir, hash, frame,
956                                                frames, NULL);
957                 if (retval < 0) {
958                         ext3_warning(sb, __FUNCTION__,
959                              "error reading index page in directory #%lu",
960                              dir->i_ino);
961                         *err = retval;
962                         goto errout;
963                 }
964         } while (retval == 1);
965
966         *err = -ENOENT;
967 errout:
968         dxtrace(printk("%s not found\n", name));
969         dx_release (frames);
970         return NULL;
971 }
972 #endif
973
974 static struct dentry *ext3_lookup(struct inode * dir, struct dentry *dentry, struct nameidata *nd)
975 {
976         struct inode * inode;
977         struct ext3_dir_entry_2 * de;
978         struct buffer_head * bh;
979
980         if (dentry->d_name.len > EXT3_NAME_LEN)
981                 return ERR_PTR(-ENAMETOOLONG);
982
983         bh = ext3_find_entry(dentry, &de);
984         inode = NULL;
985         if (bh) {
986                 unsigned long ino = le32_to_cpu(de->inode);
987                 brelse (bh);
988                 inode = iget(dir->i_sb, ino);
989
990                 if (!inode)
991                         return ERR_PTR(-EACCES);
992         }
993         if (inode)
994                 return d_splice_alias(inode, dentry);
995         d_add(dentry, inode);
996         return NULL;
997 }
998
999
1000 struct dentry *ext3_get_parent(struct dentry *child)
1001 {
1002         unsigned long ino;
1003         struct dentry *parent;
1004         struct inode *inode;
1005         struct dentry dotdot;
1006         struct ext3_dir_entry_2 * de;
1007         struct buffer_head *bh;
1008
1009         dotdot.d_name.name = "..";
1010         dotdot.d_name.len = 2;
1011         dotdot.d_parent = child; /* confusing, isn't it! */
1012
1013         bh = ext3_find_entry(&dotdot, &de);
1014         inode = NULL;
1015         if (!bh)
1016                 return ERR_PTR(-ENOENT);
1017         ino = le32_to_cpu(de->inode);
1018         brelse(bh);
1019         inode = iget(child->d_inode->i_sb, ino);
1020
1021         if (!inode)
1022                 return ERR_PTR(-EACCES);
1023
1024         parent = d_alloc_anon(inode);
1025         if (!parent) {
1026                 iput(inode);
1027                 parent = ERR_PTR(-ENOMEM);
1028         }
1029         return parent;
1030
1031
1032 #define S_SHIFT 12
1033 static unsigned char ext3_type_by_mode[S_IFMT >> S_SHIFT] = {
1034         [S_IFREG >> S_SHIFT]    = EXT3_FT_REG_FILE,
1035         [S_IFDIR >> S_SHIFT]    = EXT3_FT_DIR,
1036         [S_IFCHR >> S_SHIFT]    = EXT3_FT_CHRDEV,
1037         [S_IFBLK >> S_SHIFT]    = EXT3_FT_BLKDEV,
1038         [S_IFIFO >> S_SHIFT]    = EXT3_FT_FIFO,
1039         [S_IFSOCK >> S_SHIFT]   = EXT3_FT_SOCK,
1040         [S_IFLNK >> S_SHIFT]    = EXT3_FT_SYMLINK,
1041 };
1042
1043 static inline void ext3_set_de_type(struct super_block *sb,
1044                                 struct ext3_dir_entry_2 *de,
1045                                 umode_t mode) {
1046         if (EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_FILETYPE))
1047                 de->file_type = ext3_type_by_mode[(mode & S_IFMT)>>S_SHIFT];
1048 }
1049
1050 #ifdef CONFIG_EXT3_INDEX
1051 static struct ext3_dir_entry_2 *
1052 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count)
1053 {
1054         unsigned rec_len = 0;
1055
1056         while (count--) {
1057                 struct ext3_dir_entry_2 *de = (struct ext3_dir_entry_2 *) (from + map->offs);
1058                 rec_len = EXT3_DIR_REC_LEN(de->name_len);
1059                 memcpy (to, de, rec_len);
1060                 ((struct ext3_dir_entry_2 *) to)->rec_len =
1061                                 cpu_to_le16(rec_len);
1062                 de->inode = 0;
1063                 map++;
1064                 to += rec_len;
1065         }
1066         return (struct ext3_dir_entry_2 *) (to - rec_len);
1067 }
1068
1069 static struct ext3_dir_entry_2* dx_pack_dirents(char *base, int size)
1070 {
1071         struct ext3_dir_entry_2 *next, *to, *prev, *de = (struct ext3_dir_entry_2 *) base;
1072         unsigned rec_len = 0;
1073
1074         prev = to = de;
1075         while ((char*)de < base + size) {
1076                 next = (struct ext3_dir_entry_2 *) ((char *) de +
1077                                                     le16_to_cpu(de->rec_len));
1078                 if (de->inode && de->name_len) {
1079                         rec_len = EXT3_DIR_REC_LEN(de->name_len);
1080                         if (de > to)
1081                                 memmove(to, de, rec_len);
1082                         to->rec_len = cpu_to_le16(rec_len);
1083                         prev = to;
1084                         to = (struct ext3_dir_entry_2 *) (((char *) to) + rec_len);
1085                 }
1086                 de = next;
1087         }
1088         return prev;
1089 }
1090
1091 static struct ext3_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1092                         struct buffer_head **bh,struct dx_frame *frame,
1093                         struct dx_hash_info *hinfo, int *error)
1094 {
1095         unsigned blocksize = dir->i_sb->s_blocksize;
1096         unsigned count, continued;
1097         struct buffer_head *bh2;
1098         u32 newblock;
1099         u32 hash2;
1100         struct dx_map_entry *map;
1101         char *data1 = (*bh)->b_data, *data2;
1102         unsigned split;
1103         struct ext3_dir_entry_2 *de = NULL, *de2;
1104         int     err;
1105
1106         bh2 = ext3_append (handle, dir, &newblock, error);
1107         if (!(bh2)) {
1108                 brelse(*bh);
1109                 *bh = NULL;
1110                 goto errout;
1111         }
1112
1113         BUFFER_TRACE(*bh, "get_write_access");
1114         err = ext3_journal_get_write_access(handle, *bh);
1115         if (err) {
1116         journal_error:
1117                 brelse(*bh);
1118                 brelse(bh2);
1119                 *bh = NULL;
1120                 ext3_std_error(dir->i_sb, err);
1121                 goto errout;
1122         }
1123         BUFFER_TRACE(frame->bh, "get_write_access");
1124         err = ext3_journal_get_write_access(handle, frame->bh);
1125         if (err)
1126                 goto journal_error;
1127
1128         data2 = bh2->b_data;
1129
1130         /* create map in the end of data2 block */
1131         map = (struct dx_map_entry *) (data2 + blocksize);
1132         count = dx_make_map ((struct ext3_dir_entry_2 *) data1,
1133                              blocksize, hinfo, map);
1134         map -= count;
1135         split = count/2; // need to adjust to actual middle
1136         dx_sort_map (map, count);
1137         hash2 = map[split].hash;
1138         continued = hash2 == map[split - 1].hash;
1139         dxtrace(printk("Split block %i at %x, %i/%i\n",
1140                 dx_get_block(frame->at), hash2, split, count-split));
1141
1142         /* Fancy dance to stay within two buffers */
1143         de2 = dx_move_dirents(data1, data2, map + split, count - split);
1144         de = dx_pack_dirents(data1,blocksize);
1145         de->rec_len = cpu_to_le16(data1 + blocksize - (char *) de);
1146         de2->rec_len = cpu_to_le16(data2 + blocksize - (char *) de2);
1147         dxtrace(dx_show_leaf (hinfo, (struct ext3_dir_entry_2 *) data1, blocksize, 1));
1148         dxtrace(dx_show_leaf (hinfo, (struct ext3_dir_entry_2 *) data2, blocksize, 1));
1149
1150         /* Which block gets the new entry? */
1151         if (hinfo->hash >= hash2)
1152         {
1153                 swap(*bh, bh2);
1154                 de = de2;
1155         }
1156         dx_insert_block (frame, hash2 + continued, newblock);
1157         err = ext3_journal_dirty_metadata (handle, bh2);
1158         if (err)
1159                 goto journal_error;
1160         err = ext3_journal_dirty_metadata (handle, frame->bh);
1161         if (err)
1162                 goto journal_error;
1163         brelse (bh2);
1164         dxtrace(dx_show_index ("frame", frame->entries));
1165 errout:
1166         return de;
1167 }
1168 #endif
1169
1170
1171 /*
1172  * Add a new entry into a directory (leaf) block.  If de is non-NULL,
1173  * it points to a directory entry which is guaranteed to be large
1174  * enough for new directory entry.  If de is NULL, then
1175  * add_dirent_to_buf will attempt search the directory block for
1176  * space.  It will return -ENOSPC if no space is available, and -EIO
1177  * and -EEXIST if directory entry already exists.
1178  * 
1179  * NOTE!  bh is NOT released in the case where ENOSPC is returned.  In
1180  * all other cases bh is released.
1181  */
1182 static int add_dirent_to_buf(handle_t *handle, struct dentry *dentry,
1183                              struct inode *inode, struct ext3_dir_entry_2 *de,
1184                              struct buffer_head * bh)
1185 {
1186         struct inode    *dir = dentry->d_parent->d_inode;
1187         const char      *name = dentry->d_name.name;
1188         int             namelen = dentry->d_name.len;
1189         unsigned long   offset = 0;
1190         unsigned short  reclen;
1191         int             nlen, rlen, err;
1192         char            *top;
1193
1194         reclen = EXT3_DIR_REC_LEN(namelen);
1195         if (!de) {
1196                 de = (struct ext3_dir_entry_2 *)bh->b_data;
1197                 top = bh->b_data + dir->i_sb->s_blocksize - reclen;
1198                 while ((char *) de <= top) {
1199                         if (!ext3_check_dir_entry("ext3_add_entry", dir, de,
1200                                                   bh, offset)) {
1201                                 brelse (bh);
1202                                 return -EIO;
1203                         }
1204                         if (ext3_match (namelen, name, de)) {
1205                                 brelse (bh);
1206                                 return -EEXIST;
1207                         }
1208                         nlen = EXT3_DIR_REC_LEN(de->name_len);
1209                         rlen = le16_to_cpu(de->rec_len);
1210                         if ((de->inode? rlen - nlen: rlen) >= reclen)
1211                                 break;
1212                         de = (struct ext3_dir_entry_2 *)((char *)de + rlen);
1213                         offset += rlen;
1214                 }
1215                 if ((char *) de > top)
1216                         return -ENOSPC;
1217         }
1218         BUFFER_TRACE(bh, "get_write_access");
1219         err = ext3_journal_get_write_access(handle, bh);
1220         if (err) {
1221                 ext3_std_error(dir->i_sb, err);
1222                 brelse(bh);
1223                 return err;
1224         }
1225
1226         /* By now the buffer is marked for journaling */
1227         nlen = EXT3_DIR_REC_LEN(de->name_len);
1228         rlen = le16_to_cpu(de->rec_len);
1229         if (de->inode) {
1230                 struct ext3_dir_entry_2 *de1 = (struct ext3_dir_entry_2 *)((char *)de + nlen);
1231                 de1->rec_len = cpu_to_le16(rlen - nlen);
1232                 de->rec_len = cpu_to_le16(nlen);
1233                 de = de1;
1234         }
1235         de->file_type = EXT3_FT_UNKNOWN;
1236         if (inode) {
1237                 de->inode = cpu_to_le32(inode->i_ino);
1238                 ext3_set_de_type(dir->i_sb, de, inode->i_mode);
1239         } else
1240                 de->inode = 0;
1241         de->name_len = namelen;
1242         memcpy (de->name, name, namelen);
1243         /*
1244          * XXX shouldn't update any times until successful
1245          * completion of syscall, but too many callers depend
1246          * on this.
1247          *
1248          * XXX similarly, too many callers depend on
1249          * ext3_new_inode() setting the times, but error
1250          * recovery deletes the inode, so the worst that can
1251          * happen is that the times are slightly out of date
1252          * and/or different from the directory change time.
1253          */
1254         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
1255         ext3_update_dx_flag(dir);
1256         dir->i_version++;
1257         ext3_mark_inode_dirty(handle, dir);
1258         BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
1259         err = ext3_journal_dirty_metadata(handle, bh);
1260         if (err)
1261                 ext3_std_error(dir->i_sb, err);
1262         brelse(bh);
1263         return 0;
1264 }
1265
1266 #ifdef CONFIG_EXT3_INDEX
1267 /*
1268  * This converts a one block unindexed directory to a 3 block indexed
1269  * directory, and adds the dentry to the indexed directory.
1270  */
1271 static int make_indexed_dir(handle_t *handle, struct dentry *dentry,
1272                             struct inode *inode, struct buffer_head *bh)
1273 {
1274         struct inode    *dir = dentry->d_parent->d_inode;
1275         const char      *name = dentry->d_name.name;
1276         int             namelen = dentry->d_name.len;
1277         struct buffer_head *bh2;
1278         struct dx_root  *root;
1279         struct dx_frame frames[2], *frame;
1280         struct dx_entry *entries;
1281         struct ext3_dir_entry_2 *de, *de2;
1282         char            *data1, *top;
1283         unsigned        len;
1284         int             retval;
1285         unsigned        blocksize;
1286         struct dx_hash_info hinfo;
1287         u32             block;
1288         struct fake_dirent *fde;
1289
1290         blocksize =  dir->i_sb->s_blocksize;
1291         dxtrace(printk("Creating index\n"));
1292         retval = ext3_journal_get_write_access(handle, bh);
1293         if (retval) {
1294                 ext3_std_error(dir->i_sb, retval);
1295                 brelse(bh);
1296                 return retval;
1297         }
1298         root = (struct dx_root *) bh->b_data;
1299
1300         bh2 = ext3_append (handle, dir, &block, &retval);
1301         if (!(bh2)) {
1302                 brelse(bh);
1303                 return retval;
1304         }
1305         EXT3_I(dir)->i_flags |= EXT3_INDEX_FL;
1306         data1 = bh2->b_data;
1307
1308         /* The 0th block becomes the root, move the dirents out */
1309         fde = &root->dotdot;
1310         de = (struct ext3_dir_entry_2 *)((char *)fde + le16_to_cpu(fde->rec_len));
1311         len = ((char *) root) + blocksize - (char *) de;
1312         memcpy (data1, de, len);
1313         de = (struct ext3_dir_entry_2 *) data1;
1314         top = data1 + len;
1315         while ((char *)(de2=(void*)de+le16_to_cpu(de->rec_len)) < top)
1316                 de = de2;
1317         de->rec_len = cpu_to_le16(data1 + blocksize - (char *) de);
1318         /* Initialize the root; the dot dirents already exist */
1319         de = (struct ext3_dir_entry_2 *) (&root->dotdot);
1320         de->rec_len = cpu_to_le16(blocksize - EXT3_DIR_REC_LEN(2));
1321         memset (&root->info, 0, sizeof(root->info));
1322         root->info.info_length = sizeof(root->info);
1323         root->info.hash_version = EXT3_SB(dir->i_sb)->s_def_hash_version;
1324         entries = root->entries;
1325         dx_set_block (entries, 1);
1326         dx_set_count (entries, 1);
1327         dx_set_limit (entries, dx_root_limit(dir, sizeof(root->info)));
1328
1329         /* Initialize as for dx_probe */
1330         hinfo.hash_version = root->info.hash_version;
1331         hinfo.seed = EXT3_SB(dir->i_sb)->s_hash_seed;
1332         ext3fs_dirhash(name, namelen, &hinfo);
1333         frame = frames;
1334         frame->entries = entries;
1335         frame->at = entries;
1336         frame->bh = bh;
1337         bh = bh2;
1338         de = do_split(handle,dir, &bh, frame, &hinfo, &retval);
1339         dx_release (frames);
1340         if (!(de))
1341                 return retval;
1342
1343         return add_dirent_to_buf(handle, dentry, inode, de, bh);
1344 }
1345 #endif
1346
1347 /*
1348  *      ext3_add_entry()
1349  *
1350  * adds a file entry to the specified directory, using the same
1351  * semantics as ext3_find_entry(). It returns NULL if it failed.
1352  *
1353  * NOTE!! The inode part of 'de' is left at 0 - which means you
1354  * may not sleep between calling this and putting something into
1355  * the entry, as someone else might have used it while you slept.
1356  */
1357 static int ext3_add_entry (handle_t *handle, struct dentry *dentry,
1358         struct inode *inode)
1359 {
1360         struct inode *dir = dentry->d_parent->d_inode;
1361         unsigned long offset;
1362         struct buffer_head * bh;
1363         struct ext3_dir_entry_2 *de;
1364         struct super_block * sb;
1365         int     retval;
1366 #ifdef CONFIG_EXT3_INDEX
1367         int     dx_fallback=0;
1368 #endif
1369         unsigned blocksize;
1370         unsigned nlen, rlen;
1371         u32 block, blocks;
1372
1373         sb = dir->i_sb;
1374         blocksize = sb->s_blocksize;
1375         if (!dentry->d_name.len)
1376                 return -EINVAL;
1377 #ifdef CONFIG_EXT3_INDEX
1378         if (is_dx(dir)) {
1379                 retval = ext3_dx_add_entry(handle, dentry, inode);
1380                 if (!retval || (retval != ERR_BAD_DX_DIR))
1381                         return retval;
1382                 EXT3_I(dir)->i_flags &= ~EXT3_INDEX_FL;
1383                 dx_fallback++;
1384                 ext3_mark_inode_dirty(handle, dir);
1385         }
1386 #endif
1387         blocks = dir->i_size >> sb->s_blocksize_bits;
1388         for (block = 0, offset = 0; block < blocks; block++) {
1389                 bh = ext3_bread(handle, dir, block, 0, &retval);
1390                 if(!bh)
1391                         return retval;
1392                 retval = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
1393                 if (retval != -ENOSPC)
1394                         return retval;
1395
1396 #ifdef CONFIG_EXT3_INDEX
1397                 if (blocks == 1 && !dx_fallback &&
1398                     EXT3_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_DIR_INDEX))
1399                         return make_indexed_dir(handle, dentry, inode, bh);
1400 #endif
1401                 brelse(bh);
1402         }
1403         bh = ext3_append(handle, dir, &block, &retval);
1404         if (!bh)
1405                 return retval;
1406         de = (struct ext3_dir_entry_2 *) bh->b_data;
1407         de->inode = 0;
1408         de->rec_len = cpu_to_le16(rlen = blocksize);
1409         nlen = 0;
1410         return add_dirent_to_buf(handle, dentry, inode, de, bh);
1411 }
1412
1413 #ifdef CONFIG_EXT3_INDEX
1414 /*
1415  * Returns 0 for success, or a negative error value
1416  */
1417 static int ext3_dx_add_entry(handle_t *handle, struct dentry *dentry,
1418                              struct inode *inode)
1419 {
1420         struct dx_frame frames[2], *frame;
1421         struct dx_entry *entries, *at;
1422         struct dx_hash_info hinfo;
1423         struct buffer_head * bh;
1424         struct inode *dir = dentry->d_parent->d_inode;
1425         struct super_block * sb = dir->i_sb;
1426         struct ext3_dir_entry_2 *de;
1427         int err;
1428
1429         frame = dx_probe(dentry, NULL, &hinfo, frames, &err);
1430         if (!frame)
1431                 return err;
1432         entries = frame->entries;
1433         at = frame->at;
1434
1435         if (!(bh = ext3_bread(handle,dir, dx_get_block(frame->at), 0, &err)))
1436                 goto cleanup;
1437
1438         BUFFER_TRACE(bh, "get_write_access");
1439         err = ext3_journal_get_write_access(handle, bh);
1440         if (err)
1441                 goto journal_error;
1442
1443         err = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
1444         if (err != -ENOSPC) {
1445                 bh = NULL;
1446                 goto cleanup;
1447         }
1448
1449         /* Block full, should compress but for now just split */
1450         dxtrace(printk("using %u of %u node entries\n",
1451                        dx_get_count(entries), dx_get_limit(entries)));
1452         /* Need to split index? */
1453         if (dx_get_count(entries) == dx_get_limit(entries)) {
1454                 u32 newblock;
1455                 unsigned icount = dx_get_count(entries);
1456                 int levels = frame - frames;
1457                 struct dx_entry *entries2;
1458                 struct dx_node *node2;
1459                 struct buffer_head *bh2;
1460
1461                 if (levels && (dx_get_count(frames->entries) ==
1462                                dx_get_limit(frames->entries))) {
1463                         ext3_warning(sb, __FUNCTION__,
1464                                      "Directory index full!\n");
1465                         err = -ENOSPC;
1466                         goto cleanup;
1467                 }
1468                 bh2 = ext3_append (handle, dir, &newblock, &err);
1469                 if (!(bh2))
1470                         goto cleanup;
1471                 node2 = (struct dx_node *)(bh2->b_data);
1472                 entries2 = node2->entries;
1473                 node2->fake.rec_len = cpu_to_le16(sb->s_blocksize);
1474                 node2->fake.inode = 0;
1475                 BUFFER_TRACE(frame->bh, "get_write_access");
1476                 err = ext3_journal_get_write_access(handle, frame->bh);
1477                 if (err)
1478                         goto journal_error;
1479                 if (levels) {
1480                         unsigned icount1 = icount/2, icount2 = icount - icount1;
1481                         unsigned hash2 = dx_get_hash(entries + icount1);
1482                         dxtrace(printk("Split index %i/%i\n", icount1, icount2));
1483
1484                         BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
1485                         err = ext3_journal_get_write_access(handle,
1486                                                              frames[0].bh);
1487                         if (err)
1488                                 goto journal_error;
1489
1490                         memcpy ((char *) entries2, (char *) (entries + icount1),
1491                                 icount2 * sizeof(struct dx_entry));
1492                         dx_set_count (entries, icount1);
1493                         dx_set_count (entries2, icount2);
1494                         dx_set_limit (entries2, dx_node_limit(dir));
1495
1496                         /* Which index block gets the new entry? */
1497                         if (at - entries >= icount1) {
1498                                 frame->at = at = at - entries - icount1 + entries2;
1499                                 frame->entries = entries = entries2;
1500                                 swap(frame->bh, bh2);
1501                         }
1502                         dx_insert_block (frames + 0, hash2, newblock);
1503                         dxtrace(dx_show_index ("node", frames[1].entries));
1504                         dxtrace(dx_show_index ("node",
1505                                ((struct dx_node *) bh2->b_data)->entries));
1506                         err = ext3_journal_dirty_metadata(handle, bh2);
1507                         if (err)
1508                                 goto journal_error;
1509                         brelse (bh2);
1510                 } else {
1511                         dxtrace(printk("Creating second level index...\n"));
1512                         memcpy((char *) entries2, (char *) entries,
1513                                icount * sizeof(struct dx_entry));
1514                         dx_set_limit(entries2, dx_node_limit(dir));
1515
1516                         /* Set up root */
1517                         dx_set_count(entries, 1);
1518                         dx_set_block(entries + 0, newblock);
1519                         ((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1;
1520
1521                         /* Add new access path frame */
1522                         frame = frames + 1;
1523                         frame->at = at = at - entries + entries2;
1524                         frame->entries = entries = entries2;
1525                         frame->bh = bh2;
1526                         err = ext3_journal_get_write_access(handle,
1527                                                              frame->bh);
1528                         if (err)
1529                                 goto journal_error;
1530                 }
1531                 ext3_journal_dirty_metadata(handle, frames[0].bh);
1532         }
1533         de = do_split(handle, dir, &bh, frame, &hinfo, &err);
1534         if (!de)
1535                 goto cleanup;
1536         err = add_dirent_to_buf(handle, dentry, inode, de, bh);
1537         bh = NULL;
1538         goto cleanup;
1539
1540 journal_error:
1541         ext3_std_error(dir->i_sb, err);
1542 cleanup:
1543         if (bh)
1544                 brelse(bh);
1545         dx_release(frames);
1546         return err;
1547 }
1548 #endif
1549
1550 /*
1551  * ext3_delete_entry deletes a directory entry by merging it with the
1552  * previous entry
1553  */
1554 static int ext3_delete_entry (handle_t *handle, 
1555                               struct inode * dir,
1556                               struct ext3_dir_entry_2 * de_del,
1557                               struct buffer_head * bh)
1558 {
1559         struct ext3_dir_entry_2 * de, * pde;
1560         int i;
1561
1562         i = 0;
1563         pde = NULL;
1564         de = (struct ext3_dir_entry_2 *) bh->b_data;
1565         while (i < bh->b_size) {
1566                 if (!ext3_check_dir_entry("ext3_delete_entry", dir, de, bh, i))
1567                         return -EIO;
1568                 if (de == de_del)  {
1569                         BUFFER_TRACE(bh, "get_write_access");
1570                         ext3_journal_get_write_access(handle, bh);
1571                         if (pde)
1572                                 pde->rec_len =
1573                                         cpu_to_le16(le16_to_cpu(pde->rec_len) +
1574                                                     le16_to_cpu(de->rec_len));
1575                         else
1576                                 de->inode = 0;
1577                         dir->i_version++;
1578                         BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
1579                         ext3_journal_dirty_metadata(handle, bh);
1580                         return 0;
1581                 }
1582                 i += le16_to_cpu(de->rec_len);
1583                 pde = de;
1584                 de = (struct ext3_dir_entry_2 *)
1585                         ((char *) de + le16_to_cpu(de->rec_len));
1586         }
1587         return -ENOENT;
1588 }
1589
1590 /*
1591  * ext3_mark_inode_dirty is somewhat expensive, so unlike ext2 we
1592  * do not perform it in these functions.  We perform it at the call site,
1593  * if it is needed.
1594  */
1595 static inline void ext3_inc_count(handle_t *handle, struct inode *inode)
1596 {
1597         inode->i_nlink++;
1598 }
1599
1600 static inline void ext3_dec_count(handle_t *handle, struct inode *inode)
1601 {
1602         inode->i_nlink--;
1603 }
1604
1605 static int ext3_add_nondir(handle_t *handle,
1606                 struct dentry *dentry, struct inode *inode)
1607 {
1608         int err = ext3_add_entry(handle, dentry, inode);
1609         if (!err) {
1610                 ext3_mark_inode_dirty(handle, inode);
1611                 d_instantiate(dentry, inode);
1612                 return 0;
1613         }
1614         ext3_dec_count(handle, inode);
1615         iput(inode);
1616         return err;
1617 }
1618
1619 /*
1620  * By the time this is called, we already have created
1621  * the directory cache entry for the new file, but it
1622  * is so far negative - it has no inode.
1623  *
1624  * If the create succeeds, we fill in the inode information
1625  * with d_instantiate(). 
1626  */
1627 static int ext3_create (struct inode * dir, struct dentry * dentry, int mode,
1628                 struct nameidata *nd)
1629 {
1630         handle_t *handle; 
1631         struct inode * inode;
1632         int err, retries = 0;
1633
1634 retry:
1635         handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS +
1636                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1637                                         2*EXT3_QUOTA_INIT_BLOCKS);
1638         if (IS_ERR(handle))
1639                 return PTR_ERR(handle);
1640
1641         if (IS_DIRSYNC(dir))
1642                 handle->h_sync = 1;
1643
1644         inode = ext3_new_inode (handle, dir, mode);
1645         err = PTR_ERR(inode);
1646         if (!IS_ERR(inode)) {
1647                 inode->i_op = &ext3_file_inode_operations;
1648                 inode->i_fop = &ext3_file_operations;
1649                 ext3_set_aops(inode);
1650                 err = ext3_add_nondir(handle, dentry, inode);
1651         }
1652         ext3_journal_stop(handle);
1653         if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
1654                 goto retry;
1655         return err;
1656 }
1657
1658 static int ext3_mknod (struct inode * dir, struct dentry *dentry,
1659                         int mode, dev_t rdev)
1660 {
1661         handle_t *handle;
1662         struct inode *inode;
1663         int err, retries = 0;
1664
1665         if (!new_valid_dev(rdev))
1666                 return -EINVAL;
1667
1668 retry:
1669         handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS +
1670                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1671                                         2*EXT3_QUOTA_INIT_BLOCKS);
1672         if (IS_ERR(handle))
1673                 return PTR_ERR(handle);
1674
1675         if (IS_DIRSYNC(dir))
1676                 handle->h_sync = 1;
1677
1678         inode = ext3_new_inode (handle, dir, mode);
1679         err = PTR_ERR(inode);
1680         if (!IS_ERR(inode)) {
1681                 init_special_inode(inode, inode->i_mode, rdev);
1682 #ifdef CONFIG_EXT3_FS_XATTR
1683                 inode->i_op = &ext3_special_inode_operations;
1684 #endif
1685                 err = ext3_add_nondir(handle, dentry, inode);
1686         }
1687         ext3_journal_stop(handle);
1688         if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
1689                 goto retry;
1690         return err;
1691 }
1692
1693 static int ext3_mkdir(struct inode * dir, struct dentry * dentry, int mode)
1694 {
1695         handle_t *handle;
1696         struct inode * inode;
1697         struct buffer_head * dir_block;
1698         struct ext3_dir_entry_2 * de;
1699         int err, retries = 0;
1700
1701         if (dir->i_nlink >= EXT3_LINK_MAX)
1702                 return -EMLINK;
1703
1704 retry:
1705         handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS +
1706                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS + 3 +
1707                                         2*EXT3_QUOTA_INIT_BLOCKS);
1708         if (IS_ERR(handle))
1709                 return PTR_ERR(handle);
1710
1711         if (IS_DIRSYNC(dir))
1712                 handle->h_sync = 1;
1713
1714         inode = ext3_new_inode (handle, dir, S_IFDIR | mode);
1715         err = PTR_ERR(inode);
1716         if (IS_ERR(inode))
1717                 goto out_stop;
1718
1719         inode->i_op = &ext3_dir_inode_operations;
1720         inode->i_fop = &ext3_dir_operations;
1721         inode->i_size = EXT3_I(inode)->i_disksize = inode->i_sb->s_blocksize;
1722         dir_block = ext3_bread (handle, inode, 0, 1, &err);
1723         if (!dir_block) {
1724                 inode->i_nlink--; /* is this nlink == 0? */
1725                 ext3_mark_inode_dirty(handle, inode);
1726                 iput (inode);
1727                 goto out_stop;
1728         }
1729         BUFFER_TRACE(dir_block, "get_write_access");
1730         ext3_journal_get_write_access(handle, dir_block);
1731         de = (struct ext3_dir_entry_2 *) dir_block->b_data;
1732         de->inode = cpu_to_le32(inode->i_ino);
1733         de->name_len = 1;
1734         de->rec_len = cpu_to_le16(EXT3_DIR_REC_LEN(de->name_len));
1735         strcpy (de->name, ".");
1736         ext3_set_de_type(dir->i_sb, de, S_IFDIR);
1737         de = (struct ext3_dir_entry_2 *)
1738                         ((char *) de + le16_to_cpu(de->rec_len));
1739         de->inode = cpu_to_le32(dir->i_ino);
1740         de->rec_len = cpu_to_le16(inode->i_sb->s_blocksize-EXT3_DIR_REC_LEN(1));
1741         de->name_len = 2;
1742         strcpy (de->name, "..");
1743         ext3_set_de_type(dir->i_sb, de, S_IFDIR);
1744         inode->i_nlink = 2;
1745         BUFFER_TRACE(dir_block, "call ext3_journal_dirty_metadata");
1746         ext3_journal_dirty_metadata(handle, dir_block);
1747         brelse (dir_block);
1748         ext3_mark_inode_dirty(handle, inode);
1749         err = ext3_add_entry (handle, dentry, inode);
1750         if (err) {
1751                 inode->i_nlink = 0;
1752                 ext3_mark_inode_dirty(handle, inode);
1753                 iput (inode);
1754                 goto out_stop;
1755         }
1756         dir->i_nlink++;
1757         ext3_update_dx_flag(dir);
1758         ext3_mark_inode_dirty(handle, dir);
1759         d_instantiate(dentry, inode);
1760 out_stop:
1761         ext3_journal_stop(handle);
1762         if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
1763                 goto retry;
1764         return err;
1765 }
1766
1767 /*
1768  * routine to check that the specified directory is empty (for rmdir)
1769  */
1770 static int empty_dir (struct inode * inode)
1771 {
1772         unsigned long offset;
1773         struct buffer_head * bh;
1774         struct ext3_dir_entry_2 * de, * de1;
1775         struct super_block * sb;
1776         int err = 0;
1777
1778         sb = inode->i_sb;
1779         if (inode->i_size < EXT3_DIR_REC_LEN(1) + EXT3_DIR_REC_LEN(2) ||
1780             !(bh = ext3_bread (NULL, inode, 0, 0, &err))) {
1781                 if (err)
1782                         ext3_error(inode->i_sb, __FUNCTION__,
1783                                    "error %d reading directory #%lu offset 0",
1784                                    err, inode->i_ino);
1785                 else
1786                         ext3_warning(inode->i_sb, __FUNCTION__,
1787                                      "bad directory (dir #%lu) - no data block",
1788                                      inode->i_ino);
1789                 return 1;
1790         }
1791         de = (struct ext3_dir_entry_2 *) bh->b_data;
1792         de1 = (struct ext3_dir_entry_2 *)
1793                         ((char *) de + le16_to_cpu(de->rec_len));
1794         if (le32_to_cpu(de->inode) != inode->i_ino ||
1795                         !le32_to_cpu(de1->inode) || 
1796                         strcmp (".", de->name) ||
1797                         strcmp ("..", de1->name)) {
1798                 ext3_warning (inode->i_sb, "empty_dir",
1799                               "bad directory (dir #%lu) - no `.' or `..'",
1800                               inode->i_ino);
1801                 brelse (bh);
1802                 return 1;
1803         }
1804         offset = le16_to_cpu(de->rec_len) + le16_to_cpu(de1->rec_len);
1805         de = (struct ext3_dir_entry_2 *)
1806                         ((char *) de1 + le16_to_cpu(de1->rec_len));
1807         while (offset < inode->i_size ) {
1808                 if (!bh ||
1809                         (void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
1810                         err = 0;
1811                         brelse (bh);
1812                         bh = ext3_bread (NULL, inode,
1813                                 offset >> EXT3_BLOCK_SIZE_BITS(sb), 0, &err);
1814                         if (!bh) {
1815                                 if (err)
1816                                         ext3_error(sb, __FUNCTION__,
1817                                                    "error %d reading directory"
1818                                                    " #%lu offset %lu",
1819                                                    err, inode->i_ino, offset);
1820                                 offset += sb->s_blocksize;
1821                                 continue;
1822                         }
1823                         de = (struct ext3_dir_entry_2 *) bh->b_data;
1824                 }
1825                 if (!ext3_check_dir_entry("empty_dir", inode, de, bh, offset)) {
1826                         de = (struct ext3_dir_entry_2 *)(bh->b_data +
1827                                                          sb->s_blocksize);
1828                         offset = (offset | (sb->s_blocksize - 1)) + 1;
1829                         continue;
1830                 }
1831                 if (le32_to_cpu(de->inode)) {
1832                         brelse (bh);
1833                         return 0;
1834                 }
1835                 offset += le16_to_cpu(de->rec_len);
1836                 de = (struct ext3_dir_entry_2 *)
1837                                 ((char *) de + le16_to_cpu(de->rec_len));
1838         }
1839         brelse (bh);
1840         return 1;
1841 }
1842
1843 /* ext3_orphan_add() links an unlinked or truncated inode into a list of
1844  * such inodes, starting at the superblock, in case we crash before the
1845  * file is closed/deleted, or in case the inode truncate spans multiple
1846  * transactions and the last transaction is not recovered after a crash.
1847  *
1848  * At filesystem recovery time, we walk this list deleting unlinked
1849  * inodes and truncating linked inodes in ext3_orphan_cleanup().
1850  */
1851 int ext3_orphan_add(handle_t *handle, struct inode *inode)
1852 {
1853         struct super_block *sb = inode->i_sb;
1854         struct ext3_iloc iloc;
1855         int err = 0, rc;
1856
1857         lock_super(sb);
1858         if (!list_empty(&EXT3_I(inode)->i_orphan))
1859                 goto out_unlock;
1860
1861         /* Orphan handling is only valid for files with data blocks
1862          * being truncated, or files being unlinked. */
1863
1864         /* @@@ FIXME: Observation from aviro:
1865          * I think I can trigger J_ASSERT in ext3_orphan_add().  We block 
1866          * here (on lock_super()), so race with ext3_link() which might bump
1867          * ->i_nlink. For, say it, character device. Not a regular file,
1868          * not a directory, not a symlink and ->i_nlink > 0.
1869          */
1870         J_ASSERT ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1871                 S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
1872
1873         BUFFER_TRACE(EXT3_SB(sb)->s_sbh, "get_write_access");
1874         err = ext3_journal_get_write_access(handle, EXT3_SB(sb)->s_sbh);
1875         if (err)
1876                 goto out_unlock;
1877
1878         err = ext3_reserve_inode_write(handle, inode, &iloc);
1879         if (err)
1880                 goto out_unlock;
1881
1882         /* Insert this inode at the head of the on-disk orphan list... */
1883         NEXT_ORPHAN(inode) = le32_to_cpu(EXT3_SB(sb)->s_es->s_last_orphan);
1884         EXT3_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
1885         err = ext3_journal_dirty_metadata(handle, EXT3_SB(sb)->s_sbh);
1886         rc = ext3_mark_iloc_dirty(handle, inode, &iloc);
1887         if (!err)
1888                 err = rc;
1889
1890         /* Only add to the head of the in-memory list if all the
1891          * previous operations succeeded.  If the orphan_add is going to
1892          * fail (possibly taking the journal offline), we can't risk
1893          * leaving the inode on the orphan list: stray orphan-list
1894          * entries can cause panics at unmount time.
1895          *
1896          * This is safe: on error we're going to ignore the orphan list
1897          * anyway on the next recovery. */
1898         if (!err)
1899                 list_add(&EXT3_I(inode)->i_orphan, &EXT3_SB(sb)->s_orphan);
1900
1901         jbd_debug(4, "superblock will point to %ld\n", inode->i_ino);
1902         jbd_debug(4, "orphan inode %ld will point to %d\n",
1903                         inode->i_ino, NEXT_ORPHAN(inode));
1904 out_unlock:
1905         unlock_super(sb);
1906         ext3_std_error(inode->i_sb, err);
1907         return err;
1908 }
1909
1910 /*
1911  * ext3_orphan_del() removes an unlinked or truncated inode from the list
1912  * of such inodes stored on disk, because it is finally being cleaned up.
1913  */
1914 int ext3_orphan_del(handle_t *handle, struct inode *inode)
1915 {
1916         struct list_head *prev;
1917         struct ext3_inode_info *ei = EXT3_I(inode);
1918         struct ext3_sb_info *sbi;
1919         unsigned long ino_next;
1920         struct ext3_iloc iloc;
1921         int err = 0;
1922
1923         lock_super(inode->i_sb);
1924         if (list_empty(&ei->i_orphan)) {
1925                 unlock_super(inode->i_sb);
1926                 return 0;
1927         }
1928
1929         ino_next = NEXT_ORPHAN(inode);
1930         prev = ei->i_orphan.prev;
1931         sbi = EXT3_SB(inode->i_sb);
1932
1933         jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
1934
1935         list_del_init(&ei->i_orphan);
1936
1937         /* If we're on an error path, we may not have a valid
1938          * transaction handle with which to update the orphan list on
1939          * disk, but we still need to remove the inode from the linked
1940          * list in memory. */
1941         if (!handle)
1942                 goto out;
1943
1944         err = ext3_reserve_inode_write(handle, inode, &iloc);
1945         if (err)
1946                 goto out_err;
1947
1948         if (prev == &sbi->s_orphan) {
1949                 jbd_debug(4, "superblock will point to %lu\n", ino_next);
1950                 BUFFER_TRACE(sbi->s_sbh, "get_write_access");
1951                 err = ext3_journal_get_write_access(handle, sbi->s_sbh);
1952                 if (err)
1953                         goto out_brelse;
1954                 sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
1955                 err = ext3_journal_dirty_metadata(handle, sbi->s_sbh);
1956         } else {
1957                 struct ext3_iloc iloc2;
1958                 struct inode *i_prev =
1959                         &list_entry(prev, struct ext3_inode_info, i_orphan)->vfs_inode;
1960
1961                 jbd_debug(4, "orphan inode %lu will point to %lu\n",
1962                           i_prev->i_ino, ino_next);
1963                 err = ext3_reserve_inode_write(handle, i_prev, &iloc2);
1964                 if (err)
1965                         goto out_brelse;
1966                 NEXT_ORPHAN(i_prev) = ino_next;
1967                 err = ext3_mark_iloc_dirty(handle, i_prev, &iloc2);
1968         }
1969         if (err)
1970                 goto out_brelse;
1971         NEXT_ORPHAN(inode) = 0;
1972         err = ext3_mark_iloc_dirty(handle, inode, &iloc);
1973
1974 out_err:
1975         ext3_std_error(inode->i_sb, err);
1976 out:
1977         unlock_super(inode->i_sb);
1978         return err;
1979
1980 out_brelse:
1981         brelse(iloc.bh);
1982         goto out_err;
1983 }
1984
1985 static int ext3_rmdir (struct inode * dir, struct dentry *dentry)
1986 {
1987         int retval;
1988         struct inode * inode;
1989         struct buffer_head * bh;
1990         struct ext3_dir_entry_2 * de;
1991         handle_t *handle;
1992
1993         /* Initialize quotas before so that eventual writes go in
1994          * separate transaction */
1995         DQUOT_INIT(dentry->d_inode);
1996         handle = ext3_journal_start(dir, EXT3_DELETE_TRANS_BLOCKS);
1997         if (IS_ERR(handle))
1998                 return PTR_ERR(handle);
1999
2000         retval = -ENOENT;
2001         bh = ext3_find_entry (dentry, &de);
2002         if (!bh)
2003                 goto end_rmdir;
2004
2005         if (IS_DIRSYNC(dir))
2006                 handle->h_sync = 1;
2007
2008         inode = dentry->d_inode;
2009
2010         retval = -EIO;
2011         if (le32_to_cpu(de->inode) != inode->i_ino)
2012                 goto end_rmdir;
2013
2014         retval = -ENOTEMPTY;
2015         if (!empty_dir (inode))
2016                 goto end_rmdir;
2017
2018         retval = ext3_delete_entry(handle, dir, de, bh);
2019         if (retval)
2020                 goto end_rmdir;
2021         if (inode->i_nlink != 2)
2022                 ext3_warning (inode->i_sb, "ext3_rmdir",
2023                               "empty directory has nlink!=2 (%d)",
2024                               inode->i_nlink);
2025         inode->i_version++;
2026         inode->i_nlink = 0;
2027         /* There's no need to set i_disksize: the fact that i_nlink is
2028          * zero will ensure that the right thing happens during any
2029          * recovery. */
2030         inode->i_size = 0;
2031         ext3_orphan_add(handle, inode);
2032         inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2033         ext3_mark_inode_dirty(handle, inode);
2034         dir->i_nlink--;
2035         ext3_update_dx_flag(dir);
2036         ext3_mark_inode_dirty(handle, dir);
2037
2038 end_rmdir:
2039         ext3_journal_stop(handle);
2040         brelse (bh);
2041         return retval;
2042 }
2043
2044 static int ext3_unlink(struct inode * dir, struct dentry *dentry)
2045 {
2046         int retval;
2047         struct inode * inode;
2048         struct buffer_head * bh;
2049         struct ext3_dir_entry_2 * de;
2050         handle_t *handle;
2051
2052         /* Initialize quotas before so that eventual writes go
2053          * in separate transaction */
2054         DQUOT_INIT(dentry->d_inode);
2055         handle = ext3_journal_start(dir, EXT3_DELETE_TRANS_BLOCKS);
2056         if (IS_ERR(handle))
2057                 return PTR_ERR(handle);
2058
2059         if (IS_DIRSYNC(dir))
2060                 handle->h_sync = 1;
2061
2062         retval = -ENOENT;
2063         bh = ext3_find_entry (dentry, &de);
2064         if (!bh)
2065                 goto end_unlink;
2066
2067         inode = dentry->d_inode;
2068
2069         retval = -EIO;
2070         if (le32_to_cpu(de->inode) != inode->i_ino)
2071                 goto end_unlink;
2072
2073         if (!inode->i_nlink) {
2074                 ext3_warning (inode->i_sb, "ext3_unlink",
2075                               "Deleting nonexistent file (%lu), %d",
2076                               inode->i_ino, inode->i_nlink);
2077                 inode->i_nlink = 1;
2078         }
2079         retval = ext3_delete_entry(handle, dir, de, bh);
2080         if (retval)
2081                 goto end_unlink;
2082         dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2083         ext3_update_dx_flag(dir);
2084         ext3_mark_inode_dirty(handle, dir);
2085         inode->i_nlink--;
2086         if (!inode->i_nlink)
2087                 ext3_orphan_add(handle, inode);
2088         inode->i_ctime = dir->i_ctime;
2089         ext3_mark_inode_dirty(handle, inode);
2090         retval = 0;
2091
2092 end_unlink:
2093         ext3_journal_stop(handle);
2094         brelse (bh);
2095         return retval;
2096 }
2097
2098 static int ext3_symlink (struct inode * dir,
2099                 struct dentry *dentry, const char * symname)
2100 {
2101         handle_t *handle;
2102         struct inode * inode;
2103         int l, err, retries = 0;
2104
2105         l = strlen(symname)+1;
2106         if (l > dir->i_sb->s_blocksize)
2107                 return -ENAMETOOLONG;
2108
2109 retry:
2110         handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS +
2111                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS + 5 +
2112                                         2*EXT3_QUOTA_INIT_BLOCKS);
2113         if (IS_ERR(handle))
2114                 return PTR_ERR(handle);
2115
2116         if (IS_DIRSYNC(dir))
2117                 handle->h_sync = 1;
2118
2119         inode = ext3_new_inode (handle, dir, S_IFLNK|S_IRWXUGO);
2120         err = PTR_ERR(inode);
2121         if (IS_ERR(inode))
2122                 goto out_stop;
2123
2124         if (l > sizeof (EXT3_I(inode)->i_data)) {
2125                 inode->i_op = &ext3_symlink_inode_operations;
2126                 ext3_set_aops(inode);
2127                 /*
2128                  * page_symlink() calls into ext3_prepare/commit_write.
2129                  * We have a transaction open.  All is sweetness.  It also sets
2130                  * i_size in generic_commit_write().
2131                  */
2132                 err = page_symlink(inode, symname, l);
2133                 if (err) {
2134                         ext3_dec_count(handle, inode);
2135                         ext3_mark_inode_dirty(handle, inode);
2136                         iput (inode);
2137                         goto out_stop;
2138                 }
2139         } else {
2140                 inode->i_op = &ext3_fast_symlink_inode_operations;
2141                 memcpy((char*)&EXT3_I(inode)->i_data,symname,l);
2142                 inode->i_size = l-1;
2143         }
2144         EXT3_I(inode)->i_disksize = inode->i_size;
2145         err = ext3_add_nondir(handle, dentry, inode);
2146 out_stop:
2147         ext3_journal_stop(handle);
2148         if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
2149                 goto retry;
2150         return err;
2151 }
2152
2153 static int ext3_link (struct dentry * old_dentry,
2154                 struct inode * dir, struct dentry *dentry)
2155 {
2156         handle_t *handle;
2157         struct inode *inode = old_dentry->d_inode;
2158         int err, retries = 0;
2159
2160         if (inode->i_nlink >= EXT3_LINK_MAX)
2161                 return -EMLINK;
2162
2163 retry:
2164         handle = ext3_journal_start(dir, EXT3_DATA_TRANS_BLOCKS +
2165                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS);
2166         if (IS_ERR(handle))
2167                 return PTR_ERR(handle);
2168
2169         if (IS_DIRSYNC(dir))
2170                 handle->h_sync = 1;
2171
2172         inode->i_ctime = CURRENT_TIME;
2173         ext3_inc_count(handle, inode);
2174         atomic_inc(&inode->i_count);
2175
2176         err = ext3_add_nondir(handle, dentry, inode);
2177         ext3_journal_stop(handle);
2178         if (err == -ENOSPC && ext3_should_retry_alloc(dir->i_sb, &retries))
2179                 goto retry;
2180         return err;
2181 }
2182
2183 #define PARENT_INO(buffer) \
2184         ((struct ext3_dir_entry_2 *) ((char *) buffer + \
2185         le16_to_cpu(((struct ext3_dir_entry_2 *) buffer)->rec_len)))->inode
2186
2187 /*
2188  * Anybody can rename anything with this: the permission checks are left to the
2189  * higher-level routines.
2190  */
2191 static int ext3_rename (struct inode * old_dir, struct dentry *old_dentry,
2192                            struct inode * new_dir,struct dentry *new_dentry)
2193 {
2194         handle_t *handle;
2195         struct inode * old_inode, * new_inode;
2196         struct buffer_head * old_bh, * new_bh, * dir_bh;
2197         struct ext3_dir_entry_2 * old_de, * new_de;
2198         int retval;
2199
2200         old_bh = new_bh = dir_bh = NULL;
2201
2202         /* Initialize quotas before so that eventual writes go
2203          * in separate transaction */
2204         if (new_dentry->d_inode)
2205                 DQUOT_INIT(new_dentry->d_inode);
2206         handle = ext3_journal_start(old_dir, 2 * EXT3_DATA_TRANS_BLOCKS +
2207                                         EXT3_INDEX_EXTRA_TRANS_BLOCKS + 2);
2208         if (IS_ERR(handle))
2209                 return PTR_ERR(handle);
2210
2211         if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir))
2212                 handle->h_sync = 1;
2213
2214         old_bh = ext3_find_entry (old_dentry, &old_de);
2215         /*
2216          *  Check for inode number is _not_ due to possible IO errors.
2217          *  We might rmdir the source, keep it as pwd of some process
2218          *  and merrily kill the link to whatever was created under the
2219          *  same name. Goodbye sticky bit ;-<
2220          */
2221         old_inode = old_dentry->d_inode;
2222         retval = -ENOENT;
2223         if (!old_bh || le32_to_cpu(old_de->inode) != old_inode->i_ino)
2224                 goto end_rename;
2225
2226         new_inode = new_dentry->d_inode;
2227         new_bh = ext3_find_entry (new_dentry, &new_de);
2228         if (new_bh) {
2229                 if (!new_inode) {
2230                         brelse (new_bh);
2231                         new_bh = NULL;
2232                 }
2233         }
2234         if (S_ISDIR(old_inode->i_mode)) {
2235                 if (new_inode) {
2236                         retval = -ENOTEMPTY;
2237                         if (!empty_dir (new_inode))
2238                                 goto end_rename;
2239                 }
2240                 retval = -EIO;
2241                 dir_bh = ext3_bread (handle, old_inode, 0, 0, &retval);
2242                 if (!dir_bh)
2243                         goto end_rename;
2244                 if (le32_to_cpu(PARENT_INO(dir_bh->b_data)) != old_dir->i_ino)
2245                         goto end_rename;
2246                 retval = -EMLINK;
2247                 if (!new_inode && new_dir!=old_dir &&
2248                                 new_dir->i_nlink >= EXT3_LINK_MAX)
2249                         goto end_rename;
2250         }
2251         if (!new_bh) {
2252                 retval = ext3_add_entry (handle, new_dentry, old_inode);
2253                 if (retval)
2254                         goto end_rename;
2255         } else {
2256                 BUFFER_TRACE(new_bh, "get write access");
2257                 ext3_journal_get_write_access(handle, new_bh);
2258                 new_de->inode = cpu_to_le32(old_inode->i_ino);
2259                 if (EXT3_HAS_INCOMPAT_FEATURE(new_dir->i_sb,
2260                                               EXT3_FEATURE_INCOMPAT_FILETYPE))
2261                         new_de->file_type = old_de->file_type;
2262                 new_dir->i_version++;
2263                 BUFFER_TRACE(new_bh, "call ext3_journal_dirty_metadata");
2264                 ext3_journal_dirty_metadata(handle, new_bh);
2265                 brelse(new_bh);
2266                 new_bh = NULL;
2267         }
2268
2269         /*
2270          * Like most other Unix systems, set the ctime for inodes on a
2271          * rename.
2272          */
2273         old_inode->i_ctime = CURRENT_TIME;
2274         ext3_mark_inode_dirty(handle, old_inode);
2275
2276         /*
2277          * ok, that's it
2278          */
2279         if (le32_to_cpu(old_de->inode) != old_inode->i_ino ||
2280             old_de->name_len != old_dentry->d_name.len ||
2281             strncmp(old_de->name, old_dentry->d_name.name, old_de->name_len) ||
2282             (retval = ext3_delete_entry(handle, old_dir,
2283                                         old_de, old_bh)) == -ENOENT) {
2284                 /* old_de could have moved from under us during htree split, so
2285                  * make sure that we are deleting the right entry.  We might
2286                  * also be pointing to a stale entry in the unused part of
2287                  * old_bh so just checking inum and the name isn't enough. */
2288                 struct buffer_head *old_bh2;
2289                 struct ext3_dir_entry_2 *old_de2;
2290
2291                 old_bh2 = ext3_find_entry(old_dentry, &old_de2);
2292                 if (old_bh2) {
2293                         retval = ext3_delete_entry(handle, old_dir,
2294                                                    old_de2, old_bh2);
2295                         brelse(old_bh2);
2296                 }
2297         }
2298         if (retval) {
2299                 ext3_warning(old_dir->i_sb, "ext3_rename",
2300                                 "Deleting old file (%lu), %d, error=%d",
2301                                 old_dir->i_ino, old_dir->i_nlink, retval);
2302         }
2303
2304         if (new_inode) {
2305                 new_inode->i_nlink--;
2306                 new_inode->i_ctime = CURRENT_TIME;
2307         }
2308         old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME;
2309         ext3_update_dx_flag(old_dir);
2310         if (dir_bh) {
2311                 BUFFER_TRACE(dir_bh, "get_write_access");
2312                 ext3_journal_get_write_access(handle, dir_bh);
2313                 PARENT_INO(dir_bh->b_data) = cpu_to_le32(new_dir->i_ino);
2314                 BUFFER_TRACE(dir_bh, "call ext3_journal_dirty_metadata");
2315                 ext3_journal_dirty_metadata(handle, dir_bh);
2316                 old_dir->i_nlink--;
2317                 if (new_inode) {
2318                         new_inode->i_nlink--;
2319                 } else {
2320                         new_dir->i_nlink++;
2321                         ext3_update_dx_flag(new_dir);
2322                         ext3_mark_inode_dirty(handle, new_dir);
2323                 }
2324         }
2325         ext3_mark_inode_dirty(handle, old_dir);
2326         if (new_inode) {
2327                 ext3_mark_inode_dirty(handle, new_inode);
2328                 if (!new_inode->i_nlink)
2329                         ext3_orphan_add(handle, new_inode);
2330         }
2331         retval = 0;
2332
2333 end_rename:
2334         brelse (dir_bh);
2335         brelse (old_bh);
2336         brelse (new_bh);
2337         ext3_journal_stop(handle);
2338         return retval;
2339 }
2340
2341 /*
2342  * directories can handle most operations...
2343  */
2344 struct inode_operations ext3_dir_inode_operations = {
2345         .create         = ext3_create,
2346         .lookup         = ext3_lookup,
2347         .link           = ext3_link,
2348         .unlink         = ext3_unlink,
2349         .symlink        = ext3_symlink,
2350         .mkdir          = ext3_mkdir,
2351         .rmdir          = ext3_rmdir,
2352         .mknod          = ext3_mknod,
2353         .rename         = ext3_rename,
2354         .setattr        = ext3_setattr,
2355         .setxattr       = ext3_setxattr,
2356         .getxattr       = ext3_getxattr,
2357         .listxattr      = ext3_listxattr,
2358         .removexattr    = ext3_removexattr,
2359         .permission     = ext3_permission,
2360 };
2361
2362 struct inode_operations ext3_special_inode_operations = {
2363         .setattr        = ext3_setattr,
2364         .setxattr       = ext3_setxattr,
2365         .getxattr       = ext3_getxattr,
2366         .listxattr      = ext3_listxattr,
2367         .removexattr    = ext3_removexattr,
2368         .permission     = ext3_permission,
2369 };