xref: /openbmc/linux/fs/ext4/namei.c (revision 2c64e9cb)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/namei.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/namei.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  Big-endian to little-endian byte-swapping/bitmaps by
17  *        David S. Miller (davem@caip.rutgers.edu), 1995
18  *  Directory entry file type support and forward compatibility hooks
19  *	for B-tree directories by Theodore Ts'o (tytso@mit.edu), 1998
20  *  Hash Tree Directory indexing (c)
21  *	Daniel Phillips, 2001
22  *  Hash Tree Directory indexing porting
23  *	Christopher Li, 2002
24  *  Hash Tree Directory indexing cleanup
25  *	Theodore Ts'o, 2002
26  */
27 
28 #include <linux/fs.h>
29 #include <linux/pagemap.h>
30 #include <linux/time.h>
31 #include <linux/fcntl.h>
32 #include <linux/stat.h>
33 #include <linux/string.h>
34 #include <linux/quotaops.h>
35 #include <linux/buffer_head.h>
36 #include <linux/bio.h>
37 #include <linux/iversion.h>
38 #include <linux/unicode.h>
39 #include "ext4.h"
40 #include "ext4_jbd2.h"
41 
42 #include "xattr.h"
43 #include "acl.h"
44 
45 #include <trace/events/ext4.h>
46 /*
47  * define how far ahead to read directories while searching them.
48  */
49 #define NAMEI_RA_CHUNKS  2
50 #define NAMEI_RA_BLOCKS  4
51 #define NAMEI_RA_SIZE	     (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
52 
53 static struct buffer_head *ext4_append(handle_t *handle,
54 					struct inode *inode,
55 					ext4_lblk_t *block)
56 {
57 	struct buffer_head *bh;
58 	int err;
59 
60 	if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb &&
61 		     ((inode->i_size >> 10) >=
62 		      EXT4_SB(inode->i_sb)->s_max_dir_size_kb)))
63 		return ERR_PTR(-ENOSPC);
64 
65 	*block = inode->i_size >> inode->i_sb->s_blocksize_bits;
66 
67 	bh = ext4_bread(handle, inode, *block, EXT4_GET_BLOCKS_CREATE);
68 	if (IS_ERR(bh))
69 		return bh;
70 	inode->i_size += inode->i_sb->s_blocksize;
71 	EXT4_I(inode)->i_disksize = inode->i_size;
72 	BUFFER_TRACE(bh, "get_write_access");
73 	err = ext4_journal_get_write_access(handle, bh);
74 	if (err) {
75 		brelse(bh);
76 		ext4_std_error(inode->i_sb, err);
77 		return ERR_PTR(err);
78 	}
79 	return bh;
80 }
81 
82 static int ext4_dx_csum_verify(struct inode *inode,
83 			       struct ext4_dir_entry *dirent);
84 
85 typedef enum {
86 	EITHER, INDEX, DIRENT
87 } dirblock_type_t;
88 
89 #define ext4_read_dirblock(inode, block, type) \
90 	__ext4_read_dirblock((inode), (block), (type), __func__, __LINE__)
91 
92 static struct buffer_head *__ext4_read_dirblock(struct inode *inode,
93 						ext4_lblk_t block,
94 						dirblock_type_t type,
95 						const char *func,
96 						unsigned int line)
97 {
98 	struct buffer_head *bh;
99 	struct ext4_dir_entry *dirent;
100 	int is_dx_block = 0;
101 
102 	bh = ext4_bread(NULL, inode, block, 0);
103 	if (IS_ERR(bh)) {
104 		__ext4_warning(inode->i_sb, func, line,
105 			       "inode #%lu: lblock %lu: comm %s: "
106 			       "error %ld reading directory block",
107 			       inode->i_ino, (unsigned long)block,
108 			       current->comm, PTR_ERR(bh));
109 
110 		return bh;
111 	}
112 	if (!bh) {
113 		ext4_error_inode(inode, func, line, block,
114 				 "Directory hole found");
115 		return ERR_PTR(-EFSCORRUPTED);
116 	}
117 	dirent = (struct ext4_dir_entry *) bh->b_data;
118 	/* Determine whether or not we have an index block */
119 	if (is_dx(inode)) {
120 		if (block == 0)
121 			is_dx_block = 1;
122 		else if (ext4_rec_len_from_disk(dirent->rec_len,
123 						inode->i_sb->s_blocksize) ==
124 			 inode->i_sb->s_blocksize)
125 			is_dx_block = 1;
126 	}
127 	if (!is_dx_block && type == INDEX) {
128 		ext4_error_inode(inode, func, line, block,
129 		       "directory leaf block found instead of index block");
130 		brelse(bh);
131 		return ERR_PTR(-EFSCORRUPTED);
132 	}
133 	if (!ext4_has_metadata_csum(inode->i_sb) ||
134 	    buffer_verified(bh))
135 		return bh;
136 
137 	/*
138 	 * An empty leaf block can get mistaken for a index block; for
139 	 * this reason, we can only check the index checksum when the
140 	 * caller is sure it should be an index block.
141 	 */
142 	if (is_dx_block && type == INDEX) {
143 		if (ext4_dx_csum_verify(inode, dirent))
144 			set_buffer_verified(bh);
145 		else {
146 			ext4_error_inode(inode, func, line, block,
147 					 "Directory index failed checksum");
148 			brelse(bh);
149 			return ERR_PTR(-EFSBADCRC);
150 		}
151 	}
152 	if (!is_dx_block) {
153 		if (ext4_dirent_csum_verify(inode, dirent))
154 			set_buffer_verified(bh);
155 		else {
156 			ext4_error_inode(inode, func, line, block,
157 					 "Directory block failed checksum");
158 			brelse(bh);
159 			return ERR_PTR(-EFSBADCRC);
160 		}
161 	}
162 	return bh;
163 }
164 
165 #ifndef assert
166 #define assert(test) J_ASSERT(test)
167 #endif
168 
169 #ifdef DX_DEBUG
170 #define dxtrace(command) command
171 #else
172 #define dxtrace(command)
173 #endif
174 
175 struct fake_dirent
176 {
177 	__le32 inode;
178 	__le16 rec_len;
179 	u8 name_len;
180 	u8 file_type;
181 };
182 
183 struct dx_countlimit
184 {
185 	__le16 limit;
186 	__le16 count;
187 };
188 
189 struct dx_entry
190 {
191 	__le32 hash;
192 	__le32 block;
193 };
194 
195 /*
196  * dx_root_info is laid out so that if it should somehow get overlaid by a
197  * dirent the two low bits of the hash version will be zero.  Therefore, the
198  * hash version mod 4 should never be 0.  Sincerely, the paranoia department.
199  */
200 
201 struct dx_root
202 {
203 	struct fake_dirent dot;
204 	char dot_name[4];
205 	struct fake_dirent dotdot;
206 	char dotdot_name[4];
207 	struct dx_root_info
208 	{
209 		__le32 reserved_zero;
210 		u8 hash_version;
211 		u8 info_length; /* 8 */
212 		u8 indirect_levels;
213 		u8 unused_flags;
214 	}
215 	info;
216 	struct dx_entry	entries[0];
217 };
218 
219 struct dx_node
220 {
221 	struct fake_dirent fake;
222 	struct dx_entry	entries[0];
223 };
224 
225 
226 struct dx_frame
227 {
228 	struct buffer_head *bh;
229 	struct dx_entry *entries;
230 	struct dx_entry *at;
231 };
232 
233 struct dx_map_entry
234 {
235 	u32 hash;
236 	u16 offs;
237 	u16 size;
238 };
239 
240 /*
241  * This goes at the end of each htree block.
242  */
243 struct dx_tail {
244 	u32 dt_reserved;
245 	__le32 dt_checksum;	/* crc32c(uuid+inum+dirblock) */
246 };
247 
248 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry);
249 static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value);
250 static inline unsigned dx_get_hash(struct dx_entry *entry);
251 static void dx_set_hash(struct dx_entry *entry, unsigned value);
252 static unsigned dx_get_count(struct dx_entry *entries);
253 static unsigned dx_get_limit(struct dx_entry *entries);
254 static void dx_set_count(struct dx_entry *entries, unsigned value);
255 static void dx_set_limit(struct dx_entry *entries, unsigned value);
256 static unsigned dx_root_limit(struct inode *dir, unsigned infosize);
257 static unsigned dx_node_limit(struct inode *dir);
258 static struct dx_frame *dx_probe(struct ext4_filename *fname,
259 				 struct inode *dir,
260 				 struct dx_hash_info *hinfo,
261 				 struct dx_frame *frame);
262 static void dx_release(struct dx_frame *frames);
263 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
264 		       unsigned blocksize, struct dx_hash_info *hinfo,
265 		       struct dx_map_entry map[]);
266 static void dx_sort_map(struct dx_map_entry *map, unsigned count);
267 static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to,
268 		struct dx_map_entry *offsets, int count, unsigned blocksize);
269 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize);
270 static void dx_insert_block(struct dx_frame *frame,
271 					u32 hash, ext4_lblk_t block);
272 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
273 				 struct dx_frame *frame,
274 				 struct dx_frame *frames,
275 				 __u32 *start_hash);
276 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
277 		struct ext4_filename *fname,
278 		struct ext4_dir_entry_2 **res_dir);
279 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
280 			     struct inode *dir, struct inode *inode);
281 
282 /* checksumming functions */
283 void initialize_dirent_tail(struct ext4_dir_entry_tail *t,
284 			    unsigned int blocksize)
285 {
286 	memset(t, 0, sizeof(struct ext4_dir_entry_tail));
287 	t->det_rec_len = ext4_rec_len_to_disk(
288 			sizeof(struct ext4_dir_entry_tail), blocksize);
289 	t->det_reserved_ft = EXT4_FT_DIR_CSUM;
290 }
291 
292 /* Walk through a dirent block to find a checksum "dirent" at the tail */
293 static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode,
294 						   struct ext4_dir_entry *de)
295 {
296 	struct ext4_dir_entry_tail *t;
297 
298 #ifdef PARANOID
299 	struct ext4_dir_entry *d, *top;
300 
301 	d = de;
302 	top = (struct ext4_dir_entry *)(((void *)de) +
303 		(EXT4_BLOCK_SIZE(inode->i_sb) -
304 		sizeof(struct ext4_dir_entry_tail)));
305 	while (d < top && d->rec_len)
306 		d = (struct ext4_dir_entry *)(((void *)d) +
307 		    le16_to_cpu(d->rec_len));
308 
309 	if (d != top)
310 		return NULL;
311 
312 	t = (struct ext4_dir_entry_tail *)d;
313 #else
314 	t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb));
315 #endif
316 
317 	if (t->det_reserved_zero1 ||
318 	    le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) ||
319 	    t->det_reserved_zero2 ||
320 	    t->det_reserved_ft != EXT4_FT_DIR_CSUM)
321 		return NULL;
322 
323 	return t;
324 }
325 
326 static __le32 ext4_dirent_csum(struct inode *inode,
327 			       struct ext4_dir_entry *dirent, int size)
328 {
329 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
330 	struct ext4_inode_info *ei = EXT4_I(inode);
331 	__u32 csum;
332 
333 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
334 	return cpu_to_le32(csum);
335 }
336 
337 #define warn_no_space_for_csum(inode)					\
338 	__warn_no_space_for_csum((inode), __func__, __LINE__)
339 
340 static void __warn_no_space_for_csum(struct inode *inode, const char *func,
341 				     unsigned int line)
342 {
343 	__ext4_warning_inode(inode, func, line,
344 		"No space for directory leaf checksum. Please run e2fsck -D.");
345 }
346 
347 int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent)
348 {
349 	struct ext4_dir_entry_tail *t;
350 
351 	if (!ext4_has_metadata_csum(inode->i_sb))
352 		return 1;
353 
354 	t = get_dirent_tail(inode, dirent);
355 	if (!t) {
356 		warn_no_space_for_csum(inode);
357 		return 0;
358 	}
359 
360 	if (t->det_checksum != ext4_dirent_csum(inode, dirent,
361 						(void *)t - (void *)dirent))
362 		return 0;
363 
364 	return 1;
365 }
366 
367 static void ext4_dirent_csum_set(struct inode *inode,
368 				 struct ext4_dir_entry *dirent)
369 {
370 	struct ext4_dir_entry_tail *t;
371 
372 	if (!ext4_has_metadata_csum(inode->i_sb))
373 		return;
374 
375 	t = get_dirent_tail(inode, dirent);
376 	if (!t) {
377 		warn_no_space_for_csum(inode);
378 		return;
379 	}
380 
381 	t->det_checksum = ext4_dirent_csum(inode, dirent,
382 					   (void *)t - (void *)dirent);
383 }
384 
385 int ext4_handle_dirty_dirent_node(handle_t *handle,
386 				  struct inode *inode,
387 				  struct buffer_head *bh)
388 {
389 	ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
390 	return ext4_handle_dirty_metadata(handle, inode, bh);
391 }
392 
393 static struct dx_countlimit *get_dx_countlimit(struct inode *inode,
394 					       struct ext4_dir_entry *dirent,
395 					       int *offset)
396 {
397 	struct ext4_dir_entry *dp;
398 	struct dx_root_info *root;
399 	int count_offset;
400 
401 	if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb))
402 		count_offset = 8;
403 	else if (le16_to_cpu(dirent->rec_len) == 12) {
404 		dp = (struct ext4_dir_entry *)(((void *)dirent) + 12);
405 		if (le16_to_cpu(dp->rec_len) !=
406 		    EXT4_BLOCK_SIZE(inode->i_sb) - 12)
407 			return NULL;
408 		root = (struct dx_root_info *)(((void *)dp + 12));
409 		if (root->reserved_zero ||
410 		    root->info_length != sizeof(struct dx_root_info))
411 			return NULL;
412 		count_offset = 32;
413 	} else
414 		return NULL;
415 
416 	if (offset)
417 		*offset = count_offset;
418 	return (struct dx_countlimit *)(((void *)dirent) + count_offset);
419 }
420 
421 static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent,
422 			   int count_offset, int count, struct dx_tail *t)
423 {
424 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
425 	struct ext4_inode_info *ei = EXT4_I(inode);
426 	__u32 csum;
427 	int size;
428 	__u32 dummy_csum = 0;
429 	int offset = offsetof(struct dx_tail, dt_checksum);
430 
431 	size = count_offset + (count * sizeof(struct dx_entry));
432 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size);
433 	csum = ext4_chksum(sbi, csum, (__u8 *)t, offset);
434 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, sizeof(dummy_csum));
435 
436 	return cpu_to_le32(csum);
437 }
438 
439 static int ext4_dx_csum_verify(struct inode *inode,
440 			       struct ext4_dir_entry *dirent)
441 {
442 	struct dx_countlimit *c;
443 	struct dx_tail *t;
444 	int count_offset, limit, count;
445 
446 	if (!ext4_has_metadata_csum(inode->i_sb))
447 		return 1;
448 
449 	c = get_dx_countlimit(inode, dirent, &count_offset);
450 	if (!c) {
451 		EXT4_ERROR_INODE(inode, "dir seems corrupt?  Run e2fsck -D.");
452 		return 0;
453 	}
454 	limit = le16_to_cpu(c->limit);
455 	count = le16_to_cpu(c->count);
456 	if (count_offset + (limit * sizeof(struct dx_entry)) >
457 	    EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
458 		warn_no_space_for_csum(inode);
459 		return 0;
460 	}
461 	t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
462 
463 	if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset,
464 					    count, t))
465 		return 0;
466 	return 1;
467 }
468 
469 static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent)
470 {
471 	struct dx_countlimit *c;
472 	struct dx_tail *t;
473 	int count_offset, limit, count;
474 
475 	if (!ext4_has_metadata_csum(inode->i_sb))
476 		return;
477 
478 	c = get_dx_countlimit(inode, dirent, &count_offset);
479 	if (!c) {
480 		EXT4_ERROR_INODE(inode, "dir seems corrupt?  Run e2fsck -D.");
481 		return;
482 	}
483 	limit = le16_to_cpu(c->limit);
484 	count = le16_to_cpu(c->count);
485 	if (count_offset + (limit * sizeof(struct dx_entry)) >
486 	    EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) {
487 		warn_no_space_for_csum(inode);
488 		return;
489 	}
490 	t = (struct dx_tail *)(((struct dx_entry *)c) + limit);
491 
492 	t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t);
493 }
494 
495 static inline int ext4_handle_dirty_dx_node(handle_t *handle,
496 					    struct inode *inode,
497 					    struct buffer_head *bh)
498 {
499 	ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data);
500 	return ext4_handle_dirty_metadata(handle, inode, bh);
501 }
502 
503 /*
504  * p is at least 6 bytes before the end of page
505  */
506 static inline struct ext4_dir_entry_2 *
507 ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize)
508 {
509 	return (struct ext4_dir_entry_2 *)((char *)p +
510 		ext4_rec_len_from_disk(p->rec_len, blocksize));
511 }
512 
513 /*
514  * Future: use high four bits of block for coalesce-on-delete flags
515  * Mask them off for now.
516  */
517 
518 static inline ext4_lblk_t dx_get_block(struct dx_entry *entry)
519 {
520 	return le32_to_cpu(entry->block) & 0x0fffffff;
521 }
522 
523 static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value)
524 {
525 	entry->block = cpu_to_le32(value);
526 }
527 
528 static inline unsigned dx_get_hash(struct dx_entry *entry)
529 {
530 	return le32_to_cpu(entry->hash);
531 }
532 
533 static inline void dx_set_hash(struct dx_entry *entry, unsigned value)
534 {
535 	entry->hash = cpu_to_le32(value);
536 }
537 
538 static inline unsigned dx_get_count(struct dx_entry *entries)
539 {
540 	return le16_to_cpu(((struct dx_countlimit *) entries)->count);
541 }
542 
543 static inline unsigned dx_get_limit(struct dx_entry *entries)
544 {
545 	return le16_to_cpu(((struct dx_countlimit *) entries)->limit);
546 }
547 
548 static inline void dx_set_count(struct dx_entry *entries, unsigned value)
549 {
550 	((struct dx_countlimit *) entries)->count = cpu_to_le16(value);
551 }
552 
553 static inline void dx_set_limit(struct dx_entry *entries, unsigned value)
554 {
555 	((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
556 }
557 
558 static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize)
559 {
560 	unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) -
561 		EXT4_DIR_REC_LEN(2) - infosize;
562 
563 	if (ext4_has_metadata_csum(dir->i_sb))
564 		entry_space -= sizeof(struct dx_tail);
565 	return entry_space / sizeof(struct dx_entry);
566 }
567 
568 static inline unsigned dx_node_limit(struct inode *dir)
569 {
570 	unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0);
571 
572 	if (ext4_has_metadata_csum(dir->i_sb))
573 		entry_space -= sizeof(struct dx_tail);
574 	return entry_space / sizeof(struct dx_entry);
575 }
576 
577 /*
578  * Debug
579  */
580 #ifdef DX_DEBUG
581 static void dx_show_index(char * label, struct dx_entry *entries)
582 {
583 	int i, n = dx_get_count (entries);
584 	printk(KERN_DEBUG "%s index", label);
585 	for (i = 0; i < n; i++) {
586 		printk(KERN_CONT " %x->%lu",
587 		       i ? dx_get_hash(entries + i) : 0,
588 		       (unsigned long)dx_get_block(entries + i));
589 	}
590 	printk(KERN_CONT "\n");
591 }
592 
593 struct stats
594 {
595 	unsigned names;
596 	unsigned space;
597 	unsigned bcount;
598 };
599 
600 static struct stats dx_show_leaf(struct inode *dir,
601 				struct dx_hash_info *hinfo,
602 				struct ext4_dir_entry_2 *de,
603 				int size, int show_names)
604 {
605 	unsigned names = 0, space = 0;
606 	char *base = (char *) de;
607 	struct dx_hash_info h = *hinfo;
608 
609 	printk("names: ");
610 	while ((char *) de < base + size)
611 	{
612 		if (de->inode)
613 		{
614 			if (show_names)
615 			{
616 #ifdef CONFIG_FS_ENCRYPTION
617 				int len;
618 				char *name;
619 				struct fscrypt_str fname_crypto_str =
620 					FSTR_INIT(NULL, 0);
621 				int res = 0;
622 
623 				name  = de->name;
624 				len = de->name_len;
625 				if (IS_ENCRYPTED(dir))
626 					res = fscrypt_get_encryption_info(dir);
627 				if (res) {
628 					printk(KERN_WARNING "Error setting up"
629 					       " fname crypto: %d\n", res);
630 				}
631 				if (!fscrypt_has_encryption_key(dir)) {
632 					/* Directory is not encrypted */
633 					ext4fs_dirhash(dir, de->name,
634 						de->name_len, &h);
635 					printk("%*.s:(U)%x.%u ", len,
636 					       name, h.hash,
637 					       (unsigned) ((char *) de
638 							   - base));
639 				} else {
640 					struct fscrypt_str de_name =
641 						FSTR_INIT(name, len);
642 
643 					/* Directory is encrypted */
644 					res = fscrypt_fname_alloc_buffer(
645 						dir, len,
646 						&fname_crypto_str);
647 					if (res)
648 						printk(KERN_WARNING "Error "
649 							"allocating crypto "
650 							"buffer--skipping "
651 							"crypto\n");
652 					res = fscrypt_fname_disk_to_usr(dir,
653 						0, 0, &de_name,
654 						&fname_crypto_str);
655 					if (res) {
656 						printk(KERN_WARNING "Error "
657 							"converting filename "
658 							"from disk to usr"
659 							"\n");
660 						name = "??";
661 						len = 2;
662 					} else {
663 						name = fname_crypto_str.name;
664 						len = fname_crypto_str.len;
665 					}
666 					ext4fs_dirhash(dir, de->name,
667 						       de->name_len, &h);
668 					printk("%*.s:(E)%x.%u ", len, name,
669 					       h.hash, (unsigned) ((char *) de
670 								   - base));
671 					fscrypt_fname_free_buffer(
672 							&fname_crypto_str);
673 				}
674 #else
675 				int len = de->name_len;
676 				char *name = de->name;
677 				ext4fs_dirhash(dir, de->name, de->name_len, &h);
678 				printk("%*.s:%x.%u ", len, name, h.hash,
679 				       (unsigned) ((char *) de - base));
680 #endif
681 			}
682 			space += EXT4_DIR_REC_LEN(de->name_len);
683 			names++;
684 		}
685 		de = ext4_next_entry(de, size);
686 	}
687 	printk(KERN_CONT "(%i)\n", names);
688 	return (struct stats) { names, space, 1 };
689 }
690 
691 struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir,
692 			     struct dx_entry *entries, int levels)
693 {
694 	unsigned blocksize = dir->i_sb->s_blocksize;
695 	unsigned count = dx_get_count(entries), names = 0, space = 0, i;
696 	unsigned bcount = 0;
697 	struct buffer_head *bh;
698 	printk("%i indexed blocks...\n", count);
699 	for (i = 0; i < count; i++, entries++)
700 	{
701 		ext4_lblk_t block = dx_get_block(entries);
702 		ext4_lblk_t hash  = i ? dx_get_hash(entries): 0;
703 		u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash;
704 		struct stats stats;
705 		printk("%s%3u:%03u hash %8x/%8x ",levels?"":"   ", i, block, hash, range);
706 		bh = ext4_bread(NULL,dir, block, 0);
707 		if (!bh || IS_ERR(bh))
708 			continue;
709 		stats = levels?
710 		   dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1):
711 		   dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *)
712 			bh->b_data, blocksize, 0);
713 		names += stats.names;
714 		space += stats.space;
715 		bcount += stats.bcount;
716 		brelse(bh);
717 	}
718 	if (bcount)
719 		printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n",
720 		       levels ? "" : "   ", names, space/bcount,
721 		       (space/bcount)*100/blocksize);
722 	return (struct stats) { names, space, bcount};
723 }
724 #endif /* DX_DEBUG */
725 
726 /*
727  * Probe for a directory leaf block to search.
728  *
729  * dx_probe can return ERR_BAD_DX_DIR, which means there was a format
730  * error in the directory index, and the caller should fall back to
731  * searching the directory normally.  The callers of dx_probe **MUST**
732  * check for this error code, and make sure it never gets reflected
733  * back to userspace.
734  */
735 static struct dx_frame *
736 dx_probe(struct ext4_filename *fname, struct inode *dir,
737 	 struct dx_hash_info *hinfo, struct dx_frame *frame_in)
738 {
739 	unsigned count, indirect;
740 	struct dx_entry *at, *entries, *p, *q, *m;
741 	struct dx_root *root;
742 	struct dx_frame *frame = frame_in;
743 	struct dx_frame *ret_err = ERR_PTR(ERR_BAD_DX_DIR);
744 	u32 hash;
745 
746 	memset(frame_in, 0, EXT4_HTREE_LEVEL * sizeof(frame_in[0]));
747 	frame->bh = ext4_read_dirblock(dir, 0, INDEX);
748 	if (IS_ERR(frame->bh))
749 		return (struct dx_frame *) frame->bh;
750 
751 	root = (struct dx_root *) frame->bh->b_data;
752 	if (root->info.hash_version != DX_HASH_TEA &&
753 	    root->info.hash_version != DX_HASH_HALF_MD4 &&
754 	    root->info.hash_version != DX_HASH_LEGACY) {
755 		ext4_warning_inode(dir, "Unrecognised inode hash code %u",
756 				   root->info.hash_version);
757 		goto fail;
758 	}
759 	if (fname)
760 		hinfo = &fname->hinfo;
761 	hinfo->hash_version = root->info.hash_version;
762 	if (hinfo->hash_version <= DX_HASH_TEA)
763 		hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
764 	hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed;
765 	if (fname && fname_name(fname))
766 		ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), hinfo);
767 	hash = hinfo->hash;
768 
769 	if (root->info.unused_flags & 1) {
770 		ext4_warning_inode(dir, "Unimplemented hash flags: %#06x",
771 				   root->info.unused_flags);
772 		goto fail;
773 	}
774 
775 	indirect = root->info.indirect_levels;
776 	if (indirect >= ext4_dir_htree_level(dir->i_sb)) {
777 		ext4_warning(dir->i_sb,
778 			     "Directory (ino: %lu) htree depth %#06x exceed"
779 			     "supported value", dir->i_ino,
780 			     ext4_dir_htree_level(dir->i_sb));
781 		if (ext4_dir_htree_level(dir->i_sb) < EXT4_HTREE_LEVEL) {
782 			ext4_warning(dir->i_sb, "Enable large directory "
783 						"feature to access it");
784 		}
785 		goto fail;
786 	}
787 
788 	entries = (struct dx_entry *)(((char *)&root->info) +
789 				      root->info.info_length);
790 
791 	if (dx_get_limit(entries) != dx_root_limit(dir,
792 						   root->info.info_length)) {
793 		ext4_warning_inode(dir, "dx entry: limit %u != root limit %u",
794 				   dx_get_limit(entries),
795 				   dx_root_limit(dir, root->info.info_length));
796 		goto fail;
797 	}
798 
799 	dxtrace(printk("Look up %x", hash));
800 	while (1) {
801 		count = dx_get_count(entries);
802 		if (!count || count > dx_get_limit(entries)) {
803 			ext4_warning_inode(dir,
804 					   "dx entry: count %u beyond limit %u",
805 					   count, dx_get_limit(entries));
806 			goto fail;
807 		}
808 
809 		p = entries + 1;
810 		q = entries + count - 1;
811 		while (p <= q) {
812 			m = p + (q - p) / 2;
813 			dxtrace(printk(KERN_CONT "."));
814 			if (dx_get_hash(m) > hash)
815 				q = m - 1;
816 			else
817 				p = m + 1;
818 		}
819 
820 		if (0) { // linear search cross check
821 			unsigned n = count - 1;
822 			at = entries;
823 			while (n--)
824 			{
825 				dxtrace(printk(KERN_CONT ","));
826 				if (dx_get_hash(++at) > hash)
827 				{
828 					at--;
829 					break;
830 				}
831 			}
832 			assert (at == p - 1);
833 		}
834 
835 		at = p - 1;
836 		dxtrace(printk(KERN_CONT " %x->%u\n",
837 			       at == entries ? 0 : dx_get_hash(at),
838 			       dx_get_block(at)));
839 		frame->entries = entries;
840 		frame->at = at;
841 		if (!indirect--)
842 			return frame;
843 		frame++;
844 		frame->bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX);
845 		if (IS_ERR(frame->bh)) {
846 			ret_err = (struct dx_frame *) frame->bh;
847 			frame->bh = NULL;
848 			goto fail;
849 		}
850 		entries = ((struct dx_node *) frame->bh->b_data)->entries;
851 
852 		if (dx_get_limit(entries) != dx_node_limit(dir)) {
853 			ext4_warning_inode(dir,
854 				"dx entry: limit %u != node limit %u",
855 				dx_get_limit(entries), dx_node_limit(dir));
856 			goto fail;
857 		}
858 	}
859 fail:
860 	while (frame >= frame_in) {
861 		brelse(frame->bh);
862 		frame--;
863 	}
864 
865 	if (ret_err == ERR_PTR(ERR_BAD_DX_DIR))
866 		ext4_warning_inode(dir,
867 			"Corrupt directory, running e2fsck is recommended");
868 	return ret_err;
869 }
870 
871 static void dx_release(struct dx_frame *frames)
872 {
873 	struct dx_root_info *info;
874 	int i;
875 
876 	if (frames[0].bh == NULL)
877 		return;
878 
879 	info = &((struct dx_root *)frames[0].bh->b_data)->info;
880 	for (i = 0; i <= info->indirect_levels; i++) {
881 		if (frames[i].bh == NULL)
882 			break;
883 		brelse(frames[i].bh);
884 		frames[i].bh = NULL;
885 	}
886 }
887 
888 /*
889  * This function increments the frame pointer to search the next leaf
890  * block, and reads in the necessary intervening nodes if the search
891  * should be necessary.  Whether or not the search is necessary is
892  * controlled by the hash parameter.  If the hash value is even, then
893  * the search is only continued if the next block starts with that
894  * hash value.  This is used if we are searching for a specific file.
895  *
896  * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
897  *
898  * This function returns 1 if the caller should continue to search,
899  * or 0 if it should not.  If there is an error reading one of the
900  * index blocks, it will a negative error code.
901  *
902  * If start_hash is non-null, it will be filled in with the starting
903  * hash of the next page.
904  */
905 static int ext4_htree_next_block(struct inode *dir, __u32 hash,
906 				 struct dx_frame *frame,
907 				 struct dx_frame *frames,
908 				 __u32 *start_hash)
909 {
910 	struct dx_frame *p;
911 	struct buffer_head *bh;
912 	int num_frames = 0;
913 	__u32 bhash;
914 
915 	p = frame;
916 	/*
917 	 * Find the next leaf page by incrementing the frame pointer.
918 	 * If we run out of entries in the interior node, loop around and
919 	 * increment pointer in the parent node.  When we break out of
920 	 * this loop, num_frames indicates the number of interior
921 	 * nodes need to be read.
922 	 */
923 	while (1) {
924 		if (++(p->at) < p->entries + dx_get_count(p->entries))
925 			break;
926 		if (p == frames)
927 			return 0;
928 		num_frames++;
929 		p--;
930 	}
931 
932 	/*
933 	 * If the hash is 1, then continue only if the next page has a
934 	 * continuation hash of any value.  This is used for readdir
935 	 * handling.  Otherwise, check to see if the hash matches the
936 	 * desired contiuation hash.  If it doesn't, return since
937 	 * there's no point to read in the successive index pages.
938 	 */
939 	bhash = dx_get_hash(p->at);
940 	if (start_hash)
941 		*start_hash = bhash;
942 	if ((hash & 1) == 0) {
943 		if ((bhash & ~1) != hash)
944 			return 0;
945 	}
946 	/*
947 	 * If the hash is HASH_NB_ALWAYS, we always go to the next
948 	 * block so no check is necessary
949 	 */
950 	while (num_frames--) {
951 		bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
952 		if (IS_ERR(bh))
953 			return PTR_ERR(bh);
954 		p++;
955 		brelse(p->bh);
956 		p->bh = bh;
957 		p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
958 	}
959 	return 1;
960 }
961 
962 
963 /*
964  * This function fills a red-black tree with information from a
965  * directory block.  It returns the number directory entries loaded
966  * into the tree.  If there is an error it is returned in err.
967  */
968 static int htree_dirblock_to_tree(struct file *dir_file,
969 				  struct inode *dir, ext4_lblk_t block,
970 				  struct dx_hash_info *hinfo,
971 				  __u32 start_hash, __u32 start_minor_hash)
972 {
973 	struct buffer_head *bh;
974 	struct ext4_dir_entry_2 *de, *top;
975 	int err = 0, count = 0;
976 	struct fscrypt_str fname_crypto_str = FSTR_INIT(NULL, 0), tmp_str;
977 
978 	dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n",
979 							(unsigned long)block));
980 	bh = ext4_read_dirblock(dir, block, DIRENT);
981 	if (IS_ERR(bh))
982 		return PTR_ERR(bh);
983 
984 	de = (struct ext4_dir_entry_2 *) bh->b_data;
985 	top = (struct ext4_dir_entry_2 *) ((char *) de +
986 					   dir->i_sb->s_blocksize -
987 					   EXT4_DIR_REC_LEN(0));
988 #ifdef CONFIG_FS_ENCRYPTION
989 	/* Check if the directory is encrypted */
990 	if (IS_ENCRYPTED(dir)) {
991 		err = fscrypt_get_encryption_info(dir);
992 		if (err < 0) {
993 			brelse(bh);
994 			return err;
995 		}
996 		err = fscrypt_fname_alloc_buffer(dir, EXT4_NAME_LEN,
997 						     &fname_crypto_str);
998 		if (err < 0) {
999 			brelse(bh);
1000 			return err;
1001 		}
1002 	}
1003 #endif
1004 	for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) {
1005 		if (ext4_check_dir_entry(dir, NULL, de, bh,
1006 				bh->b_data, bh->b_size,
1007 				(block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb))
1008 					 + ((char *)de - bh->b_data))) {
1009 			/* silently ignore the rest of the block */
1010 			break;
1011 		}
1012 		ext4fs_dirhash(dir, de->name, de->name_len, hinfo);
1013 		if ((hinfo->hash < start_hash) ||
1014 		    ((hinfo->hash == start_hash) &&
1015 		     (hinfo->minor_hash < start_minor_hash)))
1016 			continue;
1017 		if (de->inode == 0)
1018 			continue;
1019 		if (!IS_ENCRYPTED(dir)) {
1020 			tmp_str.name = de->name;
1021 			tmp_str.len = de->name_len;
1022 			err = ext4_htree_store_dirent(dir_file,
1023 				   hinfo->hash, hinfo->minor_hash, de,
1024 				   &tmp_str);
1025 		} else {
1026 			int save_len = fname_crypto_str.len;
1027 			struct fscrypt_str de_name = FSTR_INIT(de->name,
1028 								de->name_len);
1029 
1030 			/* Directory is encrypted */
1031 			err = fscrypt_fname_disk_to_usr(dir, hinfo->hash,
1032 					hinfo->minor_hash, &de_name,
1033 					&fname_crypto_str);
1034 			if (err) {
1035 				count = err;
1036 				goto errout;
1037 			}
1038 			err = ext4_htree_store_dirent(dir_file,
1039 				   hinfo->hash, hinfo->minor_hash, de,
1040 					&fname_crypto_str);
1041 			fname_crypto_str.len = save_len;
1042 		}
1043 		if (err != 0) {
1044 			count = err;
1045 			goto errout;
1046 		}
1047 		count++;
1048 	}
1049 errout:
1050 	brelse(bh);
1051 #ifdef CONFIG_FS_ENCRYPTION
1052 	fscrypt_fname_free_buffer(&fname_crypto_str);
1053 #endif
1054 	return count;
1055 }
1056 
1057 
1058 /*
1059  * This function fills a red-black tree with information from a
1060  * directory.  We start scanning the directory in hash order, starting
1061  * at start_hash and start_minor_hash.
1062  *
1063  * This function returns the number of entries inserted into the tree,
1064  * or a negative error code.
1065  */
1066 int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
1067 			 __u32 start_minor_hash, __u32 *next_hash)
1068 {
1069 	struct dx_hash_info hinfo;
1070 	struct ext4_dir_entry_2 *de;
1071 	struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1072 	struct inode *dir;
1073 	ext4_lblk_t block;
1074 	int count = 0;
1075 	int ret, err;
1076 	__u32 hashval;
1077 	struct fscrypt_str tmp_str;
1078 
1079 	dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n",
1080 		       start_hash, start_minor_hash));
1081 	dir = file_inode(dir_file);
1082 	if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) {
1083 		hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
1084 		if (hinfo.hash_version <= DX_HASH_TEA)
1085 			hinfo.hash_version +=
1086 				EXT4_SB(dir->i_sb)->s_hash_unsigned;
1087 		hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
1088 		if (ext4_has_inline_data(dir)) {
1089 			int has_inline_data = 1;
1090 			count = htree_inlinedir_to_tree(dir_file, dir, 0,
1091 							&hinfo, start_hash,
1092 							start_minor_hash,
1093 							&has_inline_data);
1094 			if (has_inline_data) {
1095 				*next_hash = ~0;
1096 				return count;
1097 			}
1098 		}
1099 		count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo,
1100 					       start_hash, start_minor_hash);
1101 		*next_hash = ~0;
1102 		return count;
1103 	}
1104 	hinfo.hash = start_hash;
1105 	hinfo.minor_hash = 0;
1106 	frame = dx_probe(NULL, dir, &hinfo, frames);
1107 	if (IS_ERR(frame))
1108 		return PTR_ERR(frame);
1109 
1110 	/* Add '.' and '..' from the htree header */
1111 	if (!start_hash && !start_minor_hash) {
1112 		de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1113 		tmp_str.name = de->name;
1114 		tmp_str.len = de->name_len;
1115 		err = ext4_htree_store_dirent(dir_file, 0, 0,
1116 					      de, &tmp_str);
1117 		if (err != 0)
1118 			goto errout;
1119 		count++;
1120 	}
1121 	if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) {
1122 		de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data;
1123 		de = ext4_next_entry(de, dir->i_sb->s_blocksize);
1124 		tmp_str.name = de->name;
1125 		tmp_str.len = de->name_len;
1126 		err = ext4_htree_store_dirent(dir_file, 2, 0,
1127 					      de, &tmp_str);
1128 		if (err != 0)
1129 			goto errout;
1130 		count++;
1131 	}
1132 
1133 	while (1) {
1134 		if (fatal_signal_pending(current)) {
1135 			err = -ERESTARTSYS;
1136 			goto errout;
1137 		}
1138 		cond_resched();
1139 		block = dx_get_block(frame->at);
1140 		ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo,
1141 					     start_hash, start_minor_hash);
1142 		if (ret < 0) {
1143 			err = ret;
1144 			goto errout;
1145 		}
1146 		count += ret;
1147 		hashval = ~0;
1148 		ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS,
1149 					    frame, frames, &hashval);
1150 		*next_hash = hashval;
1151 		if (ret < 0) {
1152 			err = ret;
1153 			goto errout;
1154 		}
1155 		/*
1156 		 * Stop if:  (a) there are no more entries, or
1157 		 * (b) we have inserted at least one entry and the
1158 		 * next hash value is not a continuation
1159 		 */
1160 		if ((ret == 0) ||
1161 		    (count && ((hashval & 1) == 0)))
1162 			break;
1163 	}
1164 	dx_release(frames);
1165 	dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, "
1166 		       "next hash: %x\n", count, *next_hash));
1167 	return count;
1168 errout:
1169 	dx_release(frames);
1170 	return (err);
1171 }
1172 
1173 static inline int search_dirblock(struct buffer_head *bh,
1174 				  struct inode *dir,
1175 				  struct ext4_filename *fname,
1176 				  unsigned int offset,
1177 				  struct ext4_dir_entry_2 **res_dir)
1178 {
1179 	return ext4_search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir,
1180 			       fname, offset, res_dir);
1181 }
1182 
1183 /*
1184  * Directory block splitting, compacting
1185  */
1186 
1187 /*
1188  * Create map of hash values, offsets, and sizes, stored at end of block.
1189  * Returns number of entries mapped.
1190  */
1191 static int dx_make_map(struct inode *dir, struct ext4_dir_entry_2 *de,
1192 		       unsigned blocksize, struct dx_hash_info *hinfo,
1193 		       struct dx_map_entry *map_tail)
1194 {
1195 	int count = 0;
1196 	char *base = (char *) de;
1197 	struct dx_hash_info h = *hinfo;
1198 
1199 	while ((char *) de < base + blocksize) {
1200 		if (de->name_len && de->inode) {
1201 			ext4fs_dirhash(dir, de->name, de->name_len, &h);
1202 			map_tail--;
1203 			map_tail->hash = h.hash;
1204 			map_tail->offs = ((char *) de - base)>>2;
1205 			map_tail->size = le16_to_cpu(de->rec_len);
1206 			count++;
1207 			cond_resched();
1208 		}
1209 		/* XXX: do we need to check rec_len == 0 case? -Chris */
1210 		de = ext4_next_entry(de, blocksize);
1211 	}
1212 	return count;
1213 }
1214 
1215 /* Sort map by hash value */
1216 static void dx_sort_map (struct dx_map_entry *map, unsigned count)
1217 {
1218 	struct dx_map_entry *p, *q, *top = map + count - 1;
1219 	int more;
1220 	/* Combsort until bubble sort doesn't suck */
1221 	while (count > 2) {
1222 		count = count*10/13;
1223 		if (count - 9 < 2) /* 9, 10 -> 11 */
1224 			count = 11;
1225 		for (p = top, q = p - count; q >= map; p--, q--)
1226 			if (p->hash < q->hash)
1227 				swap(*p, *q);
1228 	}
1229 	/* Garden variety bubble sort */
1230 	do {
1231 		more = 0;
1232 		q = top;
1233 		while (q-- > map) {
1234 			if (q[1].hash >= q[0].hash)
1235 				continue;
1236 			swap(*(q+1), *q);
1237 			more = 1;
1238 		}
1239 	} while(more);
1240 }
1241 
1242 static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block)
1243 {
1244 	struct dx_entry *entries = frame->entries;
1245 	struct dx_entry *old = frame->at, *new = old + 1;
1246 	int count = dx_get_count(entries);
1247 
1248 	assert(count < dx_get_limit(entries));
1249 	assert(old < entries + count);
1250 	memmove(new + 1, new, (char *)(entries + count) - (char *)(new));
1251 	dx_set_hash(new, hash);
1252 	dx_set_block(new, block);
1253 	dx_set_count(entries, count + 1);
1254 }
1255 
1256 #ifdef CONFIG_UNICODE
1257 /*
1258  * Test whether a case-insensitive directory entry matches the filename
1259  * being searched for.
1260  *
1261  * Returns: 0 if the directory entry matches, more than 0 if it
1262  * doesn't match or less than zero on error.
1263  */
1264 int ext4_ci_compare(const struct inode *parent, const struct qstr *name,
1265 		    const struct qstr *entry)
1266 {
1267 	const struct ext4_sb_info *sbi = EXT4_SB(parent->i_sb);
1268 	const struct unicode_map *um = sbi->s_encoding;
1269 	int ret;
1270 
1271 	ret = utf8_strncasecmp(um, name, entry);
1272 	if (ret < 0) {
1273 		/* Handle invalid character sequence as either an error
1274 		 * or as an opaque byte sequence.
1275 		 */
1276 		if (ext4_has_strict_mode(sbi))
1277 			return -EINVAL;
1278 
1279 		if (name->len != entry->len)
1280 			return 1;
1281 
1282 		return !!memcmp(name->name, entry->name, name->len);
1283 	}
1284 
1285 	return ret;
1286 }
1287 #endif
1288 
1289 /*
1290  * Test whether a directory entry matches the filename being searched for.
1291  *
1292  * Return: %true if the directory entry matches, otherwise %false.
1293  */
1294 static inline bool ext4_match(const struct inode *parent,
1295 			      const struct ext4_filename *fname,
1296 			      const struct ext4_dir_entry_2 *de)
1297 {
1298 	struct fscrypt_name f;
1299 #ifdef CONFIG_UNICODE
1300 	const struct qstr entry = {.name = de->name, .len = de->name_len};
1301 #endif
1302 
1303 	if (!de->inode)
1304 		return false;
1305 
1306 	f.usr_fname = fname->usr_fname;
1307 	f.disk_name = fname->disk_name;
1308 #ifdef CONFIG_FS_ENCRYPTION
1309 	f.crypto_buf = fname->crypto_buf;
1310 #endif
1311 
1312 #ifdef CONFIG_UNICODE
1313 	if (EXT4_SB(parent->i_sb)->s_encoding && IS_CASEFOLDED(parent))
1314 		return (ext4_ci_compare(parent, fname->usr_fname, &entry) == 0);
1315 #endif
1316 
1317 	return fscrypt_match_name(&f, de->name, de->name_len);
1318 }
1319 
1320 /*
1321  * Returns 0 if not found, -1 on failure, and 1 on success
1322  */
1323 int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,
1324 		    struct inode *dir, struct ext4_filename *fname,
1325 		    unsigned int offset, struct ext4_dir_entry_2 **res_dir)
1326 {
1327 	struct ext4_dir_entry_2 * de;
1328 	char * dlimit;
1329 	int de_len;
1330 
1331 	de = (struct ext4_dir_entry_2 *)search_buf;
1332 	dlimit = search_buf + buf_size;
1333 	while ((char *) de < dlimit) {
1334 		/* this code is executed quadratically often */
1335 		/* do minimal checking `by hand' */
1336 		if ((char *) de + de->name_len <= dlimit &&
1337 		    ext4_match(dir, fname, de)) {
1338 			/* found a match - just to be sure, do
1339 			 * a full check */
1340 			if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data,
1341 						 bh->b_size, offset))
1342 				return -1;
1343 			*res_dir = de;
1344 			return 1;
1345 		}
1346 		/* prevent looping on a bad block */
1347 		de_len = ext4_rec_len_from_disk(de->rec_len,
1348 						dir->i_sb->s_blocksize);
1349 		if (de_len <= 0)
1350 			return -1;
1351 		offset += de_len;
1352 		de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
1353 	}
1354 	return 0;
1355 }
1356 
1357 static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block,
1358 			       struct ext4_dir_entry *de)
1359 {
1360 	struct super_block *sb = dir->i_sb;
1361 
1362 	if (!is_dx(dir))
1363 		return 0;
1364 	if (block == 0)
1365 		return 1;
1366 	if (de->inode == 0 &&
1367 	    ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) ==
1368 			sb->s_blocksize)
1369 		return 1;
1370 	return 0;
1371 }
1372 
1373 /*
1374  *	__ext4_find_entry()
1375  *
1376  * finds an entry in the specified directory with the wanted name. It
1377  * returns the cache buffer in which the entry was found, and the entry
1378  * itself (as a parameter - res_dir). It does NOT read the inode of the
1379  * entry - you'll have to do that yourself if you want to.
1380  *
1381  * The returned buffer_head has ->b_count elevated.  The caller is expected
1382  * to brelse() it when appropriate.
1383  */
1384 static struct buffer_head *__ext4_find_entry(struct inode *dir,
1385 					     struct ext4_filename *fname,
1386 					     struct ext4_dir_entry_2 **res_dir,
1387 					     int *inlined)
1388 {
1389 	struct super_block *sb;
1390 	struct buffer_head *bh_use[NAMEI_RA_SIZE];
1391 	struct buffer_head *bh, *ret = NULL;
1392 	ext4_lblk_t start, block;
1393 	const u8 *name = fname->usr_fname->name;
1394 	size_t ra_max = 0;	/* Number of bh's in the readahead
1395 				   buffer, bh_use[] */
1396 	size_t ra_ptr = 0;	/* Current index into readahead
1397 				   buffer */
1398 	ext4_lblk_t  nblocks;
1399 	int i, namelen, retval;
1400 
1401 	*res_dir = NULL;
1402 	sb = dir->i_sb;
1403 	namelen = fname->usr_fname->len;
1404 	if (namelen > EXT4_NAME_LEN)
1405 		return NULL;
1406 
1407 	if (ext4_has_inline_data(dir)) {
1408 		int has_inline_data = 1;
1409 		ret = ext4_find_inline_entry(dir, fname, res_dir,
1410 					     &has_inline_data);
1411 		if (has_inline_data) {
1412 			if (inlined)
1413 				*inlined = 1;
1414 			goto cleanup_and_exit;
1415 		}
1416 	}
1417 
1418 	if ((namelen <= 2) && (name[0] == '.') &&
1419 	    (name[1] == '.' || name[1] == '\0')) {
1420 		/*
1421 		 * "." or ".." will only be in the first block
1422 		 * NFS may look up ".."; "." should be handled by the VFS
1423 		 */
1424 		block = start = 0;
1425 		nblocks = 1;
1426 		goto restart;
1427 	}
1428 	if (is_dx(dir)) {
1429 		ret = ext4_dx_find_entry(dir, fname, res_dir);
1430 		/*
1431 		 * On success, or if the error was file not found,
1432 		 * return.  Otherwise, fall back to doing a search the
1433 		 * old fashioned way.
1434 		 */
1435 		if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1436 			goto cleanup_and_exit;
1437 		dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1438 			       "falling back\n"));
1439 		ret = NULL;
1440 	}
1441 	nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1442 	if (!nblocks) {
1443 		ret = NULL;
1444 		goto cleanup_and_exit;
1445 	}
1446 	start = EXT4_I(dir)->i_dir_start_lookup;
1447 	if (start >= nblocks)
1448 		start = 0;
1449 	block = start;
1450 restart:
1451 	do {
1452 		/*
1453 		 * We deal with the read-ahead logic here.
1454 		 */
1455 		if (ra_ptr >= ra_max) {
1456 			/* Refill the readahead buffer */
1457 			ra_ptr = 0;
1458 			if (block < start)
1459 				ra_max = start - block;
1460 			else
1461 				ra_max = nblocks - block;
1462 			ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1463 			retval = ext4_bread_batch(dir, block, ra_max,
1464 						  false /* wait */, bh_use);
1465 			if (retval) {
1466 				ret = ERR_PTR(retval);
1467 				ra_max = 0;
1468 				goto cleanup_and_exit;
1469 			}
1470 		}
1471 		if ((bh = bh_use[ra_ptr++]) == NULL)
1472 			goto next;
1473 		wait_on_buffer(bh);
1474 		if (!buffer_uptodate(bh)) {
1475 			EXT4_ERROR_INODE(dir, "reading directory lblock %lu",
1476 					 (unsigned long) block);
1477 			brelse(bh);
1478 			ret = ERR_PTR(-EIO);
1479 			goto cleanup_and_exit;
1480 		}
1481 		if (!buffer_verified(bh) &&
1482 		    !is_dx_internal_node(dir, block,
1483 					 (struct ext4_dir_entry *)bh->b_data) &&
1484 		    !ext4_dirent_csum_verify(dir,
1485 				(struct ext4_dir_entry *)bh->b_data)) {
1486 			EXT4_ERROR_INODE(dir, "checksumming directory "
1487 					 "block %lu", (unsigned long)block);
1488 			brelse(bh);
1489 			ret = ERR_PTR(-EFSBADCRC);
1490 			goto cleanup_and_exit;
1491 		}
1492 		set_buffer_verified(bh);
1493 		i = search_dirblock(bh, dir, fname,
1494 			    block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1495 		if (i == 1) {
1496 			EXT4_I(dir)->i_dir_start_lookup = block;
1497 			ret = bh;
1498 			goto cleanup_and_exit;
1499 		} else {
1500 			brelse(bh);
1501 			if (i < 0)
1502 				goto cleanup_and_exit;
1503 		}
1504 	next:
1505 		if (++block >= nblocks)
1506 			block = 0;
1507 	} while (block != start);
1508 
1509 	/*
1510 	 * If the directory has grown while we were searching, then
1511 	 * search the last part of the directory before giving up.
1512 	 */
1513 	block = nblocks;
1514 	nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1515 	if (block < nblocks) {
1516 		start = 0;
1517 		goto restart;
1518 	}
1519 
1520 cleanup_and_exit:
1521 	/* Clean up the read-ahead blocks */
1522 	for (; ra_ptr < ra_max; ra_ptr++)
1523 		brelse(bh_use[ra_ptr]);
1524 	return ret;
1525 }
1526 
1527 static struct buffer_head *ext4_find_entry(struct inode *dir,
1528 					   const struct qstr *d_name,
1529 					   struct ext4_dir_entry_2 **res_dir,
1530 					   int *inlined)
1531 {
1532 	int err;
1533 	struct ext4_filename fname;
1534 	struct buffer_head *bh;
1535 
1536 	err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1537 	if (err == -ENOENT)
1538 		return NULL;
1539 	if (err)
1540 		return ERR_PTR(err);
1541 
1542 	bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
1543 
1544 	ext4_fname_free_filename(&fname);
1545 	return bh;
1546 }
1547 
1548 static struct buffer_head *ext4_lookup_entry(struct inode *dir,
1549 					     struct dentry *dentry,
1550 					     struct ext4_dir_entry_2 **res_dir)
1551 {
1552 	int err;
1553 	struct ext4_filename fname;
1554 	struct buffer_head *bh;
1555 
1556 	err = ext4_fname_prepare_lookup(dir, dentry, &fname);
1557 	if (err == -ENOENT)
1558 		return NULL;
1559 	if (err)
1560 		return ERR_PTR(err);
1561 
1562 	bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
1563 
1564 	ext4_fname_free_filename(&fname);
1565 	return bh;
1566 }
1567 
1568 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1569 			struct ext4_filename *fname,
1570 			struct ext4_dir_entry_2 **res_dir)
1571 {
1572 	struct super_block * sb = dir->i_sb;
1573 	struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1574 	struct buffer_head *bh;
1575 	ext4_lblk_t block;
1576 	int retval;
1577 
1578 #ifdef CONFIG_FS_ENCRYPTION
1579 	*res_dir = NULL;
1580 #endif
1581 	frame = dx_probe(fname, dir, NULL, frames);
1582 	if (IS_ERR(frame))
1583 		return (struct buffer_head *) frame;
1584 	do {
1585 		block = dx_get_block(frame->at);
1586 		bh = ext4_read_dirblock(dir, block, DIRENT);
1587 		if (IS_ERR(bh))
1588 			goto errout;
1589 
1590 		retval = search_dirblock(bh, dir, fname,
1591 					 block << EXT4_BLOCK_SIZE_BITS(sb),
1592 					 res_dir);
1593 		if (retval == 1)
1594 			goto success;
1595 		brelse(bh);
1596 		if (retval == -1) {
1597 			bh = ERR_PTR(ERR_BAD_DX_DIR);
1598 			goto errout;
1599 		}
1600 
1601 		/* Check to see if we should continue to search */
1602 		retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1603 					       frames, NULL);
1604 		if (retval < 0) {
1605 			ext4_warning_inode(dir,
1606 				"error %d reading directory index block",
1607 				retval);
1608 			bh = ERR_PTR(retval);
1609 			goto errout;
1610 		}
1611 	} while (retval == 1);
1612 
1613 	bh = NULL;
1614 errout:
1615 	dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1616 success:
1617 	dx_release(frames);
1618 	return bh;
1619 }
1620 
1621 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1622 {
1623 	struct inode *inode;
1624 	struct ext4_dir_entry_2 *de;
1625 	struct buffer_head *bh;
1626 
1627 	if (dentry->d_name.len > EXT4_NAME_LEN)
1628 		return ERR_PTR(-ENAMETOOLONG);
1629 
1630 	bh = ext4_lookup_entry(dir, dentry, &de);
1631 	if (IS_ERR(bh))
1632 		return ERR_CAST(bh);
1633 	inode = NULL;
1634 	if (bh) {
1635 		__u32 ino = le32_to_cpu(de->inode);
1636 		brelse(bh);
1637 		if (!ext4_valid_inum(dir->i_sb, ino)) {
1638 			EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1639 			return ERR_PTR(-EFSCORRUPTED);
1640 		}
1641 		if (unlikely(ino == dir->i_ino)) {
1642 			EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1643 					 dentry);
1644 			return ERR_PTR(-EFSCORRUPTED);
1645 		}
1646 		inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1647 		if (inode == ERR_PTR(-ESTALE)) {
1648 			EXT4_ERROR_INODE(dir,
1649 					 "deleted inode referenced: %u",
1650 					 ino);
1651 			return ERR_PTR(-EFSCORRUPTED);
1652 		}
1653 		if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
1654 		    (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1655 		    !fscrypt_has_permitted_context(dir, inode)) {
1656 			ext4_warning(inode->i_sb,
1657 				     "Inconsistent encryption contexts: %lu/%lu",
1658 				     dir->i_ino, inode->i_ino);
1659 			iput(inode);
1660 			return ERR_PTR(-EPERM);
1661 		}
1662 	}
1663 
1664 #ifdef CONFIG_UNICODE
1665 	if (!inode && IS_CASEFOLDED(dir)) {
1666 		/* Eventually we want to call d_add_ci(dentry, NULL)
1667 		 * for negative dentries in the encoding case as
1668 		 * well.  For now, prevent the negative dentry
1669 		 * from being cached.
1670 		 */
1671 		return NULL;
1672 	}
1673 #endif
1674 	return d_splice_alias(inode, dentry);
1675 }
1676 
1677 
1678 struct dentry *ext4_get_parent(struct dentry *child)
1679 {
1680 	__u32 ino;
1681 	static const struct qstr dotdot = QSTR_INIT("..", 2);
1682 	struct ext4_dir_entry_2 * de;
1683 	struct buffer_head *bh;
1684 
1685 	bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1686 	if (IS_ERR(bh))
1687 		return ERR_CAST(bh);
1688 	if (!bh)
1689 		return ERR_PTR(-ENOENT);
1690 	ino = le32_to_cpu(de->inode);
1691 	brelse(bh);
1692 
1693 	if (!ext4_valid_inum(child->d_sb, ino)) {
1694 		EXT4_ERROR_INODE(d_inode(child),
1695 				 "bad parent inode number: %u", ino);
1696 		return ERR_PTR(-EFSCORRUPTED);
1697 	}
1698 
1699 	return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1700 }
1701 
1702 /*
1703  * Move count entries from end of map between two memory locations.
1704  * Returns pointer to last entry moved.
1705  */
1706 static struct ext4_dir_entry_2 *
1707 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1708 		unsigned blocksize)
1709 {
1710 	unsigned rec_len = 0;
1711 
1712 	while (count--) {
1713 		struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1714 						(from + (map->offs<<2));
1715 		rec_len = EXT4_DIR_REC_LEN(de->name_len);
1716 		memcpy (to, de, rec_len);
1717 		((struct ext4_dir_entry_2 *) to)->rec_len =
1718 				ext4_rec_len_to_disk(rec_len, blocksize);
1719 		de->inode = 0;
1720 		map++;
1721 		to += rec_len;
1722 	}
1723 	return (struct ext4_dir_entry_2 *) (to - rec_len);
1724 }
1725 
1726 /*
1727  * Compact each dir entry in the range to the minimal rec_len.
1728  * Returns pointer to last entry in range.
1729  */
1730 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1731 {
1732 	struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1733 	unsigned rec_len = 0;
1734 
1735 	prev = to = de;
1736 	while ((char*)de < base + blocksize) {
1737 		next = ext4_next_entry(de, blocksize);
1738 		if (de->inode && de->name_len) {
1739 			rec_len = EXT4_DIR_REC_LEN(de->name_len);
1740 			if (de > to)
1741 				memmove(to, de, rec_len);
1742 			to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1743 			prev = to;
1744 			to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1745 		}
1746 		de = next;
1747 	}
1748 	return prev;
1749 }
1750 
1751 /*
1752  * Split a full leaf block to make room for a new dir entry.
1753  * Allocate a new block, and move entries so that they are approx. equally full.
1754  * Returns pointer to de in block into which the new entry will be inserted.
1755  */
1756 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1757 			struct buffer_head **bh,struct dx_frame *frame,
1758 			struct dx_hash_info *hinfo)
1759 {
1760 	unsigned blocksize = dir->i_sb->s_blocksize;
1761 	unsigned count, continued;
1762 	struct buffer_head *bh2;
1763 	ext4_lblk_t newblock;
1764 	u32 hash2;
1765 	struct dx_map_entry *map;
1766 	char *data1 = (*bh)->b_data, *data2;
1767 	unsigned split, move, size;
1768 	struct ext4_dir_entry_2 *de = NULL, *de2;
1769 	struct ext4_dir_entry_tail *t;
1770 	int	csum_size = 0;
1771 	int	err = 0, i;
1772 
1773 	if (ext4_has_metadata_csum(dir->i_sb))
1774 		csum_size = sizeof(struct ext4_dir_entry_tail);
1775 
1776 	bh2 = ext4_append(handle, dir, &newblock);
1777 	if (IS_ERR(bh2)) {
1778 		brelse(*bh);
1779 		*bh = NULL;
1780 		return (struct ext4_dir_entry_2 *) bh2;
1781 	}
1782 
1783 	BUFFER_TRACE(*bh, "get_write_access");
1784 	err = ext4_journal_get_write_access(handle, *bh);
1785 	if (err)
1786 		goto journal_error;
1787 
1788 	BUFFER_TRACE(frame->bh, "get_write_access");
1789 	err = ext4_journal_get_write_access(handle, frame->bh);
1790 	if (err)
1791 		goto journal_error;
1792 
1793 	data2 = bh2->b_data;
1794 
1795 	/* create map in the end of data2 block */
1796 	map = (struct dx_map_entry *) (data2 + blocksize);
1797 	count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,
1798 			     blocksize, hinfo, map);
1799 	map -= count;
1800 	dx_sort_map(map, count);
1801 	/* Split the existing block in the middle, size-wise */
1802 	size = 0;
1803 	move = 0;
1804 	for (i = count-1; i >= 0; i--) {
1805 		/* is more than half of this entry in 2nd half of the block? */
1806 		if (size + map[i].size/2 > blocksize/2)
1807 			break;
1808 		size += map[i].size;
1809 		move++;
1810 	}
1811 	/* map index at which we will split */
1812 	split = count - move;
1813 	hash2 = map[split].hash;
1814 	continued = hash2 == map[split - 1].hash;
1815 	dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1816 			(unsigned long)dx_get_block(frame->at),
1817 					hash2, split, count-split));
1818 
1819 	/* Fancy dance to stay within two buffers */
1820 	de2 = dx_move_dirents(data1, data2, map + split, count - split,
1821 			      blocksize);
1822 	de = dx_pack_dirents(data1, blocksize);
1823 	de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1824 					   (char *) de,
1825 					   blocksize);
1826 	de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1827 					    (char *) de2,
1828 					    blocksize);
1829 	if (csum_size) {
1830 		t = EXT4_DIRENT_TAIL(data2, blocksize);
1831 		initialize_dirent_tail(t, blocksize);
1832 
1833 		t = EXT4_DIRENT_TAIL(data1, blocksize);
1834 		initialize_dirent_tail(t, blocksize);
1835 	}
1836 
1837 	dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1838 			blocksize, 1));
1839 	dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1840 			blocksize, 1));
1841 
1842 	/* Which block gets the new entry? */
1843 	if (hinfo->hash >= hash2) {
1844 		swap(*bh, bh2);
1845 		de = de2;
1846 	}
1847 	dx_insert_block(frame, hash2 + continued, newblock);
1848 	err = ext4_handle_dirty_dirent_node(handle, dir, bh2);
1849 	if (err)
1850 		goto journal_error;
1851 	err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1852 	if (err)
1853 		goto journal_error;
1854 	brelse(bh2);
1855 	dxtrace(dx_show_index("frame", frame->entries));
1856 	return de;
1857 
1858 journal_error:
1859 	brelse(*bh);
1860 	brelse(bh2);
1861 	*bh = NULL;
1862 	ext4_std_error(dir->i_sb, err);
1863 	return ERR_PTR(err);
1864 }
1865 
1866 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1867 		      struct buffer_head *bh,
1868 		      void *buf, int buf_size,
1869 		      struct ext4_filename *fname,
1870 		      struct ext4_dir_entry_2 **dest_de)
1871 {
1872 	struct ext4_dir_entry_2 *de;
1873 	unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1874 	int nlen, rlen;
1875 	unsigned int offset = 0;
1876 	char *top;
1877 
1878 	de = (struct ext4_dir_entry_2 *)buf;
1879 	top = buf + buf_size - reclen;
1880 	while ((char *) de <= top) {
1881 		if (ext4_check_dir_entry(dir, NULL, de, bh,
1882 					 buf, buf_size, offset))
1883 			return -EFSCORRUPTED;
1884 		if (ext4_match(dir, fname, de))
1885 			return -EEXIST;
1886 		nlen = EXT4_DIR_REC_LEN(de->name_len);
1887 		rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1888 		if ((de->inode ? rlen - nlen : rlen) >= reclen)
1889 			break;
1890 		de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
1891 		offset += rlen;
1892 	}
1893 	if ((char *) de > top)
1894 		return -ENOSPC;
1895 
1896 	*dest_de = de;
1897 	return 0;
1898 }
1899 
1900 void ext4_insert_dentry(struct inode *inode,
1901 			struct ext4_dir_entry_2 *de,
1902 			int buf_size,
1903 			struct ext4_filename *fname)
1904 {
1905 
1906 	int nlen, rlen;
1907 
1908 	nlen = EXT4_DIR_REC_LEN(de->name_len);
1909 	rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
1910 	if (de->inode) {
1911 		struct ext4_dir_entry_2 *de1 =
1912 			(struct ext4_dir_entry_2 *)((char *)de + nlen);
1913 		de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
1914 		de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
1915 		de = de1;
1916 	}
1917 	de->file_type = EXT4_FT_UNKNOWN;
1918 	de->inode = cpu_to_le32(inode->i_ino);
1919 	ext4_set_de_type(inode->i_sb, de, inode->i_mode);
1920 	de->name_len = fname_len(fname);
1921 	memcpy(de->name, fname_name(fname), fname_len(fname));
1922 }
1923 
1924 /*
1925  * Add a new entry into a directory (leaf) block.  If de is non-NULL,
1926  * it points to a directory entry which is guaranteed to be large
1927  * enough for new directory entry.  If de is NULL, then
1928  * add_dirent_to_buf will attempt search the directory block for
1929  * space.  It will return -ENOSPC if no space is available, and -EIO
1930  * and -EEXIST if directory entry already exists.
1931  */
1932 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
1933 			     struct inode *dir,
1934 			     struct inode *inode, struct ext4_dir_entry_2 *de,
1935 			     struct buffer_head *bh)
1936 {
1937 	unsigned int	blocksize = dir->i_sb->s_blocksize;
1938 	int		csum_size = 0;
1939 	int		err;
1940 
1941 	if (ext4_has_metadata_csum(inode->i_sb))
1942 		csum_size = sizeof(struct ext4_dir_entry_tail);
1943 
1944 	if (!de) {
1945 		err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
1946 					blocksize - csum_size, fname, &de);
1947 		if (err)
1948 			return err;
1949 	}
1950 	BUFFER_TRACE(bh, "get_write_access");
1951 	err = ext4_journal_get_write_access(handle, bh);
1952 	if (err) {
1953 		ext4_std_error(dir->i_sb, err);
1954 		return err;
1955 	}
1956 
1957 	/* By now the buffer is marked for journaling */
1958 	ext4_insert_dentry(inode, de, blocksize, fname);
1959 
1960 	/*
1961 	 * XXX shouldn't update any times until successful
1962 	 * completion of syscall, but too many callers depend
1963 	 * on this.
1964 	 *
1965 	 * XXX similarly, too many callers depend on
1966 	 * ext4_new_inode() setting the times, but error
1967 	 * recovery deletes the inode, so the worst that can
1968 	 * happen is that the times are slightly out of date
1969 	 * and/or different from the directory change time.
1970 	 */
1971 	dir->i_mtime = dir->i_ctime = current_time(dir);
1972 	ext4_update_dx_flag(dir);
1973 	inode_inc_iversion(dir);
1974 	ext4_mark_inode_dirty(handle, dir);
1975 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1976 	err = ext4_handle_dirty_dirent_node(handle, dir, bh);
1977 	if (err)
1978 		ext4_std_error(dir->i_sb, err);
1979 	return 0;
1980 }
1981 
1982 /*
1983  * This converts a one block unindexed directory to a 3 block indexed
1984  * directory, and adds the dentry to the indexed directory.
1985  */
1986 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
1987 			    struct inode *dir,
1988 			    struct inode *inode, struct buffer_head *bh)
1989 {
1990 	struct buffer_head *bh2;
1991 	struct dx_root	*root;
1992 	struct dx_frame	frames[EXT4_HTREE_LEVEL], *frame;
1993 	struct dx_entry *entries;
1994 	struct ext4_dir_entry_2	*de, *de2;
1995 	struct ext4_dir_entry_tail *t;
1996 	char		*data1, *top;
1997 	unsigned	len;
1998 	int		retval;
1999 	unsigned	blocksize;
2000 	ext4_lblk_t  block;
2001 	struct fake_dirent *fde;
2002 	int csum_size = 0;
2003 
2004 	if (ext4_has_metadata_csum(inode->i_sb))
2005 		csum_size = sizeof(struct ext4_dir_entry_tail);
2006 
2007 	blocksize =  dir->i_sb->s_blocksize;
2008 	dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2009 	BUFFER_TRACE(bh, "get_write_access");
2010 	retval = ext4_journal_get_write_access(handle, bh);
2011 	if (retval) {
2012 		ext4_std_error(dir->i_sb, retval);
2013 		brelse(bh);
2014 		return retval;
2015 	}
2016 	root = (struct dx_root *) bh->b_data;
2017 
2018 	/* The 0th block becomes the root, move the dirents out */
2019 	fde = &root->dotdot;
2020 	de = (struct ext4_dir_entry_2 *)((char *)fde +
2021 		ext4_rec_len_from_disk(fde->rec_len, blocksize));
2022 	if ((char *) de >= (((char *) root) + blocksize)) {
2023 		EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2024 		brelse(bh);
2025 		return -EFSCORRUPTED;
2026 	}
2027 	len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2028 
2029 	/* Allocate new block for the 0th block's dirents */
2030 	bh2 = ext4_append(handle, dir, &block);
2031 	if (IS_ERR(bh2)) {
2032 		brelse(bh);
2033 		return PTR_ERR(bh2);
2034 	}
2035 	ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2036 	data1 = bh2->b_data;
2037 
2038 	memcpy (data1, de, len);
2039 	de = (struct ext4_dir_entry_2 *) data1;
2040 	top = data1 + len;
2041 	while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top)
2042 		de = de2;
2043 	de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
2044 					   (char *) de,
2045 					   blocksize);
2046 
2047 	if (csum_size) {
2048 		t = EXT4_DIRENT_TAIL(data1, blocksize);
2049 		initialize_dirent_tail(t, blocksize);
2050 	}
2051 
2052 	/* Initialize the root; the dot dirents already exist */
2053 	de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2054 	de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2055 					   blocksize);
2056 	memset (&root->info, 0, sizeof(root->info));
2057 	root->info.info_length = sizeof(root->info);
2058 	root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2059 	entries = root->entries;
2060 	dx_set_block(entries, 1);
2061 	dx_set_count(entries, 1);
2062 	dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2063 
2064 	/* Initialize as for dx_probe */
2065 	fname->hinfo.hash_version = root->info.hash_version;
2066 	if (fname->hinfo.hash_version <= DX_HASH_TEA)
2067 		fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2068 	fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2069 	ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), &fname->hinfo);
2070 
2071 	memset(frames, 0, sizeof(frames));
2072 	frame = frames;
2073 	frame->entries = entries;
2074 	frame->at = entries;
2075 	frame->bh = bh;
2076 
2077 	retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2078 	if (retval)
2079 		goto out_frames;
2080 	retval = ext4_handle_dirty_dirent_node(handle, dir, bh2);
2081 	if (retval)
2082 		goto out_frames;
2083 
2084 	de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2085 	if (IS_ERR(de)) {
2086 		retval = PTR_ERR(de);
2087 		goto out_frames;
2088 	}
2089 
2090 	retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2091 out_frames:
2092 	/*
2093 	 * Even if the block split failed, we have to properly write
2094 	 * out all the changes we did so far. Otherwise we can end up
2095 	 * with corrupted filesystem.
2096 	 */
2097 	if (retval)
2098 		ext4_mark_inode_dirty(handle, dir);
2099 	dx_release(frames);
2100 	brelse(bh2);
2101 	return retval;
2102 }
2103 
2104 /*
2105  *	ext4_add_entry()
2106  *
2107  * adds a file entry to the specified directory, using the same
2108  * semantics as ext4_find_entry(). It returns NULL if it failed.
2109  *
2110  * NOTE!! The inode part of 'de' is left at 0 - which means you
2111  * may not sleep between calling this and putting something into
2112  * the entry, as someone else might have used it while you slept.
2113  */
2114 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2115 			  struct inode *inode)
2116 {
2117 	struct inode *dir = d_inode(dentry->d_parent);
2118 	struct buffer_head *bh = NULL;
2119 	struct ext4_dir_entry_2 *de;
2120 	struct ext4_dir_entry_tail *t;
2121 	struct super_block *sb;
2122 	struct ext4_sb_info *sbi;
2123 	struct ext4_filename fname;
2124 	int	retval;
2125 	int	dx_fallback=0;
2126 	unsigned blocksize;
2127 	ext4_lblk_t block, blocks;
2128 	int	csum_size = 0;
2129 
2130 	if (ext4_has_metadata_csum(inode->i_sb))
2131 		csum_size = sizeof(struct ext4_dir_entry_tail);
2132 
2133 	sb = dir->i_sb;
2134 	sbi = EXT4_SB(sb);
2135 	blocksize = sb->s_blocksize;
2136 	if (!dentry->d_name.len)
2137 		return -EINVAL;
2138 
2139 #ifdef CONFIG_UNICODE
2140 	if (ext4_has_strict_mode(sbi) && IS_CASEFOLDED(dir) &&
2141 	    utf8_validate(sbi->s_encoding, &dentry->d_name))
2142 		return -EINVAL;
2143 #endif
2144 
2145 	retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2146 	if (retval)
2147 		return retval;
2148 
2149 	if (ext4_has_inline_data(dir)) {
2150 		retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2151 		if (retval < 0)
2152 			goto out;
2153 		if (retval == 1) {
2154 			retval = 0;
2155 			goto out;
2156 		}
2157 	}
2158 
2159 	if (is_dx(dir)) {
2160 		retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2161 		if (!retval || (retval != ERR_BAD_DX_DIR))
2162 			goto out;
2163 		ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2164 		dx_fallback++;
2165 		ext4_mark_inode_dirty(handle, dir);
2166 	}
2167 	blocks = dir->i_size >> sb->s_blocksize_bits;
2168 	for (block = 0; block < blocks; block++) {
2169 		bh = ext4_read_dirblock(dir, block, DIRENT);
2170 		if (IS_ERR(bh)) {
2171 			retval = PTR_ERR(bh);
2172 			bh = NULL;
2173 			goto out;
2174 		}
2175 		retval = add_dirent_to_buf(handle, &fname, dir, inode,
2176 					   NULL, bh);
2177 		if (retval != -ENOSPC)
2178 			goto out;
2179 
2180 		if (blocks == 1 && !dx_fallback &&
2181 		    ext4_has_feature_dir_index(sb)) {
2182 			retval = make_indexed_dir(handle, &fname, dir,
2183 						  inode, bh);
2184 			bh = NULL; /* make_indexed_dir releases bh */
2185 			goto out;
2186 		}
2187 		brelse(bh);
2188 	}
2189 	bh = ext4_append(handle, dir, &block);
2190 	if (IS_ERR(bh)) {
2191 		retval = PTR_ERR(bh);
2192 		bh = NULL;
2193 		goto out;
2194 	}
2195 	de = (struct ext4_dir_entry_2 *) bh->b_data;
2196 	de->inode = 0;
2197 	de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2198 
2199 	if (csum_size) {
2200 		t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
2201 		initialize_dirent_tail(t, blocksize);
2202 	}
2203 
2204 	retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2205 out:
2206 	ext4_fname_free_filename(&fname);
2207 	brelse(bh);
2208 	if (retval == 0)
2209 		ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2210 	return retval;
2211 }
2212 
2213 /*
2214  * Returns 0 for success, or a negative error value
2215  */
2216 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2217 			     struct inode *dir, struct inode *inode)
2218 {
2219 	struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2220 	struct dx_entry *entries, *at;
2221 	struct buffer_head *bh;
2222 	struct super_block *sb = dir->i_sb;
2223 	struct ext4_dir_entry_2 *de;
2224 	int restart;
2225 	int err;
2226 
2227 again:
2228 	restart = 0;
2229 	frame = dx_probe(fname, dir, NULL, frames);
2230 	if (IS_ERR(frame))
2231 		return PTR_ERR(frame);
2232 	entries = frame->entries;
2233 	at = frame->at;
2234 	bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT);
2235 	if (IS_ERR(bh)) {
2236 		err = PTR_ERR(bh);
2237 		bh = NULL;
2238 		goto cleanup;
2239 	}
2240 
2241 	BUFFER_TRACE(bh, "get_write_access");
2242 	err = ext4_journal_get_write_access(handle, bh);
2243 	if (err)
2244 		goto journal_error;
2245 
2246 	err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2247 	if (err != -ENOSPC)
2248 		goto cleanup;
2249 
2250 	err = 0;
2251 	/* Block full, should compress but for now just split */
2252 	dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2253 		       dx_get_count(entries), dx_get_limit(entries)));
2254 	/* Need to split index? */
2255 	if (dx_get_count(entries) == dx_get_limit(entries)) {
2256 		ext4_lblk_t newblock;
2257 		int levels = frame - frames + 1;
2258 		unsigned int icount;
2259 		int add_level = 1;
2260 		struct dx_entry *entries2;
2261 		struct dx_node *node2;
2262 		struct buffer_head *bh2;
2263 
2264 		while (frame > frames) {
2265 			if (dx_get_count((frame - 1)->entries) <
2266 			    dx_get_limit((frame - 1)->entries)) {
2267 				add_level = 0;
2268 				break;
2269 			}
2270 			frame--; /* split higher index block */
2271 			at = frame->at;
2272 			entries = frame->entries;
2273 			restart = 1;
2274 		}
2275 		if (add_level && levels == ext4_dir_htree_level(sb)) {
2276 			ext4_warning(sb, "Directory (ino: %lu) index full, "
2277 					 "reach max htree level :%d",
2278 					 dir->i_ino, levels);
2279 			if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2280 				ext4_warning(sb, "Large directory feature is "
2281 						 "not enabled on this "
2282 						 "filesystem");
2283 			}
2284 			err = -ENOSPC;
2285 			goto cleanup;
2286 		}
2287 		icount = dx_get_count(entries);
2288 		bh2 = ext4_append(handle, dir, &newblock);
2289 		if (IS_ERR(bh2)) {
2290 			err = PTR_ERR(bh2);
2291 			goto cleanup;
2292 		}
2293 		node2 = (struct dx_node *)(bh2->b_data);
2294 		entries2 = node2->entries;
2295 		memset(&node2->fake, 0, sizeof(struct fake_dirent));
2296 		node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2297 							   sb->s_blocksize);
2298 		BUFFER_TRACE(frame->bh, "get_write_access");
2299 		err = ext4_journal_get_write_access(handle, frame->bh);
2300 		if (err)
2301 			goto journal_error;
2302 		if (!add_level) {
2303 			unsigned icount1 = icount/2, icount2 = icount - icount1;
2304 			unsigned hash2 = dx_get_hash(entries + icount1);
2305 			dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2306 				       icount1, icount2));
2307 
2308 			BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2309 			err = ext4_journal_get_write_access(handle,
2310 							     (frame - 1)->bh);
2311 			if (err)
2312 				goto journal_error;
2313 
2314 			memcpy((char *) entries2, (char *) (entries + icount1),
2315 			       icount2 * sizeof(struct dx_entry));
2316 			dx_set_count(entries, icount1);
2317 			dx_set_count(entries2, icount2);
2318 			dx_set_limit(entries2, dx_node_limit(dir));
2319 
2320 			/* Which index block gets the new entry? */
2321 			if (at - entries >= icount1) {
2322 				frame->at = at = at - entries - icount1 + entries2;
2323 				frame->entries = entries = entries2;
2324 				swap(frame->bh, bh2);
2325 			}
2326 			dx_insert_block((frame - 1), hash2, newblock);
2327 			dxtrace(dx_show_index("node", frame->entries));
2328 			dxtrace(dx_show_index("node",
2329 			       ((struct dx_node *) bh2->b_data)->entries));
2330 			err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2331 			if (err)
2332 				goto journal_error;
2333 			brelse (bh2);
2334 			err = ext4_handle_dirty_dx_node(handle, dir,
2335 						   (frame - 1)->bh);
2336 			if (err)
2337 				goto journal_error;
2338 			if (restart) {
2339 				err = ext4_handle_dirty_dx_node(handle, dir,
2340 							   frame->bh);
2341 				goto journal_error;
2342 			}
2343 		} else {
2344 			struct dx_root *dxroot;
2345 			memcpy((char *) entries2, (char *) entries,
2346 			       icount * sizeof(struct dx_entry));
2347 			dx_set_limit(entries2, dx_node_limit(dir));
2348 
2349 			/* Set up root */
2350 			dx_set_count(entries, 1);
2351 			dx_set_block(entries + 0, newblock);
2352 			dxroot = (struct dx_root *)frames[0].bh->b_data;
2353 			dxroot->info.indirect_levels += 1;
2354 			dxtrace(printk(KERN_DEBUG
2355 				       "Creating %d level index...\n",
2356 				       dxroot->info.indirect_levels));
2357 			err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2358 			if (err)
2359 				goto journal_error;
2360 			err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2361 			brelse(bh2);
2362 			restart = 1;
2363 			goto journal_error;
2364 		}
2365 	}
2366 	de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2367 	if (IS_ERR(de)) {
2368 		err = PTR_ERR(de);
2369 		goto cleanup;
2370 	}
2371 	err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2372 	goto cleanup;
2373 
2374 journal_error:
2375 	ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2376 cleanup:
2377 	brelse(bh);
2378 	dx_release(frames);
2379 	/* @restart is true means htree-path has been changed, we need to
2380 	 * repeat dx_probe() to find out valid htree-path
2381 	 */
2382 	if (restart && err == 0)
2383 		goto again;
2384 	return err;
2385 }
2386 
2387 /*
2388  * ext4_generic_delete_entry deletes a directory entry by merging it
2389  * with the previous entry
2390  */
2391 int ext4_generic_delete_entry(handle_t *handle,
2392 			      struct inode *dir,
2393 			      struct ext4_dir_entry_2 *de_del,
2394 			      struct buffer_head *bh,
2395 			      void *entry_buf,
2396 			      int buf_size,
2397 			      int csum_size)
2398 {
2399 	struct ext4_dir_entry_2 *de, *pde;
2400 	unsigned int blocksize = dir->i_sb->s_blocksize;
2401 	int i;
2402 
2403 	i = 0;
2404 	pde = NULL;
2405 	de = (struct ext4_dir_entry_2 *)entry_buf;
2406 	while (i < buf_size - csum_size) {
2407 		if (ext4_check_dir_entry(dir, NULL, de, bh,
2408 					 bh->b_data, bh->b_size, i))
2409 			return -EFSCORRUPTED;
2410 		if (de == de_del)  {
2411 			if (pde)
2412 				pde->rec_len = ext4_rec_len_to_disk(
2413 					ext4_rec_len_from_disk(pde->rec_len,
2414 							       blocksize) +
2415 					ext4_rec_len_from_disk(de->rec_len,
2416 							       blocksize),
2417 					blocksize);
2418 			else
2419 				de->inode = 0;
2420 			inode_inc_iversion(dir);
2421 			return 0;
2422 		}
2423 		i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2424 		pde = de;
2425 		de = ext4_next_entry(de, blocksize);
2426 	}
2427 	return -ENOENT;
2428 }
2429 
2430 static int ext4_delete_entry(handle_t *handle,
2431 			     struct inode *dir,
2432 			     struct ext4_dir_entry_2 *de_del,
2433 			     struct buffer_head *bh)
2434 {
2435 	int err, csum_size = 0;
2436 
2437 	if (ext4_has_inline_data(dir)) {
2438 		int has_inline_data = 1;
2439 		err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2440 					       &has_inline_data);
2441 		if (has_inline_data)
2442 			return err;
2443 	}
2444 
2445 	if (ext4_has_metadata_csum(dir->i_sb))
2446 		csum_size = sizeof(struct ext4_dir_entry_tail);
2447 
2448 	BUFFER_TRACE(bh, "get_write_access");
2449 	err = ext4_journal_get_write_access(handle, bh);
2450 	if (unlikely(err))
2451 		goto out;
2452 
2453 	err = ext4_generic_delete_entry(handle, dir, de_del,
2454 					bh, bh->b_data,
2455 					dir->i_sb->s_blocksize, csum_size);
2456 	if (err)
2457 		goto out;
2458 
2459 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2460 	err = ext4_handle_dirty_dirent_node(handle, dir, bh);
2461 	if (unlikely(err))
2462 		goto out;
2463 
2464 	return 0;
2465 out:
2466 	if (err != -ENOENT)
2467 		ext4_std_error(dir->i_sb, err);
2468 	return err;
2469 }
2470 
2471 /*
2472  * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2473  * since this indicates that nlinks count was previously 1 to avoid overflowing
2474  * the 16-bit i_links_count field on disk.  Directories with i_nlink == 1 mean
2475  * that subdirectory link counts are not being maintained accurately.
2476  *
2477  * The caller has already checked for i_nlink overflow in case the DIR_LINK
2478  * feature is not enabled and returned -EMLINK.  The is_dx() check is a proxy
2479  * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2480  * on regular files) and to avoid creating huge/slow non-HTREE directories.
2481  */
2482 static void ext4_inc_count(handle_t *handle, struct inode *inode)
2483 {
2484 	inc_nlink(inode);
2485 	if (is_dx(inode) &&
2486 	    (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2487 		set_nlink(inode, 1);
2488 }
2489 
2490 /*
2491  * If a directory had nlink == 1, then we should let it be 1. This indicates
2492  * directory has >EXT4_LINK_MAX subdirs.
2493  */
2494 static void ext4_dec_count(handle_t *handle, struct inode *inode)
2495 {
2496 	if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2497 		drop_nlink(inode);
2498 }
2499 
2500 
2501 static int ext4_add_nondir(handle_t *handle,
2502 		struct dentry *dentry, struct inode *inode)
2503 {
2504 	int err = ext4_add_entry(handle, dentry, inode);
2505 	if (!err) {
2506 		ext4_mark_inode_dirty(handle, inode);
2507 		d_instantiate_new(dentry, inode);
2508 		return 0;
2509 	}
2510 	drop_nlink(inode);
2511 	unlock_new_inode(inode);
2512 	iput(inode);
2513 	return err;
2514 }
2515 
2516 /*
2517  * By the time this is called, we already have created
2518  * the directory cache entry for the new file, but it
2519  * is so far negative - it has no inode.
2520  *
2521  * If the create succeeds, we fill in the inode information
2522  * with d_instantiate().
2523  */
2524 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2525 		       bool excl)
2526 {
2527 	handle_t *handle;
2528 	struct inode *inode;
2529 	int err, credits, retries = 0;
2530 
2531 	err = dquot_initialize(dir);
2532 	if (err)
2533 		return err;
2534 
2535 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2536 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2537 retry:
2538 	inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2539 					    NULL, EXT4_HT_DIR, credits);
2540 	handle = ext4_journal_current_handle();
2541 	err = PTR_ERR(inode);
2542 	if (!IS_ERR(inode)) {
2543 		inode->i_op = &ext4_file_inode_operations;
2544 		inode->i_fop = &ext4_file_operations;
2545 		ext4_set_aops(inode);
2546 		err = ext4_add_nondir(handle, dentry, inode);
2547 		if (!err && IS_DIRSYNC(dir))
2548 			ext4_handle_sync(handle);
2549 	}
2550 	if (handle)
2551 		ext4_journal_stop(handle);
2552 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2553 		goto retry;
2554 	return err;
2555 }
2556 
2557 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2558 		      umode_t mode, dev_t rdev)
2559 {
2560 	handle_t *handle;
2561 	struct inode *inode;
2562 	int err, credits, retries = 0;
2563 
2564 	err = dquot_initialize(dir);
2565 	if (err)
2566 		return err;
2567 
2568 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2569 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2570 retry:
2571 	inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2572 					    NULL, EXT4_HT_DIR, credits);
2573 	handle = ext4_journal_current_handle();
2574 	err = PTR_ERR(inode);
2575 	if (!IS_ERR(inode)) {
2576 		init_special_inode(inode, inode->i_mode, rdev);
2577 		inode->i_op = &ext4_special_inode_operations;
2578 		err = ext4_add_nondir(handle, dentry, inode);
2579 		if (!err && IS_DIRSYNC(dir))
2580 			ext4_handle_sync(handle);
2581 	}
2582 	if (handle)
2583 		ext4_journal_stop(handle);
2584 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2585 		goto retry;
2586 	return err;
2587 }
2588 
2589 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2590 {
2591 	handle_t *handle;
2592 	struct inode *inode;
2593 	int err, retries = 0;
2594 
2595 	err = dquot_initialize(dir);
2596 	if (err)
2597 		return err;
2598 
2599 retry:
2600 	inode = ext4_new_inode_start_handle(dir, mode,
2601 					    NULL, 0, NULL,
2602 					    EXT4_HT_DIR,
2603 			EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2604 			  4 + EXT4_XATTR_TRANS_BLOCKS);
2605 	handle = ext4_journal_current_handle();
2606 	err = PTR_ERR(inode);
2607 	if (!IS_ERR(inode)) {
2608 		inode->i_op = &ext4_file_inode_operations;
2609 		inode->i_fop = &ext4_file_operations;
2610 		ext4_set_aops(inode);
2611 		d_tmpfile(dentry, inode);
2612 		err = ext4_orphan_add(handle, inode);
2613 		if (err)
2614 			goto err_unlock_inode;
2615 		mark_inode_dirty(inode);
2616 		unlock_new_inode(inode);
2617 	}
2618 	if (handle)
2619 		ext4_journal_stop(handle);
2620 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2621 		goto retry;
2622 	return err;
2623 err_unlock_inode:
2624 	ext4_journal_stop(handle);
2625 	unlock_new_inode(inode);
2626 	return err;
2627 }
2628 
2629 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2630 			  struct ext4_dir_entry_2 *de,
2631 			  int blocksize, int csum_size,
2632 			  unsigned int parent_ino, int dotdot_real_len)
2633 {
2634 	de->inode = cpu_to_le32(inode->i_ino);
2635 	de->name_len = 1;
2636 	de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2637 					   blocksize);
2638 	strcpy(de->name, ".");
2639 	ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2640 
2641 	de = ext4_next_entry(de, blocksize);
2642 	de->inode = cpu_to_le32(parent_ino);
2643 	de->name_len = 2;
2644 	if (!dotdot_real_len)
2645 		de->rec_len = ext4_rec_len_to_disk(blocksize -
2646 					(csum_size + EXT4_DIR_REC_LEN(1)),
2647 					blocksize);
2648 	else
2649 		de->rec_len = ext4_rec_len_to_disk(
2650 				EXT4_DIR_REC_LEN(de->name_len), blocksize);
2651 	strcpy(de->name, "..");
2652 	ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2653 
2654 	return ext4_next_entry(de, blocksize);
2655 }
2656 
2657 static int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2658 			     struct inode *inode)
2659 {
2660 	struct buffer_head *dir_block = NULL;
2661 	struct ext4_dir_entry_2 *de;
2662 	struct ext4_dir_entry_tail *t;
2663 	ext4_lblk_t block = 0;
2664 	unsigned int blocksize = dir->i_sb->s_blocksize;
2665 	int csum_size = 0;
2666 	int err;
2667 
2668 	if (ext4_has_metadata_csum(dir->i_sb))
2669 		csum_size = sizeof(struct ext4_dir_entry_tail);
2670 
2671 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2672 		err = ext4_try_create_inline_dir(handle, dir, inode);
2673 		if (err < 0 && err != -ENOSPC)
2674 			goto out;
2675 		if (!err)
2676 			goto out;
2677 	}
2678 
2679 	inode->i_size = 0;
2680 	dir_block = ext4_append(handle, inode, &block);
2681 	if (IS_ERR(dir_block))
2682 		return PTR_ERR(dir_block);
2683 	de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2684 	ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2685 	set_nlink(inode, 2);
2686 	if (csum_size) {
2687 		t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize);
2688 		initialize_dirent_tail(t, blocksize);
2689 	}
2690 
2691 	BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2692 	err = ext4_handle_dirty_dirent_node(handle, inode, dir_block);
2693 	if (err)
2694 		goto out;
2695 	set_buffer_verified(dir_block);
2696 out:
2697 	brelse(dir_block);
2698 	return err;
2699 }
2700 
2701 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2702 {
2703 	handle_t *handle;
2704 	struct inode *inode;
2705 	int err, credits, retries = 0;
2706 
2707 	if (EXT4_DIR_LINK_MAX(dir))
2708 		return -EMLINK;
2709 
2710 	err = dquot_initialize(dir);
2711 	if (err)
2712 		return err;
2713 
2714 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2715 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2716 retry:
2717 	inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2718 					    &dentry->d_name,
2719 					    0, NULL, EXT4_HT_DIR, credits);
2720 	handle = ext4_journal_current_handle();
2721 	err = PTR_ERR(inode);
2722 	if (IS_ERR(inode))
2723 		goto out_stop;
2724 
2725 	inode->i_op = &ext4_dir_inode_operations;
2726 	inode->i_fop = &ext4_dir_operations;
2727 	err = ext4_init_new_dir(handle, dir, inode);
2728 	if (err)
2729 		goto out_clear_inode;
2730 	err = ext4_mark_inode_dirty(handle, inode);
2731 	if (!err)
2732 		err = ext4_add_entry(handle, dentry, inode);
2733 	if (err) {
2734 out_clear_inode:
2735 		clear_nlink(inode);
2736 		unlock_new_inode(inode);
2737 		ext4_mark_inode_dirty(handle, inode);
2738 		iput(inode);
2739 		goto out_stop;
2740 	}
2741 	ext4_inc_count(handle, dir);
2742 	ext4_update_dx_flag(dir);
2743 	err = ext4_mark_inode_dirty(handle, dir);
2744 	if (err)
2745 		goto out_clear_inode;
2746 	d_instantiate_new(dentry, inode);
2747 	if (IS_DIRSYNC(dir))
2748 		ext4_handle_sync(handle);
2749 
2750 out_stop:
2751 	if (handle)
2752 		ext4_journal_stop(handle);
2753 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2754 		goto retry;
2755 	return err;
2756 }
2757 
2758 /*
2759  * routine to check that the specified directory is empty (for rmdir)
2760  */
2761 bool ext4_empty_dir(struct inode *inode)
2762 {
2763 	unsigned int offset;
2764 	struct buffer_head *bh;
2765 	struct ext4_dir_entry_2 *de, *de1;
2766 	struct super_block *sb;
2767 
2768 	if (ext4_has_inline_data(inode)) {
2769 		int has_inline_data = 1;
2770 		int ret;
2771 
2772 		ret = empty_inline_dir(inode, &has_inline_data);
2773 		if (has_inline_data)
2774 			return ret;
2775 	}
2776 
2777 	sb = inode->i_sb;
2778 	if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2779 		EXT4_ERROR_INODE(inode, "invalid size");
2780 		return true;
2781 	}
2782 	bh = ext4_read_dirblock(inode, 0, EITHER);
2783 	if (IS_ERR(bh))
2784 		return true;
2785 
2786 	de = (struct ext4_dir_entry_2 *) bh->b_data;
2787 	de1 = ext4_next_entry(de, sb->s_blocksize);
2788 	if (le32_to_cpu(de->inode) != inode->i_ino ||
2789 			le32_to_cpu(de1->inode) == 0 ||
2790 			strcmp(".", de->name) || strcmp("..", de1->name)) {
2791 		ext4_warning_inode(inode, "directory missing '.' and/or '..'");
2792 		brelse(bh);
2793 		return true;
2794 	}
2795 	offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) +
2796 		 ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize);
2797 	de = ext4_next_entry(de1, sb->s_blocksize);
2798 	while (offset < inode->i_size) {
2799 		if ((void *) de >= (void *) (bh->b_data+sb->s_blocksize)) {
2800 			unsigned int lblock;
2801 			brelse(bh);
2802 			lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2803 			bh = ext4_read_dirblock(inode, lblock, EITHER);
2804 			if (IS_ERR(bh))
2805 				return true;
2806 			de = (struct ext4_dir_entry_2 *) bh->b_data;
2807 		}
2808 		if (ext4_check_dir_entry(inode, NULL, de, bh,
2809 					 bh->b_data, bh->b_size, offset)) {
2810 			de = (struct ext4_dir_entry_2 *)(bh->b_data +
2811 							 sb->s_blocksize);
2812 			offset = (offset | (sb->s_blocksize - 1)) + 1;
2813 			continue;
2814 		}
2815 		if (le32_to_cpu(de->inode)) {
2816 			brelse(bh);
2817 			return false;
2818 		}
2819 		offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2820 		de = ext4_next_entry(de, sb->s_blocksize);
2821 	}
2822 	brelse(bh);
2823 	return true;
2824 }
2825 
2826 /*
2827  * ext4_orphan_add() links an unlinked or truncated inode into a list of
2828  * such inodes, starting at the superblock, in case we crash before the
2829  * file is closed/deleted, or in case the inode truncate spans multiple
2830  * transactions and the last transaction is not recovered after a crash.
2831  *
2832  * At filesystem recovery time, we walk this list deleting unlinked
2833  * inodes and truncating linked inodes in ext4_orphan_cleanup().
2834  *
2835  * Orphan list manipulation functions must be called under i_mutex unless
2836  * we are just creating the inode or deleting it.
2837  */
2838 int ext4_orphan_add(handle_t *handle, struct inode *inode)
2839 {
2840 	struct super_block *sb = inode->i_sb;
2841 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2842 	struct ext4_iloc iloc;
2843 	int err = 0, rc;
2844 	bool dirty = false;
2845 
2846 	if (!sbi->s_journal || is_bad_inode(inode))
2847 		return 0;
2848 
2849 	WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2850 		     !inode_is_locked(inode));
2851 	/*
2852 	 * Exit early if inode already is on orphan list. This is a big speedup
2853 	 * since we don't have to contend on the global s_orphan_lock.
2854 	 */
2855 	if (!list_empty(&EXT4_I(inode)->i_orphan))
2856 		return 0;
2857 
2858 	/*
2859 	 * Orphan handling is only valid for files with data blocks
2860 	 * being truncated, or files being unlinked. Note that we either
2861 	 * hold i_mutex, or the inode can not be referenced from outside,
2862 	 * so i_nlink should not be bumped due to race
2863 	 */
2864 	J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
2865 		  S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
2866 
2867 	BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2868 	err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2869 	if (err)
2870 		goto out;
2871 
2872 	err = ext4_reserve_inode_write(handle, inode, &iloc);
2873 	if (err)
2874 		goto out;
2875 
2876 	mutex_lock(&sbi->s_orphan_lock);
2877 	/*
2878 	 * Due to previous errors inode may be already a part of on-disk
2879 	 * orphan list. If so skip on-disk list modification.
2880 	 */
2881 	if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
2882 	    (le32_to_cpu(sbi->s_es->s_inodes_count))) {
2883 		/* Insert this inode at the head of the on-disk orphan list */
2884 		NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
2885 		sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
2886 		dirty = true;
2887 	}
2888 	list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
2889 	mutex_unlock(&sbi->s_orphan_lock);
2890 
2891 	if (dirty) {
2892 		err = ext4_handle_dirty_super(handle, sb);
2893 		rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
2894 		if (!err)
2895 			err = rc;
2896 		if (err) {
2897 			/*
2898 			 * We have to remove inode from in-memory list if
2899 			 * addition to on disk orphan list failed. Stray orphan
2900 			 * list entries can cause panics at unmount time.
2901 			 */
2902 			mutex_lock(&sbi->s_orphan_lock);
2903 			list_del_init(&EXT4_I(inode)->i_orphan);
2904 			mutex_unlock(&sbi->s_orphan_lock);
2905 		}
2906 	} else
2907 		brelse(iloc.bh);
2908 
2909 	jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
2910 	jbd_debug(4, "orphan inode %lu will point to %d\n",
2911 			inode->i_ino, NEXT_ORPHAN(inode));
2912 out:
2913 	ext4_std_error(sb, err);
2914 	return err;
2915 }
2916 
2917 /*
2918  * ext4_orphan_del() removes an unlinked or truncated inode from the list
2919  * of such inodes stored on disk, because it is finally being cleaned up.
2920  */
2921 int ext4_orphan_del(handle_t *handle, struct inode *inode)
2922 {
2923 	struct list_head *prev;
2924 	struct ext4_inode_info *ei = EXT4_I(inode);
2925 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2926 	__u32 ino_next;
2927 	struct ext4_iloc iloc;
2928 	int err = 0;
2929 
2930 	if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
2931 		return 0;
2932 
2933 	WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
2934 		     !inode_is_locked(inode));
2935 	/* Do this quick check before taking global s_orphan_lock. */
2936 	if (list_empty(&ei->i_orphan))
2937 		return 0;
2938 
2939 	if (handle) {
2940 		/* Grab inode buffer early before taking global s_orphan_lock */
2941 		err = ext4_reserve_inode_write(handle, inode, &iloc);
2942 	}
2943 
2944 	mutex_lock(&sbi->s_orphan_lock);
2945 	jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
2946 
2947 	prev = ei->i_orphan.prev;
2948 	list_del_init(&ei->i_orphan);
2949 
2950 	/* If we're on an error path, we may not have a valid
2951 	 * transaction handle with which to update the orphan list on
2952 	 * disk, but we still need to remove the inode from the linked
2953 	 * list in memory. */
2954 	if (!handle || err) {
2955 		mutex_unlock(&sbi->s_orphan_lock);
2956 		goto out_err;
2957 	}
2958 
2959 	ino_next = NEXT_ORPHAN(inode);
2960 	if (prev == &sbi->s_orphan) {
2961 		jbd_debug(4, "superblock will point to %u\n", ino_next);
2962 		BUFFER_TRACE(sbi->s_sbh, "get_write_access");
2963 		err = ext4_journal_get_write_access(handle, sbi->s_sbh);
2964 		if (err) {
2965 			mutex_unlock(&sbi->s_orphan_lock);
2966 			goto out_brelse;
2967 		}
2968 		sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
2969 		mutex_unlock(&sbi->s_orphan_lock);
2970 		err = ext4_handle_dirty_super(handle, inode->i_sb);
2971 	} else {
2972 		struct ext4_iloc iloc2;
2973 		struct inode *i_prev =
2974 			&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
2975 
2976 		jbd_debug(4, "orphan inode %lu will point to %u\n",
2977 			  i_prev->i_ino, ino_next);
2978 		err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
2979 		if (err) {
2980 			mutex_unlock(&sbi->s_orphan_lock);
2981 			goto out_brelse;
2982 		}
2983 		NEXT_ORPHAN(i_prev) = ino_next;
2984 		err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
2985 		mutex_unlock(&sbi->s_orphan_lock);
2986 	}
2987 	if (err)
2988 		goto out_brelse;
2989 	NEXT_ORPHAN(inode) = 0;
2990 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
2991 out_err:
2992 	ext4_std_error(inode->i_sb, err);
2993 	return err;
2994 
2995 out_brelse:
2996 	brelse(iloc.bh);
2997 	goto out_err;
2998 }
2999 
3000 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3001 {
3002 	int retval;
3003 	struct inode *inode;
3004 	struct buffer_head *bh;
3005 	struct ext4_dir_entry_2 *de;
3006 	handle_t *handle = NULL;
3007 
3008 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3009 		return -EIO;
3010 
3011 	/* Initialize quotas before so that eventual writes go in
3012 	 * separate transaction */
3013 	retval = dquot_initialize(dir);
3014 	if (retval)
3015 		return retval;
3016 	retval = dquot_initialize(d_inode(dentry));
3017 	if (retval)
3018 		return retval;
3019 
3020 	retval = -ENOENT;
3021 	bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3022 	if (IS_ERR(bh))
3023 		return PTR_ERR(bh);
3024 	if (!bh)
3025 		goto end_rmdir;
3026 
3027 	inode = d_inode(dentry);
3028 
3029 	retval = -EFSCORRUPTED;
3030 	if (le32_to_cpu(de->inode) != inode->i_ino)
3031 		goto end_rmdir;
3032 
3033 	retval = -ENOTEMPTY;
3034 	if (!ext4_empty_dir(inode))
3035 		goto end_rmdir;
3036 
3037 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3038 				    EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3039 	if (IS_ERR(handle)) {
3040 		retval = PTR_ERR(handle);
3041 		handle = NULL;
3042 		goto end_rmdir;
3043 	}
3044 
3045 	if (IS_DIRSYNC(dir))
3046 		ext4_handle_sync(handle);
3047 
3048 	retval = ext4_delete_entry(handle, dir, de, bh);
3049 	if (retval)
3050 		goto end_rmdir;
3051 	if (!EXT4_DIR_LINK_EMPTY(inode))
3052 		ext4_warning_inode(inode,
3053 			     "empty directory '%.*s' has too many links (%u)",
3054 			     dentry->d_name.len, dentry->d_name.name,
3055 			     inode->i_nlink);
3056 	inode_inc_iversion(inode);
3057 	clear_nlink(inode);
3058 	/* There's no need to set i_disksize: the fact that i_nlink is
3059 	 * zero will ensure that the right thing happens during any
3060 	 * recovery. */
3061 	inode->i_size = 0;
3062 	ext4_orphan_add(handle, inode);
3063 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3064 	ext4_mark_inode_dirty(handle, inode);
3065 	ext4_dec_count(handle, dir);
3066 	ext4_update_dx_flag(dir);
3067 	ext4_mark_inode_dirty(handle, dir);
3068 
3069 #ifdef CONFIG_UNICODE
3070 	/* VFS negative dentries are incompatible with Encoding and
3071 	 * Case-insensitiveness. Eventually we'll want avoid
3072 	 * invalidating the dentries here, alongside with returning the
3073 	 * negative dentries at ext4_lookup(), when it is better
3074 	 * supported by the VFS for the CI case.
3075 	 */
3076 	if (IS_CASEFOLDED(dir))
3077 		d_invalidate(dentry);
3078 #endif
3079 
3080 end_rmdir:
3081 	brelse(bh);
3082 	if (handle)
3083 		ext4_journal_stop(handle);
3084 	return retval;
3085 }
3086 
3087 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3088 {
3089 	int retval;
3090 	struct inode *inode;
3091 	struct buffer_head *bh;
3092 	struct ext4_dir_entry_2 *de;
3093 	handle_t *handle = NULL;
3094 
3095 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3096 		return -EIO;
3097 
3098 	trace_ext4_unlink_enter(dir, dentry);
3099 	/* Initialize quotas before so that eventual writes go
3100 	 * in separate transaction */
3101 	retval = dquot_initialize(dir);
3102 	if (retval)
3103 		return retval;
3104 	retval = dquot_initialize(d_inode(dentry));
3105 	if (retval)
3106 		return retval;
3107 
3108 	retval = -ENOENT;
3109 	bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3110 	if (IS_ERR(bh))
3111 		return PTR_ERR(bh);
3112 	if (!bh)
3113 		goto end_unlink;
3114 
3115 	inode = d_inode(dentry);
3116 
3117 	retval = -EFSCORRUPTED;
3118 	if (le32_to_cpu(de->inode) != inode->i_ino)
3119 		goto end_unlink;
3120 
3121 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3122 				    EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3123 	if (IS_ERR(handle)) {
3124 		retval = PTR_ERR(handle);
3125 		handle = NULL;
3126 		goto end_unlink;
3127 	}
3128 
3129 	if (IS_DIRSYNC(dir))
3130 		ext4_handle_sync(handle);
3131 
3132 	if (inode->i_nlink == 0) {
3133 		ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3134 				   dentry->d_name.len, dentry->d_name.name);
3135 		set_nlink(inode, 1);
3136 	}
3137 	retval = ext4_delete_entry(handle, dir, de, bh);
3138 	if (retval)
3139 		goto end_unlink;
3140 	dir->i_ctime = dir->i_mtime = current_time(dir);
3141 	ext4_update_dx_flag(dir);
3142 	ext4_mark_inode_dirty(handle, dir);
3143 	drop_nlink(inode);
3144 	if (!inode->i_nlink)
3145 		ext4_orphan_add(handle, inode);
3146 	inode->i_ctime = current_time(inode);
3147 	ext4_mark_inode_dirty(handle, inode);
3148 
3149 #ifdef CONFIG_UNICODE
3150 	/* VFS negative dentries are incompatible with Encoding and
3151 	 * Case-insensitiveness. Eventually we'll want avoid
3152 	 * invalidating the dentries here, alongside with returning the
3153 	 * negative dentries at ext4_lookup(), when it is  better
3154 	 * supported by the VFS for the CI case.
3155 	 */
3156 	if (IS_CASEFOLDED(dir))
3157 		d_invalidate(dentry);
3158 #endif
3159 
3160 end_unlink:
3161 	brelse(bh);
3162 	if (handle)
3163 		ext4_journal_stop(handle);
3164 	trace_ext4_unlink_exit(dentry, retval);
3165 	return retval;
3166 }
3167 
3168 static int ext4_symlink(struct inode *dir,
3169 			struct dentry *dentry, const char *symname)
3170 {
3171 	handle_t *handle;
3172 	struct inode *inode;
3173 	int err, len = strlen(symname);
3174 	int credits;
3175 	struct fscrypt_str disk_link;
3176 
3177 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3178 		return -EIO;
3179 
3180 	err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3181 				      &disk_link);
3182 	if (err)
3183 		return err;
3184 
3185 	err = dquot_initialize(dir);
3186 	if (err)
3187 		return err;
3188 
3189 	if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3190 		/*
3191 		 * For non-fast symlinks, we just allocate inode and put it on
3192 		 * orphan list in the first transaction => we need bitmap,
3193 		 * group descriptor, sb, inode block, quota blocks, and
3194 		 * possibly selinux xattr blocks.
3195 		 */
3196 		credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3197 			  EXT4_XATTR_TRANS_BLOCKS;
3198 	} else {
3199 		/*
3200 		 * Fast symlink. We have to add entry to directory
3201 		 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3202 		 * allocate new inode (bitmap, group descriptor, inode block,
3203 		 * quota blocks, sb is already counted in previous macros).
3204 		 */
3205 		credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3206 			  EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3207 	}
3208 
3209 	inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3210 					    &dentry->d_name, 0, NULL,
3211 					    EXT4_HT_DIR, credits);
3212 	handle = ext4_journal_current_handle();
3213 	if (IS_ERR(inode)) {
3214 		if (handle)
3215 			ext4_journal_stop(handle);
3216 		return PTR_ERR(inode);
3217 	}
3218 
3219 	if (IS_ENCRYPTED(inode)) {
3220 		err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3221 		if (err)
3222 			goto err_drop_inode;
3223 		inode->i_op = &ext4_encrypted_symlink_inode_operations;
3224 	}
3225 
3226 	if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3227 		if (!IS_ENCRYPTED(inode))
3228 			inode->i_op = &ext4_symlink_inode_operations;
3229 		inode_nohighmem(inode);
3230 		ext4_set_aops(inode);
3231 		/*
3232 		 * We cannot call page_symlink() with transaction started
3233 		 * because it calls into ext4_write_begin() which can wait
3234 		 * for transaction commit if we are running out of space
3235 		 * and thus we deadlock. So we have to stop transaction now
3236 		 * and restart it when symlink contents is written.
3237 		 *
3238 		 * To keep fs consistent in case of crash, we have to put inode
3239 		 * to orphan list in the mean time.
3240 		 */
3241 		drop_nlink(inode);
3242 		err = ext4_orphan_add(handle, inode);
3243 		ext4_journal_stop(handle);
3244 		handle = NULL;
3245 		if (err)
3246 			goto err_drop_inode;
3247 		err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3248 		if (err)
3249 			goto err_drop_inode;
3250 		/*
3251 		 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3252 		 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3253 		 */
3254 		handle = ext4_journal_start(dir, EXT4_HT_DIR,
3255 				EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3256 				EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3257 		if (IS_ERR(handle)) {
3258 			err = PTR_ERR(handle);
3259 			handle = NULL;
3260 			goto err_drop_inode;
3261 		}
3262 		set_nlink(inode, 1);
3263 		err = ext4_orphan_del(handle, inode);
3264 		if (err)
3265 			goto err_drop_inode;
3266 	} else {
3267 		/* clear the extent format for fast symlink */
3268 		ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3269 		if (!IS_ENCRYPTED(inode)) {
3270 			inode->i_op = &ext4_fast_symlink_inode_operations;
3271 			inode->i_link = (char *)&EXT4_I(inode)->i_data;
3272 		}
3273 		memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3274 		       disk_link.len);
3275 		inode->i_size = disk_link.len - 1;
3276 	}
3277 	EXT4_I(inode)->i_disksize = inode->i_size;
3278 	err = ext4_add_nondir(handle, dentry, inode);
3279 	if (!err && IS_DIRSYNC(dir))
3280 		ext4_handle_sync(handle);
3281 
3282 	if (handle)
3283 		ext4_journal_stop(handle);
3284 	goto out_free_encrypted_link;
3285 
3286 err_drop_inode:
3287 	if (handle)
3288 		ext4_journal_stop(handle);
3289 	clear_nlink(inode);
3290 	unlock_new_inode(inode);
3291 	iput(inode);
3292 out_free_encrypted_link:
3293 	if (disk_link.name != (unsigned char *)symname)
3294 		kfree(disk_link.name);
3295 	return err;
3296 }
3297 
3298 static int ext4_link(struct dentry *old_dentry,
3299 		     struct inode *dir, struct dentry *dentry)
3300 {
3301 	handle_t *handle;
3302 	struct inode *inode = d_inode(old_dentry);
3303 	int err, retries = 0;
3304 
3305 	if (inode->i_nlink >= EXT4_LINK_MAX)
3306 		return -EMLINK;
3307 
3308 	err = fscrypt_prepare_link(old_dentry, dir, dentry);
3309 	if (err)
3310 		return err;
3311 
3312 	if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3313 	    (!projid_eq(EXT4_I(dir)->i_projid,
3314 			EXT4_I(old_dentry->d_inode)->i_projid)))
3315 		return -EXDEV;
3316 
3317 	err = dquot_initialize(dir);
3318 	if (err)
3319 		return err;
3320 
3321 retry:
3322 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3323 		(EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3324 		 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3325 	if (IS_ERR(handle))
3326 		return PTR_ERR(handle);
3327 
3328 	if (IS_DIRSYNC(dir))
3329 		ext4_handle_sync(handle);
3330 
3331 	inode->i_ctime = current_time(inode);
3332 	ext4_inc_count(handle, inode);
3333 	ihold(inode);
3334 
3335 	err = ext4_add_entry(handle, dentry, inode);
3336 	if (!err) {
3337 		ext4_mark_inode_dirty(handle, inode);
3338 		/* this can happen only for tmpfile being
3339 		 * linked the first time
3340 		 */
3341 		if (inode->i_nlink == 1)
3342 			ext4_orphan_del(handle, inode);
3343 		d_instantiate(dentry, inode);
3344 	} else {
3345 		drop_nlink(inode);
3346 		iput(inode);
3347 	}
3348 	ext4_journal_stop(handle);
3349 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3350 		goto retry;
3351 	return err;
3352 }
3353 
3354 
3355 /*
3356  * Try to find buffer head where contains the parent block.
3357  * It should be the inode block if it is inlined or the 1st block
3358  * if it is a normal dir.
3359  */
3360 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3361 					struct inode *inode,
3362 					int *retval,
3363 					struct ext4_dir_entry_2 **parent_de,
3364 					int *inlined)
3365 {
3366 	struct buffer_head *bh;
3367 
3368 	if (!ext4_has_inline_data(inode)) {
3369 		bh = ext4_read_dirblock(inode, 0, EITHER);
3370 		if (IS_ERR(bh)) {
3371 			*retval = PTR_ERR(bh);
3372 			return NULL;
3373 		}
3374 		*parent_de = ext4_next_entry(
3375 					(struct ext4_dir_entry_2 *)bh->b_data,
3376 					inode->i_sb->s_blocksize);
3377 		return bh;
3378 	}
3379 
3380 	*inlined = 1;
3381 	return ext4_get_first_inline_block(inode, parent_de, retval);
3382 }
3383 
3384 struct ext4_renament {
3385 	struct inode *dir;
3386 	struct dentry *dentry;
3387 	struct inode *inode;
3388 	bool is_dir;
3389 	int dir_nlink_delta;
3390 
3391 	/* entry for "dentry" */
3392 	struct buffer_head *bh;
3393 	struct ext4_dir_entry_2 *de;
3394 	int inlined;
3395 
3396 	/* entry for ".." in inode if it's a directory */
3397 	struct buffer_head *dir_bh;
3398 	struct ext4_dir_entry_2 *parent_de;
3399 	int dir_inlined;
3400 };
3401 
3402 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3403 {
3404 	int retval;
3405 
3406 	ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3407 					      &retval, &ent->parent_de,
3408 					      &ent->dir_inlined);
3409 	if (!ent->dir_bh)
3410 		return retval;
3411 	if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3412 		return -EFSCORRUPTED;
3413 	BUFFER_TRACE(ent->dir_bh, "get_write_access");
3414 	return ext4_journal_get_write_access(handle, ent->dir_bh);
3415 }
3416 
3417 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3418 				  unsigned dir_ino)
3419 {
3420 	int retval;
3421 
3422 	ent->parent_de->inode = cpu_to_le32(dir_ino);
3423 	BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3424 	if (!ent->dir_inlined) {
3425 		if (is_dx(ent->inode)) {
3426 			retval = ext4_handle_dirty_dx_node(handle,
3427 							   ent->inode,
3428 							   ent->dir_bh);
3429 		} else {
3430 			retval = ext4_handle_dirty_dirent_node(handle,
3431 							       ent->inode,
3432 							       ent->dir_bh);
3433 		}
3434 	} else {
3435 		retval = ext4_mark_inode_dirty(handle, ent->inode);
3436 	}
3437 	if (retval) {
3438 		ext4_std_error(ent->dir->i_sb, retval);
3439 		return retval;
3440 	}
3441 	return 0;
3442 }
3443 
3444 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3445 		       unsigned ino, unsigned file_type)
3446 {
3447 	int retval;
3448 
3449 	BUFFER_TRACE(ent->bh, "get write access");
3450 	retval = ext4_journal_get_write_access(handle, ent->bh);
3451 	if (retval)
3452 		return retval;
3453 	ent->de->inode = cpu_to_le32(ino);
3454 	if (ext4_has_feature_filetype(ent->dir->i_sb))
3455 		ent->de->file_type = file_type;
3456 	inode_inc_iversion(ent->dir);
3457 	ent->dir->i_ctime = ent->dir->i_mtime =
3458 		current_time(ent->dir);
3459 	ext4_mark_inode_dirty(handle, ent->dir);
3460 	BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3461 	if (!ent->inlined) {
3462 		retval = ext4_handle_dirty_dirent_node(handle,
3463 						       ent->dir, ent->bh);
3464 		if (unlikely(retval)) {
3465 			ext4_std_error(ent->dir->i_sb, retval);
3466 			return retval;
3467 		}
3468 	}
3469 	brelse(ent->bh);
3470 	ent->bh = NULL;
3471 
3472 	return 0;
3473 }
3474 
3475 static int ext4_find_delete_entry(handle_t *handle, struct inode *dir,
3476 				  const struct qstr *d_name)
3477 {
3478 	int retval = -ENOENT;
3479 	struct buffer_head *bh;
3480 	struct ext4_dir_entry_2 *de;
3481 
3482 	bh = ext4_find_entry(dir, d_name, &de, NULL);
3483 	if (IS_ERR(bh))
3484 		return PTR_ERR(bh);
3485 	if (bh) {
3486 		retval = ext4_delete_entry(handle, dir, de, bh);
3487 		brelse(bh);
3488 	}
3489 	return retval;
3490 }
3491 
3492 static void ext4_rename_delete(handle_t *handle, struct ext4_renament *ent,
3493 			       int force_reread)
3494 {
3495 	int retval;
3496 	/*
3497 	 * ent->de could have moved from under us during htree split, so make
3498 	 * sure that we are deleting the right entry.  We might also be pointing
3499 	 * to a stale entry in the unused part of ent->bh so just checking inum
3500 	 * and the name isn't enough.
3501 	 */
3502 	if (le32_to_cpu(ent->de->inode) != ent->inode->i_ino ||
3503 	    ent->de->name_len != ent->dentry->d_name.len ||
3504 	    strncmp(ent->de->name, ent->dentry->d_name.name,
3505 		    ent->de->name_len) ||
3506 	    force_reread) {
3507 		retval = ext4_find_delete_entry(handle, ent->dir,
3508 						&ent->dentry->d_name);
3509 	} else {
3510 		retval = ext4_delete_entry(handle, ent->dir, ent->de, ent->bh);
3511 		if (retval == -ENOENT) {
3512 			retval = ext4_find_delete_entry(handle, ent->dir,
3513 							&ent->dentry->d_name);
3514 		}
3515 	}
3516 
3517 	if (retval) {
3518 		ext4_warning_inode(ent->dir,
3519 				   "Deleting old file: nlink %d, error=%d",
3520 				   ent->dir->i_nlink, retval);
3521 	}
3522 }
3523 
3524 static void ext4_update_dir_count(handle_t *handle, struct ext4_renament *ent)
3525 {
3526 	if (ent->dir_nlink_delta) {
3527 		if (ent->dir_nlink_delta == -1)
3528 			ext4_dec_count(handle, ent->dir);
3529 		else
3530 			ext4_inc_count(handle, ent->dir);
3531 		ext4_mark_inode_dirty(handle, ent->dir);
3532 	}
3533 }
3534 
3535 static struct inode *ext4_whiteout_for_rename(struct ext4_renament *ent,
3536 					      int credits, handle_t **h)
3537 {
3538 	struct inode *wh;
3539 	handle_t *handle;
3540 	int retries = 0;
3541 
3542 	/*
3543 	 * for inode block, sb block, group summaries,
3544 	 * and inode bitmap
3545 	 */
3546 	credits += (EXT4_MAXQUOTAS_TRANS_BLOCKS(ent->dir->i_sb) +
3547 		    EXT4_XATTR_TRANS_BLOCKS + 4);
3548 retry:
3549 	wh = ext4_new_inode_start_handle(ent->dir, S_IFCHR | WHITEOUT_MODE,
3550 					 &ent->dentry->d_name, 0, NULL,
3551 					 EXT4_HT_DIR, credits);
3552 
3553 	handle = ext4_journal_current_handle();
3554 	if (IS_ERR(wh)) {
3555 		if (handle)
3556 			ext4_journal_stop(handle);
3557 		if (PTR_ERR(wh) == -ENOSPC &&
3558 		    ext4_should_retry_alloc(ent->dir->i_sb, &retries))
3559 			goto retry;
3560 	} else {
3561 		*h = handle;
3562 		init_special_inode(wh, wh->i_mode, WHITEOUT_DEV);
3563 		wh->i_op = &ext4_special_inode_operations;
3564 	}
3565 	return wh;
3566 }
3567 
3568 /*
3569  * Anybody can rename anything with this: the permission checks are left to the
3570  * higher-level routines.
3571  *
3572  * n.b.  old_{dentry,inode) refers to the source dentry/inode
3573  * while new_{dentry,inode) refers to the destination dentry/inode
3574  * This comes from rename(const char *oldpath, const char *newpath)
3575  */
3576 static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry,
3577 		       struct inode *new_dir, struct dentry *new_dentry,
3578 		       unsigned int flags)
3579 {
3580 	handle_t *handle = NULL;
3581 	struct ext4_renament old = {
3582 		.dir = old_dir,
3583 		.dentry = old_dentry,
3584 		.inode = d_inode(old_dentry),
3585 	};
3586 	struct ext4_renament new = {
3587 		.dir = new_dir,
3588 		.dentry = new_dentry,
3589 		.inode = d_inode(new_dentry),
3590 	};
3591 	int force_reread;
3592 	int retval;
3593 	struct inode *whiteout = NULL;
3594 	int credits;
3595 	u8 old_file_type;
3596 
3597 	if (new.inode && new.inode->i_nlink == 0) {
3598 		EXT4_ERROR_INODE(new.inode,
3599 				 "target of rename is already freed");
3600 		return -EFSCORRUPTED;
3601 	}
3602 
3603 	if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) &&
3604 	    (!projid_eq(EXT4_I(new_dir)->i_projid,
3605 			EXT4_I(old_dentry->d_inode)->i_projid)))
3606 		return -EXDEV;
3607 
3608 	retval = dquot_initialize(old.dir);
3609 	if (retval)
3610 		return retval;
3611 	retval = dquot_initialize(new.dir);
3612 	if (retval)
3613 		return retval;
3614 
3615 	/* Initialize quotas before so that eventual writes go
3616 	 * in separate transaction */
3617 	if (new.inode) {
3618 		retval = dquot_initialize(new.inode);
3619 		if (retval)
3620 			return retval;
3621 	}
3622 
3623 	old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3624 	if (IS_ERR(old.bh))
3625 		return PTR_ERR(old.bh);
3626 	/*
3627 	 *  Check for inode number is _not_ due to possible IO errors.
3628 	 *  We might rmdir the source, keep it as pwd of some process
3629 	 *  and merrily kill the link to whatever was created under the
3630 	 *  same name. Goodbye sticky bit ;-<
3631 	 */
3632 	retval = -ENOENT;
3633 	if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3634 		goto end_rename;
3635 
3636 	new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3637 				 &new.de, &new.inlined);
3638 	if (IS_ERR(new.bh)) {
3639 		retval = PTR_ERR(new.bh);
3640 		new.bh = NULL;
3641 		goto end_rename;
3642 	}
3643 	if (new.bh) {
3644 		if (!new.inode) {
3645 			brelse(new.bh);
3646 			new.bh = NULL;
3647 		}
3648 	}
3649 	if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3650 		ext4_alloc_da_blocks(old.inode);
3651 
3652 	credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3653 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3654 	if (!(flags & RENAME_WHITEOUT)) {
3655 		handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3656 		if (IS_ERR(handle)) {
3657 			retval = PTR_ERR(handle);
3658 			handle = NULL;
3659 			goto end_rename;
3660 		}
3661 	} else {
3662 		whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3663 		if (IS_ERR(whiteout)) {
3664 			retval = PTR_ERR(whiteout);
3665 			whiteout = NULL;
3666 			goto end_rename;
3667 		}
3668 	}
3669 
3670 	if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3671 		ext4_handle_sync(handle);
3672 
3673 	if (S_ISDIR(old.inode->i_mode)) {
3674 		if (new.inode) {
3675 			retval = -ENOTEMPTY;
3676 			if (!ext4_empty_dir(new.inode))
3677 				goto end_rename;
3678 		} else {
3679 			retval = -EMLINK;
3680 			if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3681 				goto end_rename;
3682 		}
3683 		retval = ext4_rename_dir_prepare(handle, &old);
3684 		if (retval)
3685 			goto end_rename;
3686 	}
3687 	/*
3688 	 * If we're renaming a file within an inline_data dir and adding or
3689 	 * setting the new dirent causes a conversion from inline_data to
3690 	 * extents/blockmap, we need to force the dirent delete code to
3691 	 * re-read the directory, or else we end up trying to delete a dirent
3692 	 * from what is now the extent tree root (or a block map).
3693 	 */
3694 	force_reread = (new.dir->i_ino == old.dir->i_ino &&
3695 			ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3696 
3697 	old_file_type = old.de->file_type;
3698 	if (whiteout) {
3699 		/*
3700 		 * Do this before adding a new entry, so the old entry is sure
3701 		 * to be still pointing to the valid old entry.
3702 		 */
3703 		retval = ext4_setent(handle, &old, whiteout->i_ino,
3704 				     EXT4_FT_CHRDEV);
3705 		if (retval)
3706 			goto end_rename;
3707 		ext4_mark_inode_dirty(handle, whiteout);
3708 	}
3709 	if (!new.bh) {
3710 		retval = ext4_add_entry(handle, new.dentry, old.inode);
3711 		if (retval)
3712 			goto end_rename;
3713 	} else {
3714 		retval = ext4_setent(handle, &new,
3715 				     old.inode->i_ino, old_file_type);
3716 		if (retval)
3717 			goto end_rename;
3718 	}
3719 	if (force_reread)
3720 		force_reread = !ext4_test_inode_flag(new.dir,
3721 						     EXT4_INODE_INLINE_DATA);
3722 
3723 	/*
3724 	 * Like most other Unix systems, set the ctime for inodes on a
3725 	 * rename.
3726 	 */
3727 	old.inode->i_ctime = current_time(old.inode);
3728 	ext4_mark_inode_dirty(handle, old.inode);
3729 
3730 	if (!whiteout) {
3731 		/*
3732 		 * ok, that's it
3733 		 */
3734 		ext4_rename_delete(handle, &old, force_reread);
3735 	}
3736 
3737 	if (new.inode) {
3738 		ext4_dec_count(handle, new.inode);
3739 		new.inode->i_ctime = current_time(new.inode);
3740 	}
3741 	old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
3742 	ext4_update_dx_flag(old.dir);
3743 	if (old.dir_bh) {
3744 		retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3745 		if (retval)
3746 			goto end_rename;
3747 
3748 		ext4_dec_count(handle, old.dir);
3749 		if (new.inode) {
3750 			/* checked ext4_empty_dir above, can't have another
3751 			 * parent, ext4_dec_count() won't work for many-linked
3752 			 * dirs */
3753 			clear_nlink(new.inode);
3754 		} else {
3755 			ext4_inc_count(handle, new.dir);
3756 			ext4_update_dx_flag(new.dir);
3757 			ext4_mark_inode_dirty(handle, new.dir);
3758 		}
3759 	}
3760 	ext4_mark_inode_dirty(handle, old.dir);
3761 	if (new.inode) {
3762 		ext4_mark_inode_dirty(handle, new.inode);
3763 		if (!new.inode->i_nlink)
3764 			ext4_orphan_add(handle, new.inode);
3765 	}
3766 	retval = 0;
3767 
3768 end_rename:
3769 	brelse(old.dir_bh);
3770 	brelse(old.bh);
3771 	brelse(new.bh);
3772 	if (whiteout) {
3773 		if (retval)
3774 			drop_nlink(whiteout);
3775 		unlock_new_inode(whiteout);
3776 		iput(whiteout);
3777 	}
3778 	if (handle)
3779 		ext4_journal_stop(handle);
3780 	return retval;
3781 }
3782 
3783 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
3784 			     struct inode *new_dir, struct dentry *new_dentry)
3785 {
3786 	handle_t *handle = NULL;
3787 	struct ext4_renament old = {
3788 		.dir = old_dir,
3789 		.dentry = old_dentry,
3790 		.inode = d_inode(old_dentry),
3791 	};
3792 	struct ext4_renament new = {
3793 		.dir = new_dir,
3794 		.dentry = new_dentry,
3795 		.inode = d_inode(new_dentry),
3796 	};
3797 	u8 new_file_type;
3798 	int retval;
3799 	struct timespec64 ctime;
3800 
3801 	if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
3802 	     !projid_eq(EXT4_I(new_dir)->i_projid,
3803 			EXT4_I(old_dentry->d_inode)->i_projid)) ||
3804 	    (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
3805 	     !projid_eq(EXT4_I(old_dir)->i_projid,
3806 			EXT4_I(new_dentry->d_inode)->i_projid)))
3807 		return -EXDEV;
3808 
3809 	retval = dquot_initialize(old.dir);
3810 	if (retval)
3811 		return retval;
3812 	retval = dquot_initialize(new.dir);
3813 	if (retval)
3814 		return retval;
3815 
3816 	old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
3817 				 &old.de, &old.inlined);
3818 	if (IS_ERR(old.bh))
3819 		return PTR_ERR(old.bh);
3820 	/*
3821 	 *  Check for inode number is _not_ due to possible IO errors.
3822 	 *  We might rmdir the source, keep it as pwd of some process
3823 	 *  and merrily kill the link to whatever was created under the
3824 	 *  same name. Goodbye sticky bit ;-<
3825 	 */
3826 	retval = -ENOENT;
3827 	if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3828 		goto end_rename;
3829 
3830 	new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3831 				 &new.de, &new.inlined);
3832 	if (IS_ERR(new.bh)) {
3833 		retval = PTR_ERR(new.bh);
3834 		new.bh = NULL;
3835 		goto end_rename;
3836 	}
3837 
3838 	/* RENAME_EXCHANGE case: old *and* new must both exist */
3839 	if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
3840 		goto end_rename;
3841 
3842 	handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
3843 		(2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3844 		 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
3845 	if (IS_ERR(handle)) {
3846 		retval = PTR_ERR(handle);
3847 		handle = NULL;
3848 		goto end_rename;
3849 	}
3850 
3851 	if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3852 		ext4_handle_sync(handle);
3853 
3854 	if (S_ISDIR(old.inode->i_mode)) {
3855 		old.is_dir = true;
3856 		retval = ext4_rename_dir_prepare(handle, &old);
3857 		if (retval)
3858 			goto end_rename;
3859 	}
3860 	if (S_ISDIR(new.inode->i_mode)) {
3861 		new.is_dir = true;
3862 		retval = ext4_rename_dir_prepare(handle, &new);
3863 		if (retval)
3864 			goto end_rename;
3865 	}
3866 
3867 	/*
3868 	 * Other than the special case of overwriting a directory, parents'
3869 	 * nlink only needs to be modified if this is a cross directory rename.
3870 	 */
3871 	if (old.dir != new.dir && old.is_dir != new.is_dir) {
3872 		old.dir_nlink_delta = old.is_dir ? -1 : 1;
3873 		new.dir_nlink_delta = -old.dir_nlink_delta;
3874 		retval = -EMLINK;
3875 		if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
3876 		    (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
3877 			goto end_rename;
3878 	}
3879 
3880 	new_file_type = new.de->file_type;
3881 	retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
3882 	if (retval)
3883 		goto end_rename;
3884 
3885 	retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
3886 	if (retval)
3887 		goto end_rename;
3888 
3889 	/*
3890 	 * Like most other Unix systems, set the ctime for inodes on a
3891 	 * rename.
3892 	 */
3893 	ctime = current_time(old.inode);
3894 	old.inode->i_ctime = ctime;
3895 	new.inode->i_ctime = ctime;
3896 	ext4_mark_inode_dirty(handle, old.inode);
3897 	ext4_mark_inode_dirty(handle, new.inode);
3898 
3899 	if (old.dir_bh) {
3900 		retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
3901 		if (retval)
3902 			goto end_rename;
3903 	}
3904 	if (new.dir_bh) {
3905 		retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
3906 		if (retval)
3907 			goto end_rename;
3908 	}
3909 	ext4_update_dir_count(handle, &old);
3910 	ext4_update_dir_count(handle, &new);
3911 	retval = 0;
3912 
3913 end_rename:
3914 	brelse(old.dir_bh);
3915 	brelse(new.dir_bh);
3916 	brelse(old.bh);
3917 	brelse(new.bh);
3918 	if (handle)
3919 		ext4_journal_stop(handle);
3920 	return retval;
3921 }
3922 
3923 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
3924 			struct inode *new_dir, struct dentry *new_dentry,
3925 			unsigned int flags)
3926 {
3927 	int err;
3928 
3929 	if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
3930 		return -EIO;
3931 
3932 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3933 		return -EINVAL;
3934 
3935 	err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
3936 				     flags);
3937 	if (err)
3938 		return err;
3939 
3940 	if (flags & RENAME_EXCHANGE) {
3941 		return ext4_cross_rename(old_dir, old_dentry,
3942 					 new_dir, new_dentry);
3943 	}
3944 
3945 	return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
3946 }
3947 
3948 /*
3949  * directories can handle most operations...
3950  */
3951 const struct inode_operations ext4_dir_inode_operations = {
3952 	.create		= ext4_create,
3953 	.lookup		= ext4_lookup,
3954 	.link		= ext4_link,
3955 	.unlink		= ext4_unlink,
3956 	.symlink	= ext4_symlink,
3957 	.mkdir		= ext4_mkdir,
3958 	.rmdir		= ext4_rmdir,
3959 	.mknod		= ext4_mknod,
3960 	.tmpfile	= ext4_tmpfile,
3961 	.rename		= ext4_rename2,
3962 	.setattr	= ext4_setattr,
3963 	.getattr	= ext4_getattr,
3964 	.listxattr	= ext4_listxattr,
3965 	.get_acl	= ext4_get_acl,
3966 	.set_acl	= ext4_set_acl,
3967 	.fiemap         = ext4_fiemap,
3968 };
3969 
3970 const struct inode_operations ext4_special_inode_operations = {
3971 	.setattr	= ext4_setattr,
3972 	.getattr	= ext4_getattr,
3973 	.listxattr	= ext4_listxattr,
3974 	.get_acl	= ext4_get_acl,
3975 	.set_acl	= ext4_set_acl,
3976 };
3977