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