• 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 (has_inline_data) {
1516 			if (inlined)
1517 				*inlined = 1;
1518 			goto cleanup_and_exit;
1519 		}
1520 	}
1521 
1522 	if ((namelen <= 2) && (name[0] == '.') &&
1523 	    (name[1] == '.' || name[1] == '\0')) {
1524 		/*
1525 		 * "." or ".." will only be in the first block
1526 		 * NFS may look up ".."; "." should be handled by the VFS
1527 		 */
1528 		block = start = 0;
1529 		nblocks = 1;
1530 		goto restart;
1531 	}
1532 	if (is_dx(dir)) {
1533 		ret = ext4_dx_find_entry(dir, fname, res_dir);
1534 		/*
1535 		 * On success, or if the error was file not found,
1536 		 * return.  Otherwise, fall back to doing a search the
1537 		 * old fashioned way.
1538 		 */
1539 		if (!IS_ERR(ret) || PTR_ERR(ret) != ERR_BAD_DX_DIR)
1540 			goto cleanup_and_exit;
1541 		dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, "
1542 			       "falling back\n"));
1543 		ret = NULL;
1544 	}
1545 	nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1546 	if (!nblocks) {
1547 		ret = NULL;
1548 		goto cleanup_and_exit;
1549 	}
1550 	start = EXT4_I(dir)->i_dir_start_lookup;
1551 	if (start >= nblocks)
1552 		start = 0;
1553 	block = start;
1554 restart:
1555 	do {
1556 		/*
1557 		 * We deal with the read-ahead logic here.
1558 		 */
1559 		cond_resched();
1560 		if (ra_ptr >= ra_max) {
1561 			/* Refill the readahead buffer */
1562 			ra_ptr = 0;
1563 			if (block < start)
1564 				ra_max = start - block;
1565 			else
1566 				ra_max = nblocks - block;
1567 			ra_max = min(ra_max, ARRAY_SIZE(bh_use));
1568 			retval = ext4_bread_batch(dir, block, ra_max,
1569 						  false /* wait */, bh_use);
1570 			if (retval) {
1571 				ret = ERR_PTR(retval);
1572 				ra_max = 0;
1573 				goto cleanup_and_exit;
1574 			}
1575 		}
1576 		if ((bh = bh_use[ra_ptr++]) == NULL)
1577 			goto next;
1578 		wait_on_buffer(bh);
1579 		if (!buffer_uptodate(bh)) {
1580 			EXT4_ERROR_INODE_ERR(dir, EIO,
1581 					     "reading directory lblock %lu",
1582 					     (unsigned long) block);
1583 			brelse(bh);
1584 			ret = ERR_PTR(-EIO);
1585 			goto cleanup_and_exit;
1586 		}
1587 		if (!buffer_verified(bh) &&
1588 		    !is_dx_internal_node(dir, block,
1589 					 (struct ext4_dir_entry *)bh->b_data) &&
1590 		    !ext4_dirblock_csum_verify(dir, bh)) {
1591 			EXT4_ERROR_INODE_ERR(dir, EFSBADCRC,
1592 					     "checksumming directory "
1593 					     "block %lu", (unsigned long)block);
1594 			brelse(bh);
1595 			ret = ERR_PTR(-EFSBADCRC);
1596 			goto cleanup_and_exit;
1597 		}
1598 		set_buffer_verified(bh);
1599 		i = search_dirblock(bh, dir, fname,
1600 			    block << EXT4_BLOCK_SIZE_BITS(sb), res_dir);
1601 		if (i == 1) {
1602 			EXT4_I(dir)->i_dir_start_lookup = block;
1603 			ret = bh;
1604 			goto cleanup_and_exit;
1605 		} else {
1606 			brelse(bh);
1607 			if (i < 0)
1608 				goto cleanup_and_exit;
1609 		}
1610 	next:
1611 		if (++block >= nblocks)
1612 			block = 0;
1613 	} while (block != start);
1614 
1615 	/*
1616 	 * If the directory has grown while we were searching, then
1617 	 * search the last part of the directory before giving up.
1618 	 */
1619 	block = nblocks;
1620 	nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb);
1621 	if (block < nblocks) {
1622 		start = 0;
1623 		goto restart;
1624 	}
1625 
1626 cleanup_and_exit:
1627 	/* Clean up the read-ahead blocks */
1628 	for (; ra_ptr < ra_max; ra_ptr++)
1629 		brelse(bh_use[ra_ptr]);
1630 	return ret;
1631 }
1632 
ext4_find_entry(struct inode * dir,const struct qstr * d_name,struct ext4_dir_entry_2 ** res_dir,int * inlined)1633 static struct buffer_head *ext4_find_entry(struct inode *dir,
1634 					   const struct qstr *d_name,
1635 					   struct ext4_dir_entry_2 **res_dir,
1636 					   int *inlined)
1637 {
1638 	int err;
1639 	struct ext4_filename fname;
1640 	struct buffer_head *bh;
1641 
1642 	err = ext4_fname_setup_filename(dir, d_name, 1, &fname);
1643 	if (err == -ENOENT)
1644 		return NULL;
1645 	if (err)
1646 		return ERR_PTR(err);
1647 
1648 	bh = __ext4_find_entry(dir, &fname, res_dir, inlined);
1649 
1650 	ext4_fname_free_filename(&fname);
1651 	return bh;
1652 }
1653 
ext4_lookup_entry(struct inode * dir,struct dentry * dentry,struct ext4_dir_entry_2 ** res_dir)1654 static struct buffer_head *ext4_lookup_entry(struct inode *dir,
1655 					     struct dentry *dentry,
1656 					     struct ext4_dir_entry_2 **res_dir)
1657 {
1658 	int err;
1659 	struct ext4_filename fname;
1660 	struct buffer_head *bh;
1661 
1662 	err = ext4_fname_prepare_lookup(dir, dentry, &fname);
1663 	if (err == -ENOENT)
1664 		return NULL;
1665 	if (err)
1666 		return ERR_PTR(err);
1667 
1668 	bh = __ext4_find_entry(dir, &fname, res_dir, NULL);
1669 
1670 	ext4_fname_free_filename(&fname);
1671 	return bh;
1672 }
1673 
ext4_dx_find_entry(struct inode * dir,struct ext4_filename * fname,struct ext4_dir_entry_2 ** res_dir)1674 static struct buffer_head * ext4_dx_find_entry(struct inode *dir,
1675 			struct ext4_filename *fname,
1676 			struct ext4_dir_entry_2 **res_dir)
1677 {
1678 	struct super_block * sb = dir->i_sb;
1679 	struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
1680 	struct buffer_head *bh;
1681 	ext4_lblk_t block;
1682 	int retval;
1683 
1684 #ifdef CONFIG_FS_ENCRYPTION
1685 	*res_dir = NULL;
1686 #endif
1687 	frame = dx_probe(fname, dir, NULL, frames);
1688 	if (IS_ERR(frame))
1689 		return (struct buffer_head *) frame;
1690 	do {
1691 		block = dx_get_block(frame->at);
1692 		bh = ext4_read_dirblock(dir, block, DIRENT_HTREE);
1693 		if (IS_ERR(bh))
1694 			goto errout;
1695 
1696 		retval = search_dirblock(bh, dir, fname,
1697 					 block << EXT4_BLOCK_SIZE_BITS(sb),
1698 					 res_dir);
1699 		if (retval == 1)
1700 			goto success;
1701 		brelse(bh);
1702 		if (retval == -1) {
1703 			bh = ERR_PTR(ERR_BAD_DX_DIR);
1704 			goto errout;
1705 		}
1706 
1707 		/* Check to see if we should continue to search */
1708 		retval = ext4_htree_next_block(dir, fname->hinfo.hash, frame,
1709 					       frames, NULL);
1710 		if (retval < 0) {
1711 			ext4_warning_inode(dir,
1712 				"error %d reading directory index block",
1713 				retval);
1714 			bh = ERR_PTR(retval);
1715 			goto errout;
1716 		}
1717 	} while (retval == 1);
1718 
1719 	bh = NULL;
1720 errout:
1721 	dxtrace(printk(KERN_DEBUG "%s not found\n", fname->usr_fname->name));
1722 success:
1723 	dx_release(frames);
1724 	return bh;
1725 }
1726 
ext4_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)1727 static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1728 {
1729 	struct inode *inode;
1730 	struct ext4_dir_entry_2 *de;
1731 	struct buffer_head *bh;
1732 
1733 	if (dentry->d_name.len > EXT4_NAME_LEN)
1734 		return ERR_PTR(-ENAMETOOLONG);
1735 
1736 	bh = ext4_lookup_entry(dir, dentry, &de);
1737 	if (IS_ERR(bh))
1738 		return ERR_CAST(bh);
1739 	inode = NULL;
1740 	if (bh) {
1741 		__u32 ino = le32_to_cpu(de->inode);
1742 		brelse(bh);
1743 		if (!ext4_valid_inum(dir->i_sb, ino)) {
1744 			EXT4_ERROR_INODE(dir, "bad inode number: %u", ino);
1745 			return ERR_PTR(-EFSCORRUPTED);
1746 		}
1747 		if (unlikely(ino == dir->i_ino)) {
1748 			EXT4_ERROR_INODE(dir, "'%pd' linked to parent dir",
1749 					 dentry);
1750 			return ERR_PTR(-EFSCORRUPTED);
1751 		}
1752 		inode = ext4_iget(dir->i_sb, ino, EXT4_IGET_NORMAL);
1753 		if (inode == ERR_PTR(-ESTALE)) {
1754 			EXT4_ERROR_INODE(dir,
1755 					 "deleted inode referenced: %u",
1756 					 ino);
1757 			return ERR_PTR(-EFSCORRUPTED);
1758 		}
1759 		if (!IS_ERR(inode) && IS_ENCRYPTED(dir) &&
1760 		    (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
1761 		    !fscrypt_has_permitted_context(dir, inode)) {
1762 			ext4_warning(inode->i_sb,
1763 				     "Inconsistent encryption contexts: %lu/%lu",
1764 				     dir->i_ino, inode->i_ino);
1765 			iput(inode);
1766 			return ERR_PTR(-EPERM);
1767 		}
1768 	}
1769 
1770 #ifdef CONFIG_UNICODE
1771 	if (!inode && IS_CASEFOLDED(dir)) {
1772 		/* Eventually we want to call d_add_ci(dentry, NULL)
1773 		 * for negative dentries in the encoding case as
1774 		 * well.  For now, prevent the negative dentry
1775 		 * from being cached.
1776 		 */
1777 		return NULL;
1778 	}
1779 #endif
1780 	return d_splice_alias(inode, dentry);
1781 }
1782 
1783 
ext4_get_parent(struct dentry * child)1784 struct dentry *ext4_get_parent(struct dentry *child)
1785 {
1786 	__u32 ino;
1787 	static const struct qstr dotdot = QSTR_INIT("..", 2);
1788 	struct ext4_dir_entry_2 * de;
1789 	struct buffer_head *bh;
1790 
1791 	bh = ext4_find_entry(d_inode(child), &dotdot, &de, NULL);
1792 	if (IS_ERR(bh))
1793 		return ERR_CAST(bh);
1794 	if (!bh)
1795 		return ERR_PTR(-ENOENT);
1796 	ino = le32_to_cpu(de->inode);
1797 	brelse(bh);
1798 
1799 	if (!ext4_valid_inum(child->d_sb, ino)) {
1800 		EXT4_ERROR_INODE(d_inode(child),
1801 				 "bad parent inode number: %u", ino);
1802 		return ERR_PTR(-EFSCORRUPTED);
1803 	}
1804 
1805 	return d_obtain_alias(ext4_iget(child->d_sb, ino, EXT4_IGET_NORMAL));
1806 }
1807 
1808 /*
1809  * Move count entries from end of map between two memory locations.
1810  * Returns pointer to last entry moved.
1811  */
1812 static struct ext4_dir_entry_2 *
dx_move_dirents(char * from,char * to,struct dx_map_entry * map,int count,unsigned blocksize)1813 dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count,
1814 		unsigned blocksize)
1815 {
1816 	unsigned rec_len = 0;
1817 
1818 	while (count--) {
1819 		struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *)
1820 						(from + (map->offs<<2));
1821 		rec_len = EXT4_DIR_REC_LEN(de->name_len);
1822 		memcpy (to, de, rec_len);
1823 		((struct ext4_dir_entry_2 *) to)->rec_len =
1824 				ext4_rec_len_to_disk(rec_len, blocksize);
1825 
1826 		/* wipe dir_entry excluding the rec_len field */
1827 		de->inode = 0;
1828 		memset(&de->name_len, 0, ext4_rec_len_from_disk(de->rec_len,
1829 								blocksize) -
1830 					 offsetof(struct ext4_dir_entry_2,
1831 								name_len));
1832 
1833 		map++;
1834 		to += rec_len;
1835 	}
1836 	return (struct ext4_dir_entry_2 *) (to - rec_len);
1837 }
1838 
1839 /*
1840  * Compact each dir entry in the range to the minimal rec_len.
1841  * Returns pointer to last entry in range.
1842  */
dx_pack_dirents(char * base,unsigned blocksize)1843 static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize)
1844 {
1845 	struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base;
1846 	unsigned rec_len = 0;
1847 
1848 	prev = to = de;
1849 	while ((char*)de < base + blocksize) {
1850 		next = ext4_next_entry(de, blocksize);
1851 		if (de->inode && de->name_len) {
1852 			rec_len = EXT4_DIR_REC_LEN(de->name_len);
1853 			if (de > to)
1854 				memmove(to, de, rec_len);
1855 			to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize);
1856 			prev = to;
1857 			to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len);
1858 		}
1859 		de = next;
1860 	}
1861 	return prev;
1862 }
1863 
1864 /*
1865  * Split a full leaf block to make room for a new dir entry.
1866  * Allocate a new block, and move entries so that they are approx. equally full.
1867  * Returns pointer to de in block into which the new entry will be inserted.
1868  */
do_split(handle_t * handle,struct inode * dir,struct buffer_head ** bh,struct dx_frame * frame,struct dx_hash_info * hinfo)1869 static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,
1870 			struct buffer_head **bh,struct dx_frame *frame,
1871 			struct dx_hash_info *hinfo)
1872 {
1873 	unsigned blocksize = dir->i_sb->s_blocksize;
1874 	unsigned continued;
1875 	int count;
1876 	struct buffer_head *bh2;
1877 	ext4_lblk_t newblock;
1878 	u32 hash2;
1879 	struct dx_map_entry *map;
1880 	char *data1 = (*bh)->b_data, *data2;
1881 	unsigned split, move, size;
1882 	struct ext4_dir_entry_2 *de = NULL, *de2;
1883 	int	csum_size = 0;
1884 	int	err = 0, i;
1885 
1886 	if (ext4_has_metadata_csum(dir->i_sb))
1887 		csum_size = sizeof(struct ext4_dir_entry_tail);
1888 
1889 	bh2 = ext4_append(handle, dir, &newblock);
1890 	if (IS_ERR(bh2)) {
1891 		brelse(*bh);
1892 		*bh = NULL;
1893 		return (struct ext4_dir_entry_2 *) bh2;
1894 	}
1895 
1896 	BUFFER_TRACE(*bh, "get_write_access");
1897 	err = ext4_journal_get_write_access(handle, *bh);
1898 	if (err)
1899 		goto journal_error;
1900 
1901 	BUFFER_TRACE(frame->bh, "get_write_access");
1902 	err = ext4_journal_get_write_access(handle, frame->bh);
1903 	if (err)
1904 		goto journal_error;
1905 
1906 	data2 = bh2->b_data;
1907 
1908 	/* create map in the end of data2 block */
1909 	map = (struct dx_map_entry *) (data2 + blocksize);
1910 	count = dx_make_map(dir, *bh, hinfo, map);
1911 	if (count < 0) {
1912 		err = count;
1913 		goto journal_error;
1914 	}
1915 	map -= count;
1916 	dx_sort_map(map, count);
1917 	/* Ensure that neither split block is over half full */
1918 	size = 0;
1919 	move = 0;
1920 	for (i = count-1; i >= 0; i--) {
1921 		/* is more than half of this entry in 2nd half of the block? */
1922 		if (size + map[i].size/2 > blocksize/2)
1923 			break;
1924 		size += map[i].size;
1925 		move++;
1926 	}
1927 	/*
1928 	 * map index at which we will split
1929 	 *
1930 	 * If the sum of active entries didn't exceed half the block size, just
1931 	 * split it in half by count; each resulting block will have at least
1932 	 * half the space free.
1933 	 */
1934 	if (i > 0)
1935 		split = count - move;
1936 	else
1937 		split = count/2;
1938 
1939 	hash2 = map[split].hash;
1940 	continued = hash2 == map[split - 1].hash;
1941 	dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n",
1942 			(unsigned long)dx_get_block(frame->at),
1943 					hash2, split, count-split));
1944 
1945 	/* Fancy dance to stay within two buffers */
1946 	de2 = dx_move_dirents(data1, data2, map + split, count - split,
1947 			      blocksize);
1948 	de = dx_pack_dirents(data1, blocksize);
1949 	de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -
1950 					   (char *) de,
1951 					   blocksize);
1952 	de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
1953 					    (char *) de2,
1954 					    blocksize);
1955 	if (csum_size) {
1956 		ext4_initialize_dirent_tail(*bh, blocksize);
1957 		ext4_initialize_dirent_tail(bh2, blocksize);
1958 	}
1959 
1960 	dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,
1961 			blocksize, 1));
1962 	dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,
1963 			blocksize, 1));
1964 
1965 	/* Which block gets the new entry? */
1966 	if (hinfo->hash >= hash2) {
1967 		swap(*bh, bh2);
1968 		de = de2;
1969 	}
1970 	dx_insert_block(frame, hash2 + continued, newblock);
1971 	err = ext4_handle_dirty_dirblock(handle, dir, bh2);
1972 	if (err)
1973 		goto journal_error;
1974 	err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
1975 	if (err)
1976 		goto journal_error;
1977 	brelse(bh2);
1978 	dxtrace(dx_show_index("frame", frame->entries));
1979 	return de;
1980 
1981 journal_error:
1982 	brelse(*bh);
1983 	brelse(bh2);
1984 	*bh = NULL;
1985 	ext4_std_error(dir->i_sb, err);
1986 	return ERR_PTR(err);
1987 }
1988 
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)1989 int ext4_find_dest_de(struct inode *dir, struct inode *inode,
1990 		      struct buffer_head *bh,
1991 		      void *buf, int buf_size,
1992 		      struct ext4_filename *fname,
1993 		      struct ext4_dir_entry_2 **dest_de)
1994 {
1995 	struct ext4_dir_entry_2 *de;
1996 	unsigned short reclen = EXT4_DIR_REC_LEN(fname_len(fname));
1997 	int nlen, rlen;
1998 	unsigned int offset = 0;
1999 	char *top;
2000 
2001 	de = (struct ext4_dir_entry_2 *)buf;
2002 	top = buf + buf_size - reclen;
2003 	while ((char *) de <= top) {
2004 		if (ext4_check_dir_entry(dir, NULL, de, bh,
2005 					 buf, buf_size, offset))
2006 			return -EFSCORRUPTED;
2007 		if (ext4_match(dir, fname, de))
2008 			return -EEXIST;
2009 		nlen = EXT4_DIR_REC_LEN(de->name_len);
2010 		rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
2011 		if ((de->inode ? rlen - nlen : rlen) >= reclen)
2012 			break;
2013 		de = (struct ext4_dir_entry_2 *)((char *)de + rlen);
2014 		offset += rlen;
2015 	}
2016 	if ((char *) de > top)
2017 		return -ENOSPC;
2018 
2019 	*dest_de = de;
2020 	return 0;
2021 }
2022 
ext4_insert_dentry(struct inode * inode,struct ext4_dir_entry_2 * de,int buf_size,struct ext4_filename * fname)2023 void ext4_insert_dentry(struct inode *inode,
2024 			struct ext4_dir_entry_2 *de,
2025 			int buf_size,
2026 			struct ext4_filename *fname)
2027 {
2028 
2029 	int nlen, rlen;
2030 
2031 	nlen = EXT4_DIR_REC_LEN(de->name_len);
2032 	rlen = ext4_rec_len_from_disk(de->rec_len, buf_size);
2033 	if (de->inode) {
2034 		struct ext4_dir_entry_2 *de1 =
2035 			(struct ext4_dir_entry_2 *)((char *)de + nlen);
2036 		de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size);
2037 		de->rec_len = ext4_rec_len_to_disk(nlen, buf_size);
2038 		de = de1;
2039 	}
2040 	de->file_type = EXT4_FT_UNKNOWN;
2041 	de->inode = cpu_to_le32(inode->i_ino);
2042 	ext4_set_de_type(inode->i_sb, de, inode->i_mode);
2043 	de->name_len = fname_len(fname);
2044 	memcpy(de->name, fname_name(fname), fname_len(fname));
2045 }
2046 
2047 /*
2048  * Add a new entry into a directory (leaf) block.  If de is non-NULL,
2049  * it points to a directory entry which is guaranteed to be large
2050  * enough for new directory entry.  If de is NULL, then
2051  * add_dirent_to_buf will attempt search the directory block for
2052  * space.  It will return -ENOSPC if no space is available, and -EIO
2053  * and -EEXIST if directory entry already exists.
2054  */
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)2055 static int add_dirent_to_buf(handle_t *handle, struct ext4_filename *fname,
2056 			     struct inode *dir,
2057 			     struct inode *inode, struct ext4_dir_entry_2 *de,
2058 			     struct buffer_head *bh)
2059 {
2060 	unsigned int	blocksize = dir->i_sb->s_blocksize;
2061 	int		csum_size = 0;
2062 	int		err, err2;
2063 
2064 	if (ext4_has_metadata_csum(inode->i_sb))
2065 		csum_size = sizeof(struct ext4_dir_entry_tail);
2066 
2067 	if (!de) {
2068 		err = ext4_find_dest_de(dir, inode, bh, bh->b_data,
2069 					blocksize - csum_size, fname, &de);
2070 		if (err)
2071 			return err;
2072 	}
2073 	BUFFER_TRACE(bh, "get_write_access");
2074 	err = ext4_journal_get_write_access(handle, bh);
2075 	if (err) {
2076 		ext4_std_error(dir->i_sb, err);
2077 		return err;
2078 	}
2079 
2080 	/* By now the buffer is marked for journaling */
2081 	ext4_insert_dentry(inode, de, blocksize, fname);
2082 
2083 	/*
2084 	 * XXX shouldn't update any times until successful
2085 	 * completion of syscall, but too many callers depend
2086 	 * on this.
2087 	 *
2088 	 * XXX similarly, too many callers depend on
2089 	 * ext4_new_inode() setting the times, but error
2090 	 * recovery deletes the inode, so the worst that can
2091 	 * happen is that the times are slightly out of date
2092 	 * and/or different from the directory change time.
2093 	 */
2094 	dir->i_mtime = dir->i_ctime = current_time(dir);
2095 	ext4_update_dx_flag(dir);
2096 	inode_inc_iversion(dir);
2097 	err2 = ext4_mark_inode_dirty(handle, dir);
2098 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2099 	err = ext4_handle_dirty_dirblock(handle, dir, bh);
2100 	if (err)
2101 		ext4_std_error(dir->i_sb, err);
2102 	return err ? err : err2;
2103 }
2104 
2105 /*
2106  * This converts a one block unindexed directory to a 3 block indexed
2107  * directory, and adds the dentry to the indexed directory.
2108  */
make_indexed_dir(handle_t * handle,struct ext4_filename * fname,struct inode * dir,struct inode * inode,struct buffer_head * bh)2109 static int make_indexed_dir(handle_t *handle, struct ext4_filename *fname,
2110 			    struct inode *dir,
2111 			    struct inode *inode, struct buffer_head *bh)
2112 {
2113 	struct buffer_head *bh2;
2114 	struct dx_root	*root;
2115 	struct dx_frame	frames[EXT4_HTREE_LEVEL], *frame;
2116 	struct dx_entry *entries;
2117 	struct ext4_dir_entry_2	*de, *de2;
2118 	char		*data2, *top;
2119 	unsigned	len;
2120 	int		retval;
2121 	unsigned	blocksize;
2122 	ext4_lblk_t  block;
2123 	struct fake_dirent *fde;
2124 	int csum_size = 0;
2125 
2126 	if (ext4_has_metadata_csum(inode->i_sb))
2127 		csum_size = sizeof(struct ext4_dir_entry_tail);
2128 
2129 	blocksize =  dir->i_sb->s_blocksize;
2130 	dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino));
2131 	BUFFER_TRACE(bh, "get_write_access");
2132 	retval = ext4_journal_get_write_access(handle, bh);
2133 	if (retval) {
2134 		ext4_std_error(dir->i_sb, retval);
2135 		brelse(bh);
2136 		return retval;
2137 	}
2138 	root = (struct dx_root *) bh->b_data;
2139 
2140 	/* The 0th block becomes the root, move the dirents out */
2141 	fde = &root->dotdot;
2142 	de = (struct ext4_dir_entry_2 *)((char *)fde +
2143 		ext4_rec_len_from_disk(fde->rec_len, blocksize));
2144 	if ((char *) de >= (((char *) root) + blocksize)) {
2145 		EXT4_ERROR_INODE(dir, "invalid rec_len for '..'");
2146 		brelse(bh);
2147 		return -EFSCORRUPTED;
2148 	}
2149 	len = ((char *) root) + (blocksize - csum_size) - (char *) de;
2150 
2151 	/* Allocate new block for the 0th block's dirents */
2152 	bh2 = ext4_append(handle, dir, &block);
2153 	if (IS_ERR(bh2)) {
2154 		brelse(bh);
2155 		return PTR_ERR(bh2);
2156 	}
2157 	ext4_set_inode_flag(dir, EXT4_INODE_INDEX);
2158 	data2 = bh2->b_data;
2159 
2160 	memcpy(data2, de, len);
2161 	memset(de, 0, len); /* wipe old data */
2162 	de = (struct ext4_dir_entry_2 *) data2;
2163 	top = data2 + len;
2164 	while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top) {
2165 		if (ext4_check_dir_entry(dir, NULL, de, bh2, data2, len,
2166 					 (data2 + (blocksize - csum_size) -
2167 					  (char *) de))) {
2168 			brelse(bh2);
2169 			brelse(bh);
2170 			return -EFSCORRUPTED;
2171 		}
2172 		de = de2;
2173 	}
2174 	de->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -
2175 					   (char *) de, blocksize);
2176 
2177 	if (csum_size)
2178 		ext4_initialize_dirent_tail(bh2, blocksize);
2179 
2180 	/* Initialize the root; the dot dirents already exist */
2181 	de = (struct ext4_dir_entry_2 *) (&root->dotdot);
2182 	de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2),
2183 					   blocksize);
2184 	memset (&root->info, 0, sizeof(root->info));
2185 	root->info.info_length = sizeof(root->info);
2186 	root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version;
2187 	entries = root->entries;
2188 	dx_set_block(entries, 1);
2189 	dx_set_count(entries, 1);
2190 	dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info)));
2191 
2192 	/* Initialize as for dx_probe */
2193 	fname->hinfo.hash_version = root->info.hash_version;
2194 	if (fname->hinfo.hash_version <= DX_HASH_TEA)
2195 		fname->hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned;
2196 	fname->hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed;
2197 	ext4fs_dirhash(dir, fname_name(fname), fname_len(fname), &fname->hinfo);
2198 
2199 	memset(frames, 0, sizeof(frames));
2200 	frame = frames;
2201 	frame->entries = entries;
2202 	frame->at = entries;
2203 	frame->bh = bh;
2204 
2205 	retval = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2206 	if (retval)
2207 		goto out_frames;
2208 	retval = ext4_handle_dirty_dirblock(handle, dir, bh2);
2209 	if (retval)
2210 		goto out_frames;
2211 
2212 	de = do_split(handle,dir, &bh2, frame, &fname->hinfo);
2213 	if (IS_ERR(de)) {
2214 		retval = PTR_ERR(de);
2215 		goto out_frames;
2216 	}
2217 
2218 	retval = add_dirent_to_buf(handle, fname, dir, inode, de, bh2);
2219 out_frames:
2220 	/*
2221 	 * Even if the block split failed, we have to properly write
2222 	 * out all the changes we did so far. Otherwise we can end up
2223 	 * with corrupted filesystem.
2224 	 */
2225 	if (retval)
2226 		ext4_mark_inode_dirty(handle, dir);
2227 	dx_release(frames);
2228 	brelse(bh2);
2229 	return retval;
2230 }
2231 
2232 /*
2233  *	ext4_add_entry()
2234  *
2235  * adds a file entry to the specified directory, using the same
2236  * semantics as ext4_find_entry(). It returns NULL if it failed.
2237  *
2238  * NOTE!! The inode part of 'de' is left at 0 - which means you
2239  * may not sleep between calling this and putting something into
2240  * the entry, as someone else might have used it while you slept.
2241  */
ext4_add_entry(handle_t * handle,struct dentry * dentry,struct inode * inode)2242 static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
2243 			  struct inode *inode)
2244 {
2245 	struct inode *dir = d_inode(dentry->d_parent);
2246 	struct buffer_head *bh = NULL;
2247 	struct ext4_dir_entry_2 *de;
2248 	struct super_block *sb;
2249 	struct ext4_filename fname;
2250 	int	retval;
2251 	int	dx_fallback=0;
2252 	unsigned blocksize;
2253 	ext4_lblk_t block, blocks;
2254 	int	csum_size = 0;
2255 
2256 	if (ext4_has_metadata_csum(inode->i_sb))
2257 		csum_size = sizeof(struct ext4_dir_entry_tail);
2258 
2259 	sb = dir->i_sb;
2260 	blocksize = sb->s_blocksize;
2261 	if (!dentry->d_name.len)
2262 		return -EINVAL;
2263 
2264 	if (fscrypt_is_nokey_name(dentry))
2265 		return -ENOKEY;
2266 
2267 #ifdef CONFIG_UNICODE
2268 	if (sb_has_strict_encoding(sb) && IS_CASEFOLDED(dir) &&
2269 	    sb->s_encoding && utf8_validate(sb->s_encoding, &dentry->d_name))
2270 		return -EINVAL;
2271 #endif
2272 
2273 	retval = ext4_fname_setup_filename(dir, &dentry->d_name, 0, &fname);
2274 	if (retval)
2275 		return retval;
2276 
2277 	if (ext4_has_inline_data(dir)) {
2278 		retval = ext4_try_add_inline_entry(handle, &fname, dir, inode);
2279 		if (retval < 0)
2280 			goto out;
2281 		if (retval == 1) {
2282 			retval = 0;
2283 			goto out;
2284 		}
2285 	}
2286 
2287 	if (is_dx(dir)) {
2288 		retval = ext4_dx_add_entry(handle, &fname, dir, inode);
2289 		if (!retval || (retval != ERR_BAD_DX_DIR))
2290 			goto out;
2291 		/* Can we just ignore htree data? */
2292 		if (ext4_has_metadata_csum(sb)) {
2293 			EXT4_ERROR_INODE(dir,
2294 				"Directory has corrupted htree index.");
2295 			retval = -EFSCORRUPTED;
2296 			goto out;
2297 		}
2298 		ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
2299 		dx_fallback++;
2300 		retval = ext4_mark_inode_dirty(handle, dir);
2301 		if (unlikely(retval))
2302 			goto out;
2303 	}
2304 	blocks = dir->i_size >> sb->s_blocksize_bits;
2305 	for (block = 0; block < blocks; block++) {
2306 		bh = ext4_read_dirblock(dir, block, DIRENT);
2307 		if (bh == NULL) {
2308 			bh = ext4_bread(handle, dir, block,
2309 					EXT4_GET_BLOCKS_CREATE);
2310 			goto add_to_new_block;
2311 		}
2312 		if (IS_ERR(bh)) {
2313 			retval = PTR_ERR(bh);
2314 			bh = NULL;
2315 			goto out;
2316 		}
2317 		retval = add_dirent_to_buf(handle, &fname, dir, inode,
2318 					   NULL, bh);
2319 		if (retval != -ENOSPC)
2320 			goto out;
2321 
2322 		if (blocks == 1 && !dx_fallback &&
2323 		    ext4_has_feature_dir_index(sb)) {
2324 			retval = make_indexed_dir(handle, &fname, dir,
2325 						  inode, bh);
2326 			bh = NULL; /* make_indexed_dir releases bh */
2327 			goto out;
2328 		}
2329 		brelse(bh);
2330 	}
2331 	bh = ext4_append(handle, dir, &block);
2332 add_to_new_block:
2333 	if (IS_ERR(bh)) {
2334 		retval = PTR_ERR(bh);
2335 		bh = NULL;
2336 		goto out;
2337 	}
2338 	de = (struct ext4_dir_entry_2 *) bh->b_data;
2339 	de->inode = 0;
2340 	de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
2341 
2342 	if (csum_size)
2343 		ext4_initialize_dirent_tail(bh, blocksize);
2344 
2345 	retval = add_dirent_to_buf(handle, &fname, dir, inode, de, bh);
2346 out:
2347 	ext4_fname_free_filename(&fname);
2348 	brelse(bh);
2349 	if (retval == 0)
2350 		ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
2351 	return retval;
2352 }
2353 
2354 /*
2355  * Returns 0 for success, or a negative error value
2356  */
ext4_dx_add_entry(handle_t * handle,struct ext4_filename * fname,struct inode * dir,struct inode * inode)2357 static int ext4_dx_add_entry(handle_t *handle, struct ext4_filename *fname,
2358 			     struct inode *dir, struct inode *inode)
2359 {
2360 	struct dx_frame frames[EXT4_HTREE_LEVEL], *frame;
2361 	struct dx_entry *entries, *at;
2362 	struct buffer_head *bh;
2363 	struct super_block *sb = dir->i_sb;
2364 	struct ext4_dir_entry_2 *de;
2365 	int restart;
2366 	int err;
2367 
2368 again:
2369 	restart = 0;
2370 	frame = dx_probe(fname, dir, NULL, frames);
2371 	if (IS_ERR(frame))
2372 		return PTR_ERR(frame);
2373 	entries = frame->entries;
2374 	at = frame->at;
2375 	bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT_HTREE);
2376 	if (IS_ERR(bh)) {
2377 		err = PTR_ERR(bh);
2378 		bh = NULL;
2379 		goto cleanup;
2380 	}
2381 
2382 	BUFFER_TRACE(bh, "get_write_access");
2383 	err = ext4_journal_get_write_access(handle, bh);
2384 	if (err)
2385 		goto journal_error;
2386 
2387 	err = add_dirent_to_buf(handle, fname, dir, inode, NULL, bh);
2388 	if (err != -ENOSPC)
2389 		goto cleanup;
2390 
2391 	err = 0;
2392 	/* Block full, should compress but for now just split */
2393 	dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n",
2394 		       dx_get_count(entries), dx_get_limit(entries)));
2395 	/* Need to split index? */
2396 	if (dx_get_count(entries) == dx_get_limit(entries)) {
2397 		ext4_lblk_t newblock;
2398 		int levels = frame - frames + 1;
2399 		unsigned int icount;
2400 		int add_level = 1;
2401 		struct dx_entry *entries2;
2402 		struct dx_node *node2;
2403 		struct buffer_head *bh2;
2404 
2405 		while (frame > frames) {
2406 			if (dx_get_count((frame - 1)->entries) <
2407 			    dx_get_limit((frame - 1)->entries)) {
2408 				add_level = 0;
2409 				break;
2410 			}
2411 			frame--; /* split higher index block */
2412 			at = frame->at;
2413 			entries = frame->entries;
2414 			restart = 1;
2415 		}
2416 		if (add_level && levels == ext4_dir_htree_level(sb)) {
2417 			ext4_warning(sb, "Directory (ino: %lu) index full, "
2418 					 "reach max htree level :%d",
2419 					 dir->i_ino, levels);
2420 			if (ext4_dir_htree_level(sb) < EXT4_HTREE_LEVEL) {
2421 				ext4_warning(sb, "Large directory feature is "
2422 						 "not enabled on this "
2423 						 "filesystem");
2424 			}
2425 			err = -ENOSPC;
2426 			goto cleanup;
2427 		}
2428 		icount = dx_get_count(entries);
2429 		bh2 = ext4_append(handle, dir, &newblock);
2430 		if (IS_ERR(bh2)) {
2431 			err = PTR_ERR(bh2);
2432 			goto cleanup;
2433 		}
2434 		node2 = (struct dx_node *)(bh2->b_data);
2435 		entries2 = node2->entries;
2436 		memset(&node2->fake, 0, sizeof(struct fake_dirent));
2437 		node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize,
2438 							   sb->s_blocksize);
2439 		BUFFER_TRACE(frame->bh, "get_write_access");
2440 		err = ext4_journal_get_write_access(handle, frame->bh);
2441 		if (err)
2442 			goto journal_error;
2443 		if (!add_level) {
2444 			unsigned icount1 = icount/2, icount2 = icount - icount1;
2445 			unsigned hash2 = dx_get_hash(entries + icount1);
2446 			dxtrace(printk(KERN_DEBUG "Split index %i/%i\n",
2447 				       icount1, icount2));
2448 
2449 			BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */
2450 			err = ext4_journal_get_write_access(handle,
2451 							     (frame - 1)->bh);
2452 			if (err)
2453 				goto journal_error;
2454 
2455 			memcpy((char *) entries2, (char *) (entries + icount1),
2456 			       icount2 * sizeof(struct dx_entry));
2457 			dx_set_count(entries, icount1);
2458 			dx_set_count(entries2, icount2);
2459 			dx_set_limit(entries2, dx_node_limit(dir));
2460 
2461 			/* Which index block gets the new entry? */
2462 			if (at - entries >= icount1) {
2463 				frame->at = at = at - entries - icount1 + entries2;
2464 				frame->entries = entries = entries2;
2465 				swap(frame->bh, bh2);
2466 			}
2467 			dx_insert_block((frame - 1), hash2, newblock);
2468 			dxtrace(dx_show_index("node", frame->entries));
2469 			dxtrace(dx_show_index("node",
2470 			       ((struct dx_node *) bh2->b_data)->entries));
2471 			err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2472 			if (err)
2473 				goto journal_error;
2474 			brelse (bh2);
2475 			err = ext4_handle_dirty_dx_node(handle, dir,
2476 						   (frame - 1)->bh);
2477 			if (err)
2478 				goto journal_error;
2479 			err = ext4_handle_dirty_dx_node(handle, dir,
2480 							frame->bh);
2481 			if (restart || err)
2482 				goto journal_error;
2483 		} else {
2484 			struct dx_root *dxroot;
2485 			memcpy((char *) entries2, (char *) entries,
2486 			       icount * sizeof(struct dx_entry));
2487 			dx_set_limit(entries2, dx_node_limit(dir));
2488 
2489 			/* Set up root */
2490 			dx_set_count(entries, 1);
2491 			dx_set_block(entries + 0, newblock);
2492 			dxroot = (struct dx_root *)frames[0].bh->b_data;
2493 			dxroot->info.indirect_levels += 1;
2494 			dxtrace(printk(KERN_DEBUG
2495 				       "Creating %d level index...\n",
2496 				       dxroot->info.indirect_levels));
2497 			err = ext4_handle_dirty_dx_node(handle, dir, frame->bh);
2498 			if (err)
2499 				goto journal_error;
2500 			err = ext4_handle_dirty_dx_node(handle, dir, bh2);
2501 			brelse(bh2);
2502 			restart = 1;
2503 			goto journal_error;
2504 		}
2505 	}
2506 	de = do_split(handle, dir, &bh, frame, &fname->hinfo);
2507 	if (IS_ERR(de)) {
2508 		err = PTR_ERR(de);
2509 		goto cleanup;
2510 	}
2511 	err = add_dirent_to_buf(handle, fname, dir, inode, de, bh);
2512 	goto cleanup;
2513 
2514 journal_error:
2515 	ext4_std_error(dir->i_sb, err); /* this is a no-op if err == 0 */
2516 cleanup:
2517 	brelse(bh);
2518 	dx_release(frames);
2519 	/* @restart is true means htree-path has been changed, we need to
2520 	 * repeat dx_probe() to find out valid htree-path
2521 	 */
2522 	if (restart && err == 0)
2523 		goto again;
2524 	return err;
2525 }
2526 
2527 /*
2528  * ext4_generic_delete_entry deletes a directory entry by merging it
2529  * with the previous entry
2530  */
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)2531 int ext4_generic_delete_entry(struct inode *dir,
2532 			      struct ext4_dir_entry_2 *de_del,
2533 			      struct buffer_head *bh,
2534 			      void *entry_buf,
2535 			      int buf_size,
2536 			      int csum_size)
2537 {
2538 	struct ext4_dir_entry_2 *de, *pde;
2539 	unsigned int blocksize = dir->i_sb->s_blocksize;
2540 	int i;
2541 
2542 	i = 0;
2543 	pde = NULL;
2544 	de = (struct ext4_dir_entry_2 *)entry_buf;
2545 	while (i < buf_size - csum_size) {
2546 		if (ext4_check_dir_entry(dir, NULL, de, bh,
2547 					 entry_buf, buf_size, i))
2548 			return -EFSCORRUPTED;
2549 		if (de == de_del)  {
2550 			if (pde) {
2551 				pde->rec_len = ext4_rec_len_to_disk(
2552 					ext4_rec_len_from_disk(pde->rec_len,
2553 							       blocksize) +
2554 					ext4_rec_len_from_disk(de->rec_len,
2555 							       blocksize),
2556 					blocksize);
2557 
2558 				/* wipe entire dir_entry */
2559 				memset(de, 0, ext4_rec_len_from_disk(de->rec_len,
2560 								blocksize));
2561 			} else {
2562 				/* wipe dir_entry excluding the rec_len field */
2563 				de->inode = 0;
2564 				memset(&de->name_len, 0,
2565 					ext4_rec_len_from_disk(de->rec_len,
2566 								blocksize) -
2567 					offsetof(struct ext4_dir_entry_2,
2568 								name_len));
2569 			}
2570 
2571 			inode_inc_iversion(dir);
2572 			return 0;
2573 		}
2574 		i += ext4_rec_len_from_disk(de->rec_len, blocksize);
2575 		pde = de;
2576 		de = ext4_next_entry(de, blocksize);
2577 	}
2578 	return -ENOENT;
2579 }
2580 
ext4_delete_entry(handle_t * handle,struct inode * dir,struct ext4_dir_entry_2 * de_del,struct buffer_head * bh)2581 static int ext4_delete_entry(handle_t *handle,
2582 			     struct inode *dir,
2583 			     struct ext4_dir_entry_2 *de_del,
2584 			     struct buffer_head *bh)
2585 {
2586 	int err, csum_size = 0;
2587 
2588 	if (ext4_has_inline_data(dir)) {
2589 		int has_inline_data = 1;
2590 		err = ext4_delete_inline_entry(handle, dir, de_del, bh,
2591 					       &has_inline_data);
2592 		if (has_inline_data)
2593 			return err;
2594 	}
2595 
2596 	if (ext4_has_metadata_csum(dir->i_sb))
2597 		csum_size = sizeof(struct ext4_dir_entry_tail);
2598 
2599 	BUFFER_TRACE(bh, "get_write_access");
2600 	err = ext4_journal_get_write_access(handle, bh);
2601 	if (unlikely(err))
2602 		goto out;
2603 
2604 	err = ext4_generic_delete_entry(dir, de_del, bh, bh->b_data,
2605 					dir->i_sb->s_blocksize, csum_size);
2606 	if (err)
2607 		goto out;
2608 
2609 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
2610 	err = ext4_handle_dirty_dirblock(handle, dir, bh);
2611 	if (unlikely(err))
2612 		goto out;
2613 
2614 	return 0;
2615 out:
2616 	if (err != -ENOENT)
2617 		ext4_std_error(dir->i_sb, err);
2618 	return err;
2619 }
2620 
2621 /*
2622  * Set directory link count to 1 if nlinks > EXT4_LINK_MAX, or if nlinks == 2
2623  * since this indicates that nlinks count was previously 1 to avoid overflowing
2624  * the 16-bit i_links_count field on disk.  Directories with i_nlink == 1 mean
2625  * that subdirectory link counts are not being maintained accurately.
2626  *
2627  * The caller has already checked for i_nlink overflow in case the DIR_LINK
2628  * feature is not enabled and returned -EMLINK.  The is_dx() check is a proxy
2629  * for checking S_ISDIR(inode) (since the INODE_INDEX feature will not be set
2630  * on regular files) and to avoid creating huge/slow non-HTREE directories.
2631  */
ext4_inc_count(struct inode * inode)2632 static void ext4_inc_count(struct inode *inode)
2633 {
2634 	inc_nlink(inode);
2635 	if (is_dx(inode) &&
2636 	    (inode->i_nlink > EXT4_LINK_MAX || inode->i_nlink == 2))
2637 		set_nlink(inode, 1);
2638 }
2639 
2640 /*
2641  * If a directory had nlink == 1, then we should let it be 1. This indicates
2642  * directory has >EXT4_LINK_MAX subdirs.
2643  */
ext4_dec_count(struct inode * inode)2644 static void ext4_dec_count(struct inode *inode)
2645 {
2646 	if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
2647 		drop_nlink(inode);
2648 }
2649 
2650 
2651 /*
2652  * Add non-directory inode to a directory. On success, the inode reference is
2653  * consumed by dentry is instantiation. This is also indicated by clearing of
2654  * *inodep pointer. On failure, the caller is responsible for dropping the
2655  * inode reference in the safe context.
2656  */
ext4_add_nondir(handle_t * handle,struct dentry * dentry,struct inode ** inodep)2657 static int ext4_add_nondir(handle_t *handle,
2658 		struct dentry *dentry, struct inode **inodep)
2659 {
2660 	struct inode *dir = d_inode(dentry->d_parent);
2661 	struct inode *inode = *inodep;
2662 	int err = ext4_add_entry(handle, dentry, inode);
2663 	if (!err) {
2664 		err = ext4_mark_inode_dirty(handle, inode);
2665 		if (IS_DIRSYNC(dir))
2666 			ext4_handle_sync(handle);
2667 		d_instantiate_new(dentry, inode);
2668 		*inodep = NULL;
2669 		return err;
2670 	}
2671 	drop_nlink(inode);
2672 	ext4_orphan_add(handle, inode);
2673 	unlock_new_inode(inode);
2674 	return err;
2675 }
2676 
2677 /*
2678  * By the time this is called, we already have created
2679  * the directory cache entry for the new file, but it
2680  * is so far negative - it has no inode.
2681  *
2682  * If the create succeeds, we fill in the inode information
2683  * with d_instantiate().
2684  */
ext4_create(struct inode * dir,struct dentry * dentry,umode_t mode,bool excl)2685 static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2686 		       bool excl)
2687 {
2688 	handle_t *handle;
2689 	struct inode *inode;
2690 	int err, credits, retries = 0;
2691 
2692 	err = dquot_initialize(dir);
2693 	if (err)
2694 		return err;
2695 
2696 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2697 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2698 retry:
2699 	inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2700 					    NULL, EXT4_HT_DIR, credits);
2701 	handle = ext4_journal_current_handle();
2702 	err = PTR_ERR(inode);
2703 	if (!IS_ERR(inode)) {
2704 		inode->i_op = &ext4_file_inode_operations;
2705 		inode->i_fop = &ext4_file_operations;
2706 		ext4_set_aops(inode);
2707 		err = ext4_add_nondir(handle, dentry, &inode);
2708 		if (!err)
2709 			ext4_fc_track_create(handle, dentry);
2710 	}
2711 	if (handle)
2712 		ext4_journal_stop(handle);
2713 	if (!IS_ERR_OR_NULL(inode))
2714 		iput(inode);
2715 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2716 		goto retry;
2717 	return err;
2718 }
2719 
ext4_mknod(struct inode * dir,struct dentry * dentry,umode_t mode,dev_t rdev)2720 static int ext4_mknod(struct inode *dir, struct dentry *dentry,
2721 		      umode_t mode, dev_t rdev)
2722 {
2723 	handle_t *handle;
2724 	struct inode *inode;
2725 	int err, credits, retries = 0;
2726 
2727 	err = dquot_initialize(dir);
2728 	if (err)
2729 		return err;
2730 
2731 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2732 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2733 retry:
2734 	inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0,
2735 					    NULL, EXT4_HT_DIR, credits);
2736 	handle = ext4_journal_current_handle();
2737 	err = PTR_ERR(inode);
2738 	if (!IS_ERR(inode)) {
2739 		init_special_inode(inode, inode->i_mode, rdev);
2740 		inode->i_op = &ext4_special_inode_operations;
2741 		err = ext4_add_nondir(handle, dentry, &inode);
2742 		if (!err)
2743 			ext4_fc_track_create(handle, dentry);
2744 	}
2745 	if (handle)
2746 		ext4_journal_stop(handle);
2747 	if (!IS_ERR_OR_NULL(inode))
2748 		iput(inode);
2749 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2750 		goto retry;
2751 	return err;
2752 }
2753 
ext4_tmpfile(struct inode * dir,struct dentry * dentry,umode_t mode)2754 static int ext4_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2755 {
2756 	handle_t *handle;
2757 	struct inode *inode;
2758 	int err, retries = 0;
2759 
2760 	err = dquot_initialize(dir);
2761 	if (err)
2762 		return err;
2763 
2764 retry:
2765 	inode = ext4_new_inode_start_handle(dir, mode,
2766 					    NULL, 0, NULL,
2767 					    EXT4_HT_DIR,
2768 			EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
2769 			  4 + EXT4_XATTR_TRANS_BLOCKS);
2770 	handle = ext4_journal_current_handle();
2771 	err = PTR_ERR(inode);
2772 	if (!IS_ERR(inode)) {
2773 		inode->i_op = &ext4_file_inode_operations;
2774 		inode->i_fop = &ext4_file_operations;
2775 		ext4_set_aops(inode);
2776 		d_tmpfile(dentry, inode);
2777 		err = ext4_orphan_add(handle, inode);
2778 		if (err)
2779 			goto err_unlock_inode;
2780 		mark_inode_dirty(inode);
2781 		unlock_new_inode(inode);
2782 	}
2783 	if (handle)
2784 		ext4_journal_stop(handle);
2785 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2786 		goto retry;
2787 	return err;
2788 err_unlock_inode:
2789 	ext4_journal_stop(handle);
2790 	unlock_new_inode(inode);
2791 	return err;
2792 }
2793 
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)2794 struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode,
2795 			  struct ext4_dir_entry_2 *de,
2796 			  int blocksize, int csum_size,
2797 			  unsigned int parent_ino, int dotdot_real_len)
2798 {
2799 	de->inode = cpu_to_le32(inode->i_ino);
2800 	de->name_len = 1;
2801 	de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len),
2802 					   blocksize);
2803 	strcpy(de->name, ".");
2804 	ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2805 
2806 	de = ext4_next_entry(de, blocksize);
2807 	de->inode = cpu_to_le32(parent_ino);
2808 	de->name_len = 2;
2809 	if (!dotdot_real_len)
2810 		de->rec_len = ext4_rec_len_to_disk(blocksize -
2811 					(csum_size + EXT4_DIR_REC_LEN(1)),
2812 					blocksize);
2813 	else
2814 		de->rec_len = ext4_rec_len_to_disk(
2815 				EXT4_DIR_REC_LEN(de->name_len), blocksize);
2816 	strcpy(de->name, "..");
2817 	ext4_set_de_type(inode->i_sb, de, S_IFDIR);
2818 
2819 	return ext4_next_entry(de, blocksize);
2820 }
2821 
ext4_init_new_dir(handle_t * handle,struct inode * dir,struct inode * inode)2822 int ext4_init_new_dir(handle_t *handle, struct inode *dir,
2823 			     struct inode *inode)
2824 {
2825 	struct buffer_head *dir_block = NULL;
2826 	struct ext4_dir_entry_2 *de;
2827 	ext4_lblk_t block = 0;
2828 	unsigned int blocksize = dir->i_sb->s_blocksize;
2829 	int csum_size = 0;
2830 	int err;
2831 
2832 	if (ext4_has_metadata_csum(dir->i_sb))
2833 		csum_size = sizeof(struct ext4_dir_entry_tail);
2834 
2835 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2836 		err = ext4_try_create_inline_dir(handle, dir, inode);
2837 		if (err < 0 && err != -ENOSPC)
2838 			goto out;
2839 		if (!err)
2840 			goto out;
2841 	}
2842 
2843 	inode->i_size = 0;
2844 	dir_block = ext4_append(handle, inode, &block);
2845 	if (IS_ERR(dir_block))
2846 		return PTR_ERR(dir_block);
2847 	de = (struct ext4_dir_entry_2 *)dir_block->b_data;
2848 	ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0);
2849 	set_nlink(inode, 2);
2850 	if (csum_size)
2851 		ext4_initialize_dirent_tail(dir_block, blocksize);
2852 
2853 	BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata");
2854 	err = ext4_handle_dirty_dirblock(handle, inode, dir_block);
2855 	if (err)
2856 		goto out;
2857 	set_buffer_verified(dir_block);
2858 out:
2859 	brelse(dir_block);
2860 	return err;
2861 }
2862 
ext4_mkdir(struct inode * dir,struct dentry * dentry,umode_t mode)2863 static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2864 {
2865 	handle_t *handle;
2866 	struct inode *inode;
2867 	int err, err2 = 0, credits, retries = 0;
2868 
2869 	if (EXT4_DIR_LINK_MAX(dir))
2870 		return -EMLINK;
2871 
2872 	err = dquot_initialize(dir);
2873 	if (err)
2874 		return err;
2875 
2876 	credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
2877 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3);
2878 retry:
2879 	inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode,
2880 					    &dentry->d_name,
2881 					    0, NULL, EXT4_HT_DIR, credits);
2882 	handle = ext4_journal_current_handle();
2883 	err = PTR_ERR(inode);
2884 	if (IS_ERR(inode))
2885 		goto out_stop;
2886 
2887 	inode->i_op = &ext4_dir_inode_operations;
2888 	inode->i_fop = &ext4_dir_operations;
2889 	err = ext4_init_new_dir(handle, dir, inode);
2890 	if (err)
2891 		goto out_clear_inode;
2892 	err = ext4_mark_inode_dirty(handle, inode);
2893 	if (!err)
2894 		err = ext4_add_entry(handle, dentry, inode);
2895 	if (err) {
2896 out_clear_inode:
2897 		clear_nlink(inode);
2898 		ext4_orphan_add(handle, inode);
2899 		unlock_new_inode(inode);
2900 		err2 = ext4_mark_inode_dirty(handle, inode);
2901 		if (unlikely(err2))
2902 			err = err2;
2903 		ext4_journal_stop(handle);
2904 		iput(inode);
2905 		goto out_retry;
2906 	}
2907 	ext4_inc_count(dir);
2908 
2909 	ext4_update_dx_flag(dir);
2910 	err = ext4_mark_inode_dirty(handle, dir);
2911 	if (err)
2912 		goto out_clear_inode;
2913 	d_instantiate_new(dentry, inode);
2914 	ext4_fc_track_create(handle, dentry);
2915 	if (IS_DIRSYNC(dir))
2916 		ext4_handle_sync(handle);
2917 
2918 out_stop:
2919 	if (handle)
2920 		ext4_journal_stop(handle);
2921 out_retry:
2922 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
2923 		goto retry;
2924 	return err;
2925 }
2926 
2927 /*
2928  * routine to check that the specified directory is empty (for rmdir)
2929  */
ext4_empty_dir(struct inode * inode)2930 bool ext4_empty_dir(struct inode *inode)
2931 {
2932 	unsigned int offset;
2933 	struct buffer_head *bh;
2934 	struct ext4_dir_entry_2 *de;
2935 	struct super_block *sb;
2936 
2937 	if (ext4_has_inline_data(inode)) {
2938 		int has_inline_data = 1;
2939 		int ret;
2940 
2941 		ret = empty_inline_dir(inode, &has_inline_data);
2942 		if (has_inline_data)
2943 			return ret;
2944 	}
2945 
2946 	sb = inode->i_sb;
2947 	if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) {
2948 		EXT4_ERROR_INODE(inode, "invalid size");
2949 		return false;
2950 	}
2951 	/* The first directory block must not be a hole,
2952 	 * so treat it as DIRENT_HTREE
2953 	 */
2954 	bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
2955 	if (IS_ERR(bh))
2956 		return false;
2957 
2958 	de = (struct ext4_dir_entry_2 *) bh->b_data;
2959 	if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2960 				 0) ||
2961 	    le32_to_cpu(de->inode) != inode->i_ino || strcmp(".", de->name)) {
2962 		ext4_warning_inode(inode, "directory missing '.'");
2963 		brelse(bh);
2964 		return false;
2965 	}
2966 	offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2967 	de = ext4_next_entry(de, sb->s_blocksize);
2968 	if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size,
2969 				 offset) ||
2970 	    le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
2971 		ext4_warning_inode(inode, "directory missing '..'");
2972 		brelse(bh);
2973 		return false;
2974 	}
2975 	offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2976 	while (offset < inode->i_size) {
2977 		if (!(offset & (sb->s_blocksize - 1))) {
2978 			unsigned int lblock;
2979 			brelse(bh);
2980 			lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb);
2981 			bh = ext4_read_dirblock(inode, lblock, EITHER);
2982 			if (bh == NULL) {
2983 				offset += sb->s_blocksize;
2984 				continue;
2985 			}
2986 			if (IS_ERR(bh))
2987 				return false;
2988 		}
2989 		de = (struct ext4_dir_entry_2 *) (bh->b_data +
2990 					(offset & (sb->s_blocksize - 1)));
2991 		if (ext4_check_dir_entry(inode, NULL, de, bh,
2992 					 bh->b_data, bh->b_size, offset) ||
2993 		    le32_to_cpu(de->inode)) {
2994 			brelse(bh);
2995 			return false;
2996 		}
2997 		offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize);
2998 	}
2999 	brelse(bh);
3000 	return true;
3001 }
3002 
3003 /*
3004  * ext4_orphan_add() links an unlinked or truncated inode into a list of
3005  * such inodes, starting at the superblock, in case we crash before the
3006  * file is closed/deleted, or in case the inode truncate spans multiple
3007  * transactions and the last transaction is not recovered after a crash.
3008  *
3009  * At filesystem recovery time, we walk this list deleting unlinked
3010  * inodes and truncating linked inodes in ext4_orphan_cleanup().
3011  *
3012  * Orphan list manipulation functions must be called under i_mutex unless
3013  * we are just creating the inode or deleting it.
3014  */
ext4_orphan_add(handle_t * handle,struct inode * inode)3015 int ext4_orphan_add(handle_t *handle, struct inode *inode)
3016 {
3017 	struct super_block *sb = inode->i_sb;
3018 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3019 	struct ext4_iloc iloc;
3020 	int err = 0, rc;
3021 	bool dirty = false;
3022 
3023 	if (!sbi->s_journal || is_bad_inode(inode))
3024 		return 0;
3025 
3026 	WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
3027 		     !inode_is_locked(inode));
3028 	/*
3029 	 * Exit early if inode already is on orphan list. This is a big speedup
3030 	 * since we don't have to contend on the global s_orphan_lock.
3031 	 */
3032 	if (!list_empty(&EXT4_I(inode)->i_orphan))
3033 		return 0;
3034 
3035 	/*
3036 	 * Orphan handling is only valid for files with data blocks
3037 	 * being truncated, or files being unlinked. Note that we either
3038 	 * hold i_mutex, or the inode can not be referenced from outside,
3039 	 * so i_nlink should not be bumped due to race
3040 	 */
3041 	J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3042 		  S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
3043 
3044 	BUFFER_TRACE(sbi->s_sbh, "get_write_access");
3045 	err = ext4_journal_get_write_access(handle, sbi->s_sbh);
3046 	if (err)
3047 		goto out;
3048 
3049 	err = ext4_reserve_inode_write(handle, inode, &iloc);
3050 	if (err)
3051 		goto out;
3052 
3053 	mutex_lock(&sbi->s_orphan_lock);
3054 	/*
3055 	 * Due to previous errors inode may be already a part of on-disk
3056 	 * orphan list. If so skip on-disk list modification.
3057 	 */
3058 	if (!NEXT_ORPHAN(inode) || NEXT_ORPHAN(inode) >
3059 	    (le32_to_cpu(sbi->s_es->s_inodes_count))) {
3060 		/* Insert this inode at the head of the on-disk orphan list */
3061 		NEXT_ORPHAN(inode) = le32_to_cpu(sbi->s_es->s_last_orphan);
3062 		lock_buffer(sbi->s_sbh);
3063 		sbi->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
3064 		ext4_superblock_csum_set(sb);
3065 		unlock_buffer(sbi->s_sbh);
3066 		dirty = true;
3067 	}
3068 	list_add(&EXT4_I(inode)->i_orphan, &sbi->s_orphan);
3069 	mutex_unlock(&sbi->s_orphan_lock);
3070 
3071 	if (dirty) {
3072 		err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
3073 		rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
3074 		if (!err)
3075 			err = rc;
3076 		if (err) {
3077 			/*
3078 			 * We have to remove inode from in-memory list if
3079 			 * addition to on disk orphan list failed. Stray orphan
3080 			 * list entries can cause panics at unmount time.
3081 			 */
3082 			mutex_lock(&sbi->s_orphan_lock);
3083 			list_del_init(&EXT4_I(inode)->i_orphan);
3084 			mutex_unlock(&sbi->s_orphan_lock);
3085 		}
3086 	} else
3087 		brelse(iloc.bh);
3088 
3089 	jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
3090 	jbd_debug(4, "orphan inode %lu will point to %d\n",
3091 			inode->i_ino, NEXT_ORPHAN(inode));
3092 out:
3093 	ext4_std_error(sb, err);
3094 	return err;
3095 }
3096 
3097 /*
3098  * ext4_orphan_del() removes an unlinked or truncated inode from the list
3099  * of such inodes stored on disk, because it is finally being cleaned up.
3100  */
ext4_orphan_del(handle_t * handle,struct inode * inode)3101 int ext4_orphan_del(handle_t *handle, struct inode *inode)
3102 {
3103 	struct list_head *prev;
3104 	struct ext4_inode_info *ei = EXT4_I(inode);
3105 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3106 	__u32 ino_next;
3107 	struct ext4_iloc iloc;
3108 	int err = 0;
3109 
3110 	if (!sbi->s_journal && !(sbi->s_mount_state & EXT4_ORPHAN_FS))
3111 		return 0;
3112 
3113 	WARN_ON_ONCE(!(inode->i_state & (I_NEW | I_FREEING)) &&
3114 		     !inode_is_locked(inode));
3115 	/* Do this quick check before taking global s_orphan_lock. */
3116 	if (list_empty(&ei->i_orphan))
3117 		return 0;
3118 
3119 	if (handle) {
3120 		/* Grab inode buffer early before taking global s_orphan_lock */
3121 		err = ext4_reserve_inode_write(handle, inode, &iloc);
3122 	}
3123 
3124 	mutex_lock(&sbi->s_orphan_lock);
3125 	jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
3126 
3127 	prev = ei->i_orphan.prev;
3128 	list_del_init(&ei->i_orphan);
3129 
3130 	/* If we're on an error path, we may not have a valid
3131 	 * transaction handle with which to update the orphan list on
3132 	 * disk, but we still need to remove the inode from the linked
3133 	 * list in memory. */
3134 	if (!handle || err) {
3135 		mutex_unlock(&sbi->s_orphan_lock);
3136 		goto out_err;
3137 	}
3138 
3139 	ino_next = NEXT_ORPHAN(inode);
3140 	if (prev == &sbi->s_orphan) {
3141 		jbd_debug(4, "superblock will point to %u\n", ino_next);
3142 		BUFFER_TRACE(sbi->s_sbh, "get_write_access");
3143 		err = ext4_journal_get_write_access(handle, sbi->s_sbh);
3144 		if (err) {
3145 			mutex_unlock(&sbi->s_orphan_lock);
3146 			goto out_brelse;
3147 		}
3148 		lock_buffer(sbi->s_sbh);
3149 		sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
3150 		ext4_superblock_csum_set(inode->i_sb);
3151 		unlock_buffer(sbi->s_sbh);
3152 		mutex_unlock(&sbi->s_orphan_lock);
3153 		err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
3154 	} else {
3155 		struct ext4_iloc iloc2;
3156 		struct inode *i_prev =
3157 			&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
3158 
3159 		jbd_debug(4, "orphan inode %lu will point to %u\n",
3160 			  i_prev->i_ino, ino_next);
3161 		err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
3162 		if (err) {
3163 			mutex_unlock(&sbi->s_orphan_lock);
3164 			goto out_brelse;
3165 		}
3166 		NEXT_ORPHAN(i_prev) = ino_next;
3167 		err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
3168 		mutex_unlock(&sbi->s_orphan_lock);
3169 	}
3170 	if (err)
3171 		goto out_brelse;
3172 	NEXT_ORPHAN(inode) = 0;
3173 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
3174 out_err:
3175 	ext4_std_error(inode->i_sb, err);
3176 	return err;
3177 
3178 out_brelse:
3179 	brelse(iloc.bh);
3180 	goto out_err;
3181 }
3182 
ext4_rmdir(struct inode * dir,struct dentry * dentry)3183 static int ext4_rmdir(struct inode *dir, struct dentry *dentry)
3184 {
3185 	int retval;
3186 	struct inode *inode;
3187 	struct buffer_head *bh;
3188 	struct ext4_dir_entry_2 *de;
3189 	handle_t *handle = NULL;
3190 
3191 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3192 		return -EIO;
3193 
3194 	/* Initialize quotas before so that eventual writes go in
3195 	 * separate transaction */
3196 	retval = dquot_initialize(dir);
3197 	if (retval)
3198 		return retval;
3199 	retval = dquot_initialize(d_inode(dentry));
3200 	if (retval)
3201 		return retval;
3202 
3203 	retval = -ENOENT;
3204 	bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL);
3205 	if (IS_ERR(bh))
3206 		return PTR_ERR(bh);
3207 	if (!bh)
3208 		goto end_rmdir;
3209 
3210 	inode = d_inode(dentry);
3211 
3212 	retval = -EFSCORRUPTED;
3213 	if (le32_to_cpu(de->inode) != inode->i_ino)
3214 		goto end_rmdir;
3215 
3216 	retval = -ENOTEMPTY;
3217 	if (!ext4_empty_dir(inode))
3218 		goto end_rmdir;
3219 
3220 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3221 				    EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3222 	if (IS_ERR(handle)) {
3223 		retval = PTR_ERR(handle);
3224 		handle = NULL;
3225 		goto end_rmdir;
3226 	}
3227 
3228 	if (IS_DIRSYNC(dir))
3229 		ext4_handle_sync(handle);
3230 
3231 	retval = ext4_delete_entry(handle, dir, de, bh);
3232 	if (retval)
3233 		goto end_rmdir;
3234 	if (!EXT4_DIR_LINK_EMPTY(inode))
3235 		ext4_warning_inode(inode,
3236 			     "empty directory '%.*s' has too many links (%u)",
3237 			     dentry->d_name.len, dentry->d_name.name,
3238 			     inode->i_nlink);
3239 	inode_inc_iversion(inode);
3240 	clear_nlink(inode);
3241 	/* There's no need to set i_disksize: the fact that i_nlink is
3242 	 * zero will ensure that the right thing happens during any
3243 	 * recovery. */
3244 	inode->i_size = 0;
3245 	ext4_orphan_add(handle, inode);
3246 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3247 	retval = ext4_mark_inode_dirty(handle, inode);
3248 	if (retval)
3249 		goto end_rmdir;
3250 	ext4_dec_count(dir);
3251 	ext4_update_dx_flag(dir);
3252 	ext4_fc_track_unlink(handle, dentry);
3253 	retval = ext4_mark_inode_dirty(handle, dir);
3254 
3255 #ifdef CONFIG_UNICODE
3256 	/* VFS negative dentries are incompatible with Encoding and
3257 	 * Case-insensitiveness. Eventually we'll want avoid
3258 	 * invalidating the dentries here, alongside with returning the
3259 	 * negative dentries at ext4_lookup(), when it is better
3260 	 * supported by the VFS for the CI case.
3261 	 */
3262 	if (IS_CASEFOLDED(dir))
3263 		d_invalidate(dentry);
3264 #endif
3265 
3266 end_rmdir:
3267 	brelse(bh);
3268 	if (handle)
3269 		ext4_journal_stop(handle);
3270 	return retval;
3271 }
3272 
__ext4_unlink(struct inode * dir,const struct qstr * d_name,struct inode * inode,struct dentry * dentry)3273 int __ext4_unlink(struct inode *dir, const struct qstr *d_name,
3274 		  struct inode *inode,
3275 		  struct dentry *dentry /* NULL during fast_commit recovery */)
3276 {
3277 	int retval = -ENOENT;
3278 	struct buffer_head *bh;
3279 	struct ext4_dir_entry_2 *de;
3280 	handle_t *handle;
3281 	int skip_remove_dentry = 0;
3282 
3283 	/*
3284 	 * Keep this outside the transaction; it may have to set up the
3285 	 * directory's encryption key, which isn't GFP_NOFS-safe.
3286 	 */
3287 	bh = ext4_find_entry(dir, d_name, &de, NULL);
3288 	if (IS_ERR(bh))
3289 		return PTR_ERR(bh);
3290 
3291 	if (!bh)
3292 		return -ENOENT;
3293 
3294 	if (le32_to_cpu(de->inode) != inode->i_ino) {
3295 		/*
3296 		 * It's okay if we find dont find dentry which matches
3297 		 * the inode. That's because it might have gotten
3298 		 * renamed to a different inode number
3299 		 */
3300 		if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
3301 			skip_remove_dentry = 1;
3302 		else
3303 			goto out_bh;
3304 	}
3305 
3306 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3307 				    EXT4_DATA_TRANS_BLOCKS(dir->i_sb));
3308 	if (IS_ERR(handle)) {
3309 		retval = PTR_ERR(handle);
3310 		goto out_bh;
3311 	}
3312 
3313 	if (IS_DIRSYNC(dir))
3314 		ext4_handle_sync(handle);
3315 
3316 	if (!skip_remove_dentry) {
3317 		retval = ext4_delete_entry(handle, dir, de, bh);
3318 		if (retval)
3319 			goto out_handle;
3320 		dir->i_ctime = dir->i_mtime = current_time(dir);
3321 		ext4_update_dx_flag(dir);
3322 		retval = ext4_mark_inode_dirty(handle, dir);
3323 		if (retval)
3324 			goto out_handle;
3325 	} else {
3326 		retval = 0;
3327 	}
3328 	if (inode->i_nlink == 0)
3329 		ext4_warning_inode(inode, "Deleting file '%.*s' with no links",
3330 				   d_name->len, d_name->name);
3331 	else
3332 		drop_nlink(inode);
3333 	if (!inode->i_nlink)
3334 		ext4_orphan_add(handle, inode);
3335 	inode->i_ctime = current_time(inode);
3336 	retval = ext4_mark_inode_dirty(handle, inode);
3337 	if (dentry && !retval)
3338 		ext4_fc_track_unlink(handle, dentry);
3339 out_handle:
3340 	ext4_journal_stop(handle);
3341 out_bh:
3342 	brelse(bh);
3343 	return retval;
3344 }
3345 
ext4_unlink(struct inode * dir,struct dentry * dentry)3346 static int ext4_unlink(struct inode *dir, struct dentry *dentry)
3347 {
3348 	int retval;
3349 
3350 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3351 		return -EIO;
3352 
3353 	trace_ext4_unlink_enter(dir, dentry);
3354 	/*
3355 	 * Initialize quotas before so that eventual writes go
3356 	 * in separate transaction
3357 	 */
3358 	retval = dquot_initialize(dir);
3359 	if (retval)
3360 		goto out_trace;
3361 	retval = dquot_initialize(d_inode(dentry));
3362 	if (retval)
3363 		goto out_trace;
3364 
3365 	retval = __ext4_unlink(dir, &dentry->d_name, d_inode(dentry), dentry);
3366 #ifdef CONFIG_UNICODE
3367 	/* VFS negative dentries are incompatible with Encoding and
3368 	 * Case-insensitiveness. Eventually we'll want avoid
3369 	 * invalidating the dentries here, alongside with returning the
3370 	 * negative dentries at ext4_lookup(), when it is  better
3371 	 * supported by the VFS for the CI case.
3372 	 */
3373 	if (IS_CASEFOLDED(dir))
3374 		d_invalidate(dentry);
3375 #endif
3376 
3377 out_trace:
3378 	trace_ext4_unlink_exit(dentry, retval);
3379 	return retval;
3380 }
3381 
ext4_symlink(struct inode * dir,struct dentry * dentry,const char * symname)3382 static int ext4_symlink(struct inode *dir,
3383 			struct dentry *dentry, const char *symname)
3384 {
3385 	handle_t *handle;
3386 	struct inode *inode;
3387 	int err, len = strlen(symname);
3388 	int credits;
3389 	struct fscrypt_str disk_link;
3390 
3391 	if (unlikely(ext4_forced_shutdown(EXT4_SB(dir->i_sb))))
3392 		return -EIO;
3393 
3394 	err = fscrypt_prepare_symlink(dir, symname, len, dir->i_sb->s_blocksize,
3395 				      &disk_link);
3396 	if (err)
3397 		return err;
3398 
3399 	err = dquot_initialize(dir);
3400 	if (err)
3401 		return err;
3402 
3403 	if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3404 		/*
3405 		 * For non-fast symlinks, we just allocate inode and put it on
3406 		 * orphan list in the first transaction => we need bitmap,
3407 		 * group descriptor, sb, inode block, quota blocks, and
3408 		 * possibly selinux xattr blocks.
3409 		 */
3410 		credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) +
3411 			  EXT4_XATTR_TRANS_BLOCKS;
3412 	} else {
3413 		/*
3414 		 * Fast symlink. We have to add entry to directory
3415 		 * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS),
3416 		 * allocate new inode (bitmap, group descriptor, inode block,
3417 		 * quota blocks, sb is already counted in previous macros).
3418 		 */
3419 		credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3420 			  EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3;
3421 	}
3422 
3423 	inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO,
3424 					    &dentry->d_name, 0, NULL,
3425 					    EXT4_HT_DIR, credits);
3426 	handle = ext4_journal_current_handle();
3427 	if (IS_ERR(inode)) {
3428 		if (handle)
3429 			ext4_journal_stop(handle);
3430 		return PTR_ERR(inode);
3431 	}
3432 
3433 	if (IS_ENCRYPTED(inode)) {
3434 		err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
3435 		if (err)
3436 			goto err_drop_inode;
3437 		inode->i_op = &ext4_encrypted_symlink_inode_operations;
3438 	}
3439 
3440 	if ((disk_link.len > EXT4_N_BLOCKS * 4)) {
3441 		if (!IS_ENCRYPTED(inode))
3442 			inode->i_op = &ext4_symlink_inode_operations;
3443 		inode_nohighmem(inode);
3444 		ext4_set_aops(inode);
3445 		/*
3446 		 * We cannot call page_symlink() with transaction started
3447 		 * because it calls into ext4_write_begin() which can wait
3448 		 * for transaction commit if we are running out of space
3449 		 * and thus we deadlock. So we have to stop transaction now
3450 		 * and restart it when symlink contents is written.
3451 		 *
3452 		 * To keep fs consistent in case of crash, we have to put inode
3453 		 * to orphan list in the mean time.
3454 		 */
3455 		drop_nlink(inode);
3456 		err = ext4_orphan_add(handle, inode);
3457 		if (handle)
3458 			ext4_journal_stop(handle);
3459 		handle = NULL;
3460 		if (err)
3461 			goto err_drop_inode;
3462 		err = __page_symlink(inode, disk_link.name, disk_link.len, 1);
3463 		if (err)
3464 			goto err_drop_inode;
3465 		/*
3466 		 * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS
3467 		 * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified
3468 		 */
3469 		handle = ext4_journal_start(dir, EXT4_HT_DIR,
3470 				EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3471 				EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1);
3472 		if (IS_ERR(handle)) {
3473 			err = PTR_ERR(handle);
3474 			handle = NULL;
3475 			goto err_drop_inode;
3476 		}
3477 		set_nlink(inode, 1);
3478 		err = ext4_orphan_del(handle, inode);
3479 		if (err)
3480 			goto err_drop_inode;
3481 	} else {
3482 		/* clear the extent format for fast symlink */
3483 		ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS);
3484 		if (!IS_ENCRYPTED(inode)) {
3485 			inode->i_op = &ext4_fast_symlink_inode_operations;
3486 			inode->i_link = (char *)&EXT4_I(inode)->i_data;
3487 		}
3488 		memcpy((char *)&EXT4_I(inode)->i_data, disk_link.name,
3489 		       disk_link.len);
3490 		inode->i_size = disk_link.len - 1;
3491 	}
3492 	EXT4_I(inode)->i_disksize = inode->i_size;
3493 	err = ext4_add_nondir(handle, dentry, &inode);
3494 	if (handle)
3495 		ext4_journal_stop(handle);
3496 	if (inode)
3497 		iput(inode);
3498 	goto out_free_encrypted_link;
3499 
3500 err_drop_inode:
3501 	if (handle)
3502 		ext4_journal_stop(handle);
3503 	clear_nlink(inode);
3504 	unlock_new_inode(inode);
3505 	iput(inode);
3506 out_free_encrypted_link:
3507 	if (disk_link.name != (unsigned char *)symname)
3508 		kfree(disk_link.name);
3509 	return err;
3510 }
3511 
__ext4_link(struct inode * dir,struct inode * inode,struct dentry * dentry)3512 int __ext4_link(struct inode *dir, struct inode *inode, struct dentry *dentry)
3513 {
3514 	handle_t *handle;
3515 	int err, retries = 0;
3516 retry:
3517 	handle = ext4_journal_start(dir, EXT4_HT_DIR,
3518 		(EXT4_DATA_TRANS_BLOCKS(dir->i_sb) +
3519 		 EXT4_INDEX_EXTRA_TRANS_BLOCKS) + 1);
3520 	if (IS_ERR(handle))
3521 		return PTR_ERR(handle);
3522 
3523 	if (IS_DIRSYNC(dir))
3524 		ext4_handle_sync(handle);
3525 
3526 	inode->i_ctime = current_time(inode);
3527 	ext4_inc_count(inode);
3528 	ihold(inode);
3529 
3530 	err = ext4_add_entry(handle, dentry, inode);
3531 	if (!err) {
3532 		err = ext4_mark_inode_dirty(handle, inode);
3533 		/* this can happen only for tmpfile being
3534 		 * linked the first time
3535 		 */
3536 		if (inode->i_nlink == 1)
3537 			ext4_orphan_del(handle, inode);
3538 		d_instantiate(dentry, inode);
3539 		ext4_fc_track_link(handle, dentry);
3540 	} else {
3541 		drop_nlink(inode);
3542 		iput(inode);
3543 	}
3544 	ext4_journal_stop(handle);
3545 	if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries))
3546 		goto retry;
3547 	return err;
3548 }
3549 
ext4_link(struct dentry * old_dentry,struct inode * dir,struct dentry * dentry)3550 static int ext4_link(struct dentry *old_dentry,
3551 		     struct inode *dir, struct dentry *dentry)
3552 {
3553 	struct inode *inode = d_inode(old_dentry);
3554 	int err;
3555 
3556 	if (inode->i_nlink >= EXT4_LINK_MAX)
3557 		return -EMLINK;
3558 
3559 	err = fscrypt_prepare_link(old_dentry, dir, dentry);
3560 	if (err)
3561 		return err;
3562 
3563 	if ((ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT)) &&
3564 	    (!projid_eq(EXT4_I(dir)->i_projid,
3565 			EXT4_I(old_dentry->d_inode)->i_projid)))
3566 		return -EXDEV;
3567 
3568 	err = dquot_initialize(dir);
3569 	if (err)
3570 		return err;
3571 	return __ext4_link(dir, inode, dentry);
3572 }
3573 
3574 /*
3575  * Try to find buffer head where contains the parent block.
3576  * It should be the inode block if it is inlined or the 1st block
3577  * if it is a normal dir.
3578  */
ext4_get_first_dir_block(handle_t * handle,struct inode * inode,int * retval,struct ext4_dir_entry_2 ** parent_de,int * inlined)3579 static struct buffer_head *ext4_get_first_dir_block(handle_t *handle,
3580 					struct inode *inode,
3581 					int *retval,
3582 					struct ext4_dir_entry_2 **parent_de,
3583 					int *inlined)
3584 {
3585 	struct buffer_head *bh;
3586 
3587 	if (!ext4_has_inline_data(inode)) {
3588 		struct ext4_dir_entry_2 *de;
3589 		unsigned int offset;
3590 
3591 		/* The first directory block must not be a hole, so
3592 		 * treat it as DIRENT_HTREE
3593 		 */
3594 		bh = ext4_read_dirblock(inode, 0, DIRENT_HTREE);
3595 		if (IS_ERR(bh)) {
3596 			*retval = PTR_ERR(bh);
3597 			return NULL;
3598 		}
3599 
3600 		de = (struct ext4_dir_entry_2 *) bh->b_data;
3601 		if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3602 					 bh->b_size, 0) ||
3603 		    le32_to_cpu(de->inode) != inode->i_ino ||
3604 		    strcmp(".", de->name)) {
3605 			EXT4_ERROR_INODE(inode, "directory missing '.'");
3606 			brelse(bh);
3607 			*retval = -EFSCORRUPTED;
3608 			return NULL;
3609 		}
3610 		offset = ext4_rec_len_from_disk(de->rec_len,
3611 						inode->i_sb->s_blocksize);
3612 		de = ext4_next_entry(de, inode->i_sb->s_blocksize);
3613 		if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data,
3614 					 bh->b_size, offset) ||
3615 		    le32_to_cpu(de->inode) == 0 || strcmp("..", de->name)) {
3616 			EXT4_ERROR_INODE(inode, "directory missing '..'");
3617 			brelse(bh);
3618 			*retval = -EFSCORRUPTED;
3619 			return NULL;
3620 		}
3621 		*parent_de = de;
3622 
3623 		return bh;
3624 	}
3625 
3626 	*inlined = 1;
3627 	return ext4_get_first_inline_block(inode, parent_de, retval);
3628 }
3629 
3630 struct ext4_renament {
3631 	struct inode *dir;
3632 	struct dentry *dentry;
3633 	struct inode *inode;
3634 	bool is_dir;
3635 	int dir_nlink_delta;
3636 
3637 	/* entry for "dentry" */
3638 	struct buffer_head *bh;
3639 	struct ext4_dir_entry_2 *de;
3640 	int inlined;
3641 
3642 	/* entry for ".." in inode if it's a directory */
3643 	struct buffer_head *dir_bh;
3644 	struct ext4_dir_entry_2 *parent_de;
3645 	int dir_inlined;
3646 };
3647 
ext4_rename_dir_prepare(handle_t * handle,struct ext4_renament * ent)3648 static int ext4_rename_dir_prepare(handle_t *handle, struct ext4_renament *ent)
3649 {
3650 	int retval;
3651 
3652 	ent->dir_bh = ext4_get_first_dir_block(handle, ent->inode,
3653 					      &retval, &ent->parent_de,
3654 					      &ent->dir_inlined);
3655 	if (!ent->dir_bh)
3656 		return retval;
3657 	if (le32_to_cpu(ent->parent_de->inode) != ent->dir->i_ino)
3658 		return -EFSCORRUPTED;
3659 	BUFFER_TRACE(ent->dir_bh, "get_write_access");
3660 	return ext4_journal_get_write_access(handle, ent->dir_bh);
3661 }
3662 
ext4_rename_dir_finish(handle_t * handle,struct ext4_renament * ent,unsigned dir_ino)3663 static int ext4_rename_dir_finish(handle_t *handle, struct ext4_renament *ent,
3664 				  unsigned dir_ino)
3665 {
3666 	int retval;
3667 
3668 	ent->parent_de->inode = cpu_to_le32(dir_ino);
3669 	BUFFER_TRACE(ent->dir_bh, "call ext4_handle_dirty_metadata");
3670 	if (!ent->dir_inlined) {
3671 		if (is_dx(ent->inode)) {
3672 			retval = ext4_handle_dirty_dx_node(handle,
3673 							   ent->inode,
3674 							   ent->dir_bh);
3675 		} else {
3676 			retval = ext4_handle_dirty_dirblock(handle, ent->inode,
3677 							    ent->dir_bh);
3678 		}
3679 	} else {
3680 		retval = ext4_mark_inode_dirty(handle, ent->inode);
3681 	}
3682 	if (retval) {
3683 		ext4_std_error(ent->dir->i_sb, retval);
3684 		return retval;
3685 	}
3686 	return 0;
3687 }
3688 
ext4_setent(handle_t * handle,struct ext4_renament * ent,unsigned ino,unsigned file_type)3689 static int ext4_setent(handle_t *handle, struct ext4_renament *ent,
3690 		       unsigned ino, unsigned file_type)
3691 {
3692 	int retval, retval2;
3693 
3694 	BUFFER_TRACE(ent->bh, "get write access");
3695 	retval = ext4_journal_get_write_access(handle, ent->bh);
3696 	if (retval)
3697 		return retval;
3698 	ent->de->inode = cpu_to_le32(ino);
3699 	if (ext4_has_feature_filetype(ent->dir->i_sb))
3700 		ent->de->file_type = file_type;
3701 	inode_inc_iversion(ent->dir);
3702 	ent->dir->i_ctime = ent->dir->i_mtime =
3703 		current_time(ent->dir);
3704 	retval = ext4_mark_inode_dirty(handle, ent->dir);
3705 	BUFFER_TRACE(ent->bh, "call ext4_handle_dirty_metadata");
3706 	if (!ent->inlined) {
3707 		retval2 = ext4_handle_dirty_dirblock(handle, ent->dir, ent->bh);
3708 		if (unlikely(retval2)) {
3709 			ext4_std_error(ent->dir->i_sb, retval2);
3710 			return retval2;
3711 		}
3712 	}
3713 	return retval;
3714 }
3715 
ext4_resetent(handle_t * handle,struct ext4_renament * ent,unsigned ino,unsigned file_type)3716 static void ext4_resetent(handle_t *handle, struct ext4_renament *ent,
3717 			  unsigned ino, unsigned file_type)
3718 {
3719 	struct ext4_renament old = *ent;
3720 	int retval = 0;
3721 
3722 	/*
3723 	 * old->de could have moved from under us during make indexed dir,
3724 	 * so the old->de may no longer valid and need to find it again
3725 	 * before reset old inode info.
3726 	 */
3727 	old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
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 	old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL);
3893 	if (IS_ERR(old.bh))
3894 		return PTR_ERR(old.bh);
3895 	/*
3896 	 *  Check for inode number is _not_ due to possible IO errors.
3897 	 *  We might rmdir the source, keep it as pwd of some process
3898 	 *  and merrily kill the link to whatever was created under the
3899 	 *  same name. Goodbye sticky bit ;-<
3900 	 */
3901 	retval = -ENOENT;
3902 	if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
3903 		goto release_bh;
3904 
3905 	new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
3906 				 &new.de, &new.inlined);
3907 	if (IS_ERR(new.bh)) {
3908 		retval = PTR_ERR(new.bh);
3909 		new.bh = NULL;
3910 		goto release_bh;
3911 	}
3912 	if (new.bh) {
3913 		if (!new.inode) {
3914 			brelse(new.bh);
3915 			new.bh = NULL;
3916 		}
3917 	}
3918 	if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC))
3919 		ext4_alloc_da_blocks(old.inode);
3920 
3921 	credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
3922 		   EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2);
3923 	if (!(flags & RENAME_WHITEOUT)) {
3924 		handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits);
3925 		if (IS_ERR(handle)) {
3926 			retval = PTR_ERR(handle);
3927 			goto release_bh;
3928 		}
3929 	} else {
3930 		whiteout = ext4_whiteout_for_rename(&old, credits, &handle);
3931 		if (IS_ERR(whiteout)) {
3932 			retval = PTR_ERR(whiteout);
3933 			goto release_bh;
3934 		}
3935 	}
3936 
3937 	old_file_type = old.de->file_type;
3938 	if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
3939 		ext4_handle_sync(handle);
3940 
3941 	if (S_ISDIR(old.inode->i_mode)) {
3942 		if (new.inode) {
3943 			retval = -ENOTEMPTY;
3944 			if (!ext4_empty_dir(new.inode))
3945 				goto end_rename;
3946 		} else {
3947 			retval = -EMLINK;
3948 			if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir))
3949 				goto end_rename;
3950 		}
3951 		retval = ext4_rename_dir_prepare(handle, &old);
3952 		if (retval)
3953 			goto end_rename;
3954 	}
3955 	/*
3956 	 * If we're renaming a file within an inline_data dir and adding or
3957 	 * setting the new dirent causes a conversion from inline_data to
3958 	 * extents/blockmap, we need to force the dirent delete code to
3959 	 * re-read the directory, or else we end up trying to delete a dirent
3960 	 * from what is now the extent tree root (or a block map).
3961 	 */
3962 	force_reread = (new.dir->i_ino == old.dir->i_ino &&
3963 			ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA));
3964 
3965 	if (whiteout) {
3966 		/*
3967 		 * Do this before adding a new entry, so the old entry is sure
3968 		 * to be still pointing to the valid old entry.
3969 		 */
3970 		retval = ext4_setent(handle, &old, whiteout->i_ino,
3971 				     EXT4_FT_CHRDEV);
3972 		if (retval)
3973 			goto end_rename;
3974 		retval = ext4_mark_inode_dirty(handle, whiteout);
3975 		if (unlikely(retval))
3976 			goto end_rename;
3977 
3978 	}
3979 	if (!new.bh) {
3980 		retval = ext4_add_entry(handle, new.dentry, old.inode);
3981 		if (retval)
3982 			goto end_rename;
3983 	} else {
3984 		retval = ext4_setent(handle, &new,
3985 				     old.inode->i_ino, old_file_type);
3986 		if (retval)
3987 			goto end_rename;
3988 	}
3989 	if (force_reread)
3990 		force_reread = !ext4_test_inode_flag(new.dir,
3991 						     EXT4_INODE_INLINE_DATA);
3992 
3993 	/*
3994 	 * Like most other Unix systems, set the ctime for inodes on a
3995 	 * rename.
3996 	 */
3997 	old.inode->i_ctime = current_time(old.inode);
3998 	retval = ext4_mark_inode_dirty(handle, old.inode);
3999 	if (unlikely(retval))
4000 		goto end_rename;
4001 
4002 	if (!whiteout) {
4003 		/*
4004 		 * ok, that's it
4005 		 */
4006 		ext4_rename_delete(handle, &old, force_reread);
4007 	}
4008 
4009 	if (new.inode) {
4010 		ext4_dec_count(new.inode);
4011 		new.inode->i_ctime = current_time(new.inode);
4012 	}
4013 	old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir);
4014 	ext4_update_dx_flag(old.dir);
4015 	if (old.dir_bh) {
4016 		retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
4017 		if (retval)
4018 			goto end_rename;
4019 
4020 		ext4_dec_count(old.dir);
4021 		if (new.inode) {
4022 			/* checked ext4_empty_dir above, can't have another
4023 			 * parent, ext4_dec_count() won't work for many-linked
4024 			 * dirs */
4025 			clear_nlink(new.inode);
4026 		} else {
4027 			ext4_inc_count(new.dir);
4028 			ext4_update_dx_flag(new.dir);
4029 			retval = ext4_mark_inode_dirty(handle, new.dir);
4030 			if (unlikely(retval))
4031 				goto end_rename;
4032 		}
4033 	}
4034 	retval = ext4_mark_inode_dirty(handle, old.dir);
4035 	if (unlikely(retval))
4036 		goto end_rename;
4037 
4038 	if (S_ISDIR(old.inode->i_mode)) {
4039 		/*
4040 		 * We disable fast commits here that's because the
4041 		 * replay code is not yet capable of changing dot dot
4042 		 * dirents in directories.
4043 		 */
4044 		ext4_fc_mark_ineligible(old.inode->i_sb,
4045 			EXT4_FC_REASON_RENAME_DIR);
4046 	} else {
4047 		if (new.inode)
4048 			ext4_fc_track_unlink(handle, new.dentry);
4049 		__ext4_fc_track_link(handle, old.inode, new.dentry);
4050 		__ext4_fc_track_unlink(handle, old.inode, old.dentry);
4051 		if (whiteout)
4052 			__ext4_fc_track_create(handle, whiteout, old.dentry);
4053 	}
4054 
4055 	if (new.inode) {
4056 		retval = ext4_mark_inode_dirty(handle, new.inode);
4057 		if (unlikely(retval))
4058 			goto end_rename;
4059 		if (!new.inode->i_nlink)
4060 			ext4_orphan_add(handle, new.inode);
4061 	}
4062 	retval = 0;
4063 
4064 end_rename:
4065 	if (whiteout) {
4066 		if (retval) {
4067 			ext4_resetent(handle, &old,
4068 				      old.inode->i_ino, old_file_type);
4069 			drop_nlink(whiteout);
4070 			ext4_orphan_add(handle, whiteout);
4071 		}
4072 		unlock_new_inode(whiteout);
4073 		ext4_journal_stop(handle);
4074 		iput(whiteout);
4075 	} else {
4076 		ext4_journal_stop(handle);
4077 	}
4078 release_bh:
4079 	brelse(old.dir_bh);
4080 	brelse(old.bh);
4081 	brelse(new.bh);
4082 	return retval;
4083 }
4084 
ext4_cross_rename(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)4085 static int ext4_cross_rename(struct inode *old_dir, struct dentry *old_dentry,
4086 			     struct inode *new_dir, struct dentry *new_dentry)
4087 {
4088 	handle_t *handle = NULL;
4089 	struct ext4_renament old = {
4090 		.dir = old_dir,
4091 		.dentry = old_dentry,
4092 		.inode = d_inode(old_dentry),
4093 	};
4094 	struct ext4_renament new = {
4095 		.dir = new_dir,
4096 		.dentry = new_dentry,
4097 		.inode = d_inode(new_dentry),
4098 	};
4099 	u8 new_file_type;
4100 	int retval;
4101 	struct timespec64 ctime;
4102 
4103 	if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT) &&
4104 	     !projid_eq(EXT4_I(new_dir)->i_projid,
4105 			EXT4_I(old_dentry->d_inode)->i_projid)) ||
4106 	    (ext4_test_inode_flag(old_dir, EXT4_INODE_PROJINHERIT) &&
4107 	     !projid_eq(EXT4_I(old_dir)->i_projid,
4108 			EXT4_I(new_dentry->d_inode)->i_projid)))
4109 		return -EXDEV;
4110 
4111 	retval = dquot_initialize(old.dir);
4112 	if (retval)
4113 		return retval;
4114 	retval = dquot_initialize(new.dir);
4115 	if (retval)
4116 		return retval;
4117 
4118 	old.bh = ext4_find_entry(old.dir, &old.dentry->d_name,
4119 				 &old.de, &old.inlined);
4120 	if (IS_ERR(old.bh))
4121 		return PTR_ERR(old.bh);
4122 	/*
4123 	 *  Check for inode number is _not_ due to possible IO errors.
4124 	 *  We might rmdir the source, keep it as pwd of some process
4125 	 *  and merrily kill the link to whatever was created under the
4126 	 *  same name. Goodbye sticky bit ;-<
4127 	 */
4128 	retval = -ENOENT;
4129 	if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino)
4130 		goto end_rename;
4131 
4132 	new.bh = ext4_find_entry(new.dir, &new.dentry->d_name,
4133 				 &new.de, &new.inlined);
4134 	if (IS_ERR(new.bh)) {
4135 		retval = PTR_ERR(new.bh);
4136 		new.bh = NULL;
4137 		goto end_rename;
4138 	}
4139 
4140 	/* RENAME_EXCHANGE case: old *and* new must both exist */
4141 	if (!new.bh || le32_to_cpu(new.de->inode) != new.inode->i_ino)
4142 		goto end_rename;
4143 
4144 	handle = ext4_journal_start(old.dir, EXT4_HT_DIR,
4145 		(2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) +
4146 		 2 * EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2));
4147 	if (IS_ERR(handle)) {
4148 		retval = PTR_ERR(handle);
4149 		handle = NULL;
4150 		goto end_rename;
4151 	}
4152 
4153 	if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir))
4154 		ext4_handle_sync(handle);
4155 
4156 	if (S_ISDIR(old.inode->i_mode)) {
4157 		old.is_dir = true;
4158 		retval = ext4_rename_dir_prepare(handle, &old);
4159 		if (retval)
4160 			goto end_rename;
4161 	}
4162 	if (S_ISDIR(new.inode->i_mode)) {
4163 		new.is_dir = true;
4164 		retval = ext4_rename_dir_prepare(handle, &new);
4165 		if (retval)
4166 			goto end_rename;
4167 	}
4168 
4169 	/*
4170 	 * Other than the special case of overwriting a directory, parents'
4171 	 * nlink only needs to be modified if this is a cross directory rename.
4172 	 */
4173 	if (old.dir != new.dir && old.is_dir != new.is_dir) {
4174 		old.dir_nlink_delta = old.is_dir ? -1 : 1;
4175 		new.dir_nlink_delta = -old.dir_nlink_delta;
4176 		retval = -EMLINK;
4177 		if ((old.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(old.dir)) ||
4178 		    (new.dir_nlink_delta > 0 && EXT4_DIR_LINK_MAX(new.dir)))
4179 			goto end_rename;
4180 	}
4181 
4182 	new_file_type = new.de->file_type;
4183 	retval = ext4_setent(handle, &new, old.inode->i_ino, old.de->file_type);
4184 	if (retval)
4185 		goto end_rename;
4186 
4187 	retval = ext4_setent(handle, &old, new.inode->i_ino, new_file_type);
4188 	if (retval)
4189 		goto end_rename;
4190 
4191 	/*
4192 	 * Like most other Unix systems, set the ctime for inodes on a
4193 	 * rename.
4194 	 */
4195 	ctime = current_time(old.inode);
4196 	old.inode->i_ctime = ctime;
4197 	new.inode->i_ctime = ctime;
4198 	retval = ext4_mark_inode_dirty(handle, old.inode);
4199 	if (unlikely(retval))
4200 		goto end_rename;
4201 	retval = ext4_mark_inode_dirty(handle, new.inode);
4202 	if (unlikely(retval))
4203 		goto end_rename;
4204 	ext4_fc_mark_ineligible(new.inode->i_sb,
4205 				EXT4_FC_REASON_CROSS_RENAME);
4206 	if (old.dir_bh) {
4207 		retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino);
4208 		if (retval)
4209 			goto end_rename;
4210 	}
4211 	if (new.dir_bh) {
4212 		retval = ext4_rename_dir_finish(handle, &new, old.dir->i_ino);
4213 		if (retval)
4214 			goto end_rename;
4215 	}
4216 	ext4_update_dir_count(handle, &old);
4217 	ext4_update_dir_count(handle, &new);
4218 	retval = 0;
4219 
4220 end_rename:
4221 	brelse(old.dir_bh);
4222 	brelse(new.dir_bh);
4223 	brelse(old.bh);
4224 	brelse(new.bh);
4225 	if (handle)
4226 		ext4_journal_stop(handle);
4227 	return retval;
4228 }
4229 
ext4_rename2(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry,unsigned int flags)4230 static int ext4_rename2(struct inode *old_dir, struct dentry *old_dentry,
4231 			struct inode *new_dir, struct dentry *new_dentry,
4232 			unsigned int flags)
4233 {
4234 	int err;
4235 
4236 	if (unlikely(ext4_forced_shutdown(EXT4_SB(old_dir->i_sb))))
4237 		return -EIO;
4238 
4239 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4240 		return -EINVAL;
4241 
4242 	err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
4243 				     flags);
4244 	if (err)
4245 		return err;
4246 
4247 	if (flags & RENAME_EXCHANGE) {
4248 		return ext4_cross_rename(old_dir, old_dentry,
4249 					 new_dir, new_dentry);
4250 	}
4251 
4252 	return ext4_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
4253 }
4254 
4255 /*
4256  * directories can handle most operations...
4257  */
4258 const struct inode_operations ext4_dir_inode_operations = {
4259 	.create		= ext4_create,
4260 	.lookup		= ext4_lookup,
4261 	.link		= ext4_link,
4262 	.unlink		= ext4_unlink,
4263 	.symlink	= ext4_symlink,
4264 	.mkdir		= ext4_mkdir,
4265 	.rmdir		= ext4_rmdir,
4266 	.mknod		= ext4_mknod,
4267 	.tmpfile	= ext4_tmpfile,
4268 	.rename		= ext4_rename2,
4269 	.setattr	= ext4_setattr,
4270 	.getattr	= ext4_getattr,
4271 	.listxattr	= ext4_listxattr,
4272 	.get_acl	= ext4_get_acl,
4273 	.set_acl	= ext4_set_acl,
4274 	.fiemap         = ext4_fiemap,
4275 };
4276 
4277 const struct inode_operations ext4_special_inode_operations = {
4278 	.setattr	= ext4_setattr,
4279 	.getattr	= ext4_getattr,
4280 	.listxattr	= ext4_listxattr,
4281 	.get_acl	= ext4_get_acl,
4282 	.set_acl	= ext4_set_acl,
4283 };
4284