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