xref: /linux/fs/libfs.c (revision 45eb9737058fa78a73f17a5da55c8cb482c6d5bb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *	fs/libfs.c
4  *	Library for filesystems writers.
5  */
6 
7 #include <linux/blkdev.h>
8 #include <linux/export.h>
9 #include <linux/filelock.h>
10 #include <linux/pagemap.h>
11 #include <linux/slab.h>
12 #include <linux/cred.h>
13 #include <linux/mount.h>
14 #include <linux/vfs.h>
15 #include <linux/quotaops.h>
16 #include <linux/mutex.h>
17 #include <linux/namei.h>
18 #include <linux/exportfs.h>
19 #include <linux/iversion.h>
20 #include <linux/writeback.h>
21 #include <linux/fs_context.h>
22 #include <linux/pseudo_fs.h>
23 #include <linux/fsnotify.h>
24 #include <linux/unicode.h>
25 #include <linux/fscrypt.h>
26 #include <linux/pidfs.h>
27 
28 #include <linux/uaccess.h>
29 
30 #include "internal.h"
31 
32 int simple_getattr(const struct mnt_idmap *idmap, const struct path *path,
33 		   struct kstat *stat, u32 request_mask,
34 		   unsigned int query_flags)
35 {
36 	struct inode *inode = d_inode(path->dentry);
37 	generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
38 	stat->blocks = inode->i_mapping->nrpages << (PAGE_SHIFT - 9);
39 	return 0;
40 }
41 EXPORT_SYMBOL(simple_getattr);
42 
43 int simple_statfs(struct dentry *dentry, struct kstatfs *buf)
44 {
45 	u64 id = huge_encode_dev(dentry->d_sb->s_dev);
46 
47 	buf->f_fsid = u64_to_fsid(id);
48 	buf->f_type = dentry->d_sb->s_magic;
49 	buf->f_bsize = PAGE_SIZE;
50 	buf->f_namelen = NAME_MAX;
51 	return 0;
52 }
53 EXPORT_SYMBOL(simple_statfs);
54 
55 /*
56  * Retaining negative dentries for an in-memory filesystem just wastes
57  * memory and lookup time: arrange for them to be deleted immediately.
58  */
59 int always_delete_dentry(const struct dentry *dentry)
60 {
61 	return 1;
62 }
63 EXPORT_SYMBOL(always_delete_dentry);
64 
65 /*
66  * Lookup the data. This is trivial - if the dentry didn't already
67  * exist, we know it is negative.  Set d_op to delete negative dentries.
68  */
69 struct dentry *simple_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
70 {
71 	if (dentry->d_name.len > NAME_MAX)
72 		return ERR_PTR(-ENAMETOOLONG);
73 	if (!dentry->d_op && !(dentry->d_flags & DCACHE_DONTCACHE)) {
74 		spin_lock(&dentry->d_lock);
75 		dentry->d_flags |= DCACHE_DONTCACHE;
76 		spin_unlock(&dentry->d_lock);
77 	}
78 	if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
79 		return NULL;
80 
81 	return d_splice_alias(NULL, dentry);
82 }
83 EXPORT_SYMBOL(simple_lookup);
84 
85 int dcache_dir_open(struct inode *inode, struct file *file)
86 {
87 	file->private_data = d_alloc_cursor(file->f_path.dentry);
88 
89 	return file->private_data ? 0 : -ENOMEM;
90 }
91 EXPORT_SYMBOL(dcache_dir_open);
92 
93 int dcache_dir_close(struct inode *inode, struct file *file)
94 {
95 	dput(file->private_data);
96 	return 0;
97 }
98 EXPORT_SYMBOL(dcache_dir_close);
99 
100 /* parent is locked at least shared */
101 /*
102  * Returns an element of siblings' list.
103  * We are looking for <count>th positive after <p>; if
104  * found, dentry is grabbed and returned to caller.
105  * If no such element exists, NULL is returned.
106  */
107 static struct dentry *scan_positives(struct dentry *cursor,
108 					struct hlist_node **p,
109 					loff_t count,
110 					struct dentry *last)
111 {
112 	struct dentry *dentry = cursor->d_parent, *found = NULL;
113 
114 	spin_lock(&dentry->d_lock);
115 	while (*p) {
116 		struct dentry *d = hlist_entry(*p, struct dentry, d_sib);
117 		p = &d->d_sib.next;
118 		// we must at least skip cursors, to avoid livelocks
119 		if (d->d_flags & DCACHE_DENTRY_CURSOR)
120 			continue;
121 		if (simple_positive(d) && !--count) {
122 			spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
123 			if (simple_positive(d))
124 				found = dget_dlock(d);
125 			spin_unlock(&d->d_lock);
126 			if (likely(found))
127 				break;
128 			count = 1;
129 		}
130 		if (need_resched()) {
131 			if (!hlist_unhashed(&cursor->d_sib))
132 				__hlist_del(&cursor->d_sib);
133 			hlist_add_behind(&cursor->d_sib, &d->d_sib);
134 			p = &cursor->d_sib.next;
135 			spin_unlock(&dentry->d_lock);
136 			cond_resched();
137 			spin_lock(&dentry->d_lock);
138 		}
139 	}
140 	spin_unlock(&dentry->d_lock);
141 	dput(last);
142 	return found;
143 }
144 
145 loff_t dcache_dir_lseek(struct file *file, loff_t offset, int whence)
146 {
147 	struct dentry *dentry = file->f_path.dentry;
148 	switch (whence) {
149 		case 1:
150 			offset += file->f_pos;
151 			fallthrough;
152 		case 0:
153 			if (offset >= 0)
154 				break;
155 			fallthrough;
156 		default:
157 			return -EINVAL;
158 	}
159 	if (offset != file->f_pos) {
160 		struct dentry *cursor = file->private_data;
161 		struct dentry *to = NULL;
162 
163 		inode_lock_shared(dentry->d_inode);
164 
165 		if (offset > 2)
166 			to = scan_positives(cursor, &dentry->d_children.first,
167 					    offset - 2, NULL);
168 		spin_lock(&dentry->d_lock);
169 		hlist_del_init(&cursor->d_sib);
170 		if (to)
171 			hlist_add_behind(&cursor->d_sib, &to->d_sib);
172 		spin_unlock(&dentry->d_lock);
173 		dput(to);
174 
175 		file->f_pos = offset;
176 
177 		inode_unlock_shared(dentry->d_inode);
178 	}
179 	return offset;
180 }
181 EXPORT_SYMBOL(dcache_dir_lseek);
182 
183 /*
184  * Directory is locked and all positive dentries in it are safe, since
185  * for ramfs-type trees they can't go away without unlink() or rmdir(),
186  * both impossible due to the lock on directory.
187  */
188 
189 int dcache_readdir(struct file *file, struct dir_context *ctx)
190 {
191 	struct dentry *dentry = file->f_path.dentry;
192 	struct dentry *cursor = file->private_data;
193 	struct dentry *next = NULL;
194 	struct hlist_node **p;
195 
196 	if (!dir_emit_dots(file, ctx))
197 		return 0;
198 
199 	if (ctx->pos == 2)
200 		p = &dentry->d_children.first;
201 	else
202 		p = &cursor->d_sib.next;
203 
204 	while ((next = scan_positives(cursor, p, 1, next)) != NULL) {
205 		if (!dir_emit(ctx, next->d_name.name, next->d_name.len,
206 			      d_inode(next)->i_ino,
207 			      fs_umode_to_dtype(d_inode(next)->i_mode)))
208 			break;
209 		ctx->pos++;
210 		p = &next->d_sib.next;
211 	}
212 	spin_lock(&dentry->d_lock);
213 	hlist_del_init(&cursor->d_sib);
214 	if (next)
215 		hlist_add_before(&cursor->d_sib, &next->d_sib);
216 	spin_unlock(&dentry->d_lock);
217 	dput(next);
218 
219 	return 0;
220 }
221 EXPORT_SYMBOL(dcache_readdir);
222 
223 ssize_t generic_read_dir(struct file *filp, char __user *buf, size_t siz, loff_t *ppos)
224 {
225 	return -EISDIR;
226 }
227 EXPORT_SYMBOL(generic_read_dir);
228 
229 const struct file_operations simple_dir_operations = {
230 	.open		= dcache_dir_open,
231 	.release	= dcache_dir_close,
232 	.llseek		= dcache_dir_lseek,
233 	.read		= generic_read_dir,
234 	.iterate_shared	= dcache_readdir,
235 	.fsync		= noop_fsync,
236 };
237 EXPORT_SYMBOL(simple_dir_operations);
238 
239 const struct inode_operations simple_dir_inode_operations = {
240 	.lookup		= simple_lookup,
241 };
242 EXPORT_SYMBOL(simple_dir_inode_operations);
243 
244 /* simple_offset_add() never assigns these to a dentry */
245 enum {
246 	DIR_OFFSET_FIRST	= 2,		/* Find first real entry */
247 	DIR_OFFSET_EOD		= S32_MAX,
248 };
249 
250 /* simple_offset_add() allocation range */
251 enum {
252 	DIR_OFFSET_MIN		= DIR_OFFSET_FIRST + 1,
253 	DIR_OFFSET_MAX		= DIR_OFFSET_EOD - 1,
254 };
255 
256 static void offset_set(struct dentry *dentry, long offset)
257 {
258 	dentry->d_fsdata = (void *)offset;
259 }
260 
261 static long dentry2offset(struct dentry *dentry)
262 {
263 	return (long)dentry->d_fsdata;
264 }
265 
266 /**
267  * simple_offset_init - initialize an offset_ctx
268  * @octx: directory offset map to be initialized
269  * @dir: the directory @octx belongs to
270  *
271  * The directory's i_rwsem is the lock of the offset map. Writers hold it
272  * exclusive, offset_readdir() holds it shared.
273  */
274 void simple_offset_init(struct offset_ctx *octx, struct inode *dir)
275 {
276 	mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN);
277 	mt_set_external_lock(&octx->mt, &dir->i_rwsem);
278 	octx->next_offset = DIR_OFFSET_MIN;
279 }
280 
281 /**
282  * simple_offset_add - Add an entry to a directory's offset map
283  * @octx: directory offset ctx to be updated
284  * @dentry: new dentry being added
285  *
286  * The offset map holds no reference to @dentry. Once positive, @dentry
287  * must be pinned with d_make_persistent() for as long as it is in the
288  * map, and entries may only be added, removed or renamed with the
289  * directory's i_rwsem held exclusive: offset_readdir() emits straight
290  * from the map under the shared lock.
291  *
292  * Returns zero on success. @octx and the dentry's offset are updated.
293  * Otherwise, a negative errno value is returned.
294  */
295 int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry)
296 {
297 	unsigned long offset;
298 	int ret;
299 
300 	MA_STATE(mas, &octx->mt, 0, 0);
301 
302 	if (dentry2offset(dentry) != 0)
303 		return -EBUSY;
304 
305 	ret = mas_alloc_cyclic(&mas, &offset, dentry, DIR_OFFSET_MIN,
306 			       DIR_OFFSET_MAX, &octx->next_offset, GFP_KERNEL);
307 	if (unlikely(ret < 0))
308 		return ret == -EBUSY ? -ENOSPC : ret;
309 
310 	offset_set(dentry, offset);
311 	return 0;
312 }
313 
314 static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry,
315 				 long offset)
316 {
317 	int ret;
318 
319 	MA_STATE(mas, &octx->mt, offset, offset);
320 
321 	ret = mas_store_gfp(&mas, dentry, GFP_KERNEL);
322 	if (ret)
323 		return ret;
324 	offset_set(dentry, offset);
325 	return 0;
326 }
327 
328 /**
329  * simple_offset_remove - Remove an entry to a directory's offset map
330  * @octx: directory offset ctx to be updated
331  * @dentry: dentry being removed
332  *
333  */
334 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry)
335 {
336 	long offset = dentry2offset(dentry);
337 
338 	MA_STATE(mas, &octx->mt, offset, offset);
339 
340 	if (offset == 0)
341 		return;
342 
343 	mas_erase(&mas);
344 	offset_set(dentry, 0);
345 }
346 
347 /**
348  * simple_offset_rename - handle directory offsets for rename
349  * @old_dir: parent directory of source entry
350  * @old_dentry: dentry of source entry
351  * @new_dir: parent_directory of destination entry
352  * @new_dentry: dentry of destination
353  *
354  * Caller provides appropriate serialization.
355  *
356  * User space expects the directory offset value of the replaced
357  * (new) directory entry to be unchanged after a rename.
358  *
359  * Caller must have grabbed a slot for new_dentry in the maple_tree
360  * associated with new_dir, even if dentry is negative.
361  */
362 void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
363 			  struct inode *new_dir, struct dentry *new_dentry)
364 {
365 	struct offset_ctx *old_ctx = old_dir->i_op->get_offset_ctx(old_dir);
366 	struct offset_ctx *new_ctx = new_dir->i_op->get_offset_ctx(new_dir);
367 	long new_offset = dentry2offset(new_dentry);
368 
369 	if (WARN_ON(!new_offset))
370 		return;
371 
372 	simple_offset_remove(old_ctx, old_dentry);
373 	offset_set(new_dentry, 0);
374 	WARN_ON(simple_offset_replace(new_ctx, old_dentry, new_offset));
375 }
376 
377 /**
378  * simple_offset_rename_exchange - exchange rename with directory offsets
379  * @old_dir: parent of dentry being moved
380  * @old_dentry: dentry being moved
381  * @new_dir: destination parent
382  * @new_dentry: destination dentry
383  *
384  * This API preserves the directory offset values. Caller provides
385  * appropriate serialization.
386  *
387  * Returns zero on success. Otherwise a negative errno is returned and the
388  * rename is rolled back.
389  */
390 int simple_offset_rename_exchange(struct inode *old_dir,
391 				  struct dentry *old_dentry,
392 				  struct inode *new_dir,
393 				  struct dentry *new_dentry)
394 {
395 	struct offset_ctx *old_ctx = old_dir->i_op->get_offset_ctx(old_dir);
396 	struct offset_ctx *new_ctx = new_dir->i_op->get_offset_ctx(new_dir);
397 	long old_index = dentry2offset(old_dentry);
398 	long new_index = dentry2offset(new_dentry);
399 	int ret;
400 
401 	MA_STATE(old_mas, &old_ctx->mt, old_index, old_index);
402 	MA_STATE(new_mas, &new_ctx->mt, new_index, new_index);
403 
404 	if (WARN_ON(!old_index || !new_index))
405 		return -EINVAL;
406 
407 	ret = mas_store_gfp(&new_mas, old_dentry, GFP_KERNEL);
408 	if (WARN_ON(ret))
409 		return ret;
410 
411 	ret = mas_store_gfp(&old_mas, new_dentry, GFP_KERNEL);
412 	if (WARN_ON(ret)) {
413 		mas_set(&new_mas, new_index);
414 		mas_store_gfp(&new_mas, new_dentry, GFP_KERNEL);
415 		return ret;
416 	}
417 
418 	offset_set(old_dentry, new_index);
419 	offset_set(new_dentry, old_index);
420 	simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
421 	return 0;
422 }
423 
424 /**
425  * simple_offset_destroy - Release offset map
426  * @octx: directory offset ctx that is about to be destroyed
427  *
428  * During fs teardown (eg. umount), a directory's offset map might still
429  * contain entries. __mt_destroy() cleans out anything that remains.
430  * Nothing can reach the map of a directory that is being destroyed, so
431  * this runs without the directory's i_rwsem.
432  */
433 void simple_offset_destroy(struct offset_ctx *octx)
434 {
435 	mt_on_stack(octx->mt);
436 	__mt_destroy(&octx->mt);
437 }
438 
439 /**
440  * offset_dir_llseek - Advance the read position of a directory descriptor
441  * @file: an open directory whose position is to be updated
442  * @offset: a byte offset
443  * @whence: enumerator describing the starting position for this update
444  *
445  * SEEK_END, SEEK_DATA, and SEEK_HOLE are not supported for directories.
446  *
447  * Returns the updated read position if successful; otherwise a
448  * negative errno is returned and the read position remains unchanged.
449  */
450 static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence)
451 {
452 	switch (whence) {
453 	case SEEK_CUR:
454 		offset += file->f_pos;
455 		fallthrough;
456 	case SEEK_SET:
457 		if (offset >= 0)
458 			break;
459 		fallthrough;
460 	default:
461 		return -EINVAL;
462 	}
463 
464 	return vfs_setpos(file, offset, LONG_MAX);
465 }
466 
467 static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
468 {
469 	struct inode *inode = d_inode(dentry);
470 
471 	return dir_emit(ctx, dentry->d_name.name, dentry->d_name.len,
472 			inode->i_ino, fs_umode_to_dtype(inode->i_mode));
473 }
474 
475 /*
476  * Emit entries in descending offset order. The directory's i_rwsem is the
477  * lock of the offset tree and the persistent dentries in it only change
478  * with it held exclusive. We hold it shared, so @mas stays valid across
479  * dir_emit() and the dentries need no references.
480  */
481 static void offset_iterate_dir(struct file *file, struct dir_context *ctx)
482 {
483 	struct inode *inode = file_inode(file);
484 	struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
485 	loff_t start = ctx->pos == DIR_OFFSET_FIRST ? DIR_OFFSET_MAX : ctx->pos;
486 	struct dentry *dentry;
487 
488 	MA_STATE(mas, &octx->mt, start, start);
489 
490 	for (;;) {
491 		dentry = mas_find_rev(&mas, DIR_OFFSET_MIN);
492 		if (!dentry)
493 			break;
494 		VFS_WARN_ON_ONCE(!(dentry->d_flags & DCACHE_PERSISTENT));
495 		ctx->pos = dentry2offset(dentry);
496 		if (!offset_dir_emit(ctx, dentry))
497 			return;
498 	}
499 	ctx->pos = DIR_OFFSET_EOD;
500 }
501 
502 /**
503  * offset_readdir - Emit entries starting at offset @ctx->pos
504  * @file: an open directory to iterate over
505  * @ctx: directory iteration context
506  *
507  * Caller must hold @file's i_rwsem to prevent insertion or removal of
508  * entries during this call.
509  *
510  * On entry, @ctx->pos contains an offset that represents the first entry
511  * to be read from the directory.
512  *
513  * The operation continues until there are no more entries to read, or
514  * until the ctx->actor indicates there is no more space in the caller's
515  * output buffer.
516  *
517  * On return, @ctx->pos contains an offset that will read the next entry
518  * in this directory when offset_readdir() is called again with @ctx.
519  * Caller places this value in the d_off field of the last entry in the
520  * user's buffer.
521  *
522  * Return values:
523  *   %0 - Complete
524  */
525 static int offset_readdir(struct file *file, struct dir_context *ctx)
526 {
527 	struct dentry *dir = file->f_path.dentry;
528 
529 	lockdep_assert_held(&d_inode(dir)->i_rwsem);
530 
531 	if (!dir_emit_dots(file, ctx))
532 		return 0;
533 	if (ctx->pos < DIR_OFFSET_EOD)
534 		offset_iterate_dir(file, ctx);
535 	return 0;
536 }
537 
538 const struct file_operations simple_offset_dir_operations = {
539 	.llseek		= offset_dir_llseek,
540 	.iterate_shared	= offset_readdir,
541 	.read		= generic_read_dir,
542 	.fsync		= noop_fsync,
543 	.setlease	= generic_setlease,
544 };
545 
546 struct dentry *find_next_child(struct dentry *parent, struct dentry *prev)
547 {
548 	struct dentry *child = NULL, *d;
549 
550 	spin_lock(&parent->d_lock);
551 	d = prev ? d_next_sibling(prev) : d_first_child(parent);
552 	hlist_for_each_entry_from(d, d_sib) {
553 		if (simple_positive(d)) {
554 			spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
555 			if (simple_positive(d))
556 				child = dget_dlock(d);
557 			spin_unlock(&d->d_lock);
558 			if (likely(child))
559 				break;
560 		}
561 	}
562 	spin_unlock(&parent->d_lock);
563 	dput(prev);
564 	return child;
565 }
566 EXPORT_SYMBOL(find_next_child);
567 
568 static void __simple_recursive_removal(struct dentry *dentry,
569                               void (*callback)(struct dentry *),
570 			      bool locked)
571 {
572 	struct dentry *this = dget(dentry);
573 	while (true) {
574 		struct dentry *victim = NULL, *child;
575 		struct inode *inode = this->d_inode;
576 
577 		inode_lock_nested(inode, I_MUTEX_CHILD);
578 		if (d_is_dir(this))
579 			inode->i_flags |= S_DEAD;
580 		while ((child = find_next_child(this, victim)) == NULL) {
581 			// kill and ascend
582 			// update metadata while it's still locked
583 			inode_set_ctime_current(inode);
584 			clear_nlink(inode);
585 			inode_unlock(inode);
586 			victim = this;
587 			this = this->d_parent;
588 			inode = this->d_inode;
589 			if (!locked || victim != dentry)
590 				inode_lock_nested(inode, I_MUTEX_CHILD);
591 			if (simple_positive(victim)) {
592 				d_invalidate(victim);	// avoid lost mounts
593 				if (callback)
594 					callback(victim);
595 				fsnotify_delete(inode, d_inode(victim), victim);
596 				d_make_discardable(victim);
597 			}
598 			if (victim == dentry) {
599 				inode_set_mtime_to_ts(inode,
600 						      inode_set_ctime_current(inode));
601 				if (d_is_dir(dentry))
602 					drop_nlink(inode);
603 				if (!locked)
604 					inode_unlock(inode);
605 				dput(dentry);
606 				return;
607 			}
608 		}
609 		inode_unlock(inode);
610 		this = child;
611 	}
612 }
613 
614 void simple_recursive_removal(struct dentry *dentry,
615                               void (*callback)(struct dentry *))
616 {
617 	return __simple_recursive_removal(dentry, callback, false);
618 }
619 EXPORT_SYMBOL(simple_recursive_removal);
620 
621 void simple_remove_by_name(struct dentry *parent, const char *name,
622                            void (*callback)(struct dentry *))
623 {
624 	struct dentry *dentry;
625 
626 	dentry = lookup_noperm_positive_unlocked(&QSTR(name), parent);
627 	if (!IS_ERR(dentry)) {
628 		simple_recursive_removal(dentry, callback);
629 		dput(dentry);	// paired with lookup_noperm_positive_unlocked()
630 	}
631 }
632 EXPORT_SYMBOL(simple_remove_by_name);
633 
634 /* caller holds parent directory with I_MUTEX_PARENT */
635 void locked_recursive_removal(struct dentry *dentry,
636                               void (*callback)(struct dentry *))
637 {
638 	return __simple_recursive_removal(dentry, callback, true);
639 }
640 EXPORT_SYMBOL(locked_recursive_removal);
641 
642 static const struct super_operations simple_super_operations = {
643 	.statfs		= simple_statfs,
644 };
645 
646 static int pseudo_fs_fill_super(struct super_block *s, struct fs_context *fc)
647 {
648 	struct pseudo_fs_context *ctx = fc->fs_private;
649 	struct inode *root;
650 
651 	s->s_maxbytes = MAX_LFS_FILESIZE;
652 	s->s_blocksize = PAGE_SIZE;
653 	s->s_blocksize_bits = PAGE_SHIFT;
654 	s->s_magic = ctx->magic;
655 	s->s_op = ctx->ops ?: &simple_super_operations;
656 	s->s_export_op = ctx->eops;
657 	s->s_xattr = ctx->xattr;
658 	s->s_time_gran = 1;
659 	s->s_d_flags |= ctx->s_d_flags;
660 	root = new_inode(s);
661 	if (!root)
662 		return -ENOMEM;
663 
664 	/*
665 	 * since this is the first inode, make it number 1. New inodes created
666 	 * after this must take care not to collide with it (by passing
667 	 * max_reserved of 1 to iunique).
668 	 */
669 	root->i_ino = 1;
670 	root->i_mode = S_IFDIR | S_IRUSR | S_IWUSR;
671 	simple_inode_init_ts(root);
672 	s->s_root = d_make_root(root);
673 	if (!s->s_root)
674 		return -ENOMEM;
675 	set_default_d_op(s, ctx->dops);
676 	return 0;
677 }
678 
679 static int pseudo_fs_get_tree(struct fs_context *fc)
680 {
681 	return get_tree_nodev(fc, pseudo_fs_fill_super);
682 }
683 
684 static void pseudo_fs_free(struct fs_context *fc)
685 {
686 	kfree(fc->fs_private);
687 }
688 
689 static const struct fs_context_operations pseudo_fs_context_ops = {
690 	.free		= pseudo_fs_free,
691 	.get_tree	= pseudo_fs_get_tree,
692 };
693 
694 /*
695  * Common helper for pseudo-filesystems (sockfs, pipefs, bdev - stuff that
696  * will never be mountable)
697  */
698 struct pseudo_fs_context *init_pseudo(struct fs_context *fc,
699 					unsigned long magic)
700 {
701 	struct pseudo_fs_context *ctx;
702 
703 	ctx = kzalloc_obj(struct pseudo_fs_context);
704 	if (likely(ctx)) {
705 		ctx->magic = magic;
706 		fc->fs_private = ctx;
707 		fc->ops = &pseudo_fs_context_ops;
708 		fc->sb_flags |= SB_NOUSER;
709 		fc->s_iflags |= SB_I_NOEXEC | SB_I_NODEV;
710 		fc->global = true;
711 	}
712 	return ctx;
713 }
714 EXPORT_SYMBOL(init_pseudo);
715 
716 int simple_open(struct inode *inode, struct file *file)
717 {
718 	if (inode->i_private)
719 		file->private_data = inode->i_private;
720 	return 0;
721 }
722 EXPORT_SYMBOL(simple_open);
723 
724 int simple_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
725 {
726 	struct inode *inode = d_inode(old_dentry);
727 
728 	inode_set_mtime_to_ts(dir,
729 			      inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
730 	inc_nlink(inode);
731 	ihold(inode);
732 	d_make_persistent(dentry, inode);
733 	return 0;
734 }
735 EXPORT_SYMBOL(simple_link);
736 
737 int simple_empty(struct dentry *dentry)
738 {
739 	struct dentry *child;
740 	int ret = 0;
741 
742 	spin_lock(&dentry->d_lock);
743 	hlist_for_each_entry(child, &dentry->d_children, d_sib) {
744 		spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
745 		if (simple_positive(child)) {
746 			spin_unlock(&child->d_lock);
747 			goto out;
748 		}
749 		spin_unlock(&child->d_lock);
750 	}
751 	ret = 1;
752 out:
753 	spin_unlock(&dentry->d_lock);
754 	return ret;
755 }
756 EXPORT_SYMBOL(simple_empty);
757 
758 void __simple_unlink(struct inode *dir, struct dentry *dentry)
759 {
760 	struct inode *inode = d_inode(dentry);
761 
762 	inode_set_mtime_to_ts(dir,
763 			      inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
764 	drop_nlink(inode);
765 }
766 EXPORT_SYMBOL(__simple_unlink);
767 
768 void __simple_rmdir(struct inode *dir, struct dentry *dentry)
769 {
770 	drop_nlink(d_inode(dentry));
771 	__simple_unlink(dir, dentry);
772 	drop_nlink(dir);
773 }
774 EXPORT_SYMBOL(__simple_rmdir);
775 
776 int simple_unlink(struct inode *dir, struct dentry *dentry)
777 {
778 	__simple_unlink(dir, dentry);
779 	d_make_discardable(dentry);
780 	return 0;
781 }
782 EXPORT_SYMBOL(simple_unlink);
783 
784 int simple_rmdir(struct inode *dir, struct dentry *dentry)
785 {
786 	if (!simple_empty(dentry))
787 		return -ENOTEMPTY;
788 
789 	__simple_rmdir(dir, dentry);
790 	d_make_discardable(dentry);
791 	return 0;
792 }
793 EXPORT_SYMBOL(simple_rmdir);
794 
795 /**
796  * simple_rename_timestamp - update the various inode timestamps for rename
797  * @old_dir: old parent directory
798  * @old_dentry: dentry that is being renamed
799  * @new_dir: new parent directory
800  * @new_dentry: target for rename
801  *
802  * POSIX mandates that the old and new parent directories have their ctime and
803  * mtime updated, and that inodes of @old_dentry and @new_dentry (if any), have
804  * their ctime updated.
805  */
806 void simple_rename_timestamp(struct inode *old_dir, struct dentry *old_dentry,
807 			     struct inode *new_dir, struct dentry *new_dentry)
808 {
809 	struct inode *newino = d_inode(new_dentry);
810 
811 	inode_set_mtime_to_ts(old_dir, inode_set_ctime_current(old_dir));
812 	if (new_dir != old_dir)
813 		inode_set_mtime_to_ts(new_dir,
814 				      inode_set_ctime_current(new_dir));
815 	inode_set_ctime_current(d_inode(old_dentry));
816 	if (newino)
817 		inode_set_ctime_current(newino);
818 }
819 EXPORT_SYMBOL_GPL(simple_rename_timestamp);
820 
821 int simple_rename_exchange(struct inode *old_dir, struct dentry *old_dentry,
822 			   struct inode *new_dir, struct dentry *new_dentry)
823 {
824 	bool old_is_dir = d_is_dir(old_dentry);
825 	bool new_is_dir = d_is_dir(new_dentry);
826 
827 	if (old_dir != new_dir && old_is_dir != new_is_dir) {
828 		if (old_is_dir) {
829 			drop_nlink(old_dir);
830 			inc_nlink(new_dir);
831 		} else {
832 			drop_nlink(new_dir);
833 			inc_nlink(old_dir);
834 		}
835 	}
836 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
837 	return 0;
838 }
839 EXPORT_SYMBOL_GPL(simple_rename_exchange);
840 
841 int simple_rename(const struct mnt_idmap *idmap, struct inode *old_dir,
842 		  struct dentry *old_dentry, struct inode *new_dir,
843 		  struct dentry *new_dentry, unsigned int flags)
844 {
845 	int they_are_dirs = d_is_dir(old_dentry);
846 
847 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE))
848 		return -EINVAL;
849 
850 	if (flags & RENAME_EXCHANGE)
851 		return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
852 
853 	if (!simple_empty(new_dentry))
854 		return -ENOTEMPTY;
855 
856 	if (d_really_is_positive(new_dentry)) {
857 		simple_unlink(new_dir, new_dentry);
858 		if (they_are_dirs) {
859 			drop_nlink(d_inode(new_dentry));
860 			drop_nlink(old_dir);
861 		}
862 	} else if (they_are_dirs) {
863 		drop_nlink(old_dir);
864 		inc_nlink(new_dir);
865 	}
866 
867 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
868 	return 0;
869 }
870 EXPORT_SYMBOL(simple_rename);
871 
872 /**
873  * simple_setattr - setattr for simple filesystem
874  * @idmap: idmap of the target mount
875  * @dentry: dentry
876  * @iattr: iattr structure
877  *
878  * Returns 0 on success, -error on failure.
879  *
880  * simple_setattr is a simple ->setattr implementation without a proper
881  * implementation of size changes.
882  *
883  * It can either be used for in-memory filesystems or special files
884  * on simple regular filesystems.  Anything that needs to change on-disk
885  * or wire state on size changes needs its own setattr method.
886  */
887 int simple_setattr(const struct mnt_idmap *idmap, struct dentry *dentry,
888 		   struct iattr *iattr)
889 {
890 	struct inode *inode = d_inode(dentry);
891 	int error;
892 
893 	error = setattr_prepare(idmap, dentry, iattr);
894 	if (error)
895 		return error;
896 
897 	if (iattr->ia_valid & ATTR_SIZE)
898 		truncate_setsize(inode, iattr->ia_size);
899 	setattr_copy(idmap, inode, iattr);
900 	mark_inode_dirty(inode);
901 	return 0;
902 }
903 EXPORT_SYMBOL(simple_setattr);
904 
905 static int simple_read_folio(struct file *file, struct folio *folio)
906 {
907 	folio_zero_range(folio, 0, folio_size(folio));
908 	flush_dcache_folio(folio);
909 	folio_mark_uptodate(folio);
910 	folio_unlock(folio);
911 	return 0;
912 }
913 
914 int simple_write_begin(const struct kiocb *iocb, struct address_space *mapping,
915 			loff_t pos, unsigned len,
916 			struct folio **foliop, void **fsdata)
917 {
918 	struct folio *folio;
919 
920 	folio = __filemap_get_folio(mapping, pos / PAGE_SIZE, FGP_WRITEBEGIN,
921 			mapping_gfp_mask(mapping));
922 	if (IS_ERR(folio))
923 		return PTR_ERR(folio);
924 
925 	*foliop = folio;
926 
927 	if (!folio_test_uptodate(folio) && (len != folio_size(folio))) {
928 		size_t from = offset_in_folio(folio, pos);
929 
930 		folio_zero_segments(folio, 0, from,
931 				from + len, folio_size(folio));
932 	}
933 	return 0;
934 }
935 EXPORT_SYMBOL(simple_write_begin);
936 
937 /**
938  * simple_write_end - .write_end helper for non-block-device FSes
939  * @iocb: kernel I/O control block
940  * @mapping: 		"
941  * @pos: 		"
942  * @len: 		"
943  * @copied: 		"
944  * @folio: 		"
945  * @fsdata: 		"
946  *
947  * simple_write_end does the minimum needed for updating a folio after
948  * writing is done. It has the same API signature as the .write_end of
949  * address_space_operations vector. So it can just be set onto .write_end for
950  * FSes that don't need any other processing. i_rwsem is assumed to be held
951  * exclusively.
952  * Block based filesystems should use generic_write_end().
953  * NOTE: Even though i_size might get updated by this function, mark_inode_dirty
954  * is not called, so a filesystem that actually does store data in .write_inode
955  * should extend on what's done here with a call to mark_inode_dirty() in the
956  * case that i_size has changed.
957  *
958  * Use *ONLY* with simple_read_folio()
959  */
960 static int simple_write_end(const struct kiocb *iocb,
961 			    struct address_space *mapping,
962 			    loff_t pos, unsigned len, unsigned copied,
963 			    struct folio *folio, void *fsdata)
964 {
965 	struct inode *inode = folio->mapping->host;
966 	loff_t last_pos = pos + copied;
967 
968 	/* zero the stale part of the folio if we did a short copy */
969 	if (!folio_test_uptodate(folio)) {
970 		if (copied < len) {
971 			size_t from = offset_in_folio(folio, pos);
972 
973 			folio_zero_range(folio, from + copied, len - copied);
974 		}
975 		folio_mark_uptodate(folio);
976 	}
977 	/*
978 	 * No need to use i_size_read() here, the i_size
979 	 * cannot change under us because we hold the i_rwsem.
980 	 */
981 	if (last_pos > inode->i_size)
982 		i_size_write(inode, last_pos);
983 
984 	folio_mark_dirty(folio);
985 	folio_unlock(folio);
986 	folio_put(folio);
987 
988 	return copied;
989 }
990 
991 /*
992  * Provides ramfs-style behavior: data in the pagecache, but no writeback.
993  */
994 const struct address_space_operations ram_aops = {
995 	.read_folio	= simple_read_folio,
996 	.write_begin	= simple_write_begin,
997 	.write_end	= simple_write_end,
998 	.dirty_folio	= noop_dirty_folio,
999 };
1000 EXPORT_SYMBOL(ram_aops);
1001 
1002 /*
1003  * the inodes created here are not hashed. If you use iunique to generate
1004  * unique inode values later for this filesystem, then you must take care
1005  * to pass it an appropriate max_reserved value to avoid collisions.
1006  */
1007 int simple_fill_super(struct super_block *s, unsigned long magic,
1008 		      const struct tree_descr *files)
1009 {
1010 	struct inode *inode;
1011 	struct dentry *dentry;
1012 	int i;
1013 
1014 	s->s_blocksize = PAGE_SIZE;
1015 	s->s_blocksize_bits = PAGE_SHIFT;
1016 	s->s_magic = magic;
1017 	s->s_op = &simple_super_operations;
1018 	s->s_time_gran = 1;
1019 
1020 	inode = new_inode(s);
1021 	if (!inode)
1022 		return -ENOMEM;
1023 	/*
1024 	 * because the root inode is 1, the files array must not contain an
1025 	 * entry at index 1
1026 	 */
1027 	inode->i_ino = 1;
1028 	inode->i_mode = S_IFDIR | 0755;
1029 	simple_inode_init_ts(inode);
1030 	inode->i_op = &simple_dir_inode_operations;
1031 	inode->i_fop = &simple_dir_operations;
1032 	set_nlink(inode, 2);
1033 	s->s_root = d_make_root(inode);
1034 	if (!s->s_root)
1035 		return -ENOMEM;
1036 	for (i = 0; !files->name || files->name[0]; i++, files++) {
1037 		if (!files->name)
1038 			continue;
1039 
1040 		/* warn if it tries to conflict with the root inode */
1041 		if (unlikely(i == 1))
1042 			printk(KERN_WARNING "%s: %s passed in a files array"
1043 				"with an index of 1!\n", __func__,
1044 				s->s_type->name);
1045 
1046 		dentry = d_alloc_name(s->s_root, files->name);
1047 		if (!dentry)
1048 			return -ENOMEM;
1049 		inode = new_inode(s);
1050 		if (!inode) {
1051 			dput(dentry);
1052 			return -ENOMEM;
1053 		}
1054 		inode->i_mode = S_IFREG | files->mode;
1055 		simple_inode_init_ts(inode);
1056 		inode->i_fop = files->ops;
1057 		inode->i_ino = i;
1058 		d_make_persistent(dentry, inode);
1059 		dput(dentry);
1060 	}
1061 	return 0;
1062 }
1063 EXPORT_SYMBOL(simple_fill_super);
1064 
1065 static DEFINE_SPINLOCK(pin_fs_lock);
1066 
1067 int simple_pin_fs(struct file_system_type *type, struct vfsmount **mount, int *count)
1068 {
1069 	struct vfsmount *mnt = NULL;
1070 	spin_lock(&pin_fs_lock);
1071 	if (unlikely(!*mount)) {
1072 		spin_unlock(&pin_fs_lock);
1073 		mnt = vfs_kern_mount(type, SB_KERNMOUNT, type->name, NULL);
1074 		if (IS_ERR(mnt))
1075 			return PTR_ERR(mnt);
1076 		spin_lock(&pin_fs_lock);
1077 		if (!*mount) {
1078 			*mount = mnt;
1079 			mnt = NULL;
1080 		}
1081 	}
1082 	++*count;
1083 	spin_unlock(&pin_fs_lock);
1084 	mntput(mnt);
1085 	return 0;
1086 }
1087 EXPORT_SYMBOL(simple_pin_fs);
1088 
1089 void simple_release_fs(struct vfsmount **mount, int *count)
1090 {
1091 	struct vfsmount *mnt = NULL;
1092 	spin_lock(&pin_fs_lock);
1093 	if (!--*count) {
1094 		mnt = *mount;
1095 		*mount = NULL;
1096 	}
1097 	spin_unlock(&pin_fs_lock);
1098 	mntput(mnt);
1099 }
1100 EXPORT_SYMBOL(simple_release_fs);
1101 
1102 /**
1103  * simple_read_from_buffer - copy data from the buffer to user space
1104  * @to: the user space buffer to read to
1105  * @count: the maximum number of bytes to read
1106  * @ppos: the current position in the buffer
1107  * @from: the buffer to read from
1108  * @available: the size of the buffer
1109  *
1110  * The simple_read_from_buffer() function reads up to @count bytes from the
1111  * buffer @from at offset @ppos into the user space address starting at @to.
1112  *
1113  * On success, the number of bytes read is returned and the offset @ppos is
1114  * advanced by this number, or negative value is returned on error.
1115  **/
1116 ssize_t simple_read_from_buffer(void __user *to, size_t count, loff_t *ppos,
1117 				const void *from, size_t available)
1118 {
1119 	loff_t pos = *ppos;
1120 	size_t ret;
1121 
1122 	if (pos < 0)
1123 		return -EINVAL;
1124 	if (pos >= available || !count)
1125 		return 0;
1126 	if (count > available - pos)
1127 		count = available - pos;
1128 	ret = copy_to_user(to, from + pos, count);
1129 	if (ret == count)
1130 		return -EFAULT;
1131 	count -= ret;
1132 	*ppos = pos + count;
1133 	return count;
1134 }
1135 EXPORT_SYMBOL(simple_read_from_buffer);
1136 
1137 /**
1138  * simple_write_to_buffer - copy data from user space to the buffer
1139  * @to: the buffer to write to
1140  * @available: the size of the buffer
1141  * @ppos: the current position in the buffer
1142  * @from: the user space buffer to read from
1143  * @count: the maximum number of bytes to read
1144  *
1145  * The simple_write_to_buffer() function reads up to @count bytes from the user
1146  * space address starting at @from into the buffer @to at offset @ppos.
1147  *
1148  * On success, the number of bytes written is returned and the offset @ppos is
1149  * advanced by this number, or negative value is returned on error.
1150  **/
1151 ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos,
1152 		const void __user *from, size_t count)
1153 {
1154 	loff_t pos = *ppos;
1155 	size_t res;
1156 
1157 	if (pos < 0)
1158 		return -EINVAL;
1159 	if (pos >= available || !count)
1160 		return 0;
1161 	if (count > available - pos)
1162 		count = available - pos;
1163 	res = copy_from_user(to + pos, from, count);
1164 	if (res == count)
1165 		return -EFAULT;
1166 	count -= res;
1167 	*ppos = pos + count;
1168 	return count;
1169 }
1170 EXPORT_SYMBOL(simple_write_to_buffer);
1171 
1172 /**
1173  * memory_read_from_buffer - copy data from the buffer
1174  * @to: the kernel space buffer to read to
1175  * @count: the maximum number of bytes to read
1176  * @ppos: the current position in the buffer
1177  * @from: the buffer to read from
1178  * @available: the size of the buffer
1179  *
1180  * The memory_read_from_buffer() function reads up to @count bytes from the
1181  * buffer @from at offset @ppos into the kernel space address starting at @to.
1182  *
1183  * On success, the number of bytes read is returned and the offset @ppos is
1184  * advanced by this number, or negative value is returned on error.
1185  **/
1186 ssize_t memory_read_from_buffer(void *to, size_t count, loff_t *ppos,
1187 				const void *from, size_t available)
1188 {
1189 	loff_t pos = *ppos;
1190 
1191 	if (pos < 0)
1192 		return -EINVAL;
1193 	if (pos >= available)
1194 		return 0;
1195 	if (count > available - pos)
1196 		count = available - pos;
1197 	memcpy(to, from + pos, count);
1198 	*ppos = pos + count;
1199 
1200 	return count;
1201 }
1202 EXPORT_SYMBOL(memory_read_from_buffer);
1203 
1204 /*
1205  * Transaction based IO.
1206  * The file expects a single write which triggers the transaction, and then
1207  * possibly a read which collects the result - which is stored in a
1208  * file-local buffer.
1209  */
1210 
1211 void simple_transaction_set(struct file *file, size_t n)
1212 {
1213 	struct simple_transaction_argresp *ar = file->private_data;
1214 
1215 	BUG_ON(n > SIMPLE_TRANSACTION_LIMIT);
1216 
1217 	/*
1218 	 * The barrier ensures that ar->size will really remain zero until
1219 	 * ar->data is ready for reading.
1220 	 */
1221 	smp_mb();
1222 	ar->size = n;
1223 }
1224 EXPORT_SYMBOL(simple_transaction_set);
1225 
1226 char *simple_transaction_get(struct file *file, const char __user *buf, size_t size)
1227 {
1228 	struct simple_transaction_argresp *ar;
1229 	static DEFINE_SPINLOCK(simple_transaction_lock);
1230 
1231 	if (size > SIMPLE_TRANSACTION_LIMIT - 1)
1232 		return ERR_PTR(-EFBIG);
1233 
1234 	ar = kzalloc(PAGE_SIZE, GFP_KERNEL);
1235 	if (!ar)
1236 		return ERR_PTR(-ENOMEM);
1237 
1238 	spin_lock(&simple_transaction_lock);
1239 
1240 	/* only one write allowed per open */
1241 	if (file->private_data) {
1242 		spin_unlock(&simple_transaction_lock);
1243 		kfree(ar);
1244 		return ERR_PTR(-EBUSY);
1245 	}
1246 
1247 	file->private_data = ar;
1248 
1249 	spin_unlock(&simple_transaction_lock);
1250 
1251 	if (copy_from_user(ar->data, buf, size))
1252 		return ERR_PTR(-EFAULT);
1253 
1254 	return ar->data;
1255 }
1256 EXPORT_SYMBOL(simple_transaction_get);
1257 
1258 ssize_t simple_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos)
1259 {
1260 	struct simple_transaction_argresp *ar = file->private_data;
1261 
1262 	if (!ar)
1263 		return 0;
1264 	return simple_read_from_buffer(buf, size, pos, ar->data, ar->size);
1265 }
1266 EXPORT_SYMBOL(simple_transaction_read);
1267 
1268 int simple_transaction_release(struct inode *inode, struct file *file)
1269 {
1270 	kfree(file->private_data);
1271 	return 0;
1272 }
1273 EXPORT_SYMBOL(simple_transaction_release);
1274 
1275 /* Simple attribute files */
1276 
1277 struct simple_attr {
1278 	int (*get)(void *, u64 *);
1279 	int (*set)(void *, u64);
1280 	char get_buf[24];	/* enough to store a u64 and "\n\0" */
1281 	char set_buf[24];
1282 	void *data;
1283 	const char *fmt;	/* format for read operation */
1284 	struct mutex mutex;	/* protects access to these buffers */
1285 };
1286 
1287 /* simple_attr_open is called by an actual attribute open file operation
1288  * to set the attribute specific access operations. */
1289 int simple_attr_open(struct inode *inode, struct file *file,
1290 		     int (*get)(void *, u64 *), int (*set)(void *, u64),
1291 		     const char *fmt)
1292 {
1293 	struct simple_attr *attr;
1294 
1295 	attr = kzalloc_obj(*attr);
1296 	if (!attr)
1297 		return -ENOMEM;
1298 
1299 	attr->get = get;
1300 	attr->set = set;
1301 	attr->data = inode->i_private;
1302 	attr->fmt = fmt;
1303 	mutex_init(&attr->mutex);
1304 
1305 	file->private_data = attr;
1306 
1307 	return nonseekable_open(inode, file);
1308 }
1309 EXPORT_SYMBOL_GPL(simple_attr_open);
1310 
1311 int simple_attr_release(struct inode *inode, struct file *file)
1312 {
1313 	kfree(file->private_data);
1314 	return 0;
1315 }
1316 EXPORT_SYMBOL_GPL(simple_attr_release);	/* GPL-only?  This?  Really? */
1317 
1318 /* read from the buffer that is filled with the get function */
1319 ssize_t simple_attr_read(struct file *file, char __user *buf,
1320 			 size_t len, loff_t *ppos)
1321 {
1322 	struct simple_attr *attr;
1323 	size_t size;
1324 	ssize_t ret;
1325 
1326 	attr = file->private_data;
1327 
1328 	if (!attr->get)
1329 		return -EACCES;
1330 
1331 	ret = mutex_lock_interruptible(&attr->mutex);
1332 	if (ret)
1333 		return ret;
1334 
1335 	if (*ppos && attr->get_buf[0]) {
1336 		/* continued read */
1337 		size = strlen(attr->get_buf);
1338 	} else {
1339 		/* first read */
1340 		u64 val;
1341 		ret = attr->get(attr->data, &val);
1342 		if (ret)
1343 			goto out;
1344 
1345 		size = scnprintf(attr->get_buf, sizeof(attr->get_buf),
1346 				 attr->fmt, (unsigned long long)val);
1347 	}
1348 
1349 	ret = simple_read_from_buffer(buf, len, ppos, attr->get_buf, size);
1350 out:
1351 	mutex_unlock(&attr->mutex);
1352 	return ret;
1353 }
1354 EXPORT_SYMBOL_GPL(simple_attr_read);
1355 
1356 /* interpret the buffer as a number to call the set function with */
1357 static ssize_t simple_attr_write_xsigned(struct file *file, const char __user *buf,
1358 			  size_t len, loff_t *ppos, bool is_signed)
1359 {
1360 	struct simple_attr *attr;
1361 	unsigned long long val;
1362 	size_t size;
1363 	ssize_t ret;
1364 
1365 	attr = file->private_data;
1366 	if (!attr->set)
1367 		return -EACCES;
1368 
1369 	ret = mutex_lock_interruptible(&attr->mutex);
1370 	if (ret)
1371 		return ret;
1372 
1373 	ret = -EFAULT;
1374 	size = min(sizeof(attr->set_buf) - 1, len);
1375 	if (copy_from_user(attr->set_buf, buf, size))
1376 		goto out;
1377 
1378 	attr->set_buf[size] = '\0';
1379 	if (is_signed)
1380 		ret = kstrtoll(attr->set_buf, 0, &val);
1381 	else
1382 		ret = kstrtoull(attr->set_buf, 0, &val);
1383 	if (ret)
1384 		goto out;
1385 	ret = attr->set(attr->data, val);
1386 	if (ret == 0)
1387 		ret = len; /* on success, claim we got the whole input */
1388 out:
1389 	mutex_unlock(&attr->mutex);
1390 	return ret;
1391 }
1392 
1393 ssize_t simple_attr_write(struct file *file, const char __user *buf,
1394 			  size_t len, loff_t *ppos)
1395 {
1396 	return simple_attr_write_xsigned(file, buf, len, ppos, false);
1397 }
1398 EXPORT_SYMBOL_GPL(simple_attr_write);
1399 
1400 ssize_t simple_attr_write_signed(struct file *file, const char __user *buf,
1401 			  size_t len, loff_t *ppos)
1402 {
1403 	return simple_attr_write_xsigned(file, buf, len, ppos, true);
1404 }
1405 EXPORT_SYMBOL_GPL(simple_attr_write_signed);
1406 
1407 /**
1408  * generic_encode_ino32_fh - generic export_operations->encode_fh function
1409  * @inode:   the object to encode
1410  * @fh:      where to store the file handle fragment
1411  * @max_len: maximum length to store there (in 4 byte units)
1412  * @parent:  parent directory inode, if wanted
1413  *
1414  * This generic encode_fh function assumes that the 32 inode number
1415  * is suitable for locating an inode, and that the generation number
1416  * can be used to check that it is still valid.  It places them in the
1417  * filehandle fragment where export_decode_fh expects to find them.
1418  */
1419 int generic_encode_ino32_fh(struct inode *inode, __u32 *fh, int *max_len,
1420 			    struct inode *parent)
1421 {
1422 	struct fid *fid = (void *)fh;
1423 	int len = *max_len;
1424 	int type = FILEID_INO32_GEN;
1425 
1426 	if (parent && (len < 4)) {
1427 		*max_len = 4;
1428 		return FILEID_INVALID;
1429 	} else if (len < 2) {
1430 		*max_len = 2;
1431 		return FILEID_INVALID;
1432 	}
1433 
1434 	len = 2;
1435 	fid->i32.ino = inode->i_ino;
1436 	fid->i32.gen = inode->i_generation;
1437 	if (parent) {
1438 		fid->i32.parent_ino = parent->i_ino;
1439 		fid->i32.parent_gen = parent->i_generation;
1440 		len = 4;
1441 		type = FILEID_INO32_GEN_PARENT;
1442 	}
1443 	*max_len = len;
1444 	return type;
1445 }
1446 EXPORT_SYMBOL_GPL(generic_encode_ino32_fh);
1447 
1448 /**
1449  * generic_fh_to_dentry - generic helper for the fh_to_dentry export operation
1450  * @sb:		filesystem to do the file handle conversion on
1451  * @fid:	file handle to convert
1452  * @fh_len:	length of the file handle in bytes
1453  * @fh_type:	type of file handle
1454  * @get_inode:	filesystem callback to retrieve inode
1455  *
1456  * This function decodes @fid as long as it has one of the well-known
1457  * Linux filehandle types and calls @get_inode on it to retrieve the
1458  * inode for the object specified in the file handle.
1459  */
1460 struct dentry *generic_fh_to_dentry(struct super_block *sb, struct fid *fid,
1461 		int fh_len, int fh_type, struct inode *(*get_inode)
1462 			(struct super_block *sb, u64 ino, u32 gen))
1463 {
1464 	struct inode *inode = NULL;
1465 
1466 	if (fh_len < 2)
1467 		return NULL;
1468 
1469 	switch (fh_type) {
1470 	case FILEID_INO32_GEN:
1471 	case FILEID_INO32_GEN_PARENT:
1472 		inode = get_inode(sb, fid->i32.ino, fid->i32.gen);
1473 		break;
1474 	}
1475 
1476 	return d_obtain_alias(inode);
1477 }
1478 EXPORT_SYMBOL_GPL(generic_fh_to_dentry);
1479 
1480 /**
1481  * generic_fh_to_parent - generic helper for the fh_to_parent export operation
1482  * @sb:		filesystem to do the file handle conversion on
1483  * @fid:	file handle to convert
1484  * @fh_len:	length of the file handle in bytes
1485  * @fh_type:	type of file handle
1486  * @get_inode:	filesystem callback to retrieve inode
1487  *
1488  * This function decodes @fid as long as it has one of the well-known
1489  * Linux filehandle types and calls @get_inode on it to retrieve the
1490  * inode for the _parent_ object specified in the file handle if it
1491  * is specified in the file handle, or NULL otherwise.
1492  */
1493 struct dentry *generic_fh_to_parent(struct super_block *sb, struct fid *fid,
1494 		int fh_len, int fh_type, struct inode *(*get_inode)
1495 			(struct super_block *sb, u64 ino, u32 gen))
1496 {
1497 	struct inode *inode = NULL;
1498 
1499 	if (fh_len <= 2)
1500 		return NULL;
1501 
1502 	switch (fh_type) {
1503 	case FILEID_INO32_GEN_PARENT:
1504 		inode = get_inode(sb, fid->i32.parent_ino,
1505 				  (fh_len > 3 ? fid->i32.parent_gen : 0));
1506 		break;
1507 	}
1508 
1509 	return d_obtain_alias(inode);
1510 }
1511 EXPORT_SYMBOL_GPL(generic_fh_to_parent);
1512 
1513 /**
1514  * simple_fsync_noflush - generic fsync implementation for simple filesystems
1515  *
1516  * @file:	file to synchronize
1517  * @start:	start offset in bytes
1518  * @end:	end offset in bytes (inclusive)
1519  * @datasync:	only synchronize essential metadata if true
1520  *
1521  * This function is an fsync handler for simple filesystems. It writes out
1522  * dirty data, inode (if dirty), but does not issue a cache flush.
1523  */
1524 int simple_fsync_noflush(struct file *file, loff_t start, loff_t end,
1525 			 int datasync)
1526 {
1527 	struct inode *inode = file->f_mapping->host;
1528 	int err;
1529 	int ret = 0;
1530 
1531 	err = file_write_and_wait_range(file, start, end);
1532 	if (err)
1533 		return err;
1534 
1535 	if (!(inode_state_read_once(inode) &
1536 			(I_DIRTY_ALL | I_SYNC | I_METADATA_WRITEBACK)))
1537 		goto out;
1538 	if (datasync &&
1539 	    !(inode_state_read_once(inode) &
1540 			(I_DIRTY_DATASYNC | I_SYNC | I_METADATA_WRITEBACK)))
1541 		goto out;
1542 
1543 	ret = sync_inode_metadata(inode, 1);
1544 out:
1545 	/* check and advance again to catch errors after syncing out buffers */
1546 	err = file_check_and_advance_wb_err(file);
1547 	if (ret == 0)
1548 		ret = err;
1549 	return ret;
1550 }
1551 EXPORT_SYMBOL(simple_fsync_noflush);
1552 
1553 /**
1554  * simple_fsync - fsync implementation for simple filesystems with flush
1555  * @file:	file to synchronize
1556  * @start:	start offset in bytes
1557  * @end:	end offset in bytes (inclusive)
1558  * @datasync:	only synchronize essential metadata if true
1559  *
1560  * This function is an fsync handler for simple filesystems. It writes out
1561  * dirty data, inode (if dirty), and issues a cache flush.
1562  */
1563 int simple_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1564 {
1565 	struct inode *inode = file->f_mapping->host;
1566 	int err;
1567 
1568 	err = simple_fsync_noflush(file, start, end, datasync);
1569 	if (err)
1570 		return err;
1571 	return blkdev_issue_flush(inode->i_sb->s_bdev);
1572 }
1573 EXPORT_SYMBOL(simple_fsync);
1574 
1575 /**
1576  * generic_check_addressable - Check addressability of file system
1577  * @blocksize_bits:	log of file system block size
1578  * @num_blocks:		number of blocks in file system
1579  *
1580  * Determine whether a file system with @num_blocks blocks (and a
1581  * block size of 2**@blocksize_bits) is addressable by the sector_t
1582  * and page cache of the system.  Return 0 if so and -EFBIG otherwise.
1583  */
1584 int generic_check_addressable(unsigned blocksize_bits, u64 num_blocks)
1585 {
1586 	u64 last_fs_block = num_blocks - 1;
1587 	u64 last_fs_page, max_bytes;
1588 
1589 	if (check_shl_overflow(num_blocks, blocksize_bits, &max_bytes))
1590 		return -EFBIG;
1591 
1592 	last_fs_page = (max_bytes >> PAGE_SHIFT) - 1;
1593 
1594 	if (unlikely(num_blocks == 0))
1595 		return 0;
1596 
1597 	if (blocksize_bits < 9)
1598 		return -EINVAL;
1599 
1600 	if ((last_fs_block > (sector_t)(~0ULL) >> (blocksize_bits - 9)) ||
1601 	    (last_fs_page > (pgoff_t)(~0ULL))) {
1602 		return -EFBIG;
1603 	}
1604 	return 0;
1605 }
1606 EXPORT_SYMBOL(generic_check_addressable);
1607 
1608 /*
1609  * No-op implementation of ->fsync for in-memory filesystems.
1610  */
1611 int noop_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1612 {
1613 	return 0;
1614 }
1615 EXPORT_SYMBOL(noop_fsync);
1616 
1617 ssize_t noop_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
1618 {
1619 	/*
1620 	 * iomap based filesystems support direct I/O without need for
1621 	 * this callback. However, it still needs to be set in
1622 	 * inode->a_ops so that open/fcntl know that direct I/O is
1623 	 * generally supported.
1624 	 */
1625 	return -EINVAL;
1626 }
1627 EXPORT_SYMBOL_GPL(noop_direct_IO);
1628 
1629 /* Because kfree isn't assignment-compatible with void(void*) ;-/ */
1630 void kfree_link(void *p)
1631 {
1632 	kfree(p);
1633 }
1634 EXPORT_SYMBOL(kfree_link);
1635 
1636 struct inode *alloc_anon_inode(struct super_block *s)
1637 {
1638 	static const struct address_space_operations anon_aops = {
1639 		.dirty_folio	= noop_dirty_folio,
1640 	};
1641 	struct inode *inode = new_inode_pseudo(s);
1642 
1643 	if (!inode)
1644 		return ERR_PTR(-ENOMEM);
1645 
1646 	inode->i_ino = get_next_ino();
1647 	inode->i_mapping->a_ops = &anon_aops;
1648 
1649 	/*
1650 	 * Mark the inode dirty from the very beginning,
1651 	 * that way it will never be moved to the dirty
1652 	 * list because mark_inode_dirty() will think
1653 	 * that it already _is_ on the dirty list.
1654 	 */
1655 	inode_state_assign_raw(inode, I_DIRTY);
1656 	/*
1657 	 * Historically anonymous inodes don't have a type at all and
1658 	 * userspace has come to rely on this.
1659 	 */
1660 	inode->i_mode = S_IRUSR | S_IWUSR;
1661 	inode->i_uid = current_fsuid();
1662 	inode->i_gid = current_fsgid();
1663 	inode->i_flags |= S_PRIVATE | S_ANON_INODE;
1664 	simple_inode_init_ts(inode);
1665 	return inode;
1666 }
1667 EXPORT_SYMBOL(alloc_anon_inode);
1668 
1669 /**
1670  * simple_get_link - generic helper to get the target of "fast" symlinks
1671  * @dentry: not used here
1672  * @inode: the symlink inode
1673  * @done: not used here
1674  *
1675  * Generic helper for filesystems to use for symlink inodes where a pointer to
1676  * the symlink target is stored in ->i_link.  NOTE: this isn't normally called,
1677  * since as an optimization the path lookup code uses any non-NULL ->i_link
1678  * directly, without calling ->get_link().  But ->get_link() still must be set,
1679  * to mark the inode_operations as being for a symlink.
1680  *
1681  * Return: the symlink target
1682  */
1683 const char *simple_get_link(struct dentry *dentry, struct inode *inode,
1684 			    struct delayed_call *done)
1685 {
1686 	return inode->i_link;
1687 }
1688 EXPORT_SYMBOL(simple_get_link);
1689 
1690 const struct inode_operations simple_symlink_inode_operations = {
1691 	.get_link = simple_get_link,
1692 };
1693 EXPORT_SYMBOL(simple_symlink_inode_operations);
1694 
1695 /*
1696  * Operations for a permanently empty directory.
1697  */
1698 static struct dentry *empty_dir_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1699 {
1700 	return ERR_PTR(-ENOENT);
1701 }
1702 
1703 static int empty_dir_setattr(const struct mnt_idmap *idmap,
1704 			     struct dentry *dentry, struct iattr *attr)
1705 {
1706 	return -EPERM;
1707 }
1708 
1709 static ssize_t empty_dir_listxattr(struct dentry *dentry, char *list, size_t size)
1710 {
1711 	return -EOPNOTSUPP;
1712 }
1713 
1714 static const struct inode_operations empty_dir_inode_operations = {
1715 	.lookup		= empty_dir_lookup,
1716 	.setattr	= empty_dir_setattr,
1717 	.listxattr	= empty_dir_listxattr,
1718 };
1719 
1720 static loff_t empty_dir_llseek(struct file *file, loff_t offset, int whence)
1721 {
1722 	/* An empty directory has two entries . and .. at offsets 0 and 1 */
1723 	return generic_file_llseek_size(file, offset, whence, 2, 2);
1724 }
1725 
1726 static int empty_dir_readdir(struct file *file, struct dir_context *ctx)
1727 {
1728 	dir_emit_dots(file, ctx);
1729 	return 0;
1730 }
1731 
1732 static const struct file_operations empty_dir_operations = {
1733 	.llseek		= empty_dir_llseek,
1734 	.read		= generic_read_dir,
1735 	.iterate_shared	= empty_dir_readdir,
1736 	.fsync		= noop_fsync,
1737 };
1738 
1739 
1740 void make_empty_dir_inode(struct inode *inode)
1741 {
1742 	set_nlink(inode, 2);
1743 	inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
1744 	inode->i_uid = GLOBAL_ROOT_UID;
1745 	inode->i_gid = GLOBAL_ROOT_GID;
1746 	inode->i_rdev = 0;
1747 	inode->i_size = 0;
1748 	inode->i_blkbits = PAGE_SHIFT;
1749 	inode->i_blocks = 0;
1750 
1751 	inode->i_op = &empty_dir_inode_operations;
1752 	inode->i_opflags &= ~IOP_XATTR;
1753 	inode->i_fop = &empty_dir_operations;
1754 }
1755 
1756 bool is_empty_dir_inode(struct inode *inode)
1757 {
1758 	return (inode->i_fop == &empty_dir_operations) &&
1759 		(inode->i_op == &empty_dir_inode_operations);
1760 }
1761 
1762 #if IS_ENABLED(CONFIG_UNICODE)
1763 /**
1764  * generic_ci_d_compare - generic d_compare implementation for casefolding filesystems
1765  * @dentry:	dentry whose name we are checking against
1766  * @len:	len of name of dentry
1767  * @str:	str pointer to name of dentry
1768  * @name:	Name to compare against
1769  *
1770  * Return: 0 if names match, 1 if mismatch, or -ERRNO
1771  */
1772 int generic_ci_d_compare(const struct dentry *dentry, unsigned int len,
1773 			 const char *str, const struct qstr *name)
1774 {
1775 	const struct dentry *parent;
1776 	const struct inode *dir;
1777 	union shortname_store strbuf;
1778 	struct qstr qstr;
1779 
1780 	/*
1781 	 * Attempt a case-sensitive match first. It is cheaper and
1782 	 * should cover most lookups, including all the sane
1783 	 * applications that expect a case-sensitive filesystem.
1784 	 *
1785 	 * This comparison is safe under RCU because the caller
1786 	 * guarantees the consistency between str and len. See
1787 	 * __d_lookup_rcu_op_compare() for details.
1788 	 */
1789 	if (len == name->len && !memcmp(str, name->name, len))
1790 		return 0;
1791 
1792 	parent = READ_ONCE(dentry->d_parent);
1793 	dir = READ_ONCE(parent->d_inode);
1794 	if (!dir || !IS_CASEFOLDED(dir))
1795 		return 1;
1796 
1797 	qstr.len = len;
1798 	qstr.name = str;
1799 	/*
1800 	 * If the dentry name is stored in-line, then it may be concurrently
1801 	 * modified by a rename.  If this happens, the VFS will eventually retry
1802 	 * the lookup, so it doesn't matter what ->d_compare() returns.
1803 	 * However, it's unsafe to call utf8_strncasecmp() with an unstable
1804 	 * string.  Therefore, we have to copy the name into a temporary buffer.
1805 	 * As above, len is guaranteed to match str, so the shortname case
1806 	 * is exactly when str points to ->d_shortname.
1807 	 */
1808 	if (qstr.name == dentry->d_shortname.string) {
1809 		strbuf = dentry->d_shortname; // NUL is guaranteed to be in there
1810 		qstr.name = strbuf.string;
1811 		/* prevent compiler from optimizing out the temporary buffer */
1812 		barrier();
1813 	}
1814 
1815 	return utf8_strncasecmp(dentry->d_sb->s_encoding, name, &qstr);
1816 }
1817 EXPORT_SYMBOL(generic_ci_d_compare);
1818 
1819 /**
1820  * generic_ci_d_hash - generic d_hash implementation for casefolding filesystems
1821  * @dentry:	dentry of the parent directory
1822  * @str:	qstr of name whose hash we should fill in
1823  *
1824  * Return: 0 if hash was successful or unchanged, and -EINVAL on error
1825  */
1826 int generic_ci_d_hash(const struct dentry *dentry, struct qstr *str)
1827 {
1828 	const struct inode *dir = READ_ONCE(dentry->d_inode);
1829 	struct super_block *sb = dentry->d_sb;
1830 	const struct unicode_map *um = sb->s_encoding;
1831 	int ret;
1832 
1833 	if (!dir || !IS_CASEFOLDED(dir))
1834 		return 0;
1835 
1836 	ret = utf8_casefold_hash(um, dentry, str);
1837 	if (ret < 0 && sb_has_strict_encoding(sb))
1838 		return -EINVAL;
1839 	return 0;
1840 }
1841 EXPORT_SYMBOL(generic_ci_d_hash);
1842 
1843 static const struct dentry_operations generic_ci_dentry_ops = {
1844 	.d_hash = generic_ci_d_hash,
1845 	.d_compare = generic_ci_d_compare,
1846 #ifdef CONFIG_FS_ENCRYPTION
1847 	.d_revalidate = fscrypt_d_revalidate,
1848 #endif
1849 };
1850 
1851 /**
1852  * generic_ci_match() - Match a name (case-insensitively) with a dirent.
1853  * This is a filesystem helper for comparison with directory entries.
1854  * generic_ci_d_compare should be used in VFS' ->d_compare instead.
1855  *
1856  * @parent: Inode of the parent of the dirent under comparison
1857  * @name: name under lookup.
1858  * @folded_name: Optional pre-folded name under lookup
1859  * @de_name: Dirent name.
1860  * @de_name_len: dirent name length.
1861  *
1862  * Test whether a case-insensitive directory entry matches the filename
1863  * being searched.  If @folded_name is provided, it is used instead of
1864  * recalculating the casefold of @name.
1865  *
1866  * Return: > 0 if the directory entry matches, 0 if it doesn't match, or
1867  * < 0 on error.
1868  */
1869 int generic_ci_match(const struct inode *parent,
1870 		     const struct qstr *name,
1871 		     const struct qstr *folded_name,
1872 		     const u8 *de_name, u32 de_name_len)
1873 {
1874 	const struct super_block *sb = parent->i_sb;
1875 	const struct unicode_map *um = sb->s_encoding;
1876 	struct fscrypt_str decrypted_name = FSTR_INIT(NULL, de_name_len);
1877 	struct qstr dirent = QSTR_INIT(de_name, de_name_len);
1878 	int res = 0;
1879 
1880 	if (IS_ENCRYPTED(parent)) {
1881 		const struct fscrypt_str encrypted_name =
1882 			FSTR_INIT((u8 *) de_name, de_name_len);
1883 
1884 		if (WARN_ON_ONCE(!fscrypt_has_encryption_key(parent)))
1885 			return -EINVAL;
1886 
1887 		decrypted_name.name = kmalloc(de_name_len, GFP_KERNEL);
1888 		if (!decrypted_name.name)
1889 			return -ENOMEM;
1890 		res = fscrypt_fname_disk_to_usr(parent, 0, 0, &encrypted_name,
1891 						&decrypted_name);
1892 		if (res < 0) {
1893 			kfree(decrypted_name.name);
1894 			return res;
1895 		}
1896 		dirent.name = decrypted_name.name;
1897 		dirent.len = decrypted_name.len;
1898 	}
1899 
1900 	/*
1901 	 * Attempt a case-sensitive match first. It is cheaper and
1902 	 * should cover most lookups, including all the sane
1903 	 * applications that expect a case-sensitive filesystem.
1904 	 */
1905 
1906 	if (dirent.len == name->len &&
1907 	    !memcmp(name->name, dirent.name, dirent.len))
1908 		goto out;
1909 
1910 	if (folded_name->name)
1911 		res = utf8_strncasecmp_folded(um, folded_name, &dirent);
1912 	else
1913 		res = utf8_strncasecmp(um, name, &dirent);
1914 
1915 out:
1916 	kfree(decrypted_name.name);
1917 	if (res < 0 && sb_has_strict_encoding(sb)) {
1918 		pr_err_ratelimited("Directory contains filename that is invalid UTF-8");
1919 		return 0;
1920 	}
1921 	return !res;
1922 }
1923 EXPORT_SYMBOL(generic_ci_match);
1924 #endif
1925 
1926 #ifdef CONFIG_FS_ENCRYPTION
1927 static const struct dentry_operations generic_encrypted_dentry_ops = {
1928 	.d_revalidate = fscrypt_d_revalidate,
1929 };
1930 #endif
1931 
1932 /**
1933  * generic_set_sb_d_ops - helper for choosing the set of
1934  * filesystem-wide dentry operations for the enabled features
1935  * @sb: superblock to be configured
1936  *
1937  * Filesystems supporting casefolding and/or fscrypt can call this
1938  * helper at mount-time to configure default dentry_operations to the
1939  * best set of dentry operations required for the enabled features.
1940  * The helper must be called after these have been configured, but
1941  * before the root dentry is created.
1942  */
1943 void generic_set_sb_d_ops(struct super_block *sb)
1944 {
1945 #if IS_ENABLED(CONFIG_UNICODE)
1946 	if (sb->s_encoding) {
1947 		set_default_d_op(sb, &generic_ci_dentry_ops);
1948 		return;
1949 	}
1950 #endif
1951 #ifdef CONFIG_FS_ENCRYPTION
1952 	if (sb->s_cop) {
1953 		set_default_d_op(sb, &generic_encrypted_dentry_ops);
1954 		return;
1955 	}
1956 #endif
1957 }
1958 EXPORT_SYMBOL(generic_set_sb_d_ops);
1959 
1960 /**
1961  * inode_maybe_inc_iversion - increments i_version
1962  * @inode: inode with the i_version that should be updated
1963  * @force: increment the counter even if it's not necessary?
1964  *
1965  * Every time the inode is modified, the i_version field must be seen to have
1966  * changed by any observer.
1967  *
1968  * If "force" is set or the QUERIED flag is set, then ensure that we increment
1969  * the value, and clear the queried flag.
1970  *
1971  * In the common case where neither is set, then we can return "false" without
1972  * updating i_version.
1973  *
1974  * If this function returns false, and no other metadata has changed, then we
1975  * can avoid logging the metadata.
1976  */
1977 bool inode_maybe_inc_iversion(struct inode *inode, bool force)
1978 {
1979 	u64 cur, new;
1980 
1981 	/*
1982 	 * The i_version field is not strictly ordered with any other inode
1983 	 * information, but the legacy inode_inc_iversion code used a spinlock
1984 	 * to serialize increments.
1985 	 *
1986 	 * We add a full memory barrier to ensure that any de facto ordering
1987 	 * with other state is preserved (either implicitly coming from cmpxchg
1988 	 * or explicitly from smp_mb if we don't know upfront if we will execute
1989 	 * the former).
1990 	 *
1991 	 * These barriers pair with inode_query_iversion().
1992 	 */
1993 	cur = inode_peek_iversion_raw(inode);
1994 	if (!force && !(cur & I_VERSION_QUERIED)) {
1995 		smp_mb();
1996 		cur = inode_peek_iversion_raw(inode);
1997 	}
1998 
1999 	do {
2000 		/* If flag is clear then we needn't do anything */
2001 		if (!force && !(cur & I_VERSION_QUERIED))
2002 			return false;
2003 
2004 		/* Since lowest bit is flag, add 2 to avoid it */
2005 		new = (cur & ~I_VERSION_QUERIED) + I_VERSION_INCREMENT;
2006 	} while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
2007 	return true;
2008 }
2009 EXPORT_SYMBOL(inode_maybe_inc_iversion);
2010 
2011 /**
2012  * inode_query_iversion - read i_version for later use
2013  * @inode: inode from which i_version should be read
2014  *
2015  * Read the inode i_version counter. This should be used by callers that wish
2016  * to store the returned i_version for later comparison. This will guarantee
2017  * that a later query of the i_version will result in a different value if
2018  * anything has changed.
2019  *
2020  * In this implementation, we fetch the current value, set the QUERIED flag and
2021  * then try to swap it into place with a cmpxchg, if it wasn't already set. If
2022  * that fails, we try again with the newly fetched value from the cmpxchg.
2023  */
2024 u64 inode_query_iversion(struct inode *inode)
2025 {
2026 	u64 cur, new;
2027 	bool fenced = false;
2028 
2029 	/*
2030 	 * Memory barriers (implicit in cmpxchg, explicit in smp_mb) pair with
2031 	 * inode_maybe_inc_iversion(), see that routine for more details.
2032 	 */
2033 	cur = inode_peek_iversion_raw(inode);
2034 	do {
2035 		/* If flag is already set, then no need to swap */
2036 		if (cur & I_VERSION_QUERIED) {
2037 			if (!fenced)
2038 				smp_mb();
2039 			break;
2040 		}
2041 
2042 		fenced = true;
2043 		new = cur | I_VERSION_QUERIED;
2044 	} while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
2045 	return cur >> I_VERSION_QUERIED_SHIFT;
2046 }
2047 EXPORT_SYMBOL(inode_query_iversion);
2048 
2049 ssize_t direct_write_fallback(struct kiocb *iocb, struct iov_iter *iter,
2050 		ssize_t direct_written, ssize_t buffered_written)
2051 {
2052 	struct address_space *mapping = iocb->ki_filp->f_mapping;
2053 	loff_t pos = iocb->ki_pos - buffered_written;
2054 	loff_t end = iocb->ki_pos - 1;
2055 	int err;
2056 
2057 	/*
2058 	 * If the buffered write fallback returned an error, we want to return
2059 	 * the number of bytes which were written by direct I/O, or the error
2060 	 * code if that was zero.
2061 	 *
2062 	 * Note that this differs from normal direct-io semantics, which will
2063 	 * return -EFOO even if some bytes were written.
2064 	 */
2065 	if (unlikely(buffered_written < 0)) {
2066 		if (direct_written)
2067 			return direct_written;
2068 		return buffered_written;
2069 	}
2070 
2071 	/*
2072 	 * We need to ensure that the page cache pages are written to disk and
2073 	 * invalidated to preserve the expected O_DIRECT semantics.
2074 	 */
2075 	err = filemap_write_and_wait_range(mapping, pos, end);
2076 	if (err < 0) {
2077 		/*
2078 		 * We don't know how much we wrote, so just return the number of
2079 		 * bytes which were direct-written
2080 		 */
2081 		iocb->ki_pos -= buffered_written;
2082 		if (direct_written)
2083 			return direct_written;
2084 		return err;
2085 	}
2086 	invalidate_mapping_pages(mapping, pos >> PAGE_SHIFT, end >> PAGE_SHIFT);
2087 	return direct_written + buffered_written;
2088 }
2089 EXPORT_SYMBOL_GPL(direct_write_fallback);
2090 
2091 /**
2092  * simple_inode_init_ts - initialize the timestamps for a new inode
2093  * @inode: inode to be initialized
2094  *
2095  * When a new inode is created, most filesystems set the timestamps to the
2096  * current time. Add a helper to do this.
2097  */
2098 struct timespec64 simple_inode_init_ts(struct inode *inode)
2099 {
2100 	struct timespec64 ts = inode_set_ctime_current(inode);
2101 
2102 	inode_set_atime_to_ts(inode, ts);
2103 	inode_set_mtime_to_ts(inode, ts);
2104 	return ts;
2105 }
2106 EXPORT_SYMBOL(simple_inode_init_ts);
2107 
2108 struct dentry *stashed_dentry_get(struct dentry **stashed)
2109 {
2110 	struct dentry *dentry;
2111 
2112 	guard(rcu)();
2113 	dentry = rcu_dereference(*stashed);
2114 	if (!dentry)
2115 		return NULL;
2116 	if (IS_ERR(dentry))
2117 		return dentry;
2118 	if (!lockref_get_not_dead(&dentry->d_lockref))
2119 		return NULL;
2120 	return dentry;
2121 }
2122 
2123 static struct dentry *prepare_anon_dentry(struct dentry **stashed,
2124 					  struct super_block *sb,
2125 					  void *data)
2126 {
2127 	struct dentry *dentry;
2128 	struct inode *inode;
2129 	const struct stashed_operations *sops = sb->s_fs_info;
2130 	int ret;
2131 
2132 	inode = new_inode_pseudo(sb);
2133 	if (!inode) {
2134 		sops->put_data(data);
2135 		return ERR_PTR(-ENOMEM);
2136 	}
2137 
2138 	inode->i_flags |= S_IMMUTABLE;
2139 	inode->i_mode = S_IFREG;
2140 	simple_inode_init_ts(inode);
2141 
2142 	ret = sops->init_inode(inode, data);
2143 	if (ret < 0) {
2144 		iput(inode);
2145 		return ERR_PTR(ret);
2146 	}
2147 
2148 	/* Notice when this is changed. */
2149 	WARN_ON_ONCE(!S_ISREG(inode->i_mode));
2150 
2151 	dentry = d_alloc_anon(sb);
2152 	if (!dentry) {
2153 		iput(inode);
2154 		return ERR_PTR(-ENOMEM);
2155 	}
2156 
2157 	/* Store address of location where dentry's supposed to be stashed. */
2158 	dentry->d_fsdata = stashed;
2159 
2160 	/* @data is now owned by the fs */
2161 	d_instantiate(dentry, inode);
2162 	return dentry;
2163 }
2164 
2165 struct dentry *stash_dentry(struct dentry **stashed, struct dentry *dentry)
2166 {
2167 	guard(rcu)();
2168 	for (;;) {
2169 		struct dentry *old;
2170 
2171 		/* Assume any old dentry was cleared out. */
2172 		old = cmpxchg(stashed, NULL, dentry);
2173 		if (likely(!old))
2174 			return dentry;
2175 
2176 		/* Check if somebody else installed a reusable dentry. */
2177 		if (lockref_get_not_dead(&old->d_lockref))
2178 			return old;
2179 
2180 		/* There's an old dead dentry there, try to take it over. */
2181 		if (likely(try_cmpxchg(stashed, &old, dentry)))
2182 			return dentry;
2183 	}
2184 }
2185 
2186 /**
2187  * path_from_stashed - create path from stashed or new dentry
2188  * @stashed:    where to retrieve or stash dentry
2189  * @mnt:        mnt of the filesystems to use
2190  * @data:       data to store in inode->i_private
2191  * @path:       path to create
2192  *
2193  * The function tries to retrieve a stashed dentry from @stashed. If the dentry
2194  * is still valid then it will be reused. If the dentry isn't able the function
2195  * will allocate a new dentry and inode. It will then check again whether it
2196  * can reuse an existing dentry in case one has been added in the meantime or
2197  * update @stashed with the newly added dentry.
2198  *
2199  * Special-purpose helper for nsfs and pidfs.
2200  *
2201  * Return: On success zero and on failure a negative error is returned.
2202  */
2203 int path_from_stashed(struct dentry **stashed, struct vfsmount *mnt, void *data,
2204 		      struct path *path)
2205 {
2206 	struct dentry *dentry, *res;
2207 	const struct stashed_operations *sops = mnt->mnt_sb->s_fs_info;
2208 
2209 	/* See if dentry can be reused. */
2210 	res = stashed_dentry_get(stashed);
2211 	if (IS_ERR(res))
2212 		return PTR_ERR(res);
2213 	if (res) {
2214 		sops->put_data(data);
2215 		goto make_path;
2216 	}
2217 
2218 	/* Allocate a new dentry. */
2219 	dentry = prepare_anon_dentry(stashed, mnt->mnt_sb, data);
2220 	if (IS_ERR(dentry))
2221 		return PTR_ERR(dentry);
2222 
2223 	/* Added a new dentry. @data is now owned by the filesystem. */
2224 	if (sops->stash_dentry)
2225 		res = sops->stash_dentry(stashed, dentry);
2226 	else
2227 		res = stash_dentry(stashed, dentry);
2228 	if (IS_ERR(res)) {
2229 		dput(dentry);
2230 		return PTR_ERR(res);
2231 	}
2232 	if (res != dentry)
2233 		dput(dentry);
2234 
2235 make_path:
2236 	path->dentry = res;
2237 	path->mnt = mntget(mnt);
2238 	VFS_WARN_ON_ONCE(path->dentry->d_fsdata != stashed);
2239 	VFS_WARN_ON_ONCE(d_inode(path->dentry)->i_private != data);
2240 	return 0;
2241 }
2242 
2243 void stashed_dentry_prune(struct dentry *dentry)
2244 {
2245 	struct dentry **stashed = dentry->d_fsdata;
2246 	struct inode *inode = d_inode(dentry);
2247 
2248 	if (WARN_ON_ONCE(!stashed))
2249 		return;
2250 
2251 	if (!inode)
2252 		return;
2253 
2254 	/*
2255 	 * Only replace our own @dentry as someone else might've
2256 	 * already cleared out @dentry and stashed their own
2257 	 * dentry in there.
2258 	 */
2259 	cmpxchg(stashed, dentry, NULL);
2260 }
2261 
2262 /**
2263  * simple_start_creating - prepare to create a given name
2264  * @parent: directory in which to prepare to create the name
2265  * @name:   the name to be created
2266  *
2267  * Required lock is taken and a lookup in performed prior to creating an
2268  * object in a directory.  No permission checking is performed.
2269  *
2270  * Returns: a negative dentry on which vfs_create() or similar may
2271  *  be attempted, or an error.
2272  */
2273 struct dentry *simple_start_creating(struct dentry *parent, const char *name)
2274 {
2275 	struct qstr qname = QSTR(name);
2276 	int err;
2277 
2278 	err = lookup_noperm_common(&qname, parent);
2279 	if (err)
2280 		return ERR_PTR(err);
2281 	return start_dirop(parent, &qname, LOOKUP_CREATE | LOOKUP_EXCL);
2282 }
2283 EXPORT_SYMBOL(simple_start_creating);
2284 
2285 /* parent must have been held exclusive since simple_start_creating() */
2286 void simple_done_creating(struct dentry *child)
2287 {
2288 	end_creating(child);
2289 }
2290 EXPORT_SYMBOL(simple_done_creating);
2291