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