Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

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