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