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