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