Merge tag 'vfs-6.7.ctime' of gitolite.kernel.org:pub/scm/linux/kernel/git/vfs/vfs
[linux-block.git] / fs / libfs.c
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
27 #include <linux/uaccess.h>
28
29 #include "internal.h"
30
31 int simple_getattr(struct mnt_idmap *idmap, const struct path *path,
32                    struct kstat *stat, u32 request_mask,
33                    unsigned int query_flags)
34 {
35         struct inode *inode = d_inode(path->dentry);
36         generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
37         stat->blocks = inode->i_mapping->nrpages << (PAGE_SHIFT - 9);
38         return 0;
39 }
40 EXPORT_SYMBOL(simple_getattr);
41
42 int simple_statfs(struct dentry *dentry, struct kstatfs *buf)
43 {
44         buf->f_type = dentry->d_sb->s_magic;
45         buf->f_bsize = PAGE_SIZE;
46         buf->f_namelen = NAME_MAX;
47         return 0;
48 }
49 EXPORT_SYMBOL(simple_statfs);
50
51 /*
52  * Retaining negative dentries for an in-memory filesystem just wastes
53  * memory and lookup time: arrange for them to be deleted immediately.
54  */
55 int always_delete_dentry(const struct dentry *dentry)
56 {
57         return 1;
58 }
59 EXPORT_SYMBOL(always_delete_dentry);
60
61 const struct dentry_operations simple_dentry_operations = {
62         .d_delete = always_delete_dentry,
63 };
64 EXPORT_SYMBOL(simple_dentry_operations);
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  */
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_sb->s_d_op)
75                 d_set_d_op(dentry, &simple_dentry_operations);
76         d_add(dentry, NULL);
77         return NULL;
78 }
79 EXPORT_SYMBOL(simple_lookup);
80
81 int dcache_dir_open(struct inode *inode, struct file *file)
82 {
83         file->private_data = d_alloc_cursor(file->f_path.dentry);
84
85         return file->private_data ? 0 : -ENOMEM;
86 }
87 EXPORT_SYMBOL(dcache_dir_open);
88
89 int dcache_dir_close(struct inode *inode, struct file *file)
90 {
91         dput(file->private_data);
92         return 0;
93 }
94 EXPORT_SYMBOL(dcache_dir_close);
95
96 /* parent is locked at least shared */
97 /*
98  * Returns an element of siblings' list.
99  * We are looking for <count>th positive after <p>; if
100  * found, dentry is grabbed and returned to caller.
101  * If no such element exists, NULL is returned.
102  */
103 static struct dentry *scan_positives(struct dentry *cursor,
104                                         struct list_head *p,
105                                         loff_t count,
106                                         struct dentry *last)
107 {
108         struct dentry *dentry = cursor->d_parent, *found = NULL;
109
110         spin_lock(&dentry->d_lock);
111         while ((p = p->next) != &dentry->d_subdirs) {
112                 struct dentry *d = list_entry(p, struct dentry, d_child);
113                 // we must at least skip cursors, to avoid livelocks
114                 if (d->d_flags & DCACHE_DENTRY_CURSOR)
115                         continue;
116                 if (simple_positive(d) && !--count) {
117                         spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
118                         if (simple_positive(d))
119                                 found = dget_dlock(d);
120                         spin_unlock(&d->d_lock);
121                         if (likely(found))
122                                 break;
123                         count = 1;
124                 }
125                 if (need_resched()) {
126                         list_move(&cursor->d_child, p);
127                         p = &cursor->d_child;
128                         spin_unlock(&dentry->d_lock);
129                         cond_resched();
130                         spin_lock(&dentry->d_lock);
131                 }
132         }
133         spin_unlock(&dentry->d_lock);
134         dput(last);
135         return found;
136 }
137
138 loff_t dcache_dir_lseek(struct file *file, loff_t offset, int whence)
139 {
140         struct dentry *dentry = file->f_path.dentry;
141         switch (whence) {
142                 case 1:
143                         offset += file->f_pos;
144                         fallthrough;
145                 case 0:
146                         if (offset >= 0)
147                                 break;
148                         fallthrough;
149                 default:
150                         return -EINVAL;
151         }
152         if (offset != file->f_pos) {
153                 struct dentry *cursor = file->private_data;
154                 struct dentry *to = NULL;
155
156                 inode_lock_shared(dentry->d_inode);
157
158                 if (offset > 2)
159                         to = scan_positives(cursor, &dentry->d_subdirs,
160                                             offset - 2, NULL);
161                 spin_lock(&dentry->d_lock);
162                 if (to)
163                         list_move(&cursor->d_child, &to->d_child);
164                 else
165                         list_del_init(&cursor->d_child);
166                 spin_unlock(&dentry->d_lock);
167                 dput(to);
168
169                 file->f_pos = offset;
170
171                 inode_unlock_shared(dentry->d_inode);
172         }
173         return offset;
174 }
175 EXPORT_SYMBOL(dcache_dir_lseek);
176
177 /*
178  * Directory is locked and all positive dentries in it are safe, since
179  * for ramfs-type trees they can't go away without unlink() or rmdir(),
180  * both impossible due to the lock on directory.
181  */
182
183 int dcache_readdir(struct file *file, struct dir_context *ctx)
184 {
185         struct dentry *dentry = file->f_path.dentry;
186         struct dentry *cursor = file->private_data;
187         struct list_head *anchor = &dentry->d_subdirs;
188         struct dentry *next = NULL;
189         struct list_head *p;
190
191         if (!dir_emit_dots(file, ctx))
192                 return 0;
193
194         if (ctx->pos == 2)
195                 p = anchor;
196         else if (!list_empty(&cursor->d_child))
197                 p = &cursor->d_child;
198         else
199                 return 0;
200
201         while ((next = scan_positives(cursor, p, 1, next)) != NULL) {
202                 if (!dir_emit(ctx, next->d_name.name, next->d_name.len,
203                               d_inode(next)->i_ino,
204                               fs_umode_to_dtype(d_inode(next)->i_mode)))
205                         break;
206                 ctx->pos++;
207                 p = &next->d_child;
208         }
209         spin_lock(&dentry->d_lock);
210         if (next)
211                 list_move_tail(&cursor->d_child, &next->d_child);
212         else
213                 list_del_init(&cursor->d_child);
214         spin_unlock(&dentry->d_lock);
215         dput(next);
216
217         return 0;
218 }
219 EXPORT_SYMBOL(dcache_readdir);
220
221 ssize_t generic_read_dir(struct file *filp, char __user *buf, size_t siz, loff_t *ppos)
222 {
223         return -EISDIR;
224 }
225 EXPORT_SYMBOL(generic_read_dir);
226
227 const struct file_operations simple_dir_operations = {
228         .open           = dcache_dir_open,
229         .release        = dcache_dir_close,
230         .llseek         = dcache_dir_lseek,
231         .read           = generic_read_dir,
232         .iterate_shared = dcache_readdir,
233         .fsync          = noop_fsync,
234 };
235 EXPORT_SYMBOL(simple_dir_operations);
236
237 const struct inode_operations simple_dir_inode_operations = {
238         .lookup         = simple_lookup,
239 };
240 EXPORT_SYMBOL(simple_dir_inode_operations);
241
242 static void offset_set(struct dentry *dentry, u32 offset)
243 {
244         dentry->d_fsdata = (void *)((uintptr_t)(offset));
245 }
246
247 static u32 dentry2offset(struct dentry *dentry)
248 {
249         return (u32)((uintptr_t)(dentry->d_fsdata));
250 }
251
252 static struct lock_class_key simple_offset_xa_lock;
253
254 /**
255  * simple_offset_init - initialize an offset_ctx
256  * @octx: directory offset map to be initialized
257  *
258  */
259 void simple_offset_init(struct offset_ctx *octx)
260 {
261         xa_init_flags(&octx->xa, XA_FLAGS_ALLOC1);
262         lockdep_set_class(&octx->xa.xa_lock, &simple_offset_xa_lock);
263
264         /* 0 is '.', 1 is '..', so always start with offset 2 */
265         octx->next_offset = 2;
266 }
267
268 /**
269  * simple_offset_add - Add an entry to a directory's offset map
270  * @octx: directory offset ctx to be updated
271  * @dentry: new dentry being added
272  *
273  * Returns zero on success. @so_ctx and the dentry offset are updated.
274  * Otherwise, a negative errno value is returned.
275  */
276 int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry)
277 {
278         static const struct xa_limit limit = XA_LIMIT(2, U32_MAX);
279         u32 offset;
280         int ret;
281
282         if (dentry2offset(dentry) != 0)
283                 return -EBUSY;
284
285         ret = xa_alloc_cyclic(&octx->xa, &offset, dentry, limit,
286                               &octx->next_offset, GFP_KERNEL);
287         if (ret < 0)
288                 return ret;
289
290         offset_set(dentry, offset);
291         return 0;
292 }
293
294 /**
295  * simple_offset_remove - Remove an entry to a directory's offset map
296  * @octx: directory offset ctx to be updated
297  * @dentry: dentry being removed
298  *
299  */
300 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry)
301 {
302         u32 offset;
303
304         offset = dentry2offset(dentry);
305         if (offset == 0)
306                 return;
307
308         xa_erase(&octx->xa, offset);
309         offset_set(dentry, 0);
310 }
311
312 /**
313  * simple_offset_rename_exchange - exchange rename with directory offsets
314  * @old_dir: parent of dentry being moved
315  * @old_dentry: dentry being moved
316  * @new_dir: destination parent
317  * @new_dentry: destination dentry
318  *
319  * Returns zero on success. Otherwise a negative errno is returned and the
320  * rename is rolled back.
321  */
322 int simple_offset_rename_exchange(struct inode *old_dir,
323                                   struct dentry *old_dentry,
324                                   struct inode *new_dir,
325                                   struct dentry *new_dentry)
326 {
327         struct offset_ctx *old_ctx = old_dir->i_op->get_offset_ctx(old_dir);
328         struct offset_ctx *new_ctx = new_dir->i_op->get_offset_ctx(new_dir);
329         u32 old_index = dentry2offset(old_dentry);
330         u32 new_index = dentry2offset(new_dentry);
331         int ret;
332
333         simple_offset_remove(old_ctx, old_dentry);
334         simple_offset_remove(new_ctx, new_dentry);
335
336         ret = simple_offset_add(new_ctx, old_dentry);
337         if (ret)
338                 goto out_restore;
339
340         ret = simple_offset_add(old_ctx, new_dentry);
341         if (ret) {
342                 simple_offset_remove(new_ctx, old_dentry);
343                 goto out_restore;
344         }
345
346         ret = simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
347         if (ret) {
348                 simple_offset_remove(new_ctx, old_dentry);
349                 simple_offset_remove(old_ctx, new_dentry);
350                 goto out_restore;
351         }
352         return 0;
353
354 out_restore:
355         offset_set(old_dentry, old_index);
356         xa_store(&old_ctx->xa, old_index, old_dentry, GFP_KERNEL);
357         offset_set(new_dentry, new_index);
358         xa_store(&new_ctx->xa, new_index, new_dentry, GFP_KERNEL);
359         return ret;
360 }
361
362 /**
363  * simple_offset_destroy - Release offset map
364  * @octx: directory offset ctx that is about to be destroyed
365  *
366  * During fs teardown (eg. umount), a directory's offset map might still
367  * contain entries. xa_destroy() cleans out anything that remains.
368  */
369 void simple_offset_destroy(struct offset_ctx *octx)
370 {
371         xa_destroy(&octx->xa);
372 }
373
374 /**
375  * offset_dir_llseek - Advance the read position of a directory descriptor
376  * @file: an open directory whose position is to be updated
377  * @offset: a byte offset
378  * @whence: enumerator describing the starting position for this update
379  *
380  * SEEK_END, SEEK_DATA, and SEEK_HOLE are not supported for directories.
381  *
382  * Returns the updated read position if successful; otherwise a
383  * negative errno is returned and the read position remains unchanged.
384  */
385 static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence)
386 {
387         switch (whence) {
388         case SEEK_CUR:
389                 offset += file->f_pos;
390                 fallthrough;
391         case SEEK_SET:
392                 if (offset >= 0)
393                         break;
394                 fallthrough;
395         default:
396                 return -EINVAL;
397         }
398
399         return vfs_setpos(file, offset, U32_MAX);
400 }
401
402 static struct dentry *offset_find_next(struct xa_state *xas)
403 {
404         struct dentry *child, *found = NULL;
405
406         rcu_read_lock();
407         child = xas_next_entry(xas, U32_MAX);
408         if (!child)
409                 goto out;
410         spin_lock(&child->d_lock);
411         if (simple_positive(child))
412                 found = dget_dlock(child);
413         spin_unlock(&child->d_lock);
414 out:
415         rcu_read_unlock();
416         return found;
417 }
418
419 static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
420 {
421         u32 offset = dentry2offset(dentry);
422         struct inode *inode = d_inode(dentry);
423
424         return ctx->actor(ctx, dentry->d_name.name, dentry->d_name.len, offset,
425                           inode->i_ino, fs_umode_to_dtype(inode->i_mode));
426 }
427
428 static void offset_iterate_dir(struct inode *inode, struct dir_context *ctx)
429 {
430         struct offset_ctx *so_ctx = inode->i_op->get_offset_ctx(inode);
431         XA_STATE(xas, &so_ctx->xa, ctx->pos);
432         struct dentry *dentry;
433
434         while (true) {
435                 dentry = offset_find_next(&xas);
436                 if (!dentry)
437                         break;
438
439                 if (!offset_dir_emit(ctx, dentry)) {
440                         dput(dentry);
441                         break;
442                 }
443
444                 dput(dentry);
445                 ctx->pos = xas.xa_index + 1;
446         }
447 }
448
449 /**
450  * offset_readdir - Emit entries starting at offset @ctx->pos
451  * @file: an open directory to iterate over
452  * @ctx: directory iteration context
453  *
454  * Caller must hold @file's i_rwsem to prevent insertion or removal of
455  * entries during this call.
456  *
457  * On entry, @ctx->pos contains an offset that represents the first entry
458  * to be read from the directory.
459  *
460  * The operation continues until there are no more entries to read, or
461  * until the ctx->actor indicates there is no more space in the caller's
462  * output buffer.
463  *
464  * On return, @ctx->pos contains an offset that will read the next entry
465  * in this directory when offset_readdir() is called again with @ctx.
466  *
467  * Return values:
468  *   %0 - Complete
469  */
470 static int offset_readdir(struct file *file, struct dir_context *ctx)
471 {
472         struct dentry *dir = file->f_path.dentry;
473
474         lockdep_assert_held(&d_inode(dir)->i_rwsem);
475
476         if (!dir_emit_dots(file, ctx))
477                 return 0;
478
479         offset_iterate_dir(d_inode(dir), ctx);
480         return 0;
481 }
482
483 const struct file_operations simple_offset_dir_operations = {
484         .llseek         = offset_dir_llseek,
485         .iterate_shared = offset_readdir,
486         .read           = generic_read_dir,
487         .fsync          = noop_fsync,
488 };
489
490 static struct dentry *find_next_child(struct dentry *parent, struct dentry *prev)
491 {
492         struct dentry *child = NULL;
493         struct list_head *p = prev ? &prev->d_child : &parent->d_subdirs;
494
495         spin_lock(&parent->d_lock);
496         while ((p = p->next) != &parent->d_subdirs) {
497                 struct dentry *d = container_of(p, struct dentry, d_child);
498                 if (simple_positive(d)) {
499                         spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
500                         if (simple_positive(d))
501                                 child = dget_dlock(d);
502                         spin_unlock(&d->d_lock);
503                         if (likely(child))
504                                 break;
505                 }
506         }
507         spin_unlock(&parent->d_lock);
508         dput(prev);
509         return child;
510 }
511
512 void simple_recursive_removal(struct dentry *dentry,
513                               void (*callback)(struct dentry *))
514 {
515         struct dentry *this = dget(dentry);
516         while (true) {
517                 struct dentry *victim = NULL, *child;
518                 struct inode *inode = this->d_inode;
519
520                 inode_lock(inode);
521                 if (d_is_dir(this))
522                         inode->i_flags |= S_DEAD;
523                 while ((child = find_next_child(this, victim)) == NULL) {
524                         // kill and ascend
525                         // update metadata while it's still locked
526                         inode_set_ctime_current(inode);
527                         clear_nlink(inode);
528                         inode_unlock(inode);
529                         victim = this;
530                         this = this->d_parent;
531                         inode = this->d_inode;
532                         inode_lock(inode);
533                         if (simple_positive(victim)) {
534                                 d_invalidate(victim);   // avoid lost mounts
535                                 if (d_is_dir(victim))
536                                         fsnotify_rmdir(inode, victim);
537                                 else
538                                         fsnotify_unlink(inode, victim);
539                                 if (callback)
540                                         callback(victim);
541                                 dput(victim);           // unpin it
542                         }
543                         if (victim == dentry) {
544                                 inode_set_mtime_to_ts(inode,
545                                                       inode_set_ctime_current(inode));
546                                 if (d_is_dir(dentry))
547                                         drop_nlink(inode);
548                                 inode_unlock(inode);
549                                 dput(dentry);
550                                 return;
551                         }
552                 }
553                 inode_unlock(inode);
554                 this = child;
555         }
556 }
557 EXPORT_SYMBOL(simple_recursive_removal);
558
559 static const struct super_operations simple_super_operations = {
560         .statfs         = simple_statfs,
561 };
562
563 static int pseudo_fs_fill_super(struct super_block *s, struct fs_context *fc)
564 {
565         struct pseudo_fs_context *ctx = fc->fs_private;
566         struct inode *root;
567
568         s->s_maxbytes = MAX_LFS_FILESIZE;
569         s->s_blocksize = PAGE_SIZE;
570         s->s_blocksize_bits = PAGE_SHIFT;
571         s->s_magic = ctx->magic;
572         s->s_op = ctx->ops ?: &simple_super_operations;
573         s->s_xattr = ctx->xattr;
574         s->s_time_gran = 1;
575         root = new_inode(s);
576         if (!root)
577                 return -ENOMEM;
578
579         /*
580          * since this is the first inode, make it number 1. New inodes created
581          * after this must take care not to collide with it (by passing
582          * max_reserved of 1 to iunique).
583          */
584         root->i_ino = 1;
585         root->i_mode = S_IFDIR | S_IRUSR | S_IWUSR;
586         simple_inode_init_ts(root);
587         s->s_root = d_make_root(root);
588         if (!s->s_root)
589                 return -ENOMEM;
590         s->s_d_op = ctx->dops;
591         return 0;
592 }
593
594 static int pseudo_fs_get_tree(struct fs_context *fc)
595 {
596         return get_tree_nodev(fc, pseudo_fs_fill_super);
597 }
598
599 static void pseudo_fs_free(struct fs_context *fc)
600 {
601         kfree(fc->fs_private);
602 }
603
604 static const struct fs_context_operations pseudo_fs_context_ops = {
605         .free           = pseudo_fs_free,
606         .get_tree       = pseudo_fs_get_tree,
607 };
608
609 /*
610  * Common helper for pseudo-filesystems (sockfs, pipefs, bdev - stuff that
611  * will never be mountable)
612  */
613 struct pseudo_fs_context *init_pseudo(struct fs_context *fc,
614                                         unsigned long magic)
615 {
616         struct pseudo_fs_context *ctx;
617
618         ctx = kzalloc(sizeof(struct pseudo_fs_context), GFP_KERNEL);
619         if (likely(ctx)) {
620                 ctx->magic = magic;
621                 fc->fs_private = ctx;
622                 fc->ops = &pseudo_fs_context_ops;
623                 fc->sb_flags |= SB_NOUSER;
624                 fc->global = true;
625         }
626         return ctx;
627 }
628 EXPORT_SYMBOL(init_pseudo);
629
630 int simple_open(struct inode *inode, struct file *file)
631 {
632         if (inode->i_private)
633                 file->private_data = inode->i_private;
634         return 0;
635 }
636 EXPORT_SYMBOL(simple_open);
637
638 int simple_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
639 {
640         struct inode *inode = d_inode(old_dentry);
641
642         inode_set_mtime_to_ts(dir,
643                               inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
644         inc_nlink(inode);
645         ihold(inode);
646         dget(dentry);
647         d_instantiate(dentry, inode);
648         return 0;
649 }
650 EXPORT_SYMBOL(simple_link);
651
652 int simple_empty(struct dentry *dentry)
653 {
654         struct dentry *child;
655         int ret = 0;
656
657         spin_lock(&dentry->d_lock);
658         list_for_each_entry(child, &dentry->d_subdirs, d_child) {
659                 spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
660                 if (simple_positive(child)) {
661                         spin_unlock(&child->d_lock);
662                         goto out;
663                 }
664                 spin_unlock(&child->d_lock);
665         }
666         ret = 1;
667 out:
668         spin_unlock(&dentry->d_lock);
669         return ret;
670 }
671 EXPORT_SYMBOL(simple_empty);
672
673 int simple_unlink(struct inode *dir, struct dentry *dentry)
674 {
675         struct inode *inode = d_inode(dentry);
676
677         inode_set_mtime_to_ts(dir,
678                               inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode)));
679         drop_nlink(inode);
680         dput(dentry);
681         return 0;
682 }
683 EXPORT_SYMBOL(simple_unlink);
684
685 int simple_rmdir(struct inode *dir, struct dentry *dentry)
686 {
687         if (!simple_empty(dentry))
688                 return -ENOTEMPTY;
689
690         drop_nlink(d_inode(dentry));
691         simple_unlink(dir, dentry);
692         drop_nlink(dir);
693         return 0;
694 }
695 EXPORT_SYMBOL(simple_rmdir);
696
697 /**
698  * simple_rename_timestamp - update the various inode timestamps for rename
699  * @old_dir: old parent directory
700  * @old_dentry: dentry that is being renamed
701  * @new_dir: new parent directory
702  * @new_dentry: target for rename
703  *
704  * POSIX mandates that the old and new parent directories have their ctime and
705  * mtime updated, and that inodes of @old_dentry and @new_dentry (if any), have
706  * their ctime updated.
707  */
708 void simple_rename_timestamp(struct inode *old_dir, struct dentry *old_dentry,
709                              struct inode *new_dir, struct dentry *new_dentry)
710 {
711         struct inode *newino = d_inode(new_dentry);
712
713         inode_set_mtime_to_ts(old_dir, inode_set_ctime_current(old_dir));
714         if (new_dir != old_dir)
715                 inode_set_mtime_to_ts(new_dir,
716                                       inode_set_ctime_current(new_dir));
717         inode_set_ctime_current(d_inode(old_dentry));
718         if (newino)
719                 inode_set_ctime_current(newino);
720 }
721 EXPORT_SYMBOL_GPL(simple_rename_timestamp);
722
723 int simple_rename_exchange(struct inode *old_dir, struct dentry *old_dentry,
724                            struct inode *new_dir, struct dentry *new_dentry)
725 {
726         bool old_is_dir = d_is_dir(old_dentry);
727         bool new_is_dir = d_is_dir(new_dentry);
728
729         if (old_dir != new_dir && old_is_dir != new_is_dir) {
730                 if (old_is_dir) {
731                         drop_nlink(old_dir);
732                         inc_nlink(new_dir);
733                 } else {
734                         drop_nlink(new_dir);
735                         inc_nlink(old_dir);
736                 }
737         }
738         simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
739         return 0;
740 }
741 EXPORT_SYMBOL_GPL(simple_rename_exchange);
742
743 int simple_rename(struct mnt_idmap *idmap, struct inode *old_dir,
744                   struct dentry *old_dentry, struct inode *new_dir,
745                   struct dentry *new_dentry, unsigned int flags)
746 {
747         int they_are_dirs = d_is_dir(old_dentry);
748
749         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE))
750                 return -EINVAL;
751
752         if (flags & RENAME_EXCHANGE)
753                 return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
754
755         if (!simple_empty(new_dentry))
756                 return -ENOTEMPTY;
757
758         if (d_really_is_positive(new_dentry)) {
759                 simple_unlink(new_dir, new_dentry);
760                 if (they_are_dirs) {
761                         drop_nlink(d_inode(new_dentry));
762                         drop_nlink(old_dir);
763                 }
764         } else if (they_are_dirs) {
765                 drop_nlink(old_dir);
766                 inc_nlink(new_dir);
767         }
768
769         simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
770         return 0;
771 }
772 EXPORT_SYMBOL(simple_rename);
773
774 /**
775  * simple_setattr - setattr for simple filesystem
776  * @idmap: idmap of the target mount
777  * @dentry: dentry
778  * @iattr: iattr structure
779  *
780  * Returns 0 on success, -error on failure.
781  *
782  * simple_setattr is a simple ->setattr implementation without a proper
783  * implementation of size changes.
784  *
785  * It can either be used for in-memory filesystems or special files
786  * on simple regular filesystems.  Anything that needs to change on-disk
787  * or wire state on size changes needs its own setattr method.
788  */
789 int simple_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
790                    struct iattr *iattr)
791 {
792         struct inode *inode = d_inode(dentry);
793         int error;
794
795         error = setattr_prepare(idmap, dentry, iattr);
796         if (error)
797                 return error;
798
799         if (iattr->ia_valid & ATTR_SIZE)
800                 truncate_setsize(inode, iattr->ia_size);
801         setattr_copy(idmap, inode, iattr);
802         mark_inode_dirty(inode);
803         return 0;
804 }
805 EXPORT_SYMBOL(simple_setattr);
806
807 static int simple_read_folio(struct file *file, struct folio *folio)
808 {
809         folio_zero_range(folio, 0, folio_size(folio));
810         flush_dcache_folio(folio);
811         folio_mark_uptodate(folio);
812         folio_unlock(folio);
813         return 0;
814 }
815
816 int simple_write_begin(struct file *file, struct address_space *mapping,
817                         loff_t pos, unsigned len,
818                         struct page **pagep, void **fsdata)
819 {
820         struct folio *folio;
821
822         folio = __filemap_get_folio(mapping, pos / PAGE_SIZE, FGP_WRITEBEGIN,
823                         mapping_gfp_mask(mapping));
824         if (IS_ERR(folio))
825                 return PTR_ERR(folio);
826
827         *pagep = &folio->page;
828
829         if (!folio_test_uptodate(folio) && (len != folio_size(folio))) {
830                 size_t from = offset_in_folio(folio, pos);
831
832                 folio_zero_segments(folio, 0, from,
833                                 from + len, folio_size(folio));
834         }
835         return 0;
836 }
837 EXPORT_SYMBOL(simple_write_begin);
838
839 /**
840  * simple_write_end - .write_end helper for non-block-device FSes
841  * @file: See .write_end of address_space_operations
842  * @mapping:            "
843  * @pos:                "
844  * @len:                "
845  * @copied:             "
846  * @page:               "
847  * @fsdata:             "
848  *
849  * simple_write_end does the minimum needed for updating a page after writing is
850  * done. It has the same API signature as the .write_end of
851  * address_space_operations vector. So it can just be set onto .write_end for
852  * FSes that don't need any other processing. i_mutex is assumed to be held.
853  * Block based filesystems should use generic_write_end().
854  * NOTE: Even though i_size might get updated by this function, mark_inode_dirty
855  * is not called, so a filesystem that actually does store data in .write_inode
856  * should extend on what's done here with a call to mark_inode_dirty() in the
857  * case that i_size has changed.
858  *
859  * Use *ONLY* with simple_read_folio()
860  */
861 static int simple_write_end(struct file *file, struct address_space *mapping,
862                         loff_t pos, unsigned len, unsigned copied,
863                         struct page *page, void *fsdata)
864 {
865         struct folio *folio = page_folio(page);
866         struct inode *inode = folio->mapping->host;
867         loff_t last_pos = pos + copied;
868
869         /* zero the stale part of the folio if we did a short copy */
870         if (!folio_test_uptodate(folio)) {
871                 if (copied < len) {
872                         size_t from = offset_in_folio(folio, pos);
873
874                         folio_zero_range(folio, from + copied, len - copied);
875                 }
876                 folio_mark_uptodate(folio);
877         }
878         /*
879          * No need to use i_size_read() here, the i_size
880          * cannot change under us because we hold the i_mutex.
881          */
882         if (last_pos > inode->i_size)
883                 i_size_write(inode, last_pos);
884
885         folio_mark_dirty(folio);
886         folio_unlock(folio);
887         folio_put(folio);
888
889         return copied;
890 }
891
892 /*
893  * Provides ramfs-style behavior: data in the pagecache, but no writeback.
894  */
895 const struct address_space_operations ram_aops = {
896         .read_folio     = simple_read_folio,
897         .write_begin    = simple_write_begin,
898         .write_end      = simple_write_end,
899         .dirty_folio    = noop_dirty_folio,
900 };
901 EXPORT_SYMBOL(ram_aops);
902
903 /*
904  * the inodes created here are not hashed. If you use iunique to generate
905  * unique inode values later for this filesystem, then you must take care
906  * to pass it an appropriate max_reserved value to avoid collisions.
907  */
908 int simple_fill_super(struct super_block *s, unsigned long magic,
909                       const struct tree_descr *files)
910 {
911         struct inode *inode;
912         struct dentry *root;
913         struct dentry *dentry;
914         int i;
915
916         s->s_blocksize = PAGE_SIZE;
917         s->s_blocksize_bits = PAGE_SHIFT;
918         s->s_magic = magic;
919         s->s_op = &simple_super_operations;
920         s->s_time_gran = 1;
921
922         inode = new_inode(s);
923         if (!inode)
924                 return -ENOMEM;
925         /*
926          * because the root inode is 1, the files array must not contain an
927          * entry at index 1
928          */
929         inode->i_ino = 1;
930         inode->i_mode = S_IFDIR | 0755;
931         simple_inode_init_ts(inode);
932         inode->i_op = &simple_dir_inode_operations;
933         inode->i_fop = &simple_dir_operations;
934         set_nlink(inode, 2);
935         root = d_make_root(inode);
936         if (!root)
937                 return -ENOMEM;
938         for (i = 0; !files->name || files->name[0]; i++, files++) {
939                 if (!files->name)
940                         continue;
941
942                 /* warn if it tries to conflict with the root inode */
943                 if (unlikely(i == 1))
944                         printk(KERN_WARNING "%s: %s passed in a files array"
945                                 "with an index of 1!\n", __func__,
946                                 s->s_type->name);
947
948                 dentry = d_alloc_name(root, files->name);
949                 if (!dentry)
950                         goto out;
951                 inode = new_inode(s);
952                 if (!inode) {
953                         dput(dentry);
954                         goto out;
955                 }
956                 inode->i_mode = S_IFREG | files->mode;
957                 simple_inode_init_ts(inode);
958                 inode->i_fop = files->ops;
959                 inode->i_ino = i;
960                 d_add(dentry, inode);
961         }
962         s->s_root = root;
963         return 0;
964 out:
965         d_genocide(root);
966         shrink_dcache_parent(root);
967         dput(root);
968         return -ENOMEM;
969 }
970 EXPORT_SYMBOL(simple_fill_super);
971
972 static DEFINE_SPINLOCK(pin_fs_lock);
973
974 int simple_pin_fs(struct file_system_type *type, struct vfsmount **mount, int *count)
975 {
976         struct vfsmount *mnt = NULL;
977         spin_lock(&pin_fs_lock);
978         if (unlikely(!*mount)) {
979                 spin_unlock(&pin_fs_lock);
980                 mnt = vfs_kern_mount(type, SB_KERNMOUNT, type->name, NULL);
981                 if (IS_ERR(mnt))
982                         return PTR_ERR(mnt);
983                 spin_lock(&pin_fs_lock);
984                 if (!*mount)
985                         *mount = mnt;
986         }
987         mntget(*mount);
988         ++*count;
989         spin_unlock(&pin_fs_lock);
990         mntput(mnt);
991         return 0;
992 }
993 EXPORT_SYMBOL(simple_pin_fs);
994
995 void simple_release_fs(struct vfsmount **mount, int *count)
996 {
997         struct vfsmount *mnt;
998         spin_lock(&pin_fs_lock);
999         mnt = *mount;
1000         if (!--*count)
1001                 *mount = NULL;
1002         spin_unlock(&pin_fs_lock);
1003         mntput(mnt);
1004 }
1005 EXPORT_SYMBOL(simple_release_fs);
1006
1007 /**
1008  * simple_read_from_buffer - copy data from the buffer to user space
1009  * @to: the user space buffer to read to
1010  * @count: the maximum number of bytes to read
1011  * @ppos: the current position in the buffer
1012  * @from: the buffer to read from
1013  * @available: the size of the buffer
1014  *
1015  * The simple_read_from_buffer() function reads up to @count bytes from the
1016  * buffer @from at offset @ppos into the user space address starting at @to.
1017  *
1018  * On success, the number of bytes read is returned and the offset @ppos is
1019  * advanced by this number, or negative value is returned on error.
1020  **/
1021 ssize_t simple_read_from_buffer(void __user *to, size_t count, loff_t *ppos,
1022                                 const void *from, size_t available)
1023 {
1024         loff_t pos = *ppos;
1025         size_t ret;
1026
1027         if (pos < 0)
1028                 return -EINVAL;
1029         if (pos >= available || !count)
1030                 return 0;
1031         if (count > available - pos)
1032                 count = available - pos;
1033         ret = copy_to_user(to, from + pos, count);
1034         if (ret == count)
1035                 return -EFAULT;
1036         count -= ret;
1037         *ppos = pos + count;
1038         return count;
1039 }
1040 EXPORT_SYMBOL(simple_read_from_buffer);
1041
1042 /**
1043  * simple_write_to_buffer - copy data from user space to the buffer
1044  * @to: the buffer to write to
1045  * @available: the size of the buffer
1046  * @ppos: the current position in the buffer
1047  * @from: the user space buffer to read from
1048  * @count: the maximum number of bytes to read
1049  *
1050  * The simple_write_to_buffer() function reads up to @count bytes from the user
1051  * space address starting at @from into the buffer @to at offset @ppos.
1052  *
1053  * On success, the number of bytes written is returned and the offset @ppos is
1054  * advanced by this number, or negative value is returned on error.
1055  **/
1056 ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos,
1057                 const void __user *from, size_t count)
1058 {
1059         loff_t pos = *ppos;
1060         size_t res;
1061
1062         if (pos < 0)
1063                 return -EINVAL;
1064         if (pos >= available || !count)
1065                 return 0;
1066         if (count > available - pos)
1067                 count = available - pos;
1068         res = copy_from_user(to + pos, from, count);
1069         if (res == count)
1070                 return -EFAULT;
1071         count -= res;
1072         *ppos = pos + count;
1073         return count;
1074 }
1075 EXPORT_SYMBOL(simple_write_to_buffer);
1076
1077 /**
1078  * memory_read_from_buffer - copy data from the buffer
1079  * @to: the kernel space buffer to read to
1080  * @count: the maximum number of bytes to read
1081  * @ppos: the current position in the buffer
1082  * @from: the buffer to read from
1083  * @available: the size of the buffer
1084  *
1085  * The memory_read_from_buffer() function reads up to @count bytes from the
1086  * buffer @from at offset @ppos into the kernel space address starting at @to.
1087  *
1088  * On success, the number of bytes read is returned and the offset @ppos is
1089  * advanced by this number, or negative value is returned on error.
1090  **/
1091 ssize_t memory_read_from_buffer(void *to, size_t count, loff_t *ppos,
1092                                 const void *from, size_t available)
1093 {
1094         loff_t pos = *ppos;
1095
1096         if (pos < 0)
1097                 return -EINVAL;
1098         if (pos >= available)
1099                 return 0;
1100         if (count > available - pos)
1101                 count = available - pos;
1102         memcpy(to, from + pos, count);
1103         *ppos = pos + count;
1104
1105         return count;
1106 }
1107 EXPORT_SYMBOL(memory_read_from_buffer);
1108
1109 /*
1110  * Transaction based IO.
1111  * The file expects a single write which triggers the transaction, and then
1112  * possibly a read which collects the result - which is stored in a
1113  * file-local buffer.
1114  */
1115
1116 void simple_transaction_set(struct file *file, size_t n)
1117 {
1118         struct simple_transaction_argresp *ar = file->private_data;
1119
1120         BUG_ON(n > SIMPLE_TRANSACTION_LIMIT);
1121
1122         /*
1123          * The barrier ensures that ar->size will really remain zero until
1124          * ar->data is ready for reading.
1125          */
1126         smp_mb();
1127         ar->size = n;
1128 }
1129 EXPORT_SYMBOL(simple_transaction_set);
1130
1131 char *simple_transaction_get(struct file *file, const char __user *buf, size_t size)
1132 {
1133         struct simple_transaction_argresp *ar;
1134         static DEFINE_SPINLOCK(simple_transaction_lock);
1135
1136         if (size > SIMPLE_TRANSACTION_LIMIT - 1)
1137                 return ERR_PTR(-EFBIG);
1138
1139         ar = (struct simple_transaction_argresp *)get_zeroed_page(GFP_KERNEL);
1140         if (!ar)
1141                 return ERR_PTR(-ENOMEM);
1142
1143         spin_lock(&simple_transaction_lock);
1144
1145         /* only one write allowed per open */
1146         if (file->private_data) {
1147                 spin_unlock(&simple_transaction_lock);
1148                 free_page((unsigned long)ar);
1149                 return ERR_PTR(-EBUSY);
1150         }
1151
1152         file->private_data = ar;
1153
1154         spin_unlock(&simple_transaction_lock);
1155
1156         if (copy_from_user(ar->data, buf, size))
1157                 return ERR_PTR(-EFAULT);
1158
1159         return ar->data;
1160 }
1161 EXPORT_SYMBOL(simple_transaction_get);
1162
1163 ssize_t simple_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos)
1164 {
1165         struct simple_transaction_argresp *ar = file->private_data;
1166
1167         if (!ar)
1168                 return 0;
1169         return simple_read_from_buffer(buf, size, pos, ar->data, ar->size);
1170 }
1171 EXPORT_SYMBOL(simple_transaction_read);
1172
1173 int simple_transaction_release(struct inode *inode, struct file *file)
1174 {
1175         free_page((unsigned long)file->private_data);
1176         return 0;
1177 }
1178 EXPORT_SYMBOL(simple_transaction_release);
1179
1180 /* Simple attribute files */
1181
1182 struct simple_attr {
1183         int (*get)(void *, u64 *);
1184         int (*set)(void *, u64);
1185         char get_buf[24];       /* enough to store a u64 and "\n\0" */
1186         char set_buf[24];
1187         void *data;
1188         const char *fmt;        /* format for read operation */
1189         struct mutex mutex;     /* protects access to these buffers */
1190 };
1191
1192 /* simple_attr_open is called by an actual attribute open file operation
1193  * to set the attribute specific access operations. */
1194 int simple_attr_open(struct inode *inode, struct file *file,
1195                      int (*get)(void *, u64 *), int (*set)(void *, u64),
1196                      const char *fmt)
1197 {
1198         struct simple_attr *attr;
1199
1200         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
1201         if (!attr)
1202                 return -ENOMEM;
1203
1204         attr->get = get;
1205         attr->set = set;
1206         attr->data = inode->i_private;
1207         attr->fmt = fmt;
1208         mutex_init(&attr->mutex);
1209
1210         file->private_data = attr;
1211
1212         return nonseekable_open(inode, file);
1213 }
1214 EXPORT_SYMBOL_GPL(simple_attr_open);
1215
1216 int simple_attr_release(struct inode *inode, struct file *file)
1217 {
1218         kfree(file->private_data);
1219         return 0;
1220 }
1221 EXPORT_SYMBOL_GPL(simple_attr_release); /* GPL-only?  This?  Really? */
1222
1223 /* read from the buffer that is filled with the get function */
1224 ssize_t simple_attr_read(struct file *file, char __user *buf,
1225                          size_t len, loff_t *ppos)
1226 {
1227         struct simple_attr *attr;
1228         size_t size;
1229         ssize_t ret;
1230
1231         attr = file->private_data;
1232
1233         if (!attr->get)
1234                 return -EACCES;
1235
1236         ret = mutex_lock_interruptible(&attr->mutex);
1237         if (ret)
1238                 return ret;
1239
1240         if (*ppos && attr->get_buf[0]) {
1241                 /* continued read */
1242                 size = strlen(attr->get_buf);
1243         } else {
1244                 /* first read */
1245                 u64 val;
1246                 ret = attr->get(attr->data, &val);
1247                 if (ret)
1248                         goto out;
1249
1250                 size = scnprintf(attr->get_buf, sizeof(attr->get_buf),
1251                                  attr->fmt, (unsigned long long)val);
1252         }
1253
1254         ret = simple_read_from_buffer(buf, len, ppos, attr->get_buf, size);
1255 out:
1256         mutex_unlock(&attr->mutex);
1257         return ret;
1258 }
1259 EXPORT_SYMBOL_GPL(simple_attr_read);
1260
1261 /* interpret the buffer as a number to call the set function with */
1262 static ssize_t simple_attr_write_xsigned(struct file *file, const char __user *buf,
1263                           size_t len, loff_t *ppos, bool is_signed)
1264 {
1265         struct simple_attr *attr;
1266         unsigned long long val;
1267         size_t size;
1268         ssize_t ret;
1269
1270         attr = file->private_data;
1271         if (!attr->set)
1272                 return -EACCES;
1273
1274         ret = mutex_lock_interruptible(&attr->mutex);
1275         if (ret)
1276                 return ret;
1277
1278         ret = -EFAULT;
1279         size = min(sizeof(attr->set_buf) - 1, len);
1280         if (copy_from_user(attr->set_buf, buf, size))
1281                 goto out;
1282
1283         attr->set_buf[size] = '\0';
1284         if (is_signed)
1285                 ret = kstrtoll(attr->set_buf, 0, &val);
1286         else
1287                 ret = kstrtoull(attr->set_buf, 0, &val);
1288         if (ret)
1289                 goto out;
1290         ret = attr->set(attr->data, val);
1291         if (ret == 0)
1292                 ret = len; /* on success, claim we got the whole input */
1293 out:
1294         mutex_unlock(&attr->mutex);
1295         return ret;
1296 }
1297
1298 ssize_t simple_attr_write(struct file *file, const char __user *buf,
1299                           size_t len, loff_t *ppos)
1300 {
1301         return simple_attr_write_xsigned(file, buf, len, ppos, false);
1302 }
1303 EXPORT_SYMBOL_GPL(simple_attr_write);
1304
1305 ssize_t simple_attr_write_signed(struct file *file, const char __user *buf,
1306                           size_t len, loff_t *ppos)
1307 {
1308         return simple_attr_write_xsigned(file, buf, len, ppos, true);
1309 }
1310 EXPORT_SYMBOL_GPL(simple_attr_write_signed);
1311
1312 /**
1313  * generic_fh_to_dentry - generic helper for the fh_to_dentry export operation
1314  * @sb:         filesystem to do the file handle conversion on
1315  * @fid:        file handle to convert
1316  * @fh_len:     length of the file handle in bytes
1317  * @fh_type:    type of file handle
1318  * @get_inode:  filesystem callback to retrieve inode
1319  *
1320  * This function decodes @fid as long as it has one of the well-known
1321  * Linux filehandle types and calls @get_inode on it to retrieve the
1322  * inode for the object specified in the file handle.
1323  */
1324 struct dentry *generic_fh_to_dentry(struct super_block *sb, struct fid *fid,
1325                 int fh_len, int fh_type, struct inode *(*get_inode)
1326                         (struct super_block *sb, u64 ino, u32 gen))
1327 {
1328         struct inode *inode = NULL;
1329
1330         if (fh_len < 2)
1331                 return NULL;
1332
1333         switch (fh_type) {
1334         case FILEID_INO32_GEN:
1335         case FILEID_INO32_GEN_PARENT:
1336                 inode = get_inode(sb, fid->i32.ino, fid->i32.gen);
1337                 break;
1338         }
1339
1340         return d_obtain_alias(inode);
1341 }
1342 EXPORT_SYMBOL_GPL(generic_fh_to_dentry);
1343
1344 /**
1345  * generic_fh_to_parent - generic helper for the fh_to_parent export operation
1346  * @sb:         filesystem to do the file handle conversion on
1347  * @fid:        file handle to convert
1348  * @fh_len:     length of the file handle in bytes
1349  * @fh_type:    type of file handle
1350  * @get_inode:  filesystem callback to retrieve inode
1351  *
1352  * This function decodes @fid as long as it has one of the well-known
1353  * Linux filehandle types and calls @get_inode on it to retrieve the
1354  * inode for the _parent_ object specified in the file handle if it
1355  * is specified in the file handle, or NULL otherwise.
1356  */
1357 struct dentry *generic_fh_to_parent(struct super_block *sb, struct fid *fid,
1358                 int fh_len, int fh_type, struct inode *(*get_inode)
1359                         (struct super_block *sb, u64 ino, u32 gen))
1360 {
1361         struct inode *inode = NULL;
1362
1363         if (fh_len <= 2)
1364                 return NULL;
1365
1366         switch (fh_type) {
1367         case FILEID_INO32_GEN_PARENT:
1368                 inode = get_inode(sb, fid->i32.parent_ino,
1369                                   (fh_len > 3 ? fid->i32.parent_gen : 0));
1370                 break;
1371         }
1372
1373         return d_obtain_alias(inode);
1374 }
1375 EXPORT_SYMBOL_GPL(generic_fh_to_parent);
1376
1377 /**
1378  * __generic_file_fsync - generic fsync implementation for simple filesystems
1379  *
1380  * @file:       file to synchronize
1381  * @start:      start offset in bytes
1382  * @end:        end offset in bytes (inclusive)
1383  * @datasync:   only synchronize essential metadata if true
1384  *
1385  * This is a generic implementation of the fsync method for simple
1386  * filesystems which track all non-inode metadata in the buffers list
1387  * hanging off the address_space structure.
1388  */
1389 int __generic_file_fsync(struct file *file, loff_t start, loff_t end,
1390                                  int datasync)
1391 {
1392         struct inode *inode = file->f_mapping->host;
1393         int err;
1394         int ret;
1395
1396         err = file_write_and_wait_range(file, start, end);
1397         if (err)
1398                 return err;
1399
1400         inode_lock(inode);
1401         ret = sync_mapping_buffers(inode->i_mapping);
1402         if (!(inode->i_state & I_DIRTY_ALL))
1403                 goto out;
1404         if (datasync && !(inode->i_state & I_DIRTY_DATASYNC))
1405                 goto out;
1406
1407         err = sync_inode_metadata(inode, 1);
1408         if (ret == 0)
1409                 ret = err;
1410
1411 out:
1412         inode_unlock(inode);
1413         /* check and advance again to catch errors after syncing out buffers */
1414         err = file_check_and_advance_wb_err(file);
1415         if (ret == 0)
1416                 ret = err;
1417         return ret;
1418 }
1419 EXPORT_SYMBOL(__generic_file_fsync);
1420
1421 /**
1422  * generic_file_fsync - generic fsync implementation for simple filesystems
1423  *                      with flush
1424  * @file:       file to synchronize
1425  * @start:      start offset in bytes
1426  * @end:        end offset in bytes (inclusive)
1427  * @datasync:   only synchronize essential metadata if true
1428  *
1429  */
1430
1431 int generic_file_fsync(struct file *file, loff_t start, loff_t end,
1432                        int datasync)
1433 {
1434         struct inode *inode = file->f_mapping->host;
1435         int err;
1436
1437         err = __generic_file_fsync(file, start, end, datasync);
1438         if (err)
1439                 return err;
1440         return blkdev_issue_flush(inode->i_sb->s_bdev);
1441 }
1442 EXPORT_SYMBOL(generic_file_fsync);
1443
1444 /**
1445  * generic_check_addressable - Check addressability of file system
1446  * @blocksize_bits:     log of file system block size
1447  * @num_blocks:         number of blocks in file system
1448  *
1449  * Determine whether a file system with @num_blocks blocks (and a
1450  * block size of 2**@blocksize_bits) is addressable by the sector_t
1451  * and page cache of the system.  Return 0 if so and -EFBIG otherwise.
1452  */
1453 int generic_check_addressable(unsigned blocksize_bits, u64 num_blocks)
1454 {
1455         u64 last_fs_block = num_blocks - 1;
1456         u64 last_fs_page =
1457                 last_fs_block >> (PAGE_SHIFT - blocksize_bits);
1458
1459         if (unlikely(num_blocks == 0))
1460                 return 0;
1461
1462         if ((blocksize_bits < 9) || (blocksize_bits > PAGE_SHIFT))
1463                 return -EINVAL;
1464
1465         if ((last_fs_block > (sector_t)(~0ULL) >> (blocksize_bits - 9)) ||
1466             (last_fs_page > (pgoff_t)(~0ULL))) {
1467                 return -EFBIG;
1468         }
1469         return 0;
1470 }
1471 EXPORT_SYMBOL(generic_check_addressable);
1472
1473 /*
1474  * No-op implementation of ->fsync for in-memory filesystems.
1475  */
1476 int noop_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1477 {
1478         return 0;
1479 }
1480 EXPORT_SYMBOL(noop_fsync);
1481
1482 ssize_t noop_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
1483 {
1484         /*
1485          * iomap based filesystems support direct I/O without need for
1486          * this callback. However, it still needs to be set in
1487          * inode->a_ops so that open/fcntl know that direct I/O is
1488          * generally supported.
1489          */
1490         return -EINVAL;
1491 }
1492 EXPORT_SYMBOL_GPL(noop_direct_IO);
1493
1494 /* Because kfree isn't assignment-compatible with void(void*) ;-/ */
1495 void kfree_link(void *p)
1496 {
1497         kfree(p);
1498 }
1499 EXPORT_SYMBOL(kfree_link);
1500
1501 struct inode *alloc_anon_inode(struct super_block *s)
1502 {
1503         static const struct address_space_operations anon_aops = {
1504                 .dirty_folio    = noop_dirty_folio,
1505         };
1506         struct inode *inode = new_inode_pseudo(s);
1507
1508         if (!inode)
1509                 return ERR_PTR(-ENOMEM);
1510
1511         inode->i_ino = get_next_ino();
1512         inode->i_mapping->a_ops = &anon_aops;
1513
1514         /*
1515          * Mark the inode dirty from the very beginning,
1516          * that way it will never be moved to the dirty
1517          * list because mark_inode_dirty() will think
1518          * that it already _is_ on the dirty list.
1519          */
1520         inode->i_state = I_DIRTY;
1521         inode->i_mode = S_IRUSR | S_IWUSR;
1522         inode->i_uid = current_fsuid();
1523         inode->i_gid = current_fsgid();
1524         inode->i_flags |= S_PRIVATE;
1525         simple_inode_init_ts(inode);
1526         return inode;
1527 }
1528 EXPORT_SYMBOL(alloc_anon_inode);
1529
1530 /**
1531  * simple_nosetlease - generic helper for prohibiting leases
1532  * @filp: file pointer
1533  * @arg: type of lease to obtain
1534  * @flp: new lease supplied for insertion
1535  * @priv: private data for lm_setup operation
1536  *
1537  * Generic helper for filesystems that do not wish to allow leases to be set.
1538  * All arguments are ignored and it just returns -EINVAL.
1539  */
1540 int
1541 simple_nosetlease(struct file *filp, int arg, struct file_lock **flp,
1542                   void **priv)
1543 {
1544         return -EINVAL;
1545 }
1546 EXPORT_SYMBOL(simple_nosetlease);
1547
1548 /**
1549  * simple_get_link - generic helper to get the target of "fast" symlinks
1550  * @dentry: not used here
1551  * @inode: the symlink inode
1552  * @done: not used here
1553  *
1554  * Generic helper for filesystems to use for symlink inodes where a pointer to
1555  * the symlink target is stored in ->i_link.  NOTE: this isn't normally called,
1556  * since as an optimization the path lookup code uses any non-NULL ->i_link
1557  * directly, without calling ->get_link().  But ->get_link() still must be set,
1558  * to mark the inode_operations as being for a symlink.
1559  *
1560  * Return: the symlink target
1561  */
1562 const char *simple_get_link(struct dentry *dentry, struct inode *inode,
1563                             struct delayed_call *done)
1564 {
1565         return inode->i_link;
1566 }
1567 EXPORT_SYMBOL(simple_get_link);
1568
1569 const struct inode_operations simple_symlink_inode_operations = {
1570         .get_link = simple_get_link,
1571 };
1572 EXPORT_SYMBOL(simple_symlink_inode_operations);
1573
1574 /*
1575  * Operations for a permanently empty directory.
1576  */
1577 static struct dentry *empty_dir_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
1578 {
1579         return ERR_PTR(-ENOENT);
1580 }
1581
1582 static int empty_dir_getattr(struct mnt_idmap *idmap,
1583                              const struct path *path, struct kstat *stat,
1584                              u32 request_mask, unsigned int query_flags)
1585 {
1586         struct inode *inode = d_inode(path->dentry);
1587         generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
1588         return 0;
1589 }
1590
1591 static int empty_dir_setattr(struct mnt_idmap *idmap,
1592                              struct dentry *dentry, struct iattr *attr)
1593 {
1594         return -EPERM;
1595 }
1596
1597 static ssize_t empty_dir_listxattr(struct dentry *dentry, char *list, size_t size)
1598 {
1599         return -EOPNOTSUPP;
1600 }
1601
1602 static const struct inode_operations empty_dir_inode_operations = {
1603         .lookup         = empty_dir_lookup,
1604         .permission     = generic_permission,
1605         .setattr        = empty_dir_setattr,
1606         .getattr        = empty_dir_getattr,
1607         .listxattr      = empty_dir_listxattr,
1608 };
1609
1610 static loff_t empty_dir_llseek(struct file *file, loff_t offset, int whence)
1611 {
1612         /* An empty directory has two entries . and .. at offsets 0 and 1 */
1613         return generic_file_llseek_size(file, offset, whence, 2, 2);
1614 }
1615
1616 static int empty_dir_readdir(struct file *file, struct dir_context *ctx)
1617 {
1618         dir_emit_dots(file, ctx);
1619         return 0;
1620 }
1621
1622 static const struct file_operations empty_dir_operations = {
1623         .llseek         = empty_dir_llseek,
1624         .read           = generic_read_dir,
1625         .iterate_shared = empty_dir_readdir,
1626         .fsync          = noop_fsync,
1627 };
1628
1629
1630 void make_empty_dir_inode(struct inode *inode)
1631 {
1632         set_nlink(inode, 2);
1633         inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
1634         inode->i_uid = GLOBAL_ROOT_UID;
1635         inode->i_gid = GLOBAL_ROOT_GID;
1636         inode->i_rdev = 0;
1637         inode->i_size = 0;
1638         inode->i_blkbits = PAGE_SHIFT;
1639         inode->i_blocks = 0;
1640
1641         inode->i_op = &empty_dir_inode_operations;
1642         inode->i_opflags &= ~IOP_XATTR;
1643         inode->i_fop = &empty_dir_operations;
1644 }
1645
1646 bool is_empty_dir_inode(struct inode *inode)
1647 {
1648         return (inode->i_fop == &empty_dir_operations) &&
1649                 (inode->i_op == &empty_dir_inode_operations);
1650 }
1651
1652 #if IS_ENABLED(CONFIG_UNICODE)
1653 /**
1654  * generic_ci_d_compare - generic d_compare implementation for casefolding filesystems
1655  * @dentry:     dentry whose name we are checking against
1656  * @len:        len of name of dentry
1657  * @str:        str pointer to name of dentry
1658  * @name:       Name to compare against
1659  *
1660  * Return: 0 if names match, 1 if mismatch, or -ERRNO
1661  */
1662 static int generic_ci_d_compare(const struct dentry *dentry, unsigned int len,
1663                                 const char *str, const struct qstr *name)
1664 {
1665         const struct dentry *parent = READ_ONCE(dentry->d_parent);
1666         const struct inode *dir = READ_ONCE(parent->d_inode);
1667         const struct super_block *sb = dentry->d_sb;
1668         const struct unicode_map *um = sb->s_encoding;
1669         struct qstr qstr = QSTR_INIT(str, len);
1670         char strbuf[DNAME_INLINE_LEN];
1671         int ret;
1672
1673         if (!dir || !IS_CASEFOLDED(dir))
1674                 goto fallback;
1675         /*
1676          * If the dentry name is stored in-line, then it may be concurrently
1677          * modified by a rename.  If this happens, the VFS will eventually retry
1678          * the lookup, so it doesn't matter what ->d_compare() returns.
1679          * However, it's unsafe to call utf8_strncasecmp() with an unstable
1680          * string.  Therefore, we have to copy the name into a temporary buffer.
1681          */
1682         if (len <= DNAME_INLINE_LEN - 1) {
1683                 memcpy(strbuf, str, len);
1684                 strbuf[len] = 0;
1685                 qstr.name = strbuf;
1686                 /* prevent compiler from optimizing out the temporary buffer */
1687                 barrier();
1688         }
1689         ret = utf8_strncasecmp(um, name, &qstr);
1690         if (ret >= 0)
1691                 return ret;
1692
1693         if (sb_has_strict_encoding(sb))
1694                 return -EINVAL;
1695 fallback:
1696         if (len != name->len)
1697                 return 1;
1698         return !!memcmp(str, name->name, len);
1699 }
1700
1701 /**
1702  * generic_ci_d_hash - generic d_hash implementation for casefolding filesystems
1703  * @dentry:     dentry of the parent directory
1704  * @str:        qstr of name whose hash we should fill in
1705  *
1706  * Return: 0 if hash was successful or unchanged, and -EINVAL on error
1707  */
1708 static int generic_ci_d_hash(const struct dentry *dentry, struct qstr *str)
1709 {
1710         const struct inode *dir = READ_ONCE(dentry->d_inode);
1711         struct super_block *sb = dentry->d_sb;
1712         const struct unicode_map *um = sb->s_encoding;
1713         int ret = 0;
1714
1715         if (!dir || !IS_CASEFOLDED(dir))
1716                 return 0;
1717
1718         ret = utf8_casefold_hash(um, dentry, str);
1719         if (ret < 0 && sb_has_strict_encoding(sb))
1720                 return -EINVAL;
1721         return 0;
1722 }
1723
1724 static const struct dentry_operations generic_ci_dentry_ops = {
1725         .d_hash = generic_ci_d_hash,
1726         .d_compare = generic_ci_d_compare,
1727 };
1728 #endif
1729
1730 #ifdef CONFIG_FS_ENCRYPTION
1731 static const struct dentry_operations generic_encrypted_dentry_ops = {
1732         .d_revalidate = fscrypt_d_revalidate,
1733 };
1734 #endif
1735
1736 #if defined(CONFIG_FS_ENCRYPTION) && IS_ENABLED(CONFIG_UNICODE)
1737 static const struct dentry_operations generic_encrypted_ci_dentry_ops = {
1738         .d_hash = generic_ci_d_hash,
1739         .d_compare = generic_ci_d_compare,
1740         .d_revalidate = fscrypt_d_revalidate,
1741 };
1742 #endif
1743
1744 /**
1745  * generic_set_encrypted_ci_d_ops - helper for setting d_ops for given dentry
1746  * @dentry:     dentry to set ops on
1747  *
1748  * Casefolded directories need d_hash and d_compare set, so that the dentries
1749  * contained in them are handled case-insensitively.  Note that these operations
1750  * are needed on the parent directory rather than on the dentries in it, and
1751  * while the casefolding flag can be toggled on and off on an empty directory,
1752  * dentry_operations can't be changed later.  As a result, if the filesystem has
1753  * casefolding support enabled at all, we have to give all dentries the
1754  * casefolding operations even if their inode doesn't have the casefolding flag
1755  * currently (and thus the casefolding ops would be no-ops for now).
1756  *
1757  * Encryption works differently in that the only dentry operation it needs is
1758  * d_revalidate, which it only needs on dentries that have the no-key name flag.
1759  * The no-key flag can't be set "later", so we don't have to worry about that.
1760  *
1761  * Finally, to maximize compatibility with overlayfs (which isn't compatible
1762  * with certain dentry operations) and to avoid taking an unnecessary
1763  * performance hit, we use custom dentry_operations for each possible
1764  * combination rather than always installing all operations.
1765  */
1766 void generic_set_encrypted_ci_d_ops(struct dentry *dentry)
1767 {
1768 #ifdef CONFIG_FS_ENCRYPTION
1769         bool needs_encrypt_ops = dentry->d_flags & DCACHE_NOKEY_NAME;
1770 #endif
1771 #if IS_ENABLED(CONFIG_UNICODE)
1772         bool needs_ci_ops = dentry->d_sb->s_encoding;
1773 #endif
1774 #if defined(CONFIG_FS_ENCRYPTION) && IS_ENABLED(CONFIG_UNICODE)
1775         if (needs_encrypt_ops && needs_ci_ops) {
1776                 d_set_d_op(dentry, &generic_encrypted_ci_dentry_ops);
1777                 return;
1778         }
1779 #endif
1780 #ifdef CONFIG_FS_ENCRYPTION
1781         if (needs_encrypt_ops) {
1782                 d_set_d_op(dentry, &generic_encrypted_dentry_ops);
1783                 return;
1784         }
1785 #endif
1786 #if IS_ENABLED(CONFIG_UNICODE)
1787         if (needs_ci_ops) {
1788                 d_set_d_op(dentry, &generic_ci_dentry_ops);
1789                 return;
1790         }
1791 #endif
1792 }
1793 EXPORT_SYMBOL(generic_set_encrypted_ci_d_ops);
1794
1795 /**
1796  * inode_maybe_inc_iversion - increments i_version
1797  * @inode: inode with the i_version that should be updated
1798  * @force: increment the counter even if it's not necessary?
1799  *
1800  * Every time the inode is modified, the i_version field must be seen to have
1801  * changed by any observer.
1802  *
1803  * If "force" is set or the QUERIED flag is set, then ensure that we increment
1804  * the value, and clear the queried flag.
1805  *
1806  * In the common case where neither is set, then we can return "false" without
1807  * updating i_version.
1808  *
1809  * If this function returns false, and no other metadata has changed, then we
1810  * can avoid logging the metadata.
1811  */
1812 bool inode_maybe_inc_iversion(struct inode *inode, bool force)
1813 {
1814         u64 cur, new;
1815
1816         /*
1817          * The i_version field is not strictly ordered with any other inode
1818          * information, but the legacy inode_inc_iversion code used a spinlock
1819          * to serialize increments.
1820          *
1821          * Here, we add full memory barriers to ensure that any de-facto
1822          * ordering with other info is preserved.
1823          *
1824          * This barrier pairs with the barrier in inode_query_iversion()
1825          */
1826         smp_mb();
1827         cur = inode_peek_iversion_raw(inode);
1828         do {
1829                 /* If flag is clear then we needn't do anything */
1830                 if (!force && !(cur & I_VERSION_QUERIED))
1831                         return false;
1832
1833                 /* Since lowest bit is flag, add 2 to avoid it */
1834                 new = (cur & ~I_VERSION_QUERIED) + I_VERSION_INCREMENT;
1835         } while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
1836         return true;
1837 }
1838 EXPORT_SYMBOL(inode_maybe_inc_iversion);
1839
1840 /**
1841  * inode_query_iversion - read i_version for later use
1842  * @inode: inode from which i_version should be read
1843  *
1844  * Read the inode i_version counter. This should be used by callers that wish
1845  * to store the returned i_version for later comparison. This will guarantee
1846  * that a later query of the i_version will result in a different value if
1847  * anything has changed.
1848  *
1849  * In this implementation, we fetch the current value, set the QUERIED flag and
1850  * then try to swap it into place with a cmpxchg, if it wasn't already set. If
1851  * that fails, we try again with the newly fetched value from the cmpxchg.
1852  */
1853 u64 inode_query_iversion(struct inode *inode)
1854 {
1855         u64 cur, new;
1856
1857         cur = inode_peek_iversion_raw(inode);
1858         do {
1859                 /* If flag is already set, then no need to swap */
1860                 if (cur & I_VERSION_QUERIED) {
1861                         /*
1862                          * This barrier (and the implicit barrier in the
1863                          * cmpxchg below) pairs with the barrier in
1864                          * inode_maybe_inc_iversion().
1865                          */
1866                         smp_mb();
1867                         break;
1868                 }
1869
1870                 new = cur | I_VERSION_QUERIED;
1871         } while (!atomic64_try_cmpxchg(&inode->i_version, &cur, new));
1872         return cur >> I_VERSION_QUERIED_SHIFT;
1873 }
1874 EXPORT_SYMBOL(inode_query_iversion);
1875
1876 ssize_t direct_write_fallback(struct kiocb *iocb, struct iov_iter *iter,
1877                 ssize_t direct_written, ssize_t buffered_written)
1878 {
1879         struct address_space *mapping = iocb->ki_filp->f_mapping;
1880         loff_t pos = iocb->ki_pos - buffered_written;
1881         loff_t end = iocb->ki_pos - 1;
1882         int err;
1883
1884         /*
1885          * If the buffered write fallback returned an error, we want to return
1886          * the number of bytes which were written by direct I/O, or the error
1887          * code if that was zero.
1888          *
1889          * Note that this differs from normal direct-io semantics, which will
1890          * return -EFOO even if some bytes were written.
1891          */
1892         if (unlikely(buffered_written < 0)) {
1893                 if (direct_written)
1894                         return direct_written;
1895                 return buffered_written;
1896         }
1897
1898         /*
1899          * We need to ensure that the page cache pages are written to disk and
1900          * invalidated to preserve the expected O_DIRECT semantics.
1901          */
1902         err = filemap_write_and_wait_range(mapping, pos, end);
1903         if (err < 0) {
1904                 /*
1905                  * We don't know how much we wrote, so just return the number of
1906                  * bytes which were direct-written
1907                  */
1908                 iocb->ki_pos -= buffered_written;
1909                 if (direct_written)
1910                         return direct_written;
1911                 return err;
1912         }
1913         invalidate_mapping_pages(mapping, pos >> PAGE_SHIFT, end >> PAGE_SHIFT);
1914         return direct_written + buffered_written;
1915 }
1916 EXPORT_SYMBOL_GPL(direct_write_fallback);
1917
1918 /**
1919  * simple_inode_init_ts - initialize the timestamps for a new inode
1920  * @inode: inode to be initialized
1921  *
1922  * When a new inode is created, most filesystems set the timestamps to the
1923  * current time. Add a helper to do this.
1924  */
1925 struct timespec64 simple_inode_init_ts(struct inode *inode)
1926 {
1927         struct timespec64 ts = inode_set_ctime_current(inode);
1928
1929         inode_set_atime_to_ts(inode, ts);
1930         inode_set_mtime_to_ts(inode, ts);
1931         return ts;
1932 }
1933 EXPORT_SYMBOL(simple_inode_init_ts);