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