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