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