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