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