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