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