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