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