xref: /linux/fs/f2fs/dir.c (revision 493b9dc8b52caf50bd33fbe26cb9fe931fa713e4)
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 	void *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 					void **dentry_block,
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 				*dentry_block = 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 			f2fs_folio_put(dentry_folio, false);
324 			*dentry_block = ERR_CAST(de);
325 			de = NULL;
326 			break;
327 		} else if (de) {
328 			*dentry_block = dentry_folio;
329 			break;
330 		}
331 
332 		if (max_slots >= s)
333 			room = true;
334 		f2fs_folio_put(dentry_folio, false);
335 
336 		bidx++;
337 	}
338 
339 	if (de)
340 		return de;
341 
342 	if (likely(use_hash)) {
343 		if (room && F2FS_I(dir)->chash != fname->hash) {
344 			F2FS_I(dir)->chash = fname->hash;
345 			F2FS_I(dir)->clevel = level;
346 		}
347 	} else if (++bucket_no < nbucket) {
348 		goto start_find_bucket;
349 	}
350 	return NULL;
351 }
352 
353 struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir,
354 					 const struct f2fs_filename *fname,
355 					 void **dentry_block)
356 {
357 	unsigned long npages = dir_blocks(dir);
358 	struct f2fs_dir_entry *de = NULL;
359 	unsigned int max_depth;
360 	unsigned int level;
361 	bool use_hash = true;
362 
363 	*dentry_block = NULL;
364 
365 #if IS_ENABLED(CONFIG_UNICODE)
366 start_find_entry:
367 #endif
368 	if (f2fs_has_inline_dentry(dir)) {
369 		de = f2fs_find_in_inline_dir(dir, fname, dentry_block, use_hash);
370 		goto out;
371 	}
372 
373 	if (npages == 0)
374 		goto out;
375 
376 	max_depth = F2FS_I(dir)->i_current_depth;
377 	if (unlikely(max_depth > MAX_DIR_HASH_DEPTH)) {
378 		f2fs_warn(F2FS_I_SB(dir), "Corrupted max_depth of %llu: %u",
379 			  dir->i_ino, max_depth);
380 		max_depth = MAX_DIR_HASH_DEPTH;
381 		f2fs_i_depth_write(dir, max_depth);
382 	}
383 
384 	for (level = 0; level < max_depth; level++) {
385 		de = find_in_level(dir, level, fname, dentry_block, use_hash);
386 		if (de || IS_ERR(*dentry_block))
387 			break;
388 	}
389 
390 out:
391 #if IS_ENABLED(CONFIG_UNICODE)
392 	if (f2fs_should_fallback_to_linear(dir) &&
393 		IS_CASEFOLDED(dir) && !de && use_hash) {
394 		use_hash = false;
395 		goto start_find_entry;
396 	}
397 #endif
398 	/* This is to increase the speed of f2fs_create */
399 	if (!de)
400 		F2FS_I(dir)->task = current;
401 	return de;
402 }
403 
404 /*
405  * Find an entry in the specified directory with the wanted name.
406  * It returns the page where the entry was found (as a parameter - res_page),
407  * and the entry itself. Page is returned mapped and unlocked.
408  * Entry is guaranteed to be valid.
409  */
410 struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir,
411 			const struct qstr *child, void **dentry_block)
412 {
413 	struct f2fs_dir_entry *de = NULL;
414 	struct f2fs_filename fname;
415 	int err;
416 
417 	err = f2fs_setup_filename(dir, child, 1, &fname);
418 	if (err) {
419 		if (err == -ENOENT)
420 			*dentry_block = NULL;
421 		else
422 			*dentry_block = ERR_PTR(err);
423 		return NULL;
424 	}
425 
426 	de = __f2fs_find_entry(dir, &fname, dentry_block);
427 
428 	f2fs_free_filename(&fname);
429 	return de;
430 }
431 
432 struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, void **dentry_block)
433 {
434 	return f2fs_find_entry(dir, &dotdot_name, dentry_block);
435 }
436 
437 ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr,
438 							void **dentry_block)
439 {
440 	ino_t res = 0;
441 	struct f2fs_dir_entry *de;
442 
443 	de = f2fs_find_entry(dir, qstr, dentry_block);
444 	if (de) {
445 		res = le32_to_cpu(de->ino);
446 		f2fs_put_dentry_block(*dentry_block, false);
447 	}
448 
449 	return res;
450 }
451 
452 void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de,
453 		void *dentry_block, struct inode *inode)
454 {
455 	if (f2fs_dentry_is_cache(dentry_block)) {
456 		struct f2fs_cached_block *entry =
457 				f2fs_dentry_cache(dentry_block);
458 
459 		f2fs_lock_cache(entry);
460 		f2fs_cache_wait_writeback(entry);
461 		de->ino = cpu_to_le32(inode->i_ino);
462 		de->file_type = fs_umode_to_ftype(inode->i_mode);
463 		f2fs_mark_cache_dirty(entry);
464 	} else {
465 		struct folio *folio = f2fs_dentry_folio(dentry_block);
466 
467 		folio_lock(folio);
468 		f2fs_folio_wait_writeback(folio, true, true);
469 		de->ino = cpu_to_le32(inode->i_ino);
470 		de->file_type = fs_umode_to_ftype(inode->i_mode);
471 		folio_mark_dirty(folio);
472 	}
473 
474 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
475 	f2fs_mark_inode_dirty_sync(dir, true);
476 	f2fs_put_dentry_block(dentry_block, true);
477 }
478 
479 static void init_dent_inode(struct inode *dir, struct inode *inode,
480 			    const struct f2fs_filename *fname,
481 			    struct f2fs_cached_block *ientry)
482 {
483 	struct f2fs_inode *ri;
484 
485 	if (!fname) /* tmpfile case? */
486 		return;
487 
488 	f2fs_cache_wait_writeback(ientry);
489 
490 	/* copy name info. to this inode folio */
491 	ri = F2FS_INODE(ientry);
492 	ri->i_namelen = cpu_to_le32(fname->disk_name.len);
493 	memcpy(ri->i_name, fname->disk_name.name, fname->disk_name.len);
494 	if (IS_ENCRYPTED(dir)) {
495 		file_set_enc_name(inode);
496 		/*
497 		 * Roll-forward recovery doesn't have encryption keys available,
498 		 * so it can't compute the dirhash for encrypted+casefolded
499 		 * filenames.  Append it to i_name if possible.  Else, disable
500 		 * roll-forward recovery of the dentry (i.e., make fsync'ing the
501 		 * file force a checkpoint) by setting LOST_PINO.
502 		 */
503 		if (IS_CASEFOLDED(dir)) {
504 			if (fname->disk_name.len + sizeof(f2fs_hash_t) <=
505 			    F2FS_NAME_LEN)
506 				put_unaligned(fname->hash, (f2fs_hash_t *)
507 					&ri->i_name[fname->disk_name.len]);
508 			else
509 				file_lost_pino(inode);
510 		}
511 	}
512 	f2fs_mark_cache_dirty(ientry);
513 }
514 
515 void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent,
516 					struct f2fs_dentry_ptr *d)
517 {
518 	struct fscrypt_str dot = FSTR_INIT(".", 1);
519 	struct fscrypt_str dotdot = FSTR_INIT("..", 2);
520 
521 	/* update dirent of "." */
522 	f2fs_update_dentry(inode->i_ino, inode->i_mode, d, &dot, 0, 0);
523 
524 	/* update dirent of ".." */
525 	f2fs_update_dentry(parent->i_ino, parent->i_mode, d, &dotdot, 0, 1);
526 }
527 
528 static int make_empty_dir(struct inode *inode,
529 		struct inode *parent, struct f2fs_cached_block *ientry)
530 {
531 	struct folio *dentry_folio;
532 	void *dentry_blk;
533 	struct f2fs_dentry_ptr d;
534 
535 	if (f2fs_has_inline_dentry(inode))
536 		return f2fs_make_empty_inline_dir(inode, parent, ientry);
537 
538 	dentry_folio = f2fs_get_new_data_folio(inode, ientry, 0, true);
539 	if (IS_ERR(dentry_folio))
540 		return PTR_ERR(dentry_folio);
541 
542 	dentry_blk = folio_address(dentry_folio);
543 
544 	make_dentry_ptr_block(inode, &d, dentry_blk);
545 	f2fs_do_make_empty_dir(inode, parent, &d);
546 
547 	folio_mark_dirty(dentry_folio);
548 	f2fs_folio_put(dentry_folio, true);
549 	return 0;
550 }
551 
552 struct f2fs_cached_block *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir,
553 		const struct f2fs_filename *fname, struct f2fs_cached_block *dentry)
554 {
555 	struct f2fs_cached_block *ientry;
556 	int err;
557 
558 	if (is_inode_flag_set(inode, FI_NEW_INODE)) {
559 		ientry = f2fs_new_inode_cache(inode);
560 		if (IS_ERR(ientry))
561 			return ientry;
562 
563 		if (S_ISDIR(inode->i_mode)) {
564 			/* in order to handle error case */
565 			f2fs_cache_get(ientry);
566 			err = make_empty_dir(inode, dir, ientry);
567 			if (err) {
568 				f2fs_lock_cache(ientry);
569 				goto put_error;
570 			}
571 			f2fs_put_cache(ientry, false);
572 		}
573 
574 		err = f2fs_init_acl(inode, dir, ientry, dentry);
575 		if (err)
576 			goto put_error;
577 
578 		err = f2fs_init_security(inode, dir,
579 					 fname ? fname->usr_fname : NULL,
580 					 ientry);
581 		if (err)
582 			goto put_error;
583 
584 		if (IS_ENCRYPTED(inode)) {
585 			err = fscrypt_set_context(inode, ientry);
586 			if (err)
587 				goto put_error;
588 		}
589 	} else {
590 		ientry = f2fs_get_inode_cache(F2FS_I_SB(dir), inode->i_ino);
591 		if (IS_ERR(ientry))
592 			return ientry;
593 	}
594 
595 	init_dent_inode(dir, inode, fname, ientry);
596 
597 	/*
598 	 * This file should be checkpointed during fsync.
599 	 * We lost i_pino from now on.
600 	 */
601 	if (is_inode_flag_set(inode, FI_INC_LINK)) {
602 		if (!S_ISDIR(inode->i_mode))
603 			file_lost_pino(inode);
604 		/*
605 		 * If link the tmpfile to alias through linkat path,
606 		 * we should remove this inode from orphan list.
607 		 */
608 		if (inode->i_nlink == 0)
609 			f2fs_remove_orphan_inode(F2FS_I_SB(dir), inode->i_ino);
610 		f2fs_i_links_write(inode, true);
611 	}
612 	return ientry;
613 
614 put_error:
615 	clear_nlink(inode);
616 	f2fs_update_inode(inode, ientry);
617 	f2fs_put_cache(ientry, true);
618 	return ERR_PTR(err);
619 }
620 
621 void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode,
622 						unsigned int current_depth)
623 {
624 	if (inode && is_inode_flag_set(inode, FI_NEW_INODE)) {
625 		if (S_ISDIR(inode->i_mode))
626 			f2fs_i_links_write(dir, true);
627 		clear_inode_flag(inode, FI_NEW_INODE);
628 	}
629 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
630 	f2fs_mark_inode_dirty_sync(dir, true);
631 
632 	if (F2FS_I(dir)->i_current_depth != current_depth)
633 		f2fs_i_depth_write(dir, current_depth);
634 
635 	if (inode && is_inode_flag_set(inode, FI_INC_LINK))
636 		clear_inode_flag(inode, FI_INC_LINK);
637 }
638 
639 int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots)
640 {
641 	int bit_start = 0;
642 	int zero_start, zero_end;
643 next:
644 	zero_start = find_next_zero_bit_le(bitmap, max_slots, bit_start);
645 	if (zero_start >= max_slots)
646 		return max_slots;
647 
648 	zero_end = find_next_bit_le(bitmap, max_slots, zero_start);
649 	if (zero_end - zero_start >= slots)
650 		return zero_start;
651 
652 	bit_start = zero_end + 1;
653 
654 	if (zero_end + 1 >= max_slots)
655 		return max_slots;
656 	goto next;
657 }
658 
659 bool f2fs_has_enough_room(struct inode *dir, struct f2fs_cached_block *ientry,
660 			  const struct f2fs_filename *fname)
661 {
662 	struct f2fs_dentry_ptr d;
663 	unsigned int bit_pos;
664 	int slots = GET_DENTRY_SLOTS(fname->disk_name.len);
665 
666 	make_dentry_ptr_inline(dir, &d, inline_data_addr(dir, ientry));
667 
668 	bit_pos = f2fs_room_for_filename(d.bitmap, slots, d.max);
669 
670 	return bit_pos < d.max;
671 }
672 
673 void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d,
674 			const struct fscrypt_str *name, f2fs_hash_t name_hash,
675 			unsigned int bit_pos)
676 {
677 	struct f2fs_dir_entry *de;
678 	int slots = GET_DENTRY_SLOTS(name->len);
679 	int i;
680 
681 	de = &d->dentry[bit_pos];
682 	de->hash_code = name_hash;
683 	de->name_len = cpu_to_le16(name->len);
684 	memcpy(d->filename[bit_pos], name->name, name->len);
685 	de->ino = cpu_to_le32(ino);
686 	de->file_type = fs_umode_to_ftype(mode);
687 	for (i = 0; i < slots; i++) {
688 		__set_bit_le(bit_pos + i, (void *)d->bitmap);
689 		/* avoid wrong garbage data for readdir */
690 		if (i)
691 			(de + i)->name_len = 0;
692 	}
693 }
694 
695 int f2fs_add_regular_entry(struct inode *dir, const struct f2fs_filename *fname,
696 			   struct inode *inode, nid_t ino, umode_t mode)
697 {
698 	unsigned int bit_pos;
699 	unsigned int level;
700 	unsigned int current_depth;
701 	unsigned long bidx, block;
702 	unsigned int nbucket, nblock;
703 	struct folio *dentry_folio = NULL;
704 	void *dentry_blk = NULL;
705 	struct f2fs_dentry_ptr d;
706 	struct f2fs_cached_block *entry = NULL;
707 	int slots, err = 0;
708 
709 	level = 0;
710 	slots = GET_DENTRY_SLOTS(fname->disk_name.len);
711 
712 	current_depth = F2FS_I(dir)->i_current_depth;
713 	if (F2FS_I(dir)->chash == fname->hash) {
714 		level = F2FS_I(dir)->clevel;
715 		F2FS_I(dir)->chash = 0;
716 	}
717 
718 start:
719 	if (time_to_inject(F2FS_I_SB(dir), FAULT_DIR_DEPTH))
720 		return -ENOSPC;
721 
722 	if (unlikely(current_depth == MAX_DIR_HASH_DEPTH))
723 		return -ENOSPC;
724 
725 	/* Increase the depth, if required */
726 	if (level == current_depth)
727 		++current_depth;
728 
729 	nbucket = dir_buckets(level, F2FS_I(dir)->i_dir_level);
730 	nblock = bucket_blocks(level);
731 
732 	bidx = dir_block_index(level, F2FS_I(dir)->i_dir_level,
733 				(le32_to_cpu(fname->hash) % nbucket));
734 
735 	for (block = bidx; block <= (bidx + nblock - 1); block++) {
736 		dentry_folio = f2fs_get_new_data_folio(dir, NULL, block, true);
737 		if (IS_ERR(dentry_folio))
738 			return PTR_ERR(dentry_folio);
739 
740 		dentry_blk = folio_address(dentry_folio);
741 		make_dentry_ptr_block(dir, &d, dentry_blk);
742 		bit_pos = f2fs_room_for_filename(d.bitmap, slots, d.max);
743 		if (bit_pos < d.max)
744 			goto add_dentry;
745 
746 		f2fs_folio_put(dentry_folio, true);
747 	}
748 
749 	/* Move to next level to find the empty slot for new dentry */
750 	++level;
751 	goto start;
752 add_dentry:
753 	f2fs_folio_wait_writeback(dentry_folio, true, true);
754 
755 	if (inode) {
756 		f2fs_down_write(&F2FS_I(inode)->i_sem);
757 		entry = f2fs_init_inode_metadata(inode, dir, fname, NULL);
758 		if (IS_ERR(entry)) {
759 			err = PTR_ERR(entry);
760 			goto fail;
761 		}
762 	}
763 
764 	f2fs_update_dentry(ino, mode, &d, &fname->disk_name, fname->hash,
765 			   bit_pos);
766 
767 	folio_mark_dirty(dentry_folio);
768 
769 	if (inode) {
770 		f2fs_i_pino_write(inode, dir->i_ino);
771 
772 		/* synchronize inode page's data from inode cache */
773 		if (is_inode_flag_set(inode, FI_NEW_INODE))
774 			f2fs_update_inode(inode, entry);
775 
776 		f2fs_put_cache(entry, true);
777 	}
778 
779 	f2fs_update_parent_metadata(dir, inode, current_depth);
780 fail:
781 	if (inode)
782 		f2fs_up_write(&F2FS_I(inode)->i_sem);
783 
784 	f2fs_folio_put(dentry_folio, true);
785 
786 	return err;
787 }
788 
789 int f2fs_add_dentry(struct inode *dir, const struct f2fs_filename *fname,
790 		    struct inode *inode, nid_t ino, umode_t mode)
791 {
792 	int err = -EAGAIN;
793 
794 	if (f2fs_has_inline_dentry(dir)) {
795 		/*
796 		 * Should get i_xattr_sem to keep the lock order:
797 		 * i_xattr_sem -> inode_page lock used by f2fs_setxattr.
798 		 */
799 		f2fs_down_read(&F2FS_I(dir)->i_xattr_sem);
800 		err = f2fs_add_inline_entry(dir, fname, inode, ino, mode);
801 		f2fs_up_read(&F2FS_I(dir)->i_xattr_sem);
802 	}
803 	if (err == -EAGAIN)
804 		err = f2fs_add_regular_entry(dir, fname, inode, ino, mode);
805 
806 	f2fs_update_time(F2FS_I_SB(dir), REQ_TIME);
807 	return err;
808 }
809 
810 /*
811  * Caller should grab and release a rwsem by calling f2fs_lock_op() and
812  * f2fs_unlock_op().
813  */
814 int f2fs_do_add_link(struct inode *dir, const struct qstr *name,
815 				struct inode *inode, nid_t ino, umode_t mode)
816 {
817 	struct f2fs_filename fname;
818 	void *dentry_blk = NULL;
819 	struct f2fs_dir_entry *de = NULL;
820 	int err;
821 
822 	err = f2fs_setup_filename(dir, name, 0, &fname);
823 	if (err)
824 		return err;
825 
826 	/*
827 	 * An immature stackable filesystem shows a race condition between lookup
828 	 * and create. If we have same task when doing lookup and create, it's
829 	 * definitely fine as expected by VFS normally. Otherwise, let's just
830 	 * verify on-disk dentry one more time, which guarantees filesystem
831 	 * consistency more.
832 	 */
833 	if (current != F2FS_I(dir)->task) {
834 		de = __f2fs_find_entry(dir, &fname, &dentry_blk);
835 		F2FS_I(dir)->task = NULL;
836 	}
837 	if (de) {
838 		f2fs_put_dentry_block(dentry_blk, false);
839 		err = -EEXIST;
840 	} else if (IS_ERR(dentry_blk)) {
841 		err = PTR_ERR(dentry_blk);
842 	} else {
843 		err = f2fs_add_dentry(dir, &fname, inode, ino, mode);
844 	}
845 	f2fs_free_filename(&fname);
846 	return err;
847 }
848 
849 int f2fs_do_tmpfile(struct inode *inode, struct inode *dir,
850 					struct f2fs_filename *fname)
851 {
852 	struct f2fs_cached_block *ientry;
853 	int err = 0;
854 
855 	f2fs_down_write(&F2FS_I(inode)->i_sem);
856 	ientry = f2fs_init_inode_metadata(inode, dir, fname, NULL);
857 	if (IS_ERR(ientry)) {
858 		err = PTR_ERR(ientry);
859 		goto fail;
860 	}
861 	f2fs_put_cache(ientry, true);
862 
863 	clear_inode_flag(inode, FI_NEW_INODE);
864 	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
865 fail:
866 	f2fs_up_write(&F2FS_I(inode)->i_sem);
867 	return err;
868 }
869 
870 void f2fs_drop_nlink(struct inode *dir, struct inode *inode)
871 {
872 	struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
873 
874 	f2fs_down_write(&F2FS_I(inode)->i_sem);
875 
876 	if (S_ISDIR(inode->i_mode))
877 		f2fs_i_links_write(dir, false);
878 	inode_set_ctime_current(inode);
879 
880 	f2fs_i_links_write(inode, false);
881 	if (S_ISDIR(inode->i_mode)) {
882 		f2fs_i_links_write(inode, false);
883 		f2fs_i_size_write(inode, 0);
884 	}
885 	f2fs_up_write(&F2FS_I(inode)->i_sem);
886 
887 	if (inode->i_nlink == 0)
888 		f2fs_add_orphan_inode(inode);
889 	else
890 		f2fs_release_orphan_inode(sbi);
891 }
892 
893 /*
894  * It only removes the dentry from the dentry page, corresponding name
895  * entry in name page does not need to be touched during deletion.
896  */
897 void f2fs_delete_entry(struct f2fs_dir_entry *dentry, void *dentry_block,
898 					struct inode *dir, struct inode *inode)
899 {
900 	void *dentry_blk;
901 	struct f2fs_dentry_ptr d;
902 	struct folio *folio;
903 	unsigned int bit_pos;
904 	int slots = GET_DENTRY_SLOTS(le16_to_cpu(dentry->name_len));
905 	pgoff_t index;
906 	int i;
907 
908 	f2fs_update_time(F2FS_I_SB(dir), REQ_TIME);
909 
910 	if (F2FS_OPTION(F2FS_I_SB(dir)).fsync_mode == FSYNC_MODE_STRICT)
911 		f2fs_add_ino_entry(F2FS_I_SB(dir), dir->i_ino, TRANS_DIR_INO);
912 
913 	if (f2fs_has_inline_dentry(dir))
914 		return f2fs_delete_inline_entry(dentry,
915 				f2fs_dentry_cache(dentry_block), dir, inode);
916 
917 	folio = f2fs_dentry_folio(dentry_block);
918 	index = folio->index;
919 
920 	folio_lock(folio);
921 	f2fs_folio_wait_writeback(folio, true, true);
922 
923 	dentry_blk = folio_address(folio);
924 	make_dentry_ptr_block(dir, &d, dentry_blk);
925 	bit_pos = dentry - d.dentry;
926 	for (i = 0; i < slots; i++)
927 		__clear_bit_le(bit_pos + i, d.bitmap);
928 
929 	/* Let's check and deallocate this dentry page */
930 	bit_pos = find_next_bit_le(d.bitmap, d.max, 0);
931 	folio_mark_dirty(folio);
932 
933 	if (bit_pos == d.max &&
934 	    !f2fs_truncate_hole(dir, index, index + 1)) {
935 		f2fs_clear_page_cache_dirty_tag(folio);
936 		folio_clear_dirty_for_io(folio);
937 		folio_clear_uptodate(folio);
938 		folio_detach_private(folio);
939 
940 		inode_dec_dirty_pages(dir);
941 		f2fs_remove_dirty_inode(dir);
942 	}
943 	f2fs_folio_put(folio, true);
944 
945 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
946 	f2fs_mark_inode_dirty_sync(dir, true);
947 
948 	if (inode)
949 		f2fs_drop_nlink(dir, inode);
950 }
951 
952 bool f2fs_empty_dir(struct inode *dir)
953 {
954 	unsigned long bidx = 0;
955 	unsigned int bit_pos;
956 	void *dentry_blk;
957 	struct f2fs_dentry_ptr d;
958 	unsigned long nblock = dir_blocks(dir);
959 
960 	if (f2fs_has_inline_dentry(dir))
961 		return f2fs_empty_inline_dir(dir);
962 
963 	while (bidx < nblock) {
964 		pgoff_t next_pgofs;
965 		struct folio *dentry_folio;
966 
967 		dentry_folio = f2fs_find_data_folio(dir, bidx, &next_pgofs);
968 		if (IS_ERR(dentry_folio)) {
969 			if (PTR_ERR(dentry_folio) == -ENOENT) {
970 				bidx = next_pgofs;
971 				continue;
972 			} else {
973 				return false;
974 			}
975 		}
976 
977 		dentry_blk = folio_address(dentry_folio);
978 		make_dentry_ptr_block(dir, &d, dentry_blk);
979 		if (bidx == 0)
980 			bit_pos = 2;
981 		else
982 			bit_pos = 0;
983 		bit_pos = find_next_bit_le(d.bitmap, d.max, bit_pos);
984 
985 		f2fs_folio_put(dentry_folio, false);
986 
987 		if (bit_pos < d.max)
988 			return false;
989 
990 		bidx++;
991 	}
992 	return true;
993 }
994 
995 int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d,
996 			unsigned int start_pos, struct fscrypt_str *fstr)
997 {
998 	unsigned char d_type = DT_UNKNOWN;
999 	unsigned int bit_pos;
1000 	struct f2fs_dir_entry *de = NULL;
1001 	struct fscrypt_str de_name = FSTR_INIT(NULL, 0);
1002 	struct f2fs_sb_info *sbi = F2FS_I_SB(d->inode);
1003 	struct blk_plug plug;
1004 	bool readdir_ra = sbi->readdir_ra;
1005 	bool found_valid_dirent = false;
1006 	int err = 0;
1007 
1008 	bit_pos = ((unsigned long)ctx->pos % d->max);
1009 
1010 	if (readdir_ra)
1011 		blk_start_plug(&plug);
1012 
1013 	while (bit_pos < d->max) {
1014 		bit_pos = find_next_bit_le(d->bitmap, d->max, bit_pos);
1015 		if (bit_pos >= d->max)
1016 			break;
1017 
1018 		de = &d->dentry[bit_pos];
1019 		if (de->name_len == 0) {
1020 			if (found_valid_dirent || !bit_pos) {
1021 				f2fs_warn_ratelimited(sbi,
1022 					"invalid namelen(0), ino:%u, run fsck to fix.",
1023 					le32_to_cpu(de->ino));
1024 				set_sbi_flag(sbi, SBI_NEED_FSCK);
1025 			}
1026 			bit_pos++;
1027 			ctx->pos = start_pos + bit_pos;
1028 			continue;
1029 		}
1030 
1031 		d_type = fs_ftype_to_dtype(de->file_type);
1032 
1033 		de_name.name = d->filename[bit_pos];
1034 		de_name.len = le16_to_cpu(de->name_len);
1035 
1036 		/* check memory boundary before moving forward */
1037 		bit_pos += GET_DENTRY_SLOTS(le16_to_cpu(de->name_len));
1038 		if (unlikely(bit_pos > d->max ||
1039 				le16_to_cpu(de->name_len) > F2FS_NAME_LEN)) {
1040 			f2fs_warn(sbi, "%s: corrupted namelen=%d, run fsck to fix.",
1041 				  __func__, le16_to_cpu(de->name_len));
1042 			set_sbi_flag(sbi, SBI_NEED_FSCK);
1043 			err = -EFSCORRUPTED;
1044 			f2fs_handle_error(sbi, ERROR_CORRUPTED_DIRENT);
1045 			fserror_report_file_metadata(d->inode, err, GFP_NOFS);
1046 			goto out;
1047 		}
1048 
1049 		if (IS_ENCRYPTED(d->inode)) {
1050 			int save_len = fstr->len;
1051 
1052 			err = fscrypt_fname_disk_to_usr(d->inode,
1053 						(u32)le32_to_cpu(de->hash_code),
1054 						0, &de_name, fstr);
1055 			if (err)
1056 				goto out;
1057 
1058 			de_name = *fstr;
1059 			fstr->len = save_len;
1060 		}
1061 
1062 		if (!dir_emit(ctx, de_name.name, de_name.len,
1063 					le32_to_cpu(de->ino), d_type)) {
1064 			err = 1;
1065 			goto out;
1066 		}
1067 
1068 		if (readdir_ra)
1069 			f2fs_ra_node_cache(sbi, le32_to_cpu(de->ino));
1070 
1071 		ctx->pos = start_pos + bit_pos;
1072 		found_valid_dirent = true;
1073 	}
1074 out:
1075 	if (readdir_ra)
1076 		blk_finish_plug(&plug);
1077 	return err;
1078 }
1079 
1080 static int f2fs_readdir(struct file *file, struct dir_context *ctx)
1081 {
1082 	struct inode *inode = file_inode(file);
1083 	unsigned long npages = dir_blocks(inode);
1084 	void *dentry_blk = NULL;
1085 	struct file_ra_state *ra = &file->f_ra;
1086 	loff_t start_pos = ctx->pos;
1087 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1088 	unsigned int entries = sbi->dentries_per_block;
1089 	unsigned int n = (unsigned long)ctx->pos / entries;
1090 	struct f2fs_dentry_ptr d;
1091 	struct fscrypt_str fstr = FSTR_INIT(NULL, 0);
1092 	int err = 0;
1093 
1094 	if (IS_ENCRYPTED(inode)) {
1095 		err = fscrypt_prepare_readdir(inode);
1096 		if (err)
1097 			goto out;
1098 
1099 		err = fscrypt_fname_alloc_buffer(F2FS_NAME_LEN, &fstr);
1100 		if (err < 0)
1101 			goto out;
1102 	}
1103 
1104 	if (f2fs_has_inline_dentry(inode)) {
1105 		err = f2fs_read_inline_dir(file, ctx, &fstr);
1106 		goto out_free;
1107 	}
1108 
1109 	for (; n < npages; ctx->pos = n * entries) {
1110 		struct folio *dentry_folio;
1111 		pgoff_t next_pgofs;
1112 
1113 		/* allow readdir() to be interrupted */
1114 		if (fatal_signal_pending(current)) {
1115 			err = -ERESTARTSYS;
1116 			goto out_free;
1117 		}
1118 		cond_resched();
1119 
1120 		/* readahead for multi pages of dir */
1121 		if (npages - n > 1 && !ra_has_index(ra, n))
1122 			page_cache_sync_readahead(inode->i_mapping, ra, file, n,
1123 				min(npages - n, (pgoff_t)MAX_DIR_RA_PAGES));
1124 
1125 		dentry_folio = f2fs_find_data_folio(inode, n, &next_pgofs);
1126 		if (IS_ERR(dentry_folio)) {
1127 			err = PTR_ERR(dentry_folio);
1128 			if (err == -ENOENT) {
1129 				err = 0;
1130 				n = next_pgofs;
1131 				continue;
1132 			} else {
1133 				goto out_free;
1134 			}
1135 		}
1136 
1137 		dentry_blk = folio_address(dentry_folio);
1138 
1139 		make_dentry_ptr_block(inode, &d, dentry_blk);
1140 
1141 		err = f2fs_fill_dentries(ctx, &d,
1142 				n * entries, &fstr);
1143 		f2fs_folio_put(dentry_folio, false);
1144 		if (err)
1145 			break;
1146 
1147 		n++;
1148 	}
1149 out_free:
1150 	fscrypt_fname_free_buffer(&fstr);
1151 out:
1152 	trace_f2fs_readdir(inode, start_pos, ctx->pos, err);
1153 	return err < 0 ? err : 0;
1154 }
1155 
1156 const struct file_operations f2fs_dir_operations = {
1157 	.llseek		= generic_file_llseek,
1158 	.read		= generic_read_dir,
1159 	.iterate_shared	= f2fs_readdir,
1160 	.fsync		= f2fs_sync_file,
1161 	.unlocked_ioctl	= f2fs_ioctl,
1162 #ifdef CONFIG_COMPAT
1163 	.compat_ioctl   = f2fs_compat_ioctl,
1164 #endif
1165 	.setlease	= generic_setlease,
1166 };
1167