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