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