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