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