xref: /openbmc/linux/fs/f2fs/dir.c (revision 15e3ae36)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/dir.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/f2fs_fs.h>
10 #include <linux/sched/signal.h>
11 #include <linux/unicode.h>
12 #include "f2fs.h"
13 #include "node.h"
14 #include "acl.h"
15 #include "xattr.h"
16 #include <trace/events/f2fs.h>
17 
18 static unsigned long dir_blocks(struct inode *inode)
19 {
20 	return ((unsigned long long) (i_size_read(inode) + PAGE_SIZE - 1))
21 							>> PAGE_SHIFT;
22 }
23 
24 static unsigned int dir_buckets(unsigned int level, int dir_level)
25 {
26 	if (level + dir_level < MAX_DIR_HASH_DEPTH / 2)
27 		return 1 << (level + dir_level);
28 	else
29 		return MAX_DIR_BUCKETS;
30 }
31 
32 static unsigned int bucket_blocks(unsigned int level)
33 {
34 	if (level < MAX_DIR_HASH_DEPTH / 2)
35 		return 2;
36 	else
37 		return 4;
38 }
39 
40 static unsigned char f2fs_filetype_table[F2FS_FT_MAX] = {
41 	[F2FS_FT_UNKNOWN]	= DT_UNKNOWN,
42 	[F2FS_FT_REG_FILE]	= DT_REG,
43 	[F2FS_FT_DIR]		= DT_DIR,
44 	[F2FS_FT_CHRDEV]	= DT_CHR,
45 	[F2FS_FT_BLKDEV]	= DT_BLK,
46 	[F2FS_FT_FIFO]		= DT_FIFO,
47 	[F2FS_FT_SOCK]		= DT_SOCK,
48 	[F2FS_FT_SYMLINK]	= DT_LNK,
49 };
50 
51 static unsigned char f2fs_type_by_mode[S_IFMT >> S_SHIFT] = {
52 	[S_IFREG >> S_SHIFT]	= F2FS_FT_REG_FILE,
53 	[S_IFDIR >> S_SHIFT]	= F2FS_FT_DIR,
54 	[S_IFCHR >> S_SHIFT]	= F2FS_FT_CHRDEV,
55 	[S_IFBLK >> S_SHIFT]	= F2FS_FT_BLKDEV,
56 	[S_IFIFO >> S_SHIFT]	= F2FS_FT_FIFO,
57 	[S_IFSOCK >> S_SHIFT]	= F2FS_FT_SOCK,
58 	[S_IFLNK >> S_SHIFT]	= F2FS_FT_SYMLINK,
59 };
60 
61 static void set_de_type(struct f2fs_dir_entry *de, umode_t mode)
62 {
63 	de->file_type = f2fs_type_by_mode[(mode & S_IFMT) >> S_SHIFT];
64 }
65 
66 unsigned char f2fs_get_de_type(struct f2fs_dir_entry *de)
67 {
68 	if (de->file_type < F2FS_FT_MAX)
69 		return f2fs_filetype_table[de->file_type];
70 	return DT_UNKNOWN;
71 }
72 
73 static unsigned long dir_block_index(unsigned int level,
74 				int dir_level, unsigned int idx)
75 {
76 	unsigned long i;
77 	unsigned long bidx = 0;
78 
79 	for (i = 0; i < level; i++)
80 		bidx += dir_buckets(i, dir_level) * bucket_blocks(i);
81 	bidx += idx * bucket_blocks(level);
82 	return bidx;
83 }
84 
85 static struct f2fs_dir_entry *find_in_block(struct inode *dir,
86 				struct page *dentry_page,
87 				struct fscrypt_name *fname,
88 				f2fs_hash_t namehash,
89 				int *max_slots,
90 				struct page **res_page)
91 {
92 	struct f2fs_dentry_block *dentry_blk;
93 	struct f2fs_dir_entry *de;
94 	struct f2fs_dentry_ptr d;
95 
96 	dentry_blk = (struct f2fs_dentry_block *)page_address(dentry_page);
97 
98 	make_dentry_ptr_block(dir, &d, dentry_blk);
99 	de = f2fs_find_target_dentry(fname, namehash, max_slots, &d);
100 	if (de)
101 		*res_page = dentry_page;
102 
103 	return de;
104 }
105 
106 #ifdef CONFIG_UNICODE
107 /*
108  * Test whether a case-insensitive directory entry matches the filename
109  * being searched for.
110  *
111  * Returns: 0 if the directory entry matches, more than 0 if it
112  * doesn't match or less than zero on error.
113  */
114 int f2fs_ci_compare(const struct inode *parent, const struct qstr *name,
115 				const struct qstr *entry, bool quick)
116 {
117 	const struct f2fs_sb_info *sbi = F2FS_SB(parent->i_sb);
118 	const struct unicode_map *um = sbi->s_encoding;
119 	int ret;
120 
121 	if (quick)
122 		ret = utf8_strncasecmp_folded(um, name, entry);
123 	else
124 		ret = utf8_strncasecmp(um, name, entry);
125 
126 	if (ret < 0) {
127 		/* Handle invalid character sequence as either an error
128 		 * or as an opaque byte sequence.
129 		 */
130 		if (f2fs_has_strict_mode(sbi))
131 			return -EINVAL;
132 
133 		if (name->len != entry->len)
134 			return 1;
135 
136 		return !!memcmp(name->name, entry->name, name->len);
137 	}
138 
139 	return ret;
140 }
141 
142 static void f2fs_fname_setup_ci_filename(struct inode *dir,
143 					const struct qstr *iname,
144 					struct fscrypt_str *cf_name)
145 {
146 	struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
147 
148 	if (!IS_CASEFOLDED(dir)) {
149 		cf_name->name = NULL;
150 		return;
151 	}
152 
153 	cf_name->name = f2fs_kmalloc(sbi, F2FS_NAME_LEN, GFP_NOFS);
154 	if (!cf_name->name)
155 		return;
156 
157 	cf_name->len = utf8_casefold(sbi->s_encoding,
158 					iname, cf_name->name,
159 					F2FS_NAME_LEN);
160 	if ((int)cf_name->len <= 0) {
161 		kvfree(cf_name->name);
162 		cf_name->name = NULL;
163 	}
164 }
165 #endif
166 
167 static inline bool f2fs_match_name(struct f2fs_dentry_ptr *d,
168 					struct f2fs_dir_entry *de,
169 					struct fscrypt_name *fname,
170 					struct fscrypt_str *cf_str,
171 					unsigned long bit_pos,
172 					f2fs_hash_t namehash)
173 {
174 #ifdef CONFIG_UNICODE
175 	struct inode *parent = d->inode;
176 	struct f2fs_sb_info *sbi = F2FS_I_SB(parent);
177 	struct qstr entry;
178 #endif
179 
180 	if (de->hash_code != namehash)
181 		return false;
182 
183 #ifdef CONFIG_UNICODE
184 	entry.name = d->filename[bit_pos];
185 	entry.len = de->name_len;
186 
187 	if (sbi->s_encoding && IS_CASEFOLDED(parent)) {
188 		if (cf_str->name) {
189 			struct qstr cf = {.name = cf_str->name,
190 					  .len = cf_str->len};
191 			return !f2fs_ci_compare(parent, &cf, &entry, true);
192 		}
193 		return !f2fs_ci_compare(parent, fname->usr_fname, &entry,
194 					false);
195 	}
196 #endif
197 	if (fscrypt_match_name(fname, d->filename[bit_pos],
198 				le16_to_cpu(de->name_len)))
199 		return true;
200 	return false;
201 }
202 
203 struct f2fs_dir_entry *f2fs_find_target_dentry(struct fscrypt_name *fname,
204 			f2fs_hash_t namehash, int *max_slots,
205 			struct f2fs_dentry_ptr *d)
206 {
207 	struct f2fs_dir_entry *de;
208 	struct fscrypt_str cf_str = { .name = NULL, .len = 0 };
209 	unsigned long bit_pos = 0;
210 	int max_len = 0;
211 
212 #ifdef CONFIG_UNICODE
213 	f2fs_fname_setup_ci_filename(d->inode, fname->usr_fname, &cf_str);
214 #endif
215 
216 	if (max_slots)
217 		*max_slots = 0;
218 	while (bit_pos < d->max) {
219 		if (!test_bit_le(bit_pos, d->bitmap)) {
220 			bit_pos++;
221 			max_len++;
222 			continue;
223 		}
224 
225 		de = &d->dentry[bit_pos];
226 
227 		if (unlikely(!de->name_len)) {
228 			bit_pos++;
229 			continue;
230 		}
231 
232 		if (f2fs_match_name(d, de, fname, &cf_str, bit_pos, namehash))
233 			goto found;
234 
235 		if (max_slots && max_len > *max_slots)
236 			*max_slots = max_len;
237 		max_len = 0;
238 
239 		bit_pos += GET_DENTRY_SLOTS(le16_to_cpu(de->name_len));
240 	}
241 
242 	de = NULL;
243 found:
244 	if (max_slots && max_len > *max_slots)
245 		*max_slots = max_len;
246 
247 #ifdef CONFIG_UNICODE
248 	kvfree(cf_str.name);
249 #endif
250 	return de;
251 }
252 
253 static struct f2fs_dir_entry *find_in_level(struct inode *dir,
254 					unsigned int level,
255 					struct fscrypt_name *fname,
256 					struct page **res_page)
257 {
258 	struct qstr name = FSTR_TO_QSTR(&fname->disk_name);
259 	int s = GET_DENTRY_SLOTS(name.len);
260 	unsigned int nbucket, nblock;
261 	unsigned int bidx, end_block;
262 	struct page *dentry_page;
263 	struct f2fs_dir_entry *de = NULL;
264 	bool room = false;
265 	int max_slots;
266 	f2fs_hash_t namehash = f2fs_dentry_hash(dir, &name, fname);
267 
268 	nbucket = dir_buckets(level, F2FS_I(dir)->i_dir_level);
269 	nblock = bucket_blocks(level);
270 
271 	bidx = dir_block_index(level, F2FS_I(dir)->i_dir_level,
272 					le32_to_cpu(namehash) % nbucket);
273 	end_block = bidx + nblock;
274 
275 	for (; bidx < end_block; bidx++) {
276 		/* no need to allocate new dentry pages to all the indices */
277 		dentry_page = f2fs_find_data_page(dir, bidx);
278 		if (IS_ERR(dentry_page)) {
279 			if (PTR_ERR(dentry_page) == -ENOENT) {
280 				room = true;
281 				continue;
282 			} else {
283 				*res_page = dentry_page;
284 				break;
285 			}
286 		}
287 
288 		de = find_in_block(dir, dentry_page, fname, namehash,
289 							&max_slots, res_page);
290 		if (de)
291 			break;
292 
293 		if (max_slots >= s)
294 			room = true;
295 		f2fs_put_page(dentry_page, 0);
296 	}
297 
298 	if (!de && room && F2FS_I(dir)->chash != namehash) {
299 		F2FS_I(dir)->chash = namehash;
300 		F2FS_I(dir)->clevel = level;
301 	}
302 
303 	return de;
304 }
305 
306 struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir,
307 			struct fscrypt_name *fname, struct page **res_page)
308 {
309 	unsigned long npages = dir_blocks(dir);
310 	struct f2fs_dir_entry *de = NULL;
311 	unsigned int max_depth;
312 	unsigned int level;
313 
314 	if (f2fs_has_inline_dentry(dir)) {
315 		*res_page = NULL;
316 		de = f2fs_find_in_inline_dir(dir, fname, res_page);
317 		goto out;
318 	}
319 
320 	if (npages == 0) {
321 		*res_page = NULL;
322 		goto out;
323 	}
324 
325 	max_depth = F2FS_I(dir)->i_current_depth;
326 	if (unlikely(max_depth > MAX_DIR_HASH_DEPTH)) {
327 		f2fs_warn(F2FS_I_SB(dir), "Corrupted max_depth of %lu: %u",
328 			  dir->i_ino, max_depth);
329 		max_depth = MAX_DIR_HASH_DEPTH;
330 		f2fs_i_depth_write(dir, max_depth);
331 	}
332 
333 	for (level = 0; level < max_depth; level++) {
334 		*res_page = NULL;
335 		de = find_in_level(dir, level, fname, res_page);
336 		if (de || IS_ERR(*res_page))
337 			break;
338 	}
339 out:
340 	/* This is to increase the speed of f2fs_create */
341 	if (!de)
342 		F2FS_I(dir)->task = current;
343 	return de;
344 }
345 
346 /*
347  * Find an entry in the specified directory with the wanted name.
348  * It returns the page where the entry was found (as a parameter - res_page),
349  * and the entry itself. Page is returned mapped and unlocked.
350  * Entry is guaranteed to be valid.
351  */
352 struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir,
353 			const struct qstr *child, struct page **res_page)
354 {
355 	struct f2fs_dir_entry *de = NULL;
356 	struct fscrypt_name fname;
357 	int err;
358 
359 #ifdef CONFIG_UNICODE
360 	if (f2fs_has_strict_mode(F2FS_I_SB(dir)) && IS_CASEFOLDED(dir) &&
361 			utf8_validate(F2FS_I_SB(dir)->s_encoding, child)) {
362 		*res_page = ERR_PTR(-EINVAL);
363 		return NULL;
364 	}
365 #endif
366 
367 	err = fscrypt_setup_filename(dir, child, 1, &fname);
368 	if (err) {
369 		if (err == -ENOENT)
370 			*res_page = NULL;
371 		else
372 			*res_page = ERR_PTR(err);
373 		return NULL;
374 	}
375 
376 	de = __f2fs_find_entry(dir, &fname, res_page);
377 
378 	fscrypt_free_filename(&fname);
379 	return de;
380 }
381 
382 struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p)
383 {
384 	struct qstr dotdot = QSTR_INIT("..", 2);
385 
386 	return f2fs_find_entry(dir, &dotdot, p);
387 }
388 
389 ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr,
390 							struct page **page)
391 {
392 	ino_t res = 0;
393 	struct f2fs_dir_entry *de;
394 
395 	de = f2fs_find_entry(dir, qstr, page);
396 	if (de) {
397 		res = le32_to_cpu(de->ino);
398 		f2fs_put_page(*page, 0);
399 	}
400 
401 	return res;
402 }
403 
404 void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de,
405 		struct page *page, struct inode *inode)
406 {
407 	enum page_type type = f2fs_has_inline_dentry(dir) ? NODE : DATA;
408 	lock_page(page);
409 	f2fs_wait_on_page_writeback(page, type, true, true);
410 	de->ino = cpu_to_le32(inode->i_ino);
411 	set_de_type(de, inode->i_mode);
412 	set_page_dirty(page);
413 
414 	dir->i_mtime = dir->i_ctime = current_time(dir);
415 	f2fs_mark_inode_dirty_sync(dir, false);
416 	f2fs_put_page(page, 1);
417 }
418 
419 static void init_dent_inode(const struct qstr *name, struct page *ipage)
420 {
421 	struct f2fs_inode *ri;
422 
423 	f2fs_wait_on_page_writeback(ipage, NODE, true, true);
424 
425 	/* copy name info. to this inode page */
426 	ri = F2FS_INODE(ipage);
427 	ri->i_namelen = cpu_to_le32(name->len);
428 	memcpy(ri->i_name, name->name, name->len);
429 	set_page_dirty(ipage);
430 }
431 
432 void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent,
433 					struct f2fs_dentry_ptr *d)
434 {
435 	struct qstr dot = QSTR_INIT(".", 1);
436 	struct qstr dotdot = QSTR_INIT("..", 2);
437 
438 	/* update dirent of "." */
439 	f2fs_update_dentry(inode->i_ino, inode->i_mode, d, &dot, 0, 0);
440 
441 	/* update dirent of ".." */
442 	f2fs_update_dentry(parent->i_ino, parent->i_mode, d, &dotdot, 0, 1);
443 }
444 
445 static int make_empty_dir(struct inode *inode,
446 		struct inode *parent, struct page *page)
447 {
448 	struct page *dentry_page;
449 	struct f2fs_dentry_block *dentry_blk;
450 	struct f2fs_dentry_ptr d;
451 
452 	if (f2fs_has_inline_dentry(inode))
453 		return f2fs_make_empty_inline_dir(inode, parent, page);
454 
455 	dentry_page = f2fs_get_new_data_page(inode, page, 0, true);
456 	if (IS_ERR(dentry_page))
457 		return PTR_ERR(dentry_page);
458 
459 	dentry_blk = page_address(dentry_page);
460 
461 	make_dentry_ptr_block(NULL, &d, dentry_blk);
462 	f2fs_do_make_empty_dir(inode, parent, &d);
463 
464 	set_page_dirty(dentry_page);
465 	f2fs_put_page(dentry_page, 1);
466 	return 0;
467 }
468 
469 struct page *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir,
470 			const struct qstr *new_name, const struct qstr *orig_name,
471 			struct page *dpage)
472 {
473 	struct page *page;
474 	int err;
475 
476 	if (is_inode_flag_set(inode, FI_NEW_INODE)) {
477 		page = f2fs_new_inode_page(inode);
478 		if (IS_ERR(page))
479 			return page;
480 
481 		if (S_ISDIR(inode->i_mode)) {
482 			/* in order to handle error case */
483 			get_page(page);
484 			err = make_empty_dir(inode, dir, page);
485 			if (err) {
486 				lock_page(page);
487 				goto put_error;
488 			}
489 			put_page(page);
490 		}
491 
492 		err = f2fs_init_acl(inode, dir, page, dpage);
493 		if (err)
494 			goto put_error;
495 
496 		err = f2fs_init_security(inode, dir, orig_name, page);
497 		if (err)
498 			goto put_error;
499 
500 		if (IS_ENCRYPTED(inode)) {
501 			err = fscrypt_inherit_context(dir, inode, page, false);
502 			if (err)
503 				goto put_error;
504 		}
505 	} else {
506 		page = f2fs_get_node_page(F2FS_I_SB(dir), inode->i_ino);
507 		if (IS_ERR(page))
508 			return page;
509 	}
510 
511 	if (new_name) {
512 		init_dent_inode(new_name, page);
513 		if (IS_ENCRYPTED(dir))
514 			file_set_enc_name(inode);
515 	}
516 
517 	/*
518 	 * This file should be checkpointed during fsync.
519 	 * We lost i_pino from now on.
520 	 */
521 	if (is_inode_flag_set(inode, FI_INC_LINK)) {
522 		if (!S_ISDIR(inode->i_mode))
523 			file_lost_pino(inode);
524 		/*
525 		 * If link the tmpfile to alias through linkat path,
526 		 * we should remove this inode from orphan list.
527 		 */
528 		if (inode->i_nlink == 0)
529 			f2fs_remove_orphan_inode(F2FS_I_SB(dir), inode->i_ino);
530 		f2fs_i_links_write(inode, true);
531 	}
532 	return page;
533 
534 put_error:
535 	clear_nlink(inode);
536 	f2fs_update_inode(inode, page);
537 	f2fs_put_page(page, 1);
538 	return ERR_PTR(err);
539 }
540 
541 void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode,
542 						unsigned int current_depth)
543 {
544 	if (inode && is_inode_flag_set(inode, FI_NEW_INODE)) {
545 		if (S_ISDIR(inode->i_mode))
546 			f2fs_i_links_write(dir, true);
547 		clear_inode_flag(inode, FI_NEW_INODE);
548 	}
549 	dir->i_mtime = dir->i_ctime = current_time(dir);
550 	f2fs_mark_inode_dirty_sync(dir, false);
551 
552 	if (F2FS_I(dir)->i_current_depth != current_depth)
553 		f2fs_i_depth_write(dir, current_depth);
554 
555 	if (inode && is_inode_flag_set(inode, FI_INC_LINK))
556 		clear_inode_flag(inode, FI_INC_LINK);
557 }
558 
559 int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots)
560 {
561 	int bit_start = 0;
562 	int zero_start, zero_end;
563 next:
564 	zero_start = find_next_zero_bit_le(bitmap, max_slots, bit_start);
565 	if (zero_start >= max_slots)
566 		return max_slots;
567 
568 	zero_end = find_next_bit_le(bitmap, max_slots, zero_start);
569 	if (zero_end - zero_start >= slots)
570 		return zero_start;
571 
572 	bit_start = zero_end + 1;
573 
574 	if (zero_end + 1 >= max_slots)
575 		return max_slots;
576 	goto next;
577 }
578 
579 bool f2fs_has_enough_room(struct inode *dir, struct page *ipage,
580 					struct fscrypt_name *fname)
581 {
582 	struct f2fs_dentry_ptr d;
583 	unsigned int bit_pos;
584 	int slots = GET_DENTRY_SLOTS(fname_len(fname));
585 
586 	make_dentry_ptr_inline(dir, &d, inline_data_addr(dir, ipage));
587 
588 	bit_pos = f2fs_room_for_filename(d.bitmap, slots, d.max);
589 
590 	return bit_pos < d.max;
591 }
592 
593 void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d,
594 				const struct qstr *name, f2fs_hash_t name_hash,
595 				unsigned int bit_pos)
596 {
597 	struct f2fs_dir_entry *de;
598 	int slots = GET_DENTRY_SLOTS(name->len);
599 	int i;
600 
601 	de = &d->dentry[bit_pos];
602 	de->hash_code = name_hash;
603 	de->name_len = cpu_to_le16(name->len);
604 	memcpy(d->filename[bit_pos], name->name, name->len);
605 	de->ino = cpu_to_le32(ino);
606 	set_de_type(de, mode);
607 	for (i = 0; i < slots; i++) {
608 		__set_bit_le(bit_pos + i, (void *)d->bitmap);
609 		/* avoid wrong garbage data for readdir */
610 		if (i)
611 			(de + i)->name_len = 0;
612 	}
613 }
614 
615 int f2fs_add_regular_entry(struct inode *dir, const struct qstr *new_name,
616 				const struct qstr *orig_name,
617 				struct inode *inode, nid_t ino, umode_t mode)
618 {
619 	unsigned int bit_pos;
620 	unsigned int level;
621 	unsigned int current_depth;
622 	unsigned long bidx, block;
623 	f2fs_hash_t dentry_hash;
624 	unsigned int nbucket, nblock;
625 	struct page *dentry_page = NULL;
626 	struct f2fs_dentry_block *dentry_blk = NULL;
627 	struct f2fs_dentry_ptr d;
628 	struct page *page = NULL;
629 	int slots, err = 0;
630 
631 	level = 0;
632 	slots = GET_DENTRY_SLOTS(new_name->len);
633 	dentry_hash = f2fs_dentry_hash(dir, new_name, NULL);
634 
635 	current_depth = F2FS_I(dir)->i_current_depth;
636 	if (F2FS_I(dir)->chash == dentry_hash) {
637 		level = F2FS_I(dir)->clevel;
638 		F2FS_I(dir)->chash = 0;
639 	}
640 
641 start:
642 	if (time_to_inject(F2FS_I_SB(dir), FAULT_DIR_DEPTH)) {
643 		f2fs_show_injection_info(F2FS_I_SB(dir), FAULT_DIR_DEPTH);
644 		return -ENOSPC;
645 	}
646 
647 	if (unlikely(current_depth == MAX_DIR_HASH_DEPTH))
648 		return -ENOSPC;
649 
650 	/* Increase the depth, if required */
651 	if (level == current_depth)
652 		++current_depth;
653 
654 	nbucket = dir_buckets(level, F2FS_I(dir)->i_dir_level);
655 	nblock = bucket_blocks(level);
656 
657 	bidx = dir_block_index(level, F2FS_I(dir)->i_dir_level,
658 				(le32_to_cpu(dentry_hash) % nbucket));
659 
660 	for (block = bidx; block <= (bidx + nblock - 1); block++) {
661 		dentry_page = f2fs_get_new_data_page(dir, NULL, block, true);
662 		if (IS_ERR(dentry_page))
663 			return PTR_ERR(dentry_page);
664 
665 		dentry_blk = page_address(dentry_page);
666 		bit_pos = f2fs_room_for_filename(&dentry_blk->dentry_bitmap,
667 						slots, NR_DENTRY_IN_BLOCK);
668 		if (bit_pos < NR_DENTRY_IN_BLOCK)
669 			goto add_dentry;
670 
671 		f2fs_put_page(dentry_page, 1);
672 	}
673 
674 	/* Move to next level to find the empty slot for new dentry */
675 	++level;
676 	goto start;
677 add_dentry:
678 	f2fs_wait_on_page_writeback(dentry_page, DATA, true, true);
679 
680 	if (inode) {
681 		down_write(&F2FS_I(inode)->i_sem);
682 		page = f2fs_init_inode_metadata(inode, dir, new_name,
683 						orig_name, NULL);
684 		if (IS_ERR(page)) {
685 			err = PTR_ERR(page);
686 			goto fail;
687 		}
688 	}
689 
690 	make_dentry_ptr_block(NULL, &d, dentry_blk);
691 	f2fs_update_dentry(ino, mode, &d, new_name, dentry_hash, bit_pos);
692 
693 	set_page_dirty(dentry_page);
694 
695 	if (inode) {
696 		f2fs_i_pino_write(inode, dir->i_ino);
697 
698 		/* synchronize inode page's data from inode cache */
699 		if (is_inode_flag_set(inode, FI_NEW_INODE))
700 			f2fs_update_inode(inode, page);
701 
702 		f2fs_put_page(page, 1);
703 	}
704 
705 	f2fs_update_parent_metadata(dir, inode, current_depth);
706 fail:
707 	if (inode)
708 		up_write(&F2FS_I(inode)->i_sem);
709 
710 	f2fs_put_page(dentry_page, 1);
711 
712 	return err;
713 }
714 
715 int f2fs_add_dentry(struct inode *dir, struct fscrypt_name *fname,
716 				struct inode *inode, nid_t ino, umode_t mode)
717 {
718 	struct qstr new_name;
719 	int err = -EAGAIN;
720 
721 	new_name.name = fname_name(fname);
722 	new_name.len = fname_len(fname);
723 
724 	if (f2fs_has_inline_dentry(dir))
725 		err = f2fs_add_inline_entry(dir, &new_name, fname->usr_fname,
726 							inode, ino, mode);
727 	if (err == -EAGAIN)
728 		err = f2fs_add_regular_entry(dir, &new_name, fname->usr_fname,
729 							inode, ino, mode);
730 
731 	f2fs_update_time(F2FS_I_SB(dir), REQ_TIME);
732 	return err;
733 }
734 
735 /*
736  * Caller should grab and release a rwsem by calling f2fs_lock_op() and
737  * f2fs_unlock_op().
738  */
739 int f2fs_do_add_link(struct inode *dir, const struct qstr *name,
740 				struct inode *inode, nid_t ino, umode_t mode)
741 {
742 	struct fscrypt_name fname;
743 	struct page *page = NULL;
744 	struct f2fs_dir_entry *de = NULL;
745 	int err;
746 
747 	err = fscrypt_setup_filename(dir, name, 0, &fname);
748 	if (err)
749 		return err;
750 
751 	/*
752 	 * An immature stakable filesystem shows a race condition between lookup
753 	 * and create. If we have same task when doing lookup and create, it's
754 	 * definitely fine as expected by VFS normally. Otherwise, let's just
755 	 * verify on-disk dentry one more time, which guarantees filesystem
756 	 * consistency more.
757 	 */
758 	if (current != F2FS_I(dir)->task) {
759 		de = __f2fs_find_entry(dir, &fname, &page);
760 		F2FS_I(dir)->task = NULL;
761 	}
762 	if (de) {
763 		f2fs_put_page(page, 0);
764 		err = -EEXIST;
765 	} else if (IS_ERR(page)) {
766 		err = PTR_ERR(page);
767 	} else {
768 		err = f2fs_add_dentry(dir, &fname, inode, ino, mode);
769 	}
770 	fscrypt_free_filename(&fname);
771 	return err;
772 }
773 
774 int f2fs_do_tmpfile(struct inode *inode, struct inode *dir)
775 {
776 	struct page *page;
777 	int err = 0;
778 
779 	down_write(&F2FS_I(inode)->i_sem);
780 	page = f2fs_init_inode_metadata(inode, dir, NULL, NULL, NULL);
781 	if (IS_ERR(page)) {
782 		err = PTR_ERR(page);
783 		goto fail;
784 	}
785 	f2fs_put_page(page, 1);
786 
787 	clear_inode_flag(inode, FI_NEW_INODE);
788 	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
789 fail:
790 	up_write(&F2FS_I(inode)->i_sem);
791 	return err;
792 }
793 
794 void f2fs_drop_nlink(struct inode *dir, struct inode *inode)
795 {
796 	struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
797 
798 	down_write(&F2FS_I(inode)->i_sem);
799 
800 	if (S_ISDIR(inode->i_mode))
801 		f2fs_i_links_write(dir, false);
802 	inode->i_ctime = current_time(inode);
803 
804 	f2fs_i_links_write(inode, false);
805 	if (S_ISDIR(inode->i_mode)) {
806 		f2fs_i_links_write(inode, false);
807 		f2fs_i_size_write(inode, 0);
808 	}
809 	up_write(&F2FS_I(inode)->i_sem);
810 
811 	if (inode->i_nlink == 0)
812 		f2fs_add_orphan_inode(inode);
813 	else
814 		f2fs_release_orphan_inode(sbi);
815 }
816 
817 /*
818  * It only removes the dentry from the dentry page, corresponding name
819  * entry in name page does not need to be touched during deletion.
820  */
821 void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page,
822 					struct inode *dir, struct inode *inode)
823 {
824 	struct	f2fs_dentry_block *dentry_blk;
825 	unsigned int bit_pos;
826 	int slots = GET_DENTRY_SLOTS(le16_to_cpu(dentry->name_len));
827 	int i;
828 
829 	f2fs_update_time(F2FS_I_SB(dir), REQ_TIME);
830 
831 	if (F2FS_OPTION(F2FS_I_SB(dir)).fsync_mode == FSYNC_MODE_STRICT)
832 		f2fs_add_ino_entry(F2FS_I_SB(dir), dir->i_ino, TRANS_DIR_INO);
833 
834 	if (f2fs_has_inline_dentry(dir))
835 		return f2fs_delete_inline_entry(dentry, page, dir, inode);
836 
837 	lock_page(page);
838 	f2fs_wait_on_page_writeback(page, DATA, true, true);
839 
840 	dentry_blk = page_address(page);
841 	bit_pos = dentry - dentry_blk->dentry;
842 	for (i = 0; i < slots; i++)
843 		__clear_bit_le(bit_pos + i, &dentry_blk->dentry_bitmap);
844 
845 	/* Let's check and deallocate this dentry page */
846 	bit_pos = find_next_bit_le(&dentry_blk->dentry_bitmap,
847 			NR_DENTRY_IN_BLOCK,
848 			0);
849 	set_page_dirty(page);
850 
851 	if (bit_pos == NR_DENTRY_IN_BLOCK &&
852 		!f2fs_truncate_hole(dir, page->index, page->index + 1)) {
853 		f2fs_clear_page_cache_dirty_tag(page);
854 		clear_page_dirty_for_io(page);
855 		f2fs_clear_page_private(page);
856 		ClearPageUptodate(page);
857 		clear_cold_data(page);
858 		inode_dec_dirty_pages(dir);
859 		f2fs_remove_dirty_inode(dir);
860 	}
861 	f2fs_put_page(page, 1);
862 
863 	dir->i_ctime = dir->i_mtime = current_time(dir);
864 	f2fs_mark_inode_dirty_sync(dir, false);
865 
866 	if (inode)
867 		f2fs_drop_nlink(dir, inode);
868 }
869 
870 bool f2fs_empty_dir(struct inode *dir)
871 {
872 	unsigned long bidx;
873 	struct page *dentry_page;
874 	unsigned int bit_pos;
875 	struct f2fs_dentry_block *dentry_blk;
876 	unsigned long nblock = dir_blocks(dir);
877 
878 	if (f2fs_has_inline_dentry(dir))
879 		return f2fs_empty_inline_dir(dir);
880 
881 	for (bidx = 0; bidx < nblock; bidx++) {
882 		dentry_page = f2fs_get_lock_data_page(dir, bidx, false);
883 		if (IS_ERR(dentry_page)) {
884 			if (PTR_ERR(dentry_page) == -ENOENT)
885 				continue;
886 			else
887 				return false;
888 		}
889 
890 		dentry_blk = page_address(dentry_page);
891 		if (bidx == 0)
892 			bit_pos = 2;
893 		else
894 			bit_pos = 0;
895 		bit_pos = find_next_bit_le(&dentry_blk->dentry_bitmap,
896 						NR_DENTRY_IN_BLOCK,
897 						bit_pos);
898 
899 		f2fs_put_page(dentry_page, 1);
900 
901 		if (bit_pos < NR_DENTRY_IN_BLOCK)
902 			return false;
903 	}
904 	return true;
905 }
906 
907 int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d,
908 			unsigned int start_pos, struct fscrypt_str *fstr)
909 {
910 	unsigned char d_type = DT_UNKNOWN;
911 	unsigned int bit_pos;
912 	struct f2fs_dir_entry *de = NULL;
913 	struct fscrypt_str de_name = FSTR_INIT(NULL, 0);
914 	struct f2fs_sb_info *sbi = F2FS_I_SB(d->inode);
915 	struct blk_plug plug;
916 	bool readdir_ra = sbi->readdir_ra == 1;
917 	int err = 0;
918 
919 	bit_pos = ((unsigned long)ctx->pos % d->max);
920 
921 	if (readdir_ra)
922 		blk_start_plug(&plug);
923 
924 	while (bit_pos < d->max) {
925 		bit_pos = find_next_bit_le(d->bitmap, d->max, bit_pos);
926 		if (bit_pos >= d->max)
927 			break;
928 
929 		de = &d->dentry[bit_pos];
930 		if (de->name_len == 0) {
931 			bit_pos++;
932 			ctx->pos = start_pos + bit_pos;
933 			printk_ratelimited(
934 				"%sF2FS-fs (%s): invalid namelen(0), ino:%u, run fsck to fix.",
935 				KERN_WARNING, sbi->sb->s_id,
936 				le32_to_cpu(de->ino));
937 			set_sbi_flag(sbi, SBI_NEED_FSCK);
938 			continue;
939 		}
940 
941 		d_type = f2fs_get_de_type(de);
942 
943 		de_name.name = d->filename[bit_pos];
944 		de_name.len = le16_to_cpu(de->name_len);
945 
946 		/* check memory boundary before moving forward */
947 		bit_pos += GET_DENTRY_SLOTS(le16_to_cpu(de->name_len));
948 		if (unlikely(bit_pos > d->max ||
949 				le16_to_cpu(de->name_len) > F2FS_NAME_LEN)) {
950 			f2fs_warn(sbi, "%s: corrupted namelen=%d, run fsck to fix.",
951 				  __func__, le16_to_cpu(de->name_len));
952 			set_sbi_flag(sbi, SBI_NEED_FSCK);
953 			err = -EFSCORRUPTED;
954 			goto out;
955 		}
956 
957 		if (IS_ENCRYPTED(d->inode)) {
958 			int save_len = fstr->len;
959 
960 			err = fscrypt_fname_disk_to_usr(d->inode,
961 						(u32)le32_to_cpu(de->hash_code),
962 						0, &de_name, fstr);
963 			if (err)
964 				goto out;
965 
966 			de_name = *fstr;
967 			fstr->len = save_len;
968 		}
969 
970 		if (!dir_emit(ctx, de_name.name, de_name.len,
971 					le32_to_cpu(de->ino), d_type)) {
972 			err = 1;
973 			goto out;
974 		}
975 
976 		if (readdir_ra)
977 			f2fs_ra_node_page(sbi, le32_to_cpu(de->ino));
978 
979 		ctx->pos = start_pos + bit_pos;
980 	}
981 out:
982 	if (readdir_ra)
983 		blk_finish_plug(&plug);
984 	return err;
985 }
986 
987 static int f2fs_readdir(struct file *file, struct dir_context *ctx)
988 {
989 	struct inode *inode = file_inode(file);
990 	unsigned long npages = dir_blocks(inode);
991 	struct f2fs_dentry_block *dentry_blk = NULL;
992 	struct page *dentry_page = NULL;
993 	struct file_ra_state *ra = &file->f_ra;
994 	loff_t start_pos = ctx->pos;
995 	unsigned int n = ((unsigned long)ctx->pos / NR_DENTRY_IN_BLOCK);
996 	struct f2fs_dentry_ptr d;
997 	struct fscrypt_str fstr = FSTR_INIT(NULL, 0);
998 	int err = 0;
999 
1000 	if (IS_ENCRYPTED(inode)) {
1001 		err = fscrypt_get_encryption_info(inode);
1002 		if (err)
1003 			goto out;
1004 
1005 		err = fscrypt_fname_alloc_buffer(inode, F2FS_NAME_LEN, &fstr);
1006 		if (err < 0)
1007 			goto out;
1008 	}
1009 
1010 	if (f2fs_has_inline_dentry(inode)) {
1011 		err = f2fs_read_inline_dir(file, ctx, &fstr);
1012 		goto out_free;
1013 	}
1014 
1015 	for (; n < npages; n++, ctx->pos = n * NR_DENTRY_IN_BLOCK) {
1016 
1017 		/* allow readdir() to be interrupted */
1018 		if (fatal_signal_pending(current)) {
1019 			err = -ERESTARTSYS;
1020 			goto out_free;
1021 		}
1022 		cond_resched();
1023 
1024 		/* readahead for multi pages of dir */
1025 		if (npages - n > 1 && !ra_has_index(ra, n))
1026 			page_cache_sync_readahead(inode->i_mapping, ra, file, n,
1027 				min(npages - n, (pgoff_t)MAX_DIR_RA_PAGES));
1028 
1029 		dentry_page = f2fs_find_data_page(inode, n);
1030 		if (IS_ERR(dentry_page)) {
1031 			err = PTR_ERR(dentry_page);
1032 			if (err == -ENOENT) {
1033 				err = 0;
1034 				continue;
1035 			} else {
1036 				goto out_free;
1037 			}
1038 		}
1039 
1040 		dentry_blk = page_address(dentry_page);
1041 
1042 		make_dentry_ptr_block(inode, &d, dentry_blk);
1043 
1044 		err = f2fs_fill_dentries(ctx, &d,
1045 				n * NR_DENTRY_IN_BLOCK, &fstr);
1046 		if (err) {
1047 			f2fs_put_page(dentry_page, 0);
1048 			break;
1049 		}
1050 
1051 		f2fs_put_page(dentry_page, 0);
1052 	}
1053 out_free:
1054 	fscrypt_fname_free_buffer(&fstr);
1055 out:
1056 	trace_f2fs_readdir(inode, start_pos, ctx->pos, err);
1057 	return err < 0 ? err : 0;
1058 }
1059 
1060 static int f2fs_dir_open(struct inode *inode, struct file *filp)
1061 {
1062 	if (IS_ENCRYPTED(inode))
1063 		return fscrypt_get_encryption_info(inode) ? -EACCES : 0;
1064 	return 0;
1065 }
1066 
1067 const struct file_operations f2fs_dir_operations = {
1068 	.llseek		= generic_file_llseek,
1069 	.read		= generic_read_dir,
1070 	.iterate_shared	= f2fs_readdir,
1071 	.fsync		= f2fs_sync_file,
1072 	.open		= f2fs_dir_open,
1073 	.unlocked_ioctl	= f2fs_ioctl,
1074 #ifdef CONFIG_COMPAT
1075 	.compat_ioctl   = f2fs_compat_ioctl,
1076 #endif
1077 };
1078 
1079 #ifdef CONFIG_UNICODE
1080 static int f2fs_d_compare(const struct dentry *dentry, unsigned int len,
1081 			  const char *str, const struct qstr *name)
1082 {
1083 	struct qstr qstr = {.name = str, .len = len };
1084 	const struct dentry *parent = READ_ONCE(dentry->d_parent);
1085 	const struct inode *inode = READ_ONCE(parent->d_inode);
1086 
1087 	if (!inode || !IS_CASEFOLDED(inode)) {
1088 		if (len != name->len)
1089 			return -1;
1090 		return memcmp(str, name->name, len);
1091 	}
1092 
1093 	return f2fs_ci_compare(inode, name, &qstr, false);
1094 }
1095 
1096 static int f2fs_d_hash(const struct dentry *dentry, struct qstr *str)
1097 {
1098 	struct f2fs_sb_info *sbi = F2FS_SB(dentry->d_sb);
1099 	const struct unicode_map *um = sbi->s_encoding;
1100 	const struct inode *inode = READ_ONCE(dentry->d_inode);
1101 	unsigned char *norm;
1102 	int len, ret = 0;
1103 
1104 	if (!inode || !IS_CASEFOLDED(inode))
1105 		return 0;
1106 
1107 	norm = f2fs_kmalloc(sbi, PATH_MAX, GFP_ATOMIC);
1108 	if (!norm)
1109 		return -ENOMEM;
1110 
1111 	len = utf8_casefold(um, str, norm, PATH_MAX);
1112 	if (len < 0) {
1113 		if (f2fs_has_strict_mode(sbi))
1114 			ret = -EINVAL;
1115 		goto out;
1116 	}
1117 	str->hash = full_name_hash(dentry, norm, len);
1118 out:
1119 	kvfree(norm);
1120 	return ret;
1121 }
1122 
1123 const struct dentry_operations f2fs_dentry_ops = {
1124 	.d_hash = f2fs_d_hash,
1125 	.d_compare = f2fs_d_compare,
1126 };
1127 #endif
1128