1 /* 2 * Resizable virtual memory filesystem for Linux. 3 * 4 * Copyright (C) 2000 Linus Torvalds. 5 * 2000 Transmeta Corp. 6 * 2000-2001 Christoph Rohland 7 * 2000-2001 SAP AG 8 * 2002 Red Hat Inc. 9 * Copyright (C) 2002-2011 Hugh Dickins. 10 * Copyright (C) 2011 Google Inc. 11 * Copyright (C) 2002-2005 VERITAS Software Corporation. 12 * Copyright (C) 2004 Andi Kleen, SuSE Labs 13 * 14 * Extended attribute support for tmpfs: 15 * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net> 16 * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com> 17 * 18 * tiny-shmem: 19 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com> 20 * 21 * This file is released under the GPL. 22 */ 23 24 #include <linux/fs.h> 25 #include <linux/init.h> 26 #include <linux/vfs.h> 27 #include <linux/mount.h> 28 #include <linux/ramfs.h> 29 #include <linux/pagemap.h> 30 #include <linux/file.h> 31 #include <linux/fileattr.h> 32 #include <linux/mm.h> 33 #include <linux/random.h> 34 #include <linux/sched/signal.h> 35 #include <linux/export.h> 36 #include <linux/shmem_fs.h> 37 #include <linux/swap.h> 38 #include <linux/uio.h> 39 #include <linux/hugetlb.h> 40 #include <linux/fs_parser.h> 41 #include <linux/swapfile.h> 42 #include <linux/iversion.h> 43 #include <linux/unicode.h> 44 #include "swap.h" 45 46 static struct vfsmount *shm_mnt __ro_after_init; 47 48 #ifdef CONFIG_SHMEM 49 /* 50 * This virtual memory filesystem is heavily based on the ramfs. It 51 * extends ramfs by the ability to use swap and honor resource limits 52 * which makes it a completely usable filesystem. 53 */ 54 55 #include <linux/xattr.h> 56 #include <linux/exportfs.h> 57 #include <linux/posix_acl.h> 58 #include <linux/posix_acl_xattr.h> 59 #include <linux/mman.h> 60 #include <linux/string.h> 61 #include <linux/slab.h> 62 #include <linux/backing-dev.h> 63 #include <linux/writeback.h> 64 #include <linux/pagevec.h> 65 #include <linux/percpu_counter.h> 66 #include <linux/falloc.h> 67 #include <linux/splice.h> 68 #include <linux/security.h> 69 #include <linux/swapops.h> 70 #include <linux/mempolicy.h> 71 #include <linux/namei.h> 72 #include <linux/ctype.h> 73 #include <linux/migrate.h> 74 #include <linux/highmem.h> 75 #include <linux/seq_file.h> 76 #include <linux/magic.h> 77 #include <linux/syscalls.h> 78 #include <linux/fcntl.h> 79 #include <uapi/linux/memfd.h> 80 #include <linux/rmap.h> 81 #include <linux/uuid.h> 82 #include <linux/quotaops.h> 83 #include <linux/rcupdate_wait.h> 84 85 #include <linux/uaccess.h> 86 87 #include "internal.h" 88 89 #define BLOCKS_PER_PAGE (PAGE_SIZE/512) 90 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT) 91 92 /* Pretend that each entry is of this size in directory's i_size */ 93 #define BOGO_DIRENT_SIZE 20 94 95 /* Pretend that one inode + its dentry occupy this much memory */ 96 #define BOGO_INODE_SIZE 1024 97 98 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */ 99 #define SHORT_SYMLINK_LEN 128 100 101 /* 102 * shmem_fallocate communicates with shmem_fault or shmem_writepage via 103 * inode->i_private (with i_rwsem making sure that it has only one user at 104 * a time): we would prefer not to enlarge the shmem inode just for that. 105 */ 106 struct shmem_falloc { 107 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */ 108 pgoff_t start; /* start of range currently being fallocated */ 109 pgoff_t next; /* the next page offset to be fallocated */ 110 pgoff_t nr_falloced; /* how many new pages have been fallocated */ 111 pgoff_t nr_unswapped; /* how often writepage refused to swap out */ 112 }; 113 114 struct shmem_options { 115 unsigned long long blocks; 116 unsigned long long inodes; 117 struct mempolicy *mpol; 118 kuid_t uid; 119 kgid_t gid; 120 umode_t mode; 121 bool full_inums; 122 int huge; 123 int seen; 124 bool noswap; 125 unsigned short quota_types; 126 struct shmem_quota_limits qlimits; 127 #if IS_ENABLED(CONFIG_UNICODE) 128 struct unicode_map *encoding; 129 bool strict_encoding; 130 #endif 131 #define SHMEM_SEEN_BLOCKS 1 132 #define SHMEM_SEEN_INODES 2 133 #define SHMEM_SEEN_HUGE 4 134 #define SHMEM_SEEN_INUMS 8 135 #define SHMEM_SEEN_NOSWAP 16 136 #define SHMEM_SEEN_QUOTA 32 137 }; 138 139 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 140 static unsigned long huge_shmem_orders_always __read_mostly; 141 static unsigned long huge_shmem_orders_madvise __read_mostly; 142 static unsigned long huge_shmem_orders_inherit __read_mostly; 143 static unsigned long huge_shmem_orders_within_size __read_mostly; 144 static bool shmem_orders_configured __initdata; 145 #endif 146 147 #ifdef CONFIG_TMPFS 148 static unsigned long shmem_default_max_blocks(void) 149 { 150 return totalram_pages() / 2; 151 } 152 153 static unsigned long shmem_default_max_inodes(void) 154 { 155 unsigned long nr_pages = totalram_pages(); 156 157 return min3(nr_pages - totalhigh_pages(), nr_pages / 2, 158 ULONG_MAX / BOGO_INODE_SIZE); 159 } 160 #endif 161 162 static int shmem_swapin_folio(struct inode *inode, pgoff_t index, 163 struct folio **foliop, enum sgp_type sgp, gfp_t gfp, 164 struct vm_area_struct *vma, vm_fault_t *fault_type); 165 166 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb) 167 { 168 return sb->s_fs_info; 169 } 170 171 /* 172 * shmem_file_setup pre-accounts the whole fixed size of a VM object, 173 * for shared memory and for shared anonymous (/dev/zero) mappings 174 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1), 175 * consistent with the pre-accounting of private mappings ... 176 */ 177 static inline int shmem_acct_size(unsigned long flags, loff_t size) 178 { 179 return (flags & VM_NORESERVE) ? 180 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size)); 181 } 182 183 static inline void shmem_unacct_size(unsigned long flags, loff_t size) 184 { 185 if (!(flags & VM_NORESERVE)) 186 vm_unacct_memory(VM_ACCT(size)); 187 } 188 189 static inline int shmem_reacct_size(unsigned long flags, 190 loff_t oldsize, loff_t newsize) 191 { 192 if (!(flags & VM_NORESERVE)) { 193 if (VM_ACCT(newsize) > VM_ACCT(oldsize)) 194 return security_vm_enough_memory_mm(current->mm, 195 VM_ACCT(newsize) - VM_ACCT(oldsize)); 196 else if (VM_ACCT(newsize) < VM_ACCT(oldsize)) 197 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize)); 198 } 199 return 0; 200 } 201 202 /* 203 * ... whereas tmpfs objects are accounted incrementally as 204 * pages are allocated, in order to allow large sparse files. 205 * shmem_get_folio reports shmem_acct_blocks failure as -ENOSPC not -ENOMEM, 206 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM. 207 */ 208 static inline int shmem_acct_blocks(unsigned long flags, long pages) 209 { 210 if (!(flags & VM_NORESERVE)) 211 return 0; 212 213 return security_vm_enough_memory_mm(current->mm, 214 pages * VM_ACCT(PAGE_SIZE)); 215 } 216 217 static inline void shmem_unacct_blocks(unsigned long flags, long pages) 218 { 219 if (flags & VM_NORESERVE) 220 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE)); 221 } 222 223 static int shmem_inode_acct_blocks(struct inode *inode, long pages) 224 { 225 struct shmem_inode_info *info = SHMEM_I(inode); 226 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 227 int err = -ENOSPC; 228 229 if (shmem_acct_blocks(info->flags, pages)) 230 return err; 231 232 might_sleep(); /* when quotas */ 233 if (sbinfo->max_blocks) { 234 if (!percpu_counter_limited_add(&sbinfo->used_blocks, 235 sbinfo->max_blocks, pages)) 236 goto unacct; 237 238 err = dquot_alloc_block_nodirty(inode, pages); 239 if (err) { 240 percpu_counter_sub(&sbinfo->used_blocks, pages); 241 goto unacct; 242 } 243 } else { 244 err = dquot_alloc_block_nodirty(inode, pages); 245 if (err) 246 goto unacct; 247 } 248 249 return 0; 250 251 unacct: 252 shmem_unacct_blocks(info->flags, pages); 253 return err; 254 } 255 256 static void shmem_inode_unacct_blocks(struct inode *inode, long pages) 257 { 258 struct shmem_inode_info *info = SHMEM_I(inode); 259 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 260 261 might_sleep(); /* when quotas */ 262 dquot_free_block_nodirty(inode, pages); 263 264 if (sbinfo->max_blocks) 265 percpu_counter_sub(&sbinfo->used_blocks, pages); 266 shmem_unacct_blocks(info->flags, pages); 267 } 268 269 static const struct super_operations shmem_ops; 270 static const struct address_space_operations shmem_aops; 271 static const struct file_operations shmem_file_operations; 272 static const struct inode_operations shmem_inode_operations; 273 static const struct inode_operations shmem_dir_inode_operations; 274 static const struct inode_operations shmem_special_inode_operations; 275 static const struct vm_operations_struct shmem_vm_ops; 276 static const struct vm_operations_struct shmem_anon_vm_ops; 277 static struct file_system_type shmem_fs_type; 278 279 bool shmem_mapping(struct address_space *mapping) 280 { 281 return mapping->a_ops == &shmem_aops; 282 } 283 EXPORT_SYMBOL_GPL(shmem_mapping); 284 285 bool vma_is_anon_shmem(struct vm_area_struct *vma) 286 { 287 return vma->vm_ops == &shmem_anon_vm_ops; 288 } 289 290 bool vma_is_shmem(struct vm_area_struct *vma) 291 { 292 return vma_is_anon_shmem(vma) || vma->vm_ops == &shmem_vm_ops; 293 } 294 295 static LIST_HEAD(shmem_swaplist); 296 static DEFINE_MUTEX(shmem_swaplist_mutex); 297 298 #ifdef CONFIG_TMPFS_QUOTA 299 300 static int shmem_enable_quotas(struct super_block *sb, 301 unsigned short quota_types) 302 { 303 int type, err = 0; 304 305 sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY; 306 for (type = 0; type < SHMEM_MAXQUOTAS; type++) { 307 if (!(quota_types & (1 << type))) 308 continue; 309 err = dquot_load_quota_sb(sb, type, QFMT_SHMEM, 310 DQUOT_USAGE_ENABLED | 311 DQUOT_LIMITS_ENABLED); 312 if (err) 313 goto out_err; 314 } 315 return 0; 316 317 out_err: 318 pr_warn("tmpfs: failed to enable quota tracking (type=%d, err=%d)\n", 319 type, err); 320 for (type--; type >= 0; type--) 321 dquot_quota_off(sb, type); 322 return err; 323 } 324 325 static void shmem_disable_quotas(struct super_block *sb) 326 { 327 int type; 328 329 for (type = 0; type < SHMEM_MAXQUOTAS; type++) 330 dquot_quota_off(sb, type); 331 } 332 333 static struct dquot __rcu **shmem_get_dquots(struct inode *inode) 334 { 335 return SHMEM_I(inode)->i_dquot; 336 } 337 #endif /* CONFIG_TMPFS_QUOTA */ 338 339 /* 340 * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and 341 * produces a novel ino for the newly allocated inode. 342 * 343 * It may also be called when making a hard link to permit the space needed by 344 * each dentry. However, in that case, no new inode number is needed since that 345 * internally draws from another pool of inode numbers (currently global 346 * get_next_ino()). This case is indicated by passing NULL as inop. 347 */ 348 #define SHMEM_INO_BATCH 1024 349 static int shmem_reserve_inode(struct super_block *sb, ino_t *inop) 350 { 351 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 352 ino_t ino; 353 354 if (!(sb->s_flags & SB_KERNMOUNT)) { 355 raw_spin_lock(&sbinfo->stat_lock); 356 if (sbinfo->max_inodes) { 357 if (sbinfo->free_ispace < BOGO_INODE_SIZE) { 358 raw_spin_unlock(&sbinfo->stat_lock); 359 return -ENOSPC; 360 } 361 sbinfo->free_ispace -= BOGO_INODE_SIZE; 362 } 363 if (inop) { 364 ino = sbinfo->next_ino++; 365 if (unlikely(is_zero_ino(ino))) 366 ino = sbinfo->next_ino++; 367 if (unlikely(!sbinfo->full_inums && 368 ino > UINT_MAX)) { 369 /* 370 * Emulate get_next_ino uint wraparound for 371 * compatibility 372 */ 373 if (IS_ENABLED(CONFIG_64BIT)) 374 pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n", 375 __func__, MINOR(sb->s_dev)); 376 sbinfo->next_ino = 1; 377 ino = sbinfo->next_ino++; 378 } 379 *inop = ino; 380 } 381 raw_spin_unlock(&sbinfo->stat_lock); 382 } else if (inop) { 383 /* 384 * __shmem_file_setup, one of our callers, is lock-free: it 385 * doesn't hold stat_lock in shmem_reserve_inode since 386 * max_inodes is always 0, and is called from potentially 387 * unknown contexts. As such, use a per-cpu batched allocator 388 * which doesn't require the per-sb stat_lock unless we are at 389 * the batch boundary. 390 * 391 * We don't need to worry about inode{32,64} since SB_KERNMOUNT 392 * shmem mounts are not exposed to userspace, so we don't need 393 * to worry about things like glibc compatibility. 394 */ 395 ino_t *next_ino; 396 397 next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu()); 398 ino = *next_ino; 399 if (unlikely(ino % SHMEM_INO_BATCH == 0)) { 400 raw_spin_lock(&sbinfo->stat_lock); 401 ino = sbinfo->next_ino; 402 sbinfo->next_ino += SHMEM_INO_BATCH; 403 raw_spin_unlock(&sbinfo->stat_lock); 404 if (unlikely(is_zero_ino(ino))) 405 ino++; 406 } 407 *inop = ino; 408 *next_ino = ++ino; 409 put_cpu(); 410 } 411 412 return 0; 413 } 414 415 static void shmem_free_inode(struct super_block *sb, size_t freed_ispace) 416 { 417 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 418 if (sbinfo->max_inodes) { 419 raw_spin_lock(&sbinfo->stat_lock); 420 sbinfo->free_ispace += BOGO_INODE_SIZE + freed_ispace; 421 raw_spin_unlock(&sbinfo->stat_lock); 422 } 423 } 424 425 /** 426 * shmem_recalc_inode - recalculate the block usage of an inode 427 * @inode: inode to recalc 428 * @alloced: the change in number of pages allocated to inode 429 * @swapped: the change in number of pages swapped from inode 430 * 431 * We have to calculate the free blocks since the mm can drop 432 * undirtied hole pages behind our back. 433 * 434 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped 435 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped) 436 */ 437 static void shmem_recalc_inode(struct inode *inode, long alloced, long swapped) 438 { 439 struct shmem_inode_info *info = SHMEM_I(inode); 440 long freed; 441 442 spin_lock(&info->lock); 443 info->alloced += alloced; 444 info->swapped += swapped; 445 freed = info->alloced - info->swapped - 446 READ_ONCE(inode->i_mapping->nrpages); 447 /* 448 * Special case: whereas normally shmem_recalc_inode() is called 449 * after i_mapping->nrpages has already been adjusted (up or down), 450 * shmem_writepage() has to raise swapped before nrpages is lowered - 451 * to stop a racing shmem_recalc_inode() from thinking that a page has 452 * been freed. Compensate here, to avoid the need for a followup call. 453 */ 454 if (swapped > 0) 455 freed += swapped; 456 if (freed > 0) 457 info->alloced -= freed; 458 spin_unlock(&info->lock); 459 460 /* The quota case may block */ 461 if (freed > 0) 462 shmem_inode_unacct_blocks(inode, freed); 463 } 464 465 bool shmem_charge(struct inode *inode, long pages) 466 { 467 struct address_space *mapping = inode->i_mapping; 468 469 if (shmem_inode_acct_blocks(inode, pages)) 470 return false; 471 472 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */ 473 xa_lock_irq(&mapping->i_pages); 474 mapping->nrpages += pages; 475 xa_unlock_irq(&mapping->i_pages); 476 477 shmem_recalc_inode(inode, pages, 0); 478 return true; 479 } 480 481 void shmem_uncharge(struct inode *inode, long pages) 482 { 483 /* pages argument is currently unused: keep it to help debugging */ 484 /* nrpages adjustment done by __filemap_remove_folio() or caller */ 485 486 shmem_recalc_inode(inode, 0, 0); 487 } 488 489 /* 490 * Replace item expected in xarray by a new item, while holding xa_lock. 491 */ 492 static int shmem_replace_entry(struct address_space *mapping, 493 pgoff_t index, void *expected, void *replacement) 494 { 495 XA_STATE(xas, &mapping->i_pages, index); 496 void *item; 497 498 VM_BUG_ON(!expected); 499 VM_BUG_ON(!replacement); 500 item = xas_load(&xas); 501 if (item != expected) 502 return -ENOENT; 503 xas_store(&xas, replacement); 504 return 0; 505 } 506 507 /* 508 * Sometimes, before we decide whether to proceed or to fail, we must check 509 * that an entry was not already brought back from swap by a racing thread. 510 * 511 * Checking folio is not enough: by the time a swapcache folio is locked, it 512 * might be reused, and again be swapcache, using the same swap as before. 513 */ 514 static bool shmem_confirm_swap(struct address_space *mapping, 515 pgoff_t index, swp_entry_t swap) 516 { 517 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap); 518 } 519 520 /* 521 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option 522 * 523 * SHMEM_HUGE_NEVER: 524 * disables huge pages for the mount; 525 * SHMEM_HUGE_ALWAYS: 526 * enables huge pages for the mount; 527 * SHMEM_HUGE_WITHIN_SIZE: 528 * only allocate huge pages if the page will be fully within i_size, 529 * also respect fadvise()/madvise() hints; 530 * SHMEM_HUGE_ADVISE: 531 * only allocate huge pages if requested with fadvise()/madvise(); 532 */ 533 534 #define SHMEM_HUGE_NEVER 0 535 #define SHMEM_HUGE_ALWAYS 1 536 #define SHMEM_HUGE_WITHIN_SIZE 2 537 #define SHMEM_HUGE_ADVISE 3 538 539 /* 540 * Special values. 541 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled: 542 * 543 * SHMEM_HUGE_DENY: 544 * disables huge on shm_mnt and all mounts, for emergency use; 545 * SHMEM_HUGE_FORCE: 546 * enables huge on shm_mnt and all mounts, w/o needing option, for testing; 547 * 548 */ 549 #define SHMEM_HUGE_DENY (-1) 550 #define SHMEM_HUGE_FORCE (-2) 551 552 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 553 /* ifdef here to avoid bloating shmem.o when not necessary */ 554 555 static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER; 556 557 static bool shmem_huge_global_enabled(struct inode *inode, pgoff_t index, 558 loff_t write_end, bool shmem_huge_force, 559 unsigned long vm_flags) 560 { 561 loff_t i_size; 562 563 if (HPAGE_PMD_ORDER > MAX_PAGECACHE_ORDER) 564 return false; 565 if (!S_ISREG(inode->i_mode)) 566 return false; 567 if (shmem_huge == SHMEM_HUGE_DENY) 568 return false; 569 if (shmem_huge_force || shmem_huge == SHMEM_HUGE_FORCE) 570 return true; 571 572 switch (SHMEM_SB(inode->i_sb)->huge) { 573 case SHMEM_HUGE_ALWAYS: 574 return true; 575 case SHMEM_HUGE_WITHIN_SIZE: 576 index = round_up(index + 1, HPAGE_PMD_NR); 577 i_size = max(write_end, i_size_read(inode)); 578 i_size = round_up(i_size, PAGE_SIZE); 579 if (i_size >> PAGE_SHIFT >= index) 580 return true; 581 fallthrough; 582 case SHMEM_HUGE_ADVISE: 583 if (vm_flags & VM_HUGEPAGE) 584 return true; 585 fallthrough; 586 default: 587 return false; 588 } 589 } 590 591 static int shmem_parse_huge(const char *str) 592 { 593 int huge; 594 595 if (!str) 596 return -EINVAL; 597 598 if (!strcmp(str, "never")) 599 huge = SHMEM_HUGE_NEVER; 600 else if (!strcmp(str, "always")) 601 huge = SHMEM_HUGE_ALWAYS; 602 else if (!strcmp(str, "within_size")) 603 huge = SHMEM_HUGE_WITHIN_SIZE; 604 else if (!strcmp(str, "advise")) 605 huge = SHMEM_HUGE_ADVISE; 606 else if (!strcmp(str, "deny")) 607 huge = SHMEM_HUGE_DENY; 608 else if (!strcmp(str, "force")) 609 huge = SHMEM_HUGE_FORCE; 610 else 611 return -EINVAL; 612 613 if (!has_transparent_hugepage() && 614 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY) 615 return -EINVAL; 616 617 /* Do not override huge allocation policy with non-PMD sized mTHP */ 618 if (huge == SHMEM_HUGE_FORCE && 619 huge_shmem_orders_inherit != BIT(HPAGE_PMD_ORDER)) 620 return -EINVAL; 621 622 return huge; 623 } 624 625 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS) 626 static const char *shmem_format_huge(int huge) 627 { 628 switch (huge) { 629 case SHMEM_HUGE_NEVER: 630 return "never"; 631 case SHMEM_HUGE_ALWAYS: 632 return "always"; 633 case SHMEM_HUGE_WITHIN_SIZE: 634 return "within_size"; 635 case SHMEM_HUGE_ADVISE: 636 return "advise"; 637 case SHMEM_HUGE_DENY: 638 return "deny"; 639 case SHMEM_HUGE_FORCE: 640 return "force"; 641 default: 642 VM_BUG_ON(1); 643 return "bad_val"; 644 } 645 } 646 #endif 647 648 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, 649 struct shrink_control *sc, unsigned long nr_to_free) 650 { 651 LIST_HEAD(list), *pos, *next; 652 struct inode *inode; 653 struct shmem_inode_info *info; 654 struct folio *folio; 655 unsigned long batch = sc ? sc->nr_to_scan : 128; 656 unsigned long split = 0, freed = 0; 657 658 if (list_empty(&sbinfo->shrinklist)) 659 return SHRINK_STOP; 660 661 spin_lock(&sbinfo->shrinklist_lock); 662 list_for_each_safe(pos, next, &sbinfo->shrinklist) { 663 info = list_entry(pos, struct shmem_inode_info, shrinklist); 664 665 /* pin the inode */ 666 inode = igrab(&info->vfs_inode); 667 668 /* inode is about to be evicted */ 669 if (!inode) { 670 list_del_init(&info->shrinklist); 671 goto next; 672 } 673 674 list_move(&info->shrinklist, &list); 675 next: 676 sbinfo->shrinklist_len--; 677 if (!--batch) 678 break; 679 } 680 spin_unlock(&sbinfo->shrinklist_lock); 681 682 list_for_each_safe(pos, next, &list) { 683 pgoff_t next, end; 684 loff_t i_size; 685 int ret; 686 687 info = list_entry(pos, struct shmem_inode_info, shrinklist); 688 inode = &info->vfs_inode; 689 690 if (nr_to_free && freed >= nr_to_free) 691 goto move_back; 692 693 i_size = i_size_read(inode); 694 folio = filemap_get_entry(inode->i_mapping, i_size / PAGE_SIZE); 695 if (!folio || xa_is_value(folio)) 696 goto drop; 697 698 /* No large folio at the end of the file: nothing to split */ 699 if (!folio_test_large(folio)) { 700 folio_put(folio); 701 goto drop; 702 } 703 704 /* Check if there is anything to gain from splitting */ 705 next = folio_next_index(folio); 706 end = shmem_fallocend(inode, DIV_ROUND_UP(i_size, PAGE_SIZE)); 707 if (end <= folio->index || end >= next) { 708 folio_put(folio); 709 goto drop; 710 } 711 712 /* 713 * Move the inode on the list back to shrinklist if we failed 714 * to lock the page at this time. 715 * 716 * Waiting for the lock may lead to deadlock in the 717 * reclaim path. 718 */ 719 if (!folio_trylock(folio)) { 720 folio_put(folio); 721 goto move_back; 722 } 723 724 ret = split_folio(folio); 725 folio_unlock(folio); 726 folio_put(folio); 727 728 /* If split failed move the inode on the list back to shrinklist */ 729 if (ret) 730 goto move_back; 731 732 freed += next - end; 733 split++; 734 drop: 735 list_del_init(&info->shrinklist); 736 goto put; 737 move_back: 738 /* 739 * Make sure the inode is either on the global list or deleted 740 * from any local list before iput() since it could be deleted 741 * in another thread once we put the inode (then the local list 742 * is corrupted). 743 */ 744 spin_lock(&sbinfo->shrinklist_lock); 745 list_move(&info->shrinklist, &sbinfo->shrinklist); 746 sbinfo->shrinklist_len++; 747 spin_unlock(&sbinfo->shrinklist_lock); 748 put: 749 iput(inode); 750 } 751 752 return split; 753 } 754 755 static long shmem_unused_huge_scan(struct super_block *sb, 756 struct shrink_control *sc) 757 { 758 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 759 760 if (!READ_ONCE(sbinfo->shrinklist_len)) 761 return SHRINK_STOP; 762 763 return shmem_unused_huge_shrink(sbinfo, sc, 0); 764 } 765 766 static long shmem_unused_huge_count(struct super_block *sb, 767 struct shrink_control *sc) 768 { 769 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 770 return READ_ONCE(sbinfo->shrinklist_len); 771 } 772 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */ 773 774 #define shmem_huge SHMEM_HUGE_DENY 775 776 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, 777 struct shrink_control *sc, unsigned long nr_to_free) 778 { 779 return 0; 780 } 781 782 static bool shmem_huge_global_enabled(struct inode *inode, pgoff_t index, 783 loff_t write_end, bool shmem_huge_force, 784 unsigned long vm_flags) 785 { 786 return false; 787 } 788 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 789 790 /* 791 * Somewhat like filemap_add_folio, but error if expected item has gone. 792 */ 793 static int shmem_add_to_page_cache(struct folio *folio, 794 struct address_space *mapping, 795 pgoff_t index, void *expected, gfp_t gfp) 796 { 797 XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio)); 798 long nr = folio_nr_pages(folio); 799 800 VM_BUG_ON_FOLIO(index != round_down(index, nr), folio); 801 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 802 VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio); 803 804 folio_ref_add(folio, nr); 805 folio->mapping = mapping; 806 folio->index = index; 807 808 gfp &= GFP_RECLAIM_MASK; 809 folio_throttle_swaprate(folio, gfp); 810 811 do { 812 xas_lock_irq(&xas); 813 if (expected != xas_find_conflict(&xas)) { 814 xas_set_err(&xas, -EEXIST); 815 goto unlock; 816 } 817 if (expected && xas_find_conflict(&xas)) { 818 xas_set_err(&xas, -EEXIST); 819 goto unlock; 820 } 821 xas_store(&xas, folio); 822 if (xas_error(&xas)) 823 goto unlock; 824 if (folio_test_pmd_mappable(folio)) 825 __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr); 826 __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr); 827 __lruvec_stat_mod_folio(folio, NR_SHMEM, nr); 828 mapping->nrpages += nr; 829 unlock: 830 xas_unlock_irq(&xas); 831 } while (xas_nomem(&xas, gfp)); 832 833 if (xas_error(&xas)) { 834 folio->mapping = NULL; 835 folio_ref_sub(folio, nr); 836 return xas_error(&xas); 837 } 838 839 return 0; 840 } 841 842 /* 843 * Somewhat like filemap_remove_folio, but substitutes swap for @folio. 844 */ 845 static void shmem_delete_from_page_cache(struct folio *folio, void *radswap) 846 { 847 struct address_space *mapping = folio->mapping; 848 long nr = folio_nr_pages(folio); 849 int error; 850 851 xa_lock_irq(&mapping->i_pages); 852 error = shmem_replace_entry(mapping, folio->index, folio, radswap); 853 folio->mapping = NULL; 854 mapping->nrpages -= nr; 855 __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr); 856 __lruvec_stat_mod_folio(folio, NR_SHMEM, -nr); 857 xa_unlock_irq(&mapping->i_pages); 858 folio_put_refs(folio, nr); 859 BUG_ON(error); 860 } 861 862 /* 863 * Remove swap entry from page cache, free the swap and its page cache. Returns 864 * the number of pages being freed. 0 means entry not found in XArray (0 pages 865 * being freed). 866 */ 867 static long shmem_free_swap(struct address_space *mapping, 868 pgoff_t index, void *radswap) 869 { 870 int order = xa_get_order(&mapping->i_pages, index); 871 void *old; 872 873 old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0); 874 if (old != radswap) 875 return 0; 876 free_swap_and_cache_nr(radix_to_swp_entry(radswap), 1 << order); 877 878 return 1 << order; 879 } 880 881 /* 882 * Determine (in bytes) how many of the shmem object's pages mapped by the 883 * given offsets are swapped out. 884 * 885 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU, 886 * as long as the inode doesn't go away and racy results are not a problem. 887 */ 888 unsigned long shmem_partial_swap_usage(struct address_space *mapping, 889 pgoff_t start, pgoff_t end) 890 { 891 XA_STATE(xas, &mapping->i_pages, start); 892 struct page *page; 893 unsigned long swapped = 0; 894 unsigned long max = end - 1; 895 896 rcu_read_lock(); 897 xas_for_each(&xas, page, max) { 898 if (xas_retry(&xas, page)) 899 continue; 900 if (xa_is_value(page)) 901 swapped += 1 << xas_get_order(&xas); 902 if (xas.xa_index == max) 903 break; 904 if (need_resched()) { 905 xas_pause(&xas); 906 cond_resched_rcu(); 907 } 908 } 909 rcu_read_unlock(); 910 911 return swapped << PAGE_SHIFT; 912 } 913 914 /* 915 * Determine (in bytes) how many of the shmem object's pages mapped by the 916 * given vma is swapped out. 917 * 918 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU, 919 * as long as the inode doesn't go away and racy results are not a problem. 920 */ 921 unsigned long shmem_swap_usage(struct vm_area_struct *vma) 922 { 923 struct inode *inode = file_inode(vma->vm_file); 924 struct shmem_inode_info *info = SHMEM_I(inode); 925 struct address_space *mapping = inode->i_mapping; 926 unsigned long swapped; 927 928 /* Be careful as we don't hold info->lock */ 929 swapped = READ_ONCE(info->swapped); 930 931 /* 932 * The easier cases are when the shmem object has nothing in swap, or 933 * the vma maps it whole. Then we can simply use the stats that we 934 * already track. 935 */ 936 if (!swapped) 937 return 0; 938 939 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size) 940 return swapped << PAGE_SHIFT; 941 942 /* Here comes the more involved part */ 943 return shmem_partial_swap_usage(mapping, vma->vm_pgoff, 944 vma->vm_pgoff + vma_pages(vma)); 945 } 946 947 /* 948 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists. 949 */ 950 void shmem_unlock_mapping(struct address_space *mapping) 951 { 952 struct folio_batch fbatch; 953 pgoff_t index = 0; 954 955 folio_batch_init(&fbatch); 956 /* 957 * Minor point, but we might as well stop if someone else SHM_LOCKs it. 958 */ 959 while (!mapping_unevictable(mapping) && 960 filemap_get_folios(mapping, &index, ~0UL, &fbatch)) { 961 check_move_unevictable_folios(&fbatch); 962 folio_batch_release(&fbatch); 963 cond_resched(); 964 } 965 } 966 967 static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index) 968 { 969 struct folio *folio; 970 971 /* 972 * At first avoid shmem_get_folio(,,,SGP_READ): that fails 973 * beyond i_size, and reports fallocated folios as holes. 974 */ 975 folio = filemap_get_entry(inode->i_mapping, index); 976 if (!folio) 977 return folio; 978 if (!xa_is_value(folio)) { 979 folio_lock(folio); 980 if (folio->mapping == inode->i_mapping) 981 return folio; 982 /* The folio has been swapped out */ 983 folio_unlock(folio); 984 folio_put(folio); 985 } 986 /* 987 * But read a folio back from swap if any of it is within i_size 988 * (although in some cases this is just a waste of time). 989 */ 990 folio = NULL; 991 shmem_get_folio(inode, index, 0, &folio, SGP_READ); 992 return folio; 993 } 994 995 /* 996 * Remove range of pages and swap entries from page cache, and free them. 997 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate. 998 */ 999 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend, 1000 bool unfalloc) 1001 { 1002 struct address_space *mapping = inode->i_mapping; 1003 struct shmem_inode_info *info = SHMEM_I(inode); 1004 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT; 1005 pgoff_t end = (lend + 1) >> PAGE_SHIFT; 1006 struct folio_batch fbatch; 1007 pgoff_t indices[PAGEVEC_SIZE]; 1008 struct folio *folio; 1009 bool same_folio; 1010 long nr_swaps_freed = 0; 1011 pgoff_t index; 1012 int i; 1013 1014 if (lend == -1) 1015 end = -1; /* unsigned, so actually very big */ 1016 1017 if (info->fallocend > start && info->fallocend <= end && !unfalloc) 1018 info->fallocend = start; 1019 1020 folio_batch_init(&fbatch); 1021 index = start; 1022 while (index < end && find_lock_entries(mapping, &index, end - 1, 1023 &fbatch, indices)) { 1024 for (i = 0; i < folio_batch_count(&fbatch); i++) { 1025 folio = fbatch.folios[i]; 1026 1027 if (xa_is_value(folio)) { 1028 if (unfalloc) 1029 continue; 1030 nr_swaps_freed += shmem_free_swap(mapping, 1031 indices[i], folio); 1032 continue; 1033 } 1034 1035 if (!unfalloc || !folio_test_uptodate(folio)) 1036 truncate_inode_folio(mapping, folio); 1037 folio_unlock(folio); 1038 } 1039 folio_batch_remove_exceptionals(&fbatch); 1040 folio_batch_release(&fbatch); 1041 cond_resched(); 1042 } 1043 1044 /* 1045 * When undoing a failed fallocate, we want none of the partial folio 1046 * zeroing and splitting below, but shall want to truncate the whole 1047 * folio when !uptodate indicates that it was added by this fallocate, 1048 * even when [lstart, lend] covers only a part of the folio. 1049 */ 1050 if (unfalloc) 1051 goto whole_folios; 1052 1053 same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT); 1054 folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT); 1055 if (folio) { 1056 same_folio = lend < folio_pos(folio) + folio_size(folio); 1057 folio_mark_dirty(folio); 1058 if (!truncate_inode_partial_folio(folio, lstart, lend)) { 1059 start = folio_next_index(folio); 1060 if (same_folio) 1061 end = folio->index; 1062 } 1063 folio_unlock(folio); 1064 folio_put(folio); 1065 folio = NULL; 1066 } 1067 1068 if (!same_folio) 1069 folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT); 1070 if (folio) { 1071 folio_mark_dirty(folio); 1072 if (!truncate_inode_partial_folio(folio, lstart, lend)) 1073 end = folio->index; 1074 folio_unlock(folio); 1075 folio_put(folio); 1076 } 1077 1078 whole_folios: 1079 1080 index = start; 1081 while (index < end) { 1082 cond_resched(); 1083 1084 if (!find_get_entries(mapping, &index, end - 1, &fbatch, 1085 indices)) { 1086 /* If all gone or hole-punch or unfalloc, we're done */ 1087 if (index == start || end != -1) 1088 break; 1089 /* But if truncating, restart to make sure all gone */ 1090 index = start; 1091 continue; 1092 } 1093 for (i = 0; i < folio_batch_count(&fbatch); i++) { 1094 folio = fbatch.folios[i]; 1095 1096 if (xa_is_value(folio)) { 1097 long swaps_freed; 1098 1099 if (unfalloc) 1100 continue; 1101 swaps_freed = shmem_free_swap(mapping, indices[i], folio); 1102 if (!swaps_freed) { 1103 /* Swap was replaced by page: retry */ 1104 index = indices[i]; 1105 break; 1106 } 1107 nr_swaps_freed += swaps_freed; 1108 continue; 1109 } 1110 1111 folio_lock(folio); 1112 1113 if (!unfalloc || !folio_test_uptodate(folio)) { 1114 if (folio_mapping(folio) != mapping) { 1115 /* Page was replaced by swap: retry */ 1116 folio_unlock(folio); 1117 index = indices[i]; 1118 break; 1119 } 1120 VM_BUG_ON_FOLIO(folio_test_writeback(folio), 1121 folio); 1122 1123 if (!folio_test_large(folio)) { 1124 truncate_inode_folio(mapping, folio); 1125 } else if (truncate_inode_partial_folio(folio, lstart, lend)) { 1126 /* 1127 * If we split a page, reset the loop so 1128 * that we pick up the new sub pages. 1129 * Otherwise the THP was entirely 1130 * dropped or the target range was 1131 * zeroed, so just continue the loop as 1132 * is. 1133 */ 1134 if (!folio_test_large(folio)) { 1135 folio_unlock(folio); 1136 index = start; 1137 break; 1138 } 1139 } 1140 } 1141 folio_unlock(folio); 1142 } 1143 folio_batch_remove_exceptionals(&fbatch); 1144 folio_batch_release(&fbatch); 1145 } 1146 1147 shmem_recalc_inode(inode, 0, -nr_swaps_freed); 1148 } 1149 1150 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 1151 { 1152 shmem_undo_range(inode, lstart, lend, false); 1153 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode)); 1154 inode_inc_iversion(inode); 1155 } 1156 EXPORT_SYMBOL_GPL(shmem_truncate_range); 1157 1158 static int shmem_getattr(struct mnt_idmap *idmap, 1159 const struct path *path, struct kstat *stat, 1160 u32 request_mask, unsigned int query_flags) 1161 { 1162 struct inode *inode = path->dentry->d_inode; 1163 struct shmem_inode_info *info = SHMEM_I(inode); 1164 1165 if (info->alloced - info->swapped != inode->i_mapping->nrpages) 1166 shmem_recalc_inode(inode, 0, 0); 1167 1168 if (info->fsflags & FS_APPEND_FL) 1169 stat->attributes |= STATX_ATTR_APPEND; 1170 if (info->fsflags & FS_IMMUTABLE_FL) 1171 stat->attributes |= STATX_ATTR_IMMUTABLE; 1172 if (info->fsflags & FS_NODUMP_FL) 1173 stat->attributes |= STATX_ATTR_NODUMP; 1174 stat->attributes_mask |= (STATX_ATTR_APPEND | 1175 STATX_ATTR_IMMUTABLE | 1176 STATX_ATTR_NODUMP); 1177 generic_fillattr(idmap, request_mask, inode, stat); 1178 1179 if (shmem_huge_global_enabled(inode, 0, 0, false, 0)) 1180 stat->blksize = HPAGE_PMD_SIZE; 1181 1182 if (request_mask & STATX_BTIME) { 1183 stat->result_mask |= STATX_BTIME; 1184 stat->btime.tv_sec = info->i_crtime.tv_sec; 1185 stat->btime.tv_nsec = info->i_crtime.tv_nsec; 1186 } 1187 1188 return 0; 1189 } 1190 1191 static int shmem_setattr(struct mnt_idmap *idmap, 1192 struct dentry *dentry, struct iattr *attr) 1193 { 1194 struct inode *inode = d_inode(dentry); 1195 struct shmem_inode_info *info = SHMEM_I(inode); 1196 int error; 1197 bool update_mtime = false; 1198 bool update_ctime = true; 1199 1200 error = setattr_prepare(idmap, dentry, attr); 1201 if (error) 1202 return error; 1203 1204 if ((info->seals & F_SEAL_EXEC) && (attr->ia_valid & ATTR_MODE)) { 1205 if ((inode->i_mode ^ attr->ia_mode) & 0111) { 1206 return -EPERM; 1207 } 1208 } 1209 1210 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { 1211 loff_t oldsize = inode->i_size; 1212 loff_t newsize = attr->ia_size; 1213 1214 /* protected by i_rwsem */ 1215 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) || 1216 (newsize > oldsize && (info->seals & F_SEAL_GROW))) 1217 return -EPERM; 1218 1219 if (newsize != oldsize) { 1220 error = shmem_reacct_size(SHMEM_I(inode)->flags, 1221 oldsize, newsize); 1222 if (error) 1223 return error; 1224 i_size_write(inode, newsize); 1225 update_mtime = true; 1226 } else { 1227 update_ctime = false; 1228 } 1229 if (newsize <= oldsize) { 1230 loff_t holebegin = round_up(newsize, PAGE_SIZE); 1231 if (oldsize > holebegin) 1232 unmap_mapping_range(inode->i_mapping, 1233 holebegin, 0, 1); 1234 if (info->alloced) 1235 shmem_truncate_range(inode, 1236 newsize, (loff_t)-1); 1237 /* unmap again to remove racily COWed private pages */ 1238 if (oldsize > holebegin) 1239 unmap_mapping_range(inode->i_mapping, 1240 holebegin, 0, 1); 1241 } 1242 } 1243 1244 if (is_quota_modification(idmap, inode, attr)) { 1245 error = dquot_initialize(inode); 1246 if (error) 1247 return error; 1248 } 1249 1250 /* Transfer quota accounting */ 1251 if (i_uid_needs_update(idmap, attr, inode) || 1252 i_gid_needs_update(idmap, attr, inode)) { 1253 error = dquot_transfer(idmap, inode, attr); 1254 if (error) 1255 return error; 1256 } 1257 1258 setattr_copy(idmap, inode, attr); 1259 if (attr->ia_valid & ATTR_MODE) 1260 error = posix_acl_chmod(idmap, dentry, inode->i_mode); 1261 if (!error && update_ctime) { 1262 inode_set_ctime_current(inode); 1263 if (update_mtime) 1264 inode_set_mtime_to_ts(inode, inode_get_ctime(inode)); 1265 inode_inc_iversion(inode); 1266 } 1267 return error; 1268 } 1269 1270 static void shmem_evict_inode(struct inode *inode) 1271 { 1272 struct shmem_inode_info *info = SHMEM_I(inode); 1273 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 1274 size_t freed = 0; 1275 1276 if (shmem_mapping(inode->i_mapping)) { 1277 shmem_unacct_size(info->flags, inode->i_size); 1278 inode->i_size = 0; 1279 mapping_set_exiting(inode->i_mapping); 1280 shmem_truncate_range(inode, 0, (loff_t)-1); 1281 if (!list_empty(&info->shrinklist)) { 1282 spin_lock(&sbinfo->shrinklist_lock); 1283 if (!list_empty(&info->shrinklist)) { 1284 list_del_init(&info->shrinklist); 1285 sbinfo->shrinklist_len--; 1286 } 1287 spin_unlock(&sbinfo->shrinklist_lock); 1288 } 1289 while (!list_empty(&info->swaplist)) { 1290 /* Wait while shmem_unuse() is scanning this inode... */ 1291 wait_var_event(&info->stop_eviction, 1292 !atomic_read(&info->stop_eviction)); 1293 mutex_lock(&shmem_swaplist_mutex); 1294 /* ...but beware of the race if we peeked too early */ 1295 if (!atomic_read(&info->stop_eviction)) 1296 list_del_init(&info->swaplist); 1297 mutex_unlock(&shmem_swaplist_mutex); 1298 } 1299 } 1300 1301 simple_xattrs_free(&info->xattrs, sbinfo->max_inodes ? &freed : NULL); 1302 shmem_free_inode(inode->i_sb, freed); 1303 WARN_ON(inode->i_blocks); 1304 clear_inode(inode); 1305 #ifdef CONFIG_TMPFS_QUOTA 1306 dquot_free_inode(inode); 1307 dquot_drop(inode); 1308 #endif 1309 } 1310 1311 static int shmem_find_swap_entries(struct address_space *mapping, 1312 pgoff_t start, struct folio_batch *fbatch, 1313 pgoff_t *indices, unsigned int type) 1314 { 1315 XA_STATE(xas, &mapping->i_pages, start); 1316 struct folio *folio; 1317 swp_entry_t entry; 1318 1319 rcu_read_lock(); 1320 xas_for_each(&xas, folio, ULONG_MAX) { 1321 if (xas_retry(&xas, folio)) 1322 continue; 1323 1324 if (!xa_is_value(folio)) 1325 continue; 1326 1327 entry = radix_to_swp_entry(folio); 1328 /* 1329 * swapin error entries can be found in the mapping. But they're 1330 * deliberately ignored here as we've done everything we can do. 1331 */ 1332 if (swp_type(entry) != type) 1333 continue; 1334 1335 indices[folio_batch_count(fbatch)] = xas.xa_index; 1336 if (!folio_batch_add(fbatch, folio)) 1337 break; 1338 1339 if (need_resched()) { 1340 xas_pause(&xas); 1341 cond_resched_rcu(); 1342 } 1343 } 1344 rcu_read_unlock(); 1345 1346 return xas.xa_index; 1347 } 1348 1349 /* 1350 * Move the swapped pages for an inode to page cache. Returns the count 1351 * of pages swapped in, or the error in case of failure. 1352 */ 1353 static int shmem_unuse_swap_entries(struct inode *inode, 1354 struct folio_batch *fbatch, pgoff_t *indices) 1355 { 1356 int i = 0; 1357 int ret = 0; 1358 int error = 0; 1359 struct address_space *mapping = inode->i_mapping; 1360 1361 for (i = 0; i < folio_batch_count(fbatch); i++) { 1362 struct folio *folio = fbatch->folios[i]; 1363 1364 if (!xa_is_value(folio)) 1365 continue; 1366 error = shmem_swapin_folio(inode, indices[i], &folio, SGP_CACHE, 1367 mapping_gfp_mask(mapping), NULL, NULL); 1368 if (error == 0) { 1369 folio_unlock(folio); 1370 folio_put(folio); 1371 ret++; 1372 } 1373 if (error == -ENOMEM) 1374 break; 1375 error = 0; 1376 } 1377 return error ? error : ret; 1378 } 1379 1380 /* 1381 * If swap found in inode, free it and move page from swapcache to filecache. 1382 */ 1383 static int shmem_unuse_inode(struct inode *inode, unsigned int type) 1384 { 1385 struct address_space *mapping = inode->i_mapping; 1386 pgoff_t start = 0; 1387 struct folio_batch fbatch; 1388 pgoff_t indices[PAGEVEC_SIZE]; 1389 int ret = 0; 1390 1391 do { 1392 folio_batch_init(&fbatch); 1393 shmem_find_swap_entries(mapping, start, &fbatch, indices, type); 1394 if (folio_batch_count(&fbatch) == 0) { 1395 ret = 0; 1396 break; 1397 } 1398 1399 ret = shmem_unuse_swap_entries(inode, &fbatch, indices); 1400 if (ret < 0) 1401 break; 1402 1403 start = indices[folio_batch_count(&fbatch) - 1]; 1404 } while (true); 1405 1406 return ret; 1407 } 1408 1409 /* 1410 * Read all the shared memory data that resides in the swap 1411 * device 'type' back into memory, so the swap device can be 1412 * unused. 1413 */ 1414 int shmem_unuse(unsigned int type) 1415 { 1416 struct shmem_inode_info *info, *next; 1417 int error = 0; 1418 1419 if (list_empty(&shmem_swaplist)) 1420 return 0; 1421 1422 mutex_lock(&shmem_swaplist_mutex); 1423 list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) { 1424 if (!info->swapped) { 1425 list_del_init(&info->swaplist); 1426 continue; 1427 } 1428 /* 1429 * Drop the swaplist mutex while searching the inode for swap; 1430 * but before doing so, make sure shmem_evict_inode() will not 1431 * remove placeholder inode from swaplist, nor let it be freed 1432 * (igrab() would protect from unlink, but not from unmount). 1433 */ 1434 atomic_inc(&info->stop_eviction); 1435 mutex_unlock(&shmem_swaplist_mutex); 1436 1437 error = shmem_unuse_inode(&info->vfs_inode, type); 1438 cond_resched(); 1439 1440 mutex_lock(&shmem_swaplist_mutex); 1441 next = list_next_entry(info, swaplist); 1442 if (!info->swapped) 1443 list_del_init(&info->swaplist); 1444 if (atomic_dec_and_test(&info->stop_eviction)) 1445 wake_up_var(&info->stop_eviction); 1446 if (error) 1447 break; 1448 } 1449 mutex_unlock(&shmem_swaplist_mutex); 1450 1451 return error; 1452 } 1453 1454 /* 1455 * Move the page from the page cache to the swap cache. 1456 */ 1457 static int shmem_writepage(struct page *page, struct writeback_control *wbc) 1458 { 1459 struct folio *folio = page_folio(page); 1460 struct address_space *mapping = folio->mapping; 1461 struct inode *inode = mapping->host; 1462 struct shmem_inode_info *info = SHMEM_I(inode); 1463 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 1464 swp_entry_t swap; 1465 pgoff_t index; 1466 int nr_pages; 1467 bool split = false; 1468 1469 /* 1470 * Our capabilities prevent regular writeback or sync from ever calling 1471 * shmem_writepage; but a stacking filesystem might use ->writepage of 1472 * its underlying filesystem, in which case tmpfs should write out to 1473 * swap only in response to memory pressure, and not for the writeback 1474 * threads or sync. 1475 */ 1476 if (WARN_ON_ONCE(!wbc->for_reclaim)) 1477 goto redirty; 1478 1479 if (WARN_ON_ONCE((info->flags & VM_LOCKED) || sbinfo->noswap)) 1480 goto redirty; 1481 1482 if (!total_swap_pages) 1483 goto redirty; 1484 1485 /* 1486 * If CONFIG_THP_SWAP is not enabled, the large folio should be 1487 * split when swapping. 1488 * 1489 * And shrinkage of pages beyond i_size does not split swap, so 1490 * swapout of a large folio crossing i_size needs to split too 1491 * (unless fallocate has been used to preallocate beyond EOF). 1492 */ 1493 if (folio_test_large(folio)) { 1494 index = shmem_fallocend(inode, 1495 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE)); 1496 if ((index > folio->index && index < folio_next_index(folio)) || 1497 !IS_ENABLED(CONFIG_THP_SWAP)) 1498 split = true; 1499 } 1500 1501 if (split) { 1502 try_split: 1503 /* Ensure the subpages are still dirty */ 1504 folio_test_set_dirty(folio); 1505 if (split_huge_page_to_list_to_order(page, wbc->list, 0)) 1506 goto redirty; 1507 folio = page_folio(page); 1508 folio_clear_dirty(folio); 1509 } 1510 1511 index = folio->index; 1512 nr_pages = folio_nr_pages(folio); 1513 1514 /* 1515 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC 1516 * value into swapfile.c, the only way we can correctly account for a 1517 * fallocated folio arriving here is now to initialize it and write it. 1518 * 1519 * That's okay for a folio already fallocated earlier, but if we have 1520 * not yet completed the fallocation, then (a) we want to keep track 1521 * of this folio in case we have to undo it, and (b) it may not be a 1522 * good idea to continue anyway, once we're pushing into swap. So 1523 * reactivate the folio, and let shmem_fallocate() quit when too many. 1524 */ 1525 if (!folio_test_uptodate(folio)) { 1526 if (inode->i_private) { 1527 struct shmem_falloc *shmem_falloc; 1528 spin_lock(&inode->i_lock); 1529 shmem_falloc = inode->i_private; 1530 if (shmem_falloc && 1531 !shmem_falloc->waitq && 1532 index >= shmem_falloc->start && 1533 index < shmem_falloc->next) 1534 shmem_falloc->nr_unswapped++; 1535 else 1536 shmem_falloc = NULL; 1537 spin_unlock(&inode->i_lock); 1538 if (shmem_falloc) 1539 goto redirty; 1540 } 1541 folio_zero_range(folio, 0, folio_size(folio)); 1542 flush_dcache_folio(folio); 1543 folio_mark_uptodate(folio); 1544 } 1545 1546 swap = folio_alloc_swap(folio); 1547 if (!swap.val) { 1548 if (nr_pages > 1) 1549 goto try_split; 1550 1551 goto redirty; 1552 } 1553 1554 /* 1555 * Add inode to shmem_unuse()'s list of swapped-out inodes, 1556 * if it's not already there. Do it now before the folio is 1557 * moved to swap cache, when its pagelock no longer protects 1558 * the inode from eviction. But don't unlock the mutex until 1559 * we've incremented swapped, because shmem_unuse_inode() will 1560 * prune a !swapped inode from the swaplist under this mutex. 1561 */ 1562 mutex_lock(&shmem_swaplist_mutex); 1563 if (list_empty(&info->swaplist)) 1564 list_add(&info->swaplist, &shmem_swaplist); 1565 1566 if (add_to_swap_cache(folio, swap, 1567 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN, 1568 NULL) == 0) { 1569 shmem_recalc_inode(inode, 0, nr_pages); 1570 swap_shmem_alloc(swap, nr_pages); 1571 shmem_delete_from_page_cache(folio, swp_to_radix_entry(swap)); 1572 1573 mutex_unlock(&shmem_swaplist_mutex); 1574 BUG_ON(folio_mapped(folio)); 1575 return swap_writepage(&folio->page, wbc); 1576 } 1577 1578 mutex_unlock(&shmem_swaplist_mutex); 1579 put_swap_folio(folio, swap); 1580 redirty: 1581 folio_mark_dirty(folio); 1582 if (wbc->for_reclaim) 1583 return AOP_WRITEPAGE_ACTIVATE; /* Return with folio locked */ 1584 folio_unlock(folio); 1585 return 0; 1586 } 1587 1588 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS) 1589 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1590 { 1591 char buffer[64]; 1592 1593 if (!mpol || mpol->mode == MPOL_DEFAULT) 1594 return; /* show nothing */ 1595 1596 mpol_to_str(buffer, sizeof(buffer), mpol); 1597 1598 seq_printf(seq, ",mpol=%s", buffer); 1599 } 1600 1601 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1602 { 1603 struct mempolicy *mpol = NULL; 1604 if (sbinfo->mpol) { 1605 raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */ 1606 mpol = sbinfo->mpol; 1607 mpol_get(mpol); 1608 raw_spin_unlock(&sbinfo->stat_lock); 1609 } 1610 return mpol; 1611 } 1612 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */ 1613 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1614 { 1615 } 1616 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1617 { 1618 return NULL; 1619 } 1620 #endif /* CONFIG_NUMA && CONFIG_TMPFS */ 1621 1622 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 1623 pgoff_t index, unsigned int order, pgoff_t *ilx); 1624 1625 static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp, 1626 struct shmem_inode_info *info, pgoff_t index) 1627 { 1628 struct mempolicy *mpol; 1629 pgoff_t ilx; 1630 struct folio *folio; 1631 1632 mpol = shmem_get_pgoff_policy(info, index, 0, &ilx); 1633 folio = swap_cluster_readahead(swap, gfp, mpol, ilx); 1634 mpol_cond_put(mpol); 1635 1636 return folio; 1637 } 1638 1639 /* 1640 * Make sure huge_gfp is always more limited than limit_gfp. 1641 * Some of the flags set permissions, while others set limitations. 1642 */ 1643 static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp) 1644 { 1645 gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM; 1646 gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY; 1647 gfp_t zoneflags = limit_gfp & GFP_ZONEMASK; 1648 gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK); 1649 1650 /* Allow allocations only from the originally specified zones. */ 1651 result |= zoneflags; 1652 1653 /* 1654 * Minimize the result gfp by taking the union with the deny flags, 1655 * and the intersection of the allow flags. 1656 */ 1657 result |= (limit_gfp & denyflags); 1658 result |= (huge_gfp & limit_gfp) & allowflags; 1659 1660 return result; 1661 } 1662 1663 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1664 bool shmem_hpage_pmd_enabled(void) 1665 { 1666 if (shmem_huge == SHMEM_HUGE_DENY) 1667 return false; 1668 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always)) 1669 return true; 1670 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise)) 1671 return true; 1672 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size)) 1673 return true; 1674 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) && 1675 shmem_huge != SHMEM_HUGE_NEVER) 1676 return true; 1677 1678 return false; 1679 } 1680 1681 unsigned long shmem_allowable_huge_orders(struct inode *inode, 1682 struct vm_area_struct *vma, pgoff_t index, 1683 loff_t write_end, bool shmem_huge_force) 1684 { 1685 unsigned long mask = READ_ONCE(huge_shmem_orders_always); 1686 unsigned long within_size_orders = READ_ONCE(huge_shmem_orders_within_size); 1687 unsigned long vm_flags = vma ? vma->vm_flags : 0; 1688 bool global_huge; 1689 loff_t i_size; 1690 int order; 1691 1692 if (thp_disabled_by_hw() || (vma && vma_thp_disabled(vma, vm_flags))) 1693 return 0; 1694 1695 global_huge = shmem_huge_global_enabled(inode, index, write_end, 1696 shmem_huge_force, vm_flags); 1697 if (!vma || !vma_is_anon_shmem(vma)) { 1698 /* 1699 * For tmpfs, we now only support PMD sized THP if huge page 1700 * is enabled, otherwise fallback to order 0. 1701 */ 1702 return global_huge ? BIT(HPAGE_PMD_ORDER) : 0; 1703 } 1704 1705 /* 1706 * Following the 'deny' semantics of the top level, force the huge 1707 * option off from all mounts. 1708 */ 1709 if (shmem_huge == SHMEM_HUGE_DENY) 1710 return 0; 1711 1712 /* 1713 * Only allow inherit orders if the top-level value is 'force', which 1714 * means non-PMD sized THP can not override 'huge' mount option now. 1715 */ 1716 if (shmem_huge == SHMEM_HUGE_FORCE) 1717 return READ_ONCE(huge_shmem_orders_inherit); 1718 1719 /* Allow mTHP that will be fully within i_size. */ 1720 order = highest_order(within_size_orders); 1721 while (within_size_orders) { 1722 index = round_up(index + 1, order); 1723 i_size = round_up(i_size_read(inode), PAGE_SIZE); 1724 if (i_size >> PAGE_SHIFT >= index) { 1725 mask |= within_size_orders; 1726 break; 1727 } 1728 1729 order = next_order(&within_size_orders, order); 1730 } 1731 1732 if (vm_flags & VM_HUGEPAGE) 1733 mask |= READ_ONCE(huge_shmem_orders_madvise); 1734 1735 if (global_huge) 1736 mask |= READ_ONCE(huge_shmem_orders_inherit); 1737 1738 return THP_ORDERS_ALL_FILE_DEFAULT & mask; 1739 } 1740 1741 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf, 1742 struct address_space *mapping, pgoff_t index, 1743 unsigned long orders) 1744 { 1745 struct vm_area_struct *vma = vmf ? vmf->vma : NULL; 1746 pgoff_t aligned_index; 1747 unsigned long pages; 1748 int order; 1749 1750 if (vma) { 1751 orders = thp_vma_suitable_orders(vma, vmf->address, orders); 1752 if (!orders) 1753 return 0; 1754 } 1755 1756 /* Find the highest order that can add into the page cache */ 1757 order = highest_order(orders); 1758 while (orders) { 1759 pages = 1UL << order; 1760 aligned_index = round_down(index, pages); 1761 /* 1762 * Check for conflict before waiting on a huge allocation. 1763 * Conflict might be that a huge page has just been allocated 1764 * and added to page cache by a racing thread, or that there 1765 * is already at least one small page in the huge extent. 1766 * Be careful to retry when appropriate, but not forever! 1767 * Elsewhere -EEXIST would be the right code, but not here. 1768 */ 1769 if (!xa_find(&mapping->i_pages, &aligned_index, 1770 aligned_index + pages - 1, XA_PRESENT)) 1771 break; 1772 order = next_order(&orders, order); 1773 } 1774 1775 return orders; 1776 } 1777 #else 1778 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf, 1779 struct address_space *mapping, pgoff_t index, 1780 unsigned long orders) 1781 { 1782 return 0; 1783 } 1784 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 1785 1786 static struct folio *shmem_alloc_folio(gfp_t gfp, int order, 1787 struct shmem_inode_info *info, pgoff_t index) 1788 { 1789 struct mempolicy *mpol; 1790 pgoff_t ilx; 1791 struct folio *folio; 1792 1793 mpol = shmem_get_pgoff_policy(info, index, order, &ilx); 1794 folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id()); 1795 mpol_cond_put(mpol); 1796 1797 return folio; 1798 } 1799 1800 static struct folio *shmem_alloc_and_add_folio(struct vm_fault *vmf, 1801 gfp_t gfp, struct inode *inode, pgoff_t index, 1802 struct mm_struct *fault_mm, unsigned long orders) 1803 { 1804 struct address_space *mapping = inode->i_mapping; 1805 struct shmem_inode_info *info = SHMEM_I(inode); 1806 unsigned long suitable_orders = 0; 1807 struct folio *folio = NULL; 1808 long pages; 1809 int error, order; 1810 1811 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 1812 orders = 0; 1813 1814 if (orders > 0) { 1815 suitable_orders = shmem_suitable_orders(inode, vmf, 1816 mapping, index, orders); 1817 1818 order = highest_order(suitable_orders); 1819 while (suitable_orders) { 1820 pages = 1UL << order; 1821 index = round_down(index, pages); 1822 folio = shmem_alloc_folio(gfp, order, info, index); 1823 if (folio) 1824 goto allocated; 1825 1826 if (pages == HPAGE_PMD_NR) 1827 count_vm_event(THP_FILE_FALLBACK); 1828 count_mthp_stat(order, MTHP_STAT_SHMEM_FALLBACK); 1829 order = next_order(&suitable_orders, order); 1830 } 1831 } else { 1832 pages = 1; 1833 folio = shmem_alloc_folio(gfp, 0, info, index); 1834 } 1835 if (!folio) 1836 return ERR_PTR(-ENOMEM); 1837 1838 allocated: 1839 __folio_set_locked(folio); 1840 __folio_set_swapbacked(folio); 1841 1842 gfp &= GFP_RECLAIM_MASK; 1843 error = mem_cgroup_charge(folio, fault_mm, gfp); 1844 if (error) { 1845 if (xa_find(&mapping->i_pages, &index, 1846 index + pages - 1, XA_PRESENT)) { 1847 error = -EEXIST; 1848 } else if (pages > 1) { 1849 if (pages == HPAGE_PMD_NR) { 1850 count_vm_event(THP_FILE_FALLBACK); 1851 count_vm_event(THP_FILE_FALLBACK_CHARGE); 1852 } 1853 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK); 1854 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK_CHARGE); 1855 } 1856 goto unlock; 1857 } 1858 1859 error = shmem_add_to_page_cache(folio, mapping, index, NULL, gfp); 1860 if (error) 1861 goto unlock; 1862 1863 error = shmem_inode_acct_blocks(inode, pages); 1864 if (error) { 1865 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 1866 long freed; 1867 /* 1868 * Try to reclaim some space by splitting a few 1869 * large folios beyond i_size on the filesystem. 1870 */ 1871 shmem_unused_huge_shrink(sbinfo, NULL, pages); 1872 /* 1873 * And do a shmem_recalc_inode() to account for freed pages: 1874 * except our folio is there in cache, so not quite balanced. 1875 */ 1876 spin_lock(&info->lock); 1877 freed = pages + info->alloced - info->swapped - 1878 READ_ONCE(mapping->nrpages); 1879 if (freed > 0) 1880 info->alloced -= freed; 1881 spin_unlock(&info->lock); 1882 if (freed > 0) 1883 shmem_inode_unacct_blocks(inode, freed); 1884 error = shmem_inode_acct_blocks(inode, pages); 1885 if (error) { 1886 filemap_remove_folio(folio); 1887 goto unlock; 1888 } 1889 } 1890 1891 shmem_recalc_inode(inode, pages, 0); 1892 folio_add_lru(folio); 1893 return folio; 1894 1895 unlock: 1896 folio_unlock(folio); 1897 folio_put(folio); 1898 return ERR_PTR(error); 1899 } 1900 1901 /* 1902 * When a page is moved from swapcache to shmem filecache (either by the 1903 * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of 1904 * shmem_unuse_inode()), it may have been read in earlier from swap, in 1905 * ignorance of the mapping it belongs to. If that mapping has special 1906 * constraints (like the gma500 GEM driver, which requires RAM below 4GB), 1907 * we may need to copy to a suitable page before moving to filecache. 1908 * 1909 * In a future release, this may well be extended to respect cpuset and 1910 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page(); 1911 * but for now it is a simple matter of zone. 1912 */ 1913 static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp) 1914 { 1915 return folio_zonenum(folio) > gfp_zone(gfp); 1916 } 1917 1918 static int shmem_replace_folio(struct folio **foliop, gfp_t gfp, 1919 struct shmem_inode_info *info, pgoff_t index, 1920 struct vm_area_struct *vma) 1921 { 1922 struct folio *new, *old = *foliop; 1923 swp_entry_t entry = old->swap; 1924 struct address_space *swap_mapping = swap_address_space(entry); 1925 pgoff_t swap_index = swap_cache_index(entry); 1926 XA_STATE(xas, &swap_mapping->i_pages, swap_index); 1927 int nr_pages = folio_nr_pages(old); 1928 int error = 0, i; 1929 1930 /* 1931 * We have arrived here because our zones are constrained, so don't 1932 * limit chance of success by further cpuset and node constraints. 1933 */ 1934 gfp &= ~GFP_CONSTRAINT_MASK; 1935 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1936 if (nr_pages > 1) { 1937 gfp_t huge_gfp = vma_thp_gfp_mask(vma); 1938 1939 gfp = limit_gfp_mask(huge_gfp, gfp); 1940 } 1941 #endif 1942 1943 new = shmem_alloc_folio(gfp, folio_order(old), info, index); 1944 if (!new) 1945 return -ENOMEM; 1946 1947 folio_ref_add(new, nr_pages); 1948 folio_copy(new, old); 1949 flush_dcache_folio(new); 1950 1951 __folio_set_locked(new); 1952 __folio_set_swapbacked(new); 1953 folio_mark_uptodate(new); 1954 new->swap = entry; 1955 folio_set_swapcache(new); 1956 1957 /* Swap cache still stores N entries instead of a high-order entry */ 1958 xa_lock_irq(&swap_mapping->i_pages); 1959 for (i = 0; i < nr_pages; i++) { 1960 void *item = xas_load(&xas); 1961 1962 if (item != old) { 1963 error = -ENOENT; 1964 break; 1965 } 1966 1967 xas_store(&xas, new); 1968 xas_next(&xas); 1969 } 1970 if (!error) { 1971 mem_cgroup_replace_folio(old, new); 1972 __lruvec_stat_mod_folio(new, NR_FILE_PAGES, nr_pages); 1973 __lruvec_stat_mod_folio(new, NR_SHMEM, nr_pages); 1974 __lruvec_stat_mod_folio(old, NR_FILE_PAGES, -nr_pages); 1975 __lruvec_stat_mod_folio(old, NR_SHMEM, -nr_pages); 1976 } 1977 xa_unlock_irq(&swap_mapping->i_pages); 1978 1979 if (unlikely(error)) { 1980 /* 1981 * Is this possible? I think not, now that our callers 1982 * check both the swapcache flag and folio->private 1983 * after getting the folio lock; but be defensive. 1984 * Reverse old to newpage for clear and free. 1985 */ 1986 old = new; 1987 } else { 1988 folio_add_lru(new); 1989 *foliop = new; 1990 } 1991 1992 folio_clear_swapcache(old); 1993 old->private = NULL; 1994 1995 folio_unlock(old); 1996 /* 1997 * The old folio are removed from swap cache, drop the 'nr_pages' 1998 * reference, as well as one temporary reference getting from swap 1999 * cache. 2000 */ 2001 folio_put_refs(old, nr_pages + 1); 2002 return error; 2003 } 2004 2005 static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index, 2006 struct folio *folio, swp_entry_t swap) 2007 { 2008 struct address_space *mapping = inode->i_mapping; 2009 swp_entry_t swapin_error; 2010 void *old; 2011 int nr_pages; 2012 2013 swapin_error = make_poisoned_swp_entry(); 2014 old = xa_cmpxchg_irq(&mapping->i_pages, index, 2015 swp_to_radix_entry(swap), 2016 swp_to_radix_entry(swapin_error), 0); 2017 if (old != swp_to_radix_entry(swap)) 2018 return; 2019 2020 nr_pages = folio_nr_pages(folio); 2021 folio_wait_writeback(folio); 2022 delete_from_swap_cache(folio); 2023 /* 2024 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks 2025 * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks) 2026 * in shmem_evict_inode(). 2027 */ 2028 shmem_recalc_inode(inode, -nr_pages, -nr_pages); 2029 swap_free_nr(swap, nr_pages); 2030 } 2031 2032 static int shmem_split_large_entry(struct inode *inode, pgoff_t index, 2033 swp_entry_t swap, gfp_t gfp) 2034 { 2035 struct address_space *mapping = inode->i_mapping; 2036 XA_STATE_ORDER(xas, &mapping->i_pages, index, 0); 2037 void *alloced_shadow = NULL; 2038 int alloced_order = 0, i; 2039 2040 /* Convert user data gfp flags to xarray node gfp flags */ 2041 gfp &= GFP_RECLAIM_MASK; 2042 2043 for (;;) { 2044 int order = -1, split_order = 0; 2045 void *old = NULL; 2046 2047 xas_lock_irq(&xas); 2048 old = xas_load(&xas); 2049 if (!xa_is_value(old) || swp_to_radix_entry(swap) != old) { 2050 xas_set_err(&xas, -EEXIST); 2051 goto unlock; 2052 } 2053 2054 order = xas_get_order(&xas); 2055 2056 /* Swap entry may have changed before we re-acquire the lock */ 2057 if (alloced_order && 2058 (old != alloced_shadow || order != alloced_order)) { 2059 xas_destroy(&xas); 2060 alloced_order = 0; 2061 } 2062 2063 /* Try to split large swap entry in pagecache */ 2064 if (order > 0) { 2065 if (!alloced_order) { 2066 split_order = order; 2067 goto unlock; 2068 } 2069 xas_split(&xas, old, order); 2070 2071 /* 2072 * Re-set the swap entry after splitting, and the swap 2073 * offset of the original large entry must be continuous. 2074 */ 2075 for (i = 0; i < 1 << order; i++) { 2076 pgoff_t aligned_index = round_down(index, 1 << order); 2077 swp_entry_t tmp; 2078 2079 tmp = swp_entry(swp_type(swap), swp_offset(swap) + i); 2080 __xa_store(&mapping->i_pages, aligned_index + i, 2081 swp_to_radix_entry(tmp), 0); 2082 } 2083 } 2084 2085 unlock: 2086 xas_unlock_irq(&xas); 2087 2088 /* split needed, alloc here and retry. */ 2089 if (split_order) { 2090 xas_split_alloc(&xas, old, split_order, gfp); 2091 if (xas_error(&xas)) 2092 goto error; 2093 alloced_shadow = old; 2094 alloced_order = split_order; 2095 xas_reset(&xas); 2096 continue; 2097 } 2098 2099 if (!xas_nomem(&xas, gfp)) 2100 break; 2101 } 2102 2103 error: 2104 if (xas_error(&xas)) 2105 return xas_error(&xas); 2106 2107 return alloced_order; 2108 } 2109 2110 /* 2111 * Swap in the folio pointed to by *foliop. 2112 * Caller has to make sure that *foliop contains a valid swapped folio. 2113 * Returns 0 and the folio in foliop if success. On failure, returns the 2114 * error code and NULL in *foliop. 2115 */ 2116 static int shmem_swapin_folio(struct inode *inode, pgoff_t index, 2117 struct folio **foliop, enum sgp_type sgp, 2118 gfp_t gfp, struct vm_area_struct *vma, 2119 vm_fault_t *fault_type) 2120 { 2121 struct address_space *mapping = inode->i_mapping; 2122 struct mm_struct *fault_mm = vma ? vma->vm_mm : NULL; 2123 struct shmem_inode_info *info = SHMEM_I(inode); 2124 struct swap_info_struct *si; 2125 struct folio *folio = NULL; 2126 swp_entry_t swap; 2127 int error, nr_pages; 2128 2129 VM_BUG_ON(!*foliop || !xa_is_value(*foliop)); 2130 swap = radix_to_swp_entry(*foliop); 2131 *foliop = NULL; 2132 2133 if (is_poisoned_swp_entry(swap)) 2134 return -EIO; 2135 2136 si = get_swap_device(swap); 2137 if (!si) { 2138 if (!shmem_confirm_swap(mapping, index, swap)) 2139 return -EEXIST; 2140 else 2141 return -EINVAL; 2142 } 2143 2144 /* Look it up and read it in.. */ 2145 folio = swap_cache_get_folio(swap, NULL, 0); 2146 if (!folio) { 2147 int split_order; 2148 2149 /* Or update major stats only when swapin succeeds?? */ 2150 if (fault_type) { 2151 *fault_type |= VM_FAULT_MAJOR; 2152 count_vm_event(PGMAJFAULT); 2153 count_memcg_event_mm(fault_mm, PGMAJFAULT); 2154 } 2155 2156 /* 2157 * Now swap device can only swap in order 0 folio, then we 2158 * should split the large swap entry stored in the pagecache 2159 * if necessary. 2160 */ 2161 split_order = shmem_split_large_entry(inode, index, swap, gfp); 2162 if (split_order < 0) { 2163 error = split_order; 2164 goto failed; 2165 } 2166 2167 /* 2168 * If the large swap entry has already been split, it is 2169 * necessary to recalculate the new swap entry based on 2170 * the old order alignment. 2171 */ 2172 if (split_order > 0) { 2173 pgoff_t offset = index - round_down(index, 1 << split_order); 2174 2175 swap = swp_entry(swp_type(swap), swp_offset(swap) + offset); 2176 } 2177 2178 /* Here we actually start the io */ 2179 folio = shmem_swapin_cluster(swap, gfp, info, index); 2180 if (!folio) { 2181 error = -ENOMEM; 2182 goto failed; 2183 } 2184 } 2185 2186 /* We have to do this with folio locked to prevent races */ 2187 folio_lock(folio); 2188 if (!folio_test_swapcache(folio) || 2189 folio->swap.val != swap.val || 2190 !shmem_confirm_swap(mapping, index, swap)) { 2191 error = -EEXIST; 2192 goto unlock; 2193 } 2194 if (!folio_test_uptodate(folio)) { 2195 error = -EIO; 2196 goto failed; 2197 } 2198 folio_wait_writeback(folio); 2199 nr_pages = folio_nr_pages(folio); 2200 2201 /* 2202 * Some architectures may have to restore extra metadata to the 2203 * folio after reading from swap. 2204 */ 2205 arch_swap_restore(folio_swap(swap, folio), folio); 2206 2207 if (shmem_should_replace_folio(folio, gfp)) { 2208 error = shmem_replace_folio(&folio, gfp, info, index, vma); 2209 if (error) 2210 goto failed; 2211 } 2212 2213 error = shmem_add_to_page_cache(folio, mapping, 2214 round_down(index, nr_pages), 2215 swp_to_radix_entry(swap), gfp); 2216 if (error) 2217 goto failed; 2218 2219 shmem_recalc_inode(inode, 0, -nr_pages); 2220 2221 if (sgp == SGP_WRITE) 2222 folio_mark_accessed(folio); 2223 2224 delete_from_swap_cache(folio); 2225 folio_mark_dirty(folio); 2226 swap_free_nr(swap, nr_pages); 2227 put_swap_device(si); 2228 2229 *foliop = folio; 2230 return 0; 2231 failed: 2232 if (!shmem_confirm_swap(mapping, index, swap)) 2233 error = -EEXIST; 2234 if (error == -EIO) 2235 shmem_set_folio_swapin_error(inode, index, folio, swap); 2236 unlock: 2237 if (folio) { 2238 folio_unlock(folio); 2239 folio_put(folio); 2240 } 2241 put_swap_device(si); 2242 2243 return error; 2244 } 2245 2246 /* 2247 * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate 2248 * 2249 * If we allocate a new one we do not mark it dirty. That's up to the 2250 * vm. If we swap it in we mark it dirty since we also free the swap 2251 * entry since a page cannot live in both the swap and page cache. 2252 * 2253 * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL. 2254 */ 2255 static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index, 2256 loff_t write_end, struct folio **foliop, enum sgp_type sgp, 2257 gfp_t gfp, struct vm_fault *vmf, vm_fault_t *fault_type) 2258 { 2259 struct vm_area_struct *vma = vmf ? vmf->vma : NULL; 2260 struct mm_struct *fault_mm; 2261 struct folio *folio; 2262 int error; 2263 bool alloced; 2264 unsigned long orders = 0; 2265 2266 if (WARN_ON_ONCE(!shmem_mapping(inode->i_mapping))) 2267 return -EINVAL; 2268 2269 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT)) 2270 return -EFBIG; 2271 repeat: 2272 if (sgp <= SGP_CACHE && 2273 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) 2274 return -EINVAL; 2275 2276 alloced = false; 2277 fault_mm = vma ? vma->vm_mm : NULL; 2278 2279 folio = filemap_get_entry(inode->i_mapping, index); 2280 if (folio && vma && userfaultfd_minor(vma)) { 2281 if (!xa_is_value(folio)) 2282 folio_put(folio); 2283 *fault_type = handle_userfault(vmf, VM_UFFD_MINOR); 2284 return 0; 2285 } 2286 2287 if (xa_is_value(folio)) { 2288 error = shmem_swapin_folio(inode, index, &folio, 2289 sgp, gfp, vma, fault_type); 2290 if (error == -EEXIST) 2291 goto repeat; 2292 2293 *foliop = folio; 2294 return error; 2295 } 2296 2297 if (folio) { 2298 folio_lock(folio); 2299 2300 /* Has the folio been truncated or swapped out? */ 2301 if (unlikely(folio->mapping != inode->i_mapping)) { 2302 folio_unlock(folio); 2303 folio_put(folio); 2304 goto repeat; 2305 } 2306 if (sgp == SGP_WRITE) 2307 folio_mark_accessed(folio); 2308 if (folio_test_uptodate(folio)) 2309 goto out; 2310 /* fallocated folio */ 2311 if (sgp != SGP_READ) 2312 goto clear; 2313 folio_unlock(folio); 2314 folio_put(folio); 2315 } 2316 2317 /* 2318 * SGP_READ: succeed on hole, with NULL folio, letting caller zero. 2319 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail. 2320 */ 2321 *foliop = NULL; 2322 if (sgp == SGP_READ) 2323 return 0; 2324 if (sgp == SGP_NOALLOC) 2325 return -ENOENT; 2326 2327 /* 2328 * Fast cache lookup and swap lookup did not find it: allocate. 2329 */ 2330 2331 if (vma && userfaultfd_missing(vma)) { 2332 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING); 2333 return 0; 2334 } 2335 2336 /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */ 2337 orders = shmem_allowable_huge_orders(inode, vma, index, write_end, false); 2338 if (orders > 0) { 2339 gfp_t huge_gfp; 2340 2341 huge_gfp = vma_thp_gfp_mask(vma); 2342 huge_gfp = limit_gfp_mask(huge_gfp, gfp); 2343 folio = shmem_alloc_and_add_folio(vmf, huge_gfp, 2344 inode, index, fault_mm, orders); 2345 if (!IS_ERR(folio)) { 2346 if (folio_test_pmd_mappable(folio)) 2347 count_vm_event(THP_FILE_ALLOC); 2348 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_ALLOC); 2349 goto alloced; 2350 } 2351 if (PTR_ERR(folio) == -EEXIST) 2352 goto repeat; 2353 } 2354 2355 folio = shmem_alloc_and_add_folio(vmf, gfp, inode, index, fault_mm, 0); 2356 if (IS_ERR(folio)) { 2357 error = PTR_ERR(folio); 2358 if (error == -EEXIST) 2359 goto repeat; 2360 folio = NULL; 2361 goto unlock; 2362 } 2363 2364 alloced: 2365 alloced = true; 2366 if (folio_test_large(folio) && 2367 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) < 2368 folio_next_index(folio)) { 2369 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 2370 struct shmem_inode_info *info = SHMEM_I(inode); 2371 /* 2372 * Part of the large folio is beyond i_size: subject 2373 * to shrink under memory pressure. 2374 */ 2375 spin_lock(&sbinfo->shrinklist_lock); 2376 /* 2377 * _careful to defend against unlocked access to 2378 * ->shrink_list in shmem_unused_huge_shrink() 2379 */ 2380 if (list_empty_careful(&info->shrinklist)) { 2381 list_add_tail(&info->shrinklist, 2382 &sbinfo->shrinklist); 2383 sbinfo->shrinklist_len++; 2384 } 2385 spin_unlock(&sbinfo->shrinklist_lock); 2386 } 2387 2388 if (sgp == SGP_WRITE) 2389 folio_set_referenced(folio); 2390 /* 2391 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio. 2392 */ 2393 if (sgp == SGP_FALLOC) 2394 sgp = SGP_WRITE; 2395 clear: 2396 /* 2397 * Let SGP_WRITE caller clear ends if write does not fill folio; 2398 * but SGP_FALLOC on a folio fallocated earlier must initialize 2399 * it now, lest undo on failure cancel our earlier guarantee. 2400 */ 2401 if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) { 2402 long i, n = folio_nr_pages(folio); 2403 2404 for (i = 0; i < n; i++) 2405 clear_highpage(folio_page(folio, i)); 2406 flush_dcache_folio(folio); 2407 folio_mark_uptodate(folio); 2408 } 2409 2410 /* Perhaps the file has been truncated since we checked */ 2411 if (sgp <= SGP_CACHE && 2412 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) { 2413 error = -EINVAL; 2414 goto unlock; 2415 } 2416 out: 2417 *foliop = folio; 2418 return 0; 2419 2420 /* 2421 * Error recovery. 2422 */ 2423 unlock: 2424 if (alloced) 2425 filemap_remove_folio(folio); 2426 shmem_recalc_inode(inode, 0, 0); 2427 if (folio) { 2428 folio_unlock(folio); 2429 folio_put(folio); 2430 } 2431 return error; 2432 } 2433 2434 /** 2435 * shmem_get_folio - find, and lock a shmem folio. 2436 * @inode: inode to search 2437 * @index: the page index. 2438 * @write_end: end of a write, could extend inode size 2439 * @foliop: pointer to the folio if found 2440 * @sgp: SGP_* flags to control behavior 2441 * 2442 * Looks up the page cache entry at @inode & @index. If a folio is 2443 * present, it is returned locked with an increased refcount. 2444 * 2445 * If the caller modifies data in the folio, it must call folio_mark_dirty() 2446 * before unlocking the folio to ensure that the folio is not reclaimed. 2447 * There is no need to reserve space before calling folio_mark_dirty(). 2448 * 2449 * When no folio is found, the behavior depends on @sgp: 2450 * - for SGP_READ, *@foliop is %NULL and 0 is returned 2451 * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned 2452 * - for all other flags a new folio is allocated, inserted into the 2453 * page cache and returned locked in @foliop. 2454 * 2455 * Context: May sleep. 2456 * Return: 0 if successful, else a negative error code. 2457 */ 2458 int shmem_get_folio(struct inode *inode, pgoff_t index, loff_t write_end, 2459 struct folio **foliop, enum sgp_type sgp) 2460 { 2461 return shmem_get_folio_gfp(inode, index, write_end, foliop, sgp, 2462 mapping_gfp_mask(inode->i_mapping), NULL, NULL); 2463 } 2464 EXPORT_SYMBOL_GPL(shmem_get_folio); 2465 2466 /* 2467 * This is like autoremove_wake_function, but it removes the wait queue 2468 * entry unconditionally - even if something else had already woken the 2469 * target. 2470 */ 2471 static int synchronous_wake_function(wait_queue_entry_t *wait, 2472 unsigned int mode, int sync, void *key) 2473 { 2474 int ret = default_wake_function(wait, mode, sync, key); 2475 list_del_init(&wait->entry); 2476 return ret; 2477 } 2478 2479 /* 2480 * Trinity finds that probing a hole which tmpfs is punching can 2481 * prevent the hole-punch from ever completing: which in turn 2482 * locks writers out with its hold on i_rwsem. So refrain from 2483 * faulting pages into the hole while it's being punched. Although 2484 * shmem_undo_range() does remove the additions, it may be unable to 2485 * keep up, as each new page needs its own unmap_mapping_range() call, 2486 * and the i_mmap tree grows ever slower to scan if new vmas are added. 2487 * 2488 * It does not matter if we sometimes reach this check just before the 2489 * hole-punch begins, so that one fault then races with the punch: 2490 * we just need to make racing faults a rare case. 2491 * 2492 * The implementation below would be much simpler if we just used a 2493 * standard mutex or completion: but we cannot take i_rwsem in fault, 2494 * and bloating every shmem inode for this unlikely case would be sad. 2495 */ 2496 static vm_fault_t shmem_falloc_wait(struct vm_fault *vmf, struct inode *inode) 2497 { 2498 struct shmem_falloc *shmem_falloc; 2499 struct file *fpin = NULL; 2500 vm_fault_t ret = 0; 2501 2502 spin_lock(&inode->i_lock); 2503 shmem_falloc = inode->i_private; 2504 if (shmem_falloc && 2505 shmem_falloc->waitq && 2506 vmf->pgoff >= shmem_falloc->start && 2507 vmf->pgoff < shmem_falloc->next) { 2508 wait_queue_head_t *shmem_falloc_waitq; 2509 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function); 2510 2511 ret = VM_FAULT_NOPAGE; 2512 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 2513 shmem_falloc_waitq = shmem_falloc->waitq; 2514 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait, 2515 TASK_UNINTERRUPTIBLE); 2516 spin_unlock(&inode->i_lock); 2517 schedule(); 2518 2519 /* 2520 * shmem_falloc_waitq points into the shmem_fallocate() 2521 * stack of the hole-punching task: shmem_falloc_waitq 2522 * is usually invalid by the time we reach here, but 2523 * finish_wait() does not dereference it in that case; 2524 * though i_lock needed lest racing with wake_up_all(). 2525 */ 2526 spin_lock(&inode->i_lock); 2527 finish_wait(shmem_falloc_waitq, &shmem_fault_wait); 2528 } 2529 spin_unlock(&inode->i_lock); 2530 if (fpin) { 2531 fput(fpin); 2532 ret = VM_FAULT_RETRY; 2533 } 2534 return ret; 2535 } 2536 2537 static vm_fault_t shmem_fault(struct vm_fault *vmf) 2538 { 2539 struct inode *inode = file_inode(vmf->vma->vm_file); 2540 gfp_t gfp = mapping_gfp_mask(inode->i_mapping); 2541 struct folio *folio = NULL; 2542 vm_fault_t ret = 0; 2543 int err; 2544 2545 /* 2546 * Trinity finds that probing a hole which tmpfs is punching can 2547 * prevent the hole-punch from ever completing: noted in i_private. 2548 */ 2549 if (unlikely(inode->i_private)) { 2550 ret = shmem_falloc_wait(vmf, inode); 2551 if (ret) 2552 return ret; 2553 } 2554 2555 WARN_ON_ONCE(vmf->page != NULL); 2556 err = shmem_get_folio_gfp(inode, vmf->pgoff, 0, &folio, SGP_CACHE, 2557 gfp, vmf, &ret); 2558 if (err) 2559 return vmf_error(err); 2560 if (folio) { 2561 vmf->page = folio_file_page(folio, vmf->pgoff); 2562 ret |= VM_FAULT_LOCKED; 2563 } 2564 return ret; 2565 } 2566 2567 unsigned long shmem_get_unmapped_area(struct file *file, 2568 unsigned long uaddr, unsigned long len, 2569 unsigned long pgoff, unsigned long flags) 2570 { 2571 unsigned long addr; 2572 unsigned long offset; 2573 unsigned long inflated_len; 2574 unsigned long inflated_addr; 2575 unsigned long inflated_offset; 2576 unsigned long hpage_size; 2577 2578 if (len > TASK_SIZE) 2579 return -ENOMEM; 2580 2581 addr = mm_get_unmapped_area(current->mm, file, uaddr, len, pgoff, 2582 flags); 2583 2584 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 2585 return addr; 2586 if (IS_ERR_VALUE(addr)) 2587 return addr; 2588 if (addr & ~PAGE_MASK) 2589 return addr; 2590 if (addr > TASK_SIZE - len) 2591 return addr; 2592 2593 if (shmem_huge == SHMEM_HUGE_DENY) 2594 return addr; 2595 if (flags & MAP_FIXED) 2596 return addr; 2597 /* 2598 * Our priority is to support MAP_SHARED mapped hugely; 2599 * and support MAP_PRIVATE mapped hugely too, until it is COWed. 2600 * But if caller specified an address hint and we allocated area there 2601 * successfully, respect that as before. 2602 */ 2603 if (uaddr == addr) 2604 return addr; 2605 2606 hpage_size = HPAGE_PMD_SIZE; 2607 if (shmem_huge != SHMEM_HUGE_FORCE) { 2608 struct super_block *sb; 2609 unsigned long __maybe_unused hpage_orders; 2610 int order = 0; 2611 2612 if (file) { 2613 VM_BUG_ON(file->f_op != &shmem_file_operations); 2614 sb = file_inode(file)->i_sb; 2615 } else { 2616 /* 2617 * Called directly from mm/mmap.c, or drivers/char/mem.c 2618 * for "/dev/zero", to create a shared anonymous object. 2619 */ 2620 if (IS_ERR(shm_mnt)) 2621 return addr; 2622 sb = shm_mnt->mnt_sb; 2623 2624 /* 2625 * Find the highest mTHP order used for anonymous shmem to 2626 * provide a suitable alignment address. 2627 */ 2628 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2629 hpage_orders = READ_ONCE(huge_shmem_orders_always); 2630 hpage_orders |= READ_ONCE(huge_shmem_orders_within_size); 2631 hpage_orders |= READ_ONCE(huge_shmem_orders_madvise); 2632 if (SHMEM_SB(sb)->huge != SHMEM_HUGE_NEVER) 2633 hpage_orders |= READ_ONCE(huge_shmem_orders_inherit); 2634 2635 if (hpage_orders > 0) { 2636 order = highest_order(hpage_orders); 2637 hpage_size = PAGE_SIZE << order; 2638 } 2639 #endif 2640 } 2641 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER && !order) 2642 return addr; 2643 } 2644 2645 if (len < hpage_size) 2646 return addr; 2647 2648 offset = (pgoff << PAGE_SHIFT) & (hpage_size - 1); 2649 if (offset && offset + len < 2 * hpage_size) 2650 return addr; 2651 if ((addr & (hpage_size - 1)) == offset) 2652 return addr; 2653 2654 inflated_len = len + hpage_size - PAGE_SIZE; 2655 if (inflated_len > TASK_SIZE) 2656 return addr; 2657 if (inflated_len < len) 2658 return addr; 2659 2660 inflated_addr = mm_get_unmapped_area(current->mm, NULL, uaddr, 2661 inflated_len, 0, flags); 2662 if (IS_ERR_VALUE(inflated_addr)) 2663 return addr; 2664 if (inflated_addr & ~PAGE_MASK) 2665 return addr; 2666 2667 inflated_offset = inflated_addr & (hpage_size - 1); 2668 inflated_addr += offset - inflated_offset; 2669 if (inflated_offset > offset) 2670 inflated_addr += hpage_size; 2671 2672 if (inflated_addr > TASK_SIZE - len) 2673 return addr; 2674 return inflated_addr; 2675 } 2676 2677 #ifdef CONFIG_NUMA 2678 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol) 2679 { 2680 struct inode *inode = file_inode(vma->vm_file); 2681 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol); 2682 } 2683 2684 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma, 2685 unsigned long addr, pgoff_t *ilx) 2686 { 2687 struct inode *inode = file_inode(vma->vm_file); 2688 pgoff_t index; 2689 2690 /* 2691 * Bias interleave by inode number to distribute better across nodes; 2692 * but this interface is independent of which page order is used, so 2693 * supplies only that bias, letting caller apply the offset (adjusted 2694 * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()). 2695 */ 2696 *ilx = inode->i_ino; 2697 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; 2698 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index); 2699 } 2700 2701 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 2702 pgoff_t index, unsigned int order, pgoff_t *ilx) 2703 { 2704 struct mempolicy *mpol; 2705 2706 /* Bias interleave by inode number to distribute better across nodes */ 2707 *ilx = info->vfs_inode.i_ino + (index >> order); 2708 2709 mpol = mpol_shared_policy_lookup(&info->policy, index); 2710 return mpol ? mpol : get_task_policy(current); 2711 } 2712 #else 2713 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 2714 pgoff_t index, unsigned int order, pgoff_t *ilx) 2715 { 2716 *ilx = 0; 2717 return NULL; 2718 } 2719 #endif /* CONFIG_NUMA */ 2720 2721 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 2722 { 2723 struct inode *inode = file_inode(file); 2724 struct shmem_inode_info *info = SHMEM_I(inode); 2725 int retval = -ENOMEM; 2726 2727 /* 2728 * What serializes the accesses to info->flags? 2729 * ipc_lock_object() when called from shmctl_do_lock(), 2730 * no serialization needed when called from shm_destroy(). 2731 */ 2732 if (lock && !(info->flags & VM_LOCKED)) { 2733 if (!user_shm_lock(inode->i_size, ucounts)) 2734 goto out_nomem; 2735 info->flags |= VM_LOCKED; 2736 mapping_set_unevictable(file->f_mapping); 2737 } 2738 if (!lock && (info->flags & VM_LOCKED) && ucounts) { 2739 user_shm_unlock(inode->i_size, ucounts); 2740 info->flags &= ~VM_LOCKED; 2741 mapping_clear_unevictable(file->f_mapping); 2742 } 2743 retval = 0; 2744 2745 out_nomem: 2746 return retval; 2747 } 2748 2749 static int shmem_mmap(struct file *file, struct vm_area_struct *vma) 2750 { 2751 struct inode *inode = file_inode(file); 2752 struct shmem_inode_info *info = SHMEM_I(inode); 2753 int ret; 2754 2755 ret = seal_check_write(info->seals, vma); 2756 if (ret) 2757 return ret; 2758 2759 file_accessed(file); 2760 /* This is anonymous shared memory if it is unlinked at the time of mmap */ 2761 if (inode->i_nlink) 2762 vma->vm_ops = &shmem_vm_ops; 2763 else 2764 vma->vm_ops = &shmem_anon_vm_ops; 2765 return 0; 2766 } 2767 2768 static int shmem_file_open(struct inode *inode, struct file *file) 2769 { 2770 file->f_mode |= FMODE_CAN_ODIRECT; 2771 return generic_file_open(inode, file); 2772 } 2773 2774 #ifdef CONFIG_TMPFS_XATTR 2775 static int shmem_initxattrs(struct inode *, const struct xattr *, void *); 2776 2777 #if IS_ENABLED(CONFIG_UNICODE) 2778 /* 2779 * shmem_inode_casefold_flags - Deal with casefold file attribute flag 2780 * 2781 * The casefold file attribute needs some special checks. I can just be added to 2782 * an empty dir, and can't be removed from a non-empty dir. 2783 */ 2784 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags, 2785 struct dentry *dentry, unsigned int *i_flags) 2786 { 2787 unsigned int old = inode->i_flags; 2788 struct super_block *sb = inode->i_sb; 2789 2790 if (fsflags & FS_CASEFOLD_FL) { 2791 if (!(old & S_CASEFOLD)) { 2792 if (!sb->s_encoding) 2793 return -EOPNOTSUPP; 2794 2795 if (!S_ISDIR(inode->i_mode)) 2796 return -ENOTDIR; 2797 2798 if (dentry && !simple_empty(dentry)) 2799 return -ENOTEMPTY; 2800 } 2801 2802 *i_flags = *i_flags | S_CASEFOLD; 2803 } else if (old & S_CASEFOLD) { 2804 if (dentry && !simple_empty(dentry)) 2805 return -ENOTEMPTY; 2806 } 2807 2808 return 0; 2809 } 2810 #else 2811 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags, 2812 struct dentry *dentry, unsigned int *i_flags) 2813 { 2814 if (fsflags & FS_CASEFOLD_FL) 2815 return -EOPNOTSUPP; 2816 2817 return 0; 2818 } 2819 #endif 2820 2821 /* 2822 * chattr's fsflags are unrelated to extended attributes, 2823 * but tmpfs has chosen to enable them under the same config option. 2824 */ 2825 static int shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry) 2826 { 2827 unsigned int i_flags = 0; 2828 int ret; 2829 2830 ret = shmem_inode_casefold_flags(inode, fsflags, dentry, &i_flags); 2831 if (ret) 2832 return ret; 2833 2834 if (fsflags & FS_NOATIME_FL) 2835 i_flags |= S_NOATIME; 2836 if (fsflags & FS_APPEND_FL) 2837 i_flags |= S_APPEND; 2838 if (fsflags & FS_IMMUTABLE_FL) 2839 i_flags |= S_IMMUTABLE; 2840 /* 2841 * But FS_NODUMP_FL does not require any action in i_flags. 2842 */ 2843 inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE | S_CASEFOLD); 2844 2845 return 0; 2846 } 2847 #else 2848 static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry) 2849 { 2850 } 2851 #define shmem_initxattrs NULL 2852 #endif 2853 2854 static struct offset_ctx *shmem_get_offset_ctx(struct inode *inode) 2855 { 2856 return &SHMEM_I(inode)->dir_offsets; 2857 } 2858 2859 static struct inode *__shmem_get_inode(struct mnt_idmap *idmap, 2860 struct super_block *sb, 2861 struct inode *dir, umode_t mode, 2862 dev_t dev, unsigned long flags) 2863 { 2864 struct inode *inode; 2865 struct shmem_inode_info *info; 2866 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 2867 ino_t ino; 2868 int err; 2869 2870 err = shmem_reserve_inode(sb, &ino); 2871 if (err) 2872 return ERR_PTR(err); 2873 2874 inode = new_inode(sb); 2875 if (!inode) { 2876 shmem_free_inode(sb, 0); 2877 return ERR_PTR(-ENOSPC); 2878 } 2879 2880 inode->i_ino = ino; 2881 inode_init_owner(idmap, inode, dir, mode); 2882 inode->i_blocks = 0; 2883 simple_inode_init_ts(inode); 2884 inode->i_generation = get_random_u32(); 2885 info = SHMEM_I(inode); 2886 memset(info, 0, (char *)inode - (char *)info); 2887 spin_lock_init(&info->lock); 2888 atomic_set(&info->stop_eviction, 0); 2889 info->seals = F_SEAL_SEAL; 2890 info->flags = flags & VM_NORESERVE; 2891 info->i_crtime = inode_get_mtime(inode); 2892 info->fsflags = (dir == NULL) ? 0 : 2893 SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED; 2894 if (info->fsflags) 2895 shmem_set_inode_flags(inode, info->fsflags, NULL); 2896 INIT_LIST_HEAD(&info->shrinklist); 2897 INIT_LIST_HEAD(&info->swaplist); 2898 simple_xattrs_init(&info->xattrs); 2899 cache_no_acl(inode); 2900 if (sbinfo->noswap) 2901 mapping_set_unevictable(inode->i_mapping); 2902 2903 /* Don't consider 'deny' for emergencies and 'force' for testing */ 2904 if (sbinfo->huge) 2905 mapping_set_large_folios(inode->i_mapping); 2906 2907 switch (mode & S_IFMT) { 2908 default: 2909 inode->i_op = &shmem_special_inode_operations; 2910 init_special_inode(inode, mode, dev); 2911 break; 2912 case S_IFREG: 2913 inode->i_mapping->a_ops = &shmem_aops; 2914 inode->i_op = &shmem_inode_operations; 2915 inode->i_fop = &shmem_file_operations; 2916 mpol_shared_policy_init(&info->policy, 2917 shmem_get_sbmpol(sbinfo)); 2918 break; 2919 case S_IFDIR: 2920 inc_nlink(inode); 2921 /* Some things misbehave if size == 0 on a directory */ 2922 inode->i_size = 2 * BOGO_DIRENT_SIZE; 2923 inode->i_op = &shmem_dir_inode_operations; 2924 inode->i_fop = &simple_offset_dir_operations; 2925 simple_offset_init(shmem_get_offset_ctx(inode)); 2926 break; 2927 case S_IFLNK: 2928 /* 2929 * Must not load anything in the rbtree, 2930 * mpol_free_shared_policy will not be called. 2931 */ 2932 mpol_shared_policy_init(&info->policy, NULL); 2933 break; 2934 } 2935 2936 lockdep_annotate_inode_mutex_key(inode); 2937 return inode; 2938 } 2939 2940 #ifdef CONFIG_TMPFS_QUOTA 2941 static struct inode *shmem_get_inode(struct mnt_idmap *idmap, 2942 struct super_block *sb, struct inode *dir, 2943 umode_t mode, dev_t dev, unsigned long flags) 2944 { 2945 int err; 2946 struct inode *inode; 2947 2948 inode = __shmem_get_inode(idmap, sb, dir, mode, dev, flags); 2949 if (IS_ERR(inode)) 2950 return inode; 2951 2952 err = dquot_initialize(inode); 2953 if (err) 2954 goto errout; 2955 2956 err = dquot_alloc_inode(inode); 2957 if (err) { 2958 dquot_drop(inode); 2959 goto errout; 2960 } 2961 return inode; 2962 2963 errout: 2964 inode->i_flags |= S_NOQUOTA; 2965 iput(inode); 2966 return ERR_PTR(err); 2967 } 2968 #else 2969 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap, 2970 struct super_block *sb, struct inode *dir, 2971 umode_t mode, dev_t dev, unsigned long flags) 2972 { 2973 return __shmem_get_inode(idmap, sb, dir, mode, dev, flags); 2974 } 2975 #endif /* CONFIG_TMPFS_QUOTA */ 2976 2977 #ifdef CONFIG_USERFAULTFD 2978 int shmem_mfill_atomic_pte(pmd_t *dst_pmd, 2979 struct vm_area_struct *dst_vma, 2980 unsigned long dst_addr, 2981 unsigned long src_addr, 2982 uffd_flags_t flags, 2983 struct folio **foliop) 2984 { 2985 struct inode *inode = file_inode(dst_vma->vm_file); 2986 struct shmem_inode_info *info = SHMEM_I(inode); 2987 struct address_space *mapping = inode->i_mapping; 2988 gfp_t gfp = mapping_gfp_mask(mapping); 2989 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr); 2990 void *page_kaddr; 2991 struct folio *folio; 2992 int ret; 2993 pgoff_t max_off; 2994 2995 if (shmem_inode_acct_blocks(inode, 1)) { 2996 /* 2997 * We may have got a page, returned -ENOENT triggering a retry, 2998 * and now we find ourselves with -ENOMEM. Release the page, to 2999 * avoid a BUG_ON in our caller. 3000 */ 3001 if (unlikely(*foliop)) { 3002 folio_put(*foliop); 3003 *foliop = NULL; 3004 } 3005 return -ENOMEM; 3006 } 3007 3008 if (!*foliop) { 3009 ret = -ENOMEM; 3010 folio = shmem_alloc_folio(gfp, 0, info, pgoff); 3011 if (!folio) 3012 goto out_unacct_blocks; 3013 3014 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY)) { 3015 page_kaddr = kmap_local_folio(folio, 0); 3016 /* 3017 * The read mmap_lock is held here. Despite the 3018 * mmap_lock being read recursive a deadlock is still 3019 * possible if a writer has taken a lock. For example: 3020 * 3021 * process A thread 1 takes read lock on own mmap_lock 3022 * process A thread 2 calls mmap, blocks taking write lock 3023 * process B thread 1 takes page fault, read lock on own mmap lock 3024 * process B thread 2 calls mmap, blocks taking write lock 3025 * process A thread 1 blocks taking read lock on process B 3026 * process B thread 1 blocks taking read lock on process A 3027 * 3028 * Disable page faults to prevent potential deadlock 3029 * and retry the copy outside the mmap_lock. 3030 */ 3031 pagefault_disable(); 3032 ret = copy_from_user(page_kaddr, 3033 (const void __user *)src_addr, 3034 PAGE_SIZE); 3035 pagefault_enable(); 3036 kunmap_local(page_kaddr); 3037 3038 /* fallback to copy_from_user outside mmap_lock */ 3039 if (unlikely(ret)) { 3040 *foliop = folio; 3041 ret = -ENOENT; 3042 /* don't free the page */ 3043 goto out_unacct_blocks; 3044 } 3045 3046 flush_dcache_folio(folio); 3047 } else { /* ZEROPAGE */ 3048 clear_user_highpage(&folio->page, dst_addr); 3049 } 3050 } else { 3051 folio = *foliop; 3052 VM_BUG_ON_FOLIO(folio_test_large(folio), folio); 3053 *foliop = NULL; 3054 } 3055 3056 VM_BUG_ON(folio_test_locked(folio)); 3057 VM_BUG_ON(folio_test_swapbacked(folio)); 3058 __folio_set_locked(folio); 3059 __folio_set_swapbacked(folio); 3060 __folio_mark_uptodate(folio); 3061 3062 ret = -EFAULT; 3063 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 3064 if (unlikely(pgoff >= max_off)) 3065 goto out_release; 3066 3067 ret = mem_cgroup_charge(folio, dst_vma->vm_mm, gfp); 3068 if (ret) 3069 goto out_release; 3070 ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL, gfp); 3071 if (ret) 3072 goto out_release; 3073 3074 ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr, 3075 &folio->page, true, flags); 3076 if (ret) 3077 goto out_delete_from_cache; 3078 3079 shmem_recalc_inode(inode, 1, 0); 3080 folio_unlock(folio); 3081 return 0; 3082 out_delete_from_cache: 3083 filemap_remove_folio(folio); 3084 out_release: 3085 folio_unlock(folio); 3086 folio_put(folio); 3087 out_unacct_blocks: 3088 shmem_inode_unacct_blocks(inode, 1); 3089 return ret; 3090 } 3091 #endif /* CONFIG_USERFAULTFD */ 3092 3093 #ifdef CONFIG_TMPFS 3094 static const struct inode_operations shmem_symlink_inode_operations; 3095 static const struct inode_operations shmem_short_symlink_operations; 3096 3097 static int 3098 shmem_write_begin(struct file *file, struct address_space *mapping, 3099 loff_t pos, unsigned len, 3100 struct folio **foliop, void **fsdata) 3101 { 3102 struct inode *inode = mapping->host; 3103 struct shmem_inode_info *info = SHMEM_I(inode); 3104 pgoff_t index = pos >> PAGE_SHIFT; 3105 struct folio *folio; 3106 int ret = 0; 3107 3108 /* i_rwsem is held by caller */ 3109 if (unlikely(info->seals & (F_SEAL_GROW | 3110 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) { 3111 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) 3112 return -EPERM; 3113 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size) 3114 return -EPERM; 3115 } 3116 3117 ret = shmem_get_folio(inode, index, pos + len, &folio, SGP_WRITE); 3118 if (ret) 3119 return ret; 3120 3121 if (folio_test_hwpoison(folio) || 3122 (folio_test_large(folio) && folio_test_has_hwpoisoned(folio))) { 3123 folio_unlock(folio); 3124 folio_put(folio); 3125 return -EIO; 3126 } 3127 3128 *foliop = folio; 3129 return 0; 3130 } 3131 3132 static int 3133 shmem_write_end(struct file *file, struct address_space *mapping, 3134 loff_t pos, unsigned len, unsigned copied, 3135 struct folio *folio, void *fsdata) 3136 { 3137 struct inode *inode = mapping->host; 3138 3139 if (pos + copied > inode->i_size) 3140 i_size_write(inode, pos + copied); 3141 3142 if (!folio_test_uptodate(folio)) { 3143 if (copied < folio_size(folio)) { 3144 size_t from = offset_in_folio(folio, pos); 3145 folio_zero_segments(folio, 0, from, 3146 from + copied, folio_size(folio)); 3147 } 3148 folio_mark_uptodate(folio); 3149 } 3150 folio_mark_dirty(folio); 3151 folio_unlock(folio); 3152 folio_put(folio); 3153 3154 return copied; 3155 } 3156 3157 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) 3158 { 3159 struct file *file = iocb->ki_filp; 3160 struct inode *inode = file_inode(file); 3161 struct address_space *mapping = inode->i_mapping; 3162 pgoff_t index; 3163 unsigned long offset; 3164 int error = 0; 3165 ssize_t retval = 0; 3166 3167 for (;;) { 3168 struct folio *folio = NULL; 3169 struct page *page = NULL; 3170 unsigned long nr, ret; 3171 loff_t end_offset, i_size = i_size_read(inode); 3172 bool fallback_page_copy = false; 3173 size_t fsize; 3174 3175 if (unlikely(iocb->ki_pos >= i_size)) 3176 break; 3177 3178 index = iocb->ki_pos >> PAGE_SHIFT; 3179 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ); 3180 if (error) { 3181 if (error == -EINVAL) 3182 error = 0; 3183 break; 3184 } 3185 if (folio) { 3186 folio_unlock(folio); 3187 3188 page = folio_file_page(folio, index); 3189 if (PageHWPoison(page)) { 3190 folio_put(folio); 3191 error = -EIO; 3192 break; 3193 } 3194 3195 if (folio_test_large(folio) && 3196 folio_test_has_hwpoisoned(folio)) 3197 fallback_page_copy = true; 3198 } 3199 3200 /* 3201 * We must evaluate after, since reads (unlike writes) 3202 * are called without i_rwsem protection against truncate 3203 */ 3204 i_size = i_size_read(inode); 3205 if (unlikely(iocb->ki_pos >= i_size)) { 3206 if (folio) 3207 folio_put(folio); 3208 break; 3209 } 3210 end_offset = min_t(loff_t, i_size, iocb->ki_pos + to->count); 3211 if (folio && likely(!fallback_page_copy)) 3212 fsize = folio_size(folio); 3213 else 3214 fsize = PAGE_SIZE; 3215 offset = iocb->ki_pos & (fsize - 1); 3216 nr = min_t(loff_t, end_offset - iocb->ki_pos, fsize - offset); 3217 3218 if (folio) { 3219 /* 3220 * If users can be writing to this page using arbitrary 3221 * virtual addresses, take care about potential aliasing 3222 * before reading the page on the kernel side. 3223 */ 3224 if (mapping_writably_mapped(mapping)) { 3225 if (likely(!fallback_page_copy)) 3226 flush_dcache_folio(folio); 3227 else 3228 flush_dcache_page(page); 3229 } 3230 3231 /* 3232 * Mark the folio accessed if we read the beginning. 3233 */ 3234 if (!offset) 3235 folio_mark_accessed(folio); 3236 /* 3237 * Ok, we have the page, and it's up-to-date, so 3238 * now we can copy it to user space... 3239 */ 3240 if (likely(!fallback_page_copy)) 3241 ret = copy_folio_to_iter(folio, offset, nr, to); 3242 else 3243 ret = copy_page_to_iter(page, offset, nr, to); 3244 folio_put(folio); 3245 } else if (user_backed_iter(to)) { 3246 /* 3247 * Copy to user tends to be so well optimized, but 3248 * clear_user() not so much, that it is noticeably 3249 * faster to copy the zero page instead of clearing. 3250 */ 3251 ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to); 3252 } else { 3253 /* 3254 * But submitting the same page twice in a row to 3255 * splice() - or others? - can result in confusion: 3256 * so don't attempt that optimization on pipes etc. 3257 */ 3258 ret = iov_iter_zero(nr, to); 3259 } 3260 3261 retval += ret; 3262 iocb->ki_pos += ret; 3263 3264 if (!iov_iter_count(to)) 3265 break; 3266 if (ret < nr) { 3267 error = -EFAULT; 3268 break; 3269 } 3270 cond_resched(); 3271 } 3272 3273 file_accessed(file); 3274 return retval ? retval : error; 3275 } 3276 3277 static ssize_t shmem_file_write_iter(struct kiocb *iocb, struct iov_iter *from) 3278 { 3279 struct file *file = iocb->ki_filp; 3280 struct inode *inode = file->f_mapping->host; 3281 ssize_t ret; 3282 3283 inode_lock(inode); 3284 ret = generic_write_checks(iocb, from); 3285 if (ret <= 0) 3286 goto unlock; 3287 ret = file_remove_privs(file); 3288 if (ret) 3289 goto unlock; 3290 ret = file_update_time(file); 3291 if (ret) 3292 goto unlock; 3293 ret = generic_perform_write(iocb, from); 3294 unlock: 3295 inode_unlock(inode); 3296 return ret; 3297 } 3298 3299 static bool zero_pipe_buf_get(struct pipe_inode_info *pipe, 3300 struct pipe_buffer *buf) 3301 { 3302 return true; 3303 } 3304 3305 static void zero_pipe_buf_release(struct pipe_inode_info *pipe, 3306 struct pipe_buffer *buf) 3307 { 3308 } 3309 3310 static bool zero_pipe_buf_try_steal(struct pipe_inode_info *pipe, 3311 struct pipe_buffer *buf) 3312 { 3313 return false; 3314 } 3315 3316 static const struct pipe_buf_operations zero_pipe_buf_ops = { 3317 .release = zero_pipe_buf_release, 3318 .try_steal = zero_pipe_buf_try_steal, 3319 .get = zero_pipe_buf_get, 3320 }; 3321 3322 static size_t splice_zeropage_into_pipe(struct pipe_inode_info *pipe, 3323 loff_t fpos, size_t size) 3324 { 3325 size_t offset = fpos & ~PAGE_MASK; 3326 3327 size = min_t(size_t, size, PAGE_SIZE - offset); 3328 3329 if (!pipe_full(pipe->head, pipe->tail, pipe->max_usage)) { 3330 struct pipe_buffer *buf = pipe_head_buf(pipe); 3331 3332 *buf = (struct pipe_buffer) { 3333 .ops = &zero_pipe_buf_ops, 3334 .page = ZERO_PAGE(0), 3335 .offset = offset, 3336 .len = size, 3337 }; 3338 pipe->head++; 3339 } 3340 3341 return size; 3342 } 3343 3344 static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, 3345 struct pipe_inode_info *pipe, 3346 size_t len, unsigned int flags) 3347 { 3348 struct inode *inode = file_inode(in); 3349 struct address_space *mapping = inode->i_mapping; 3350 struct folio *folio = NULL; 3351 size_t total_spliced = 0, used, npages, n, part; 3352 loff_t isize; 3353 int error = 0; 3354 3355 /* Work out how much data we can actually add into the pipe */ 3356 used = pipe_occupancy(pipe->head, pipe->tail); 3357 npages = max_t(ssize_t, pipe->max_usage - used, 0); 3358 len = min_t(size_t, len, npages * PAGE_SIZE); 3359 3360 do { 3361 bool fallback_page_splice = false; 3362 struct page *page = NULL; 3363 pgoff_t index; 3364 size_t size; 3365 3366 if (*ppos >= i_size_read(inode)) 3367 break; 3368 3369 index = *ppos >> PAGE_SHIFT; 3370 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ); 3371 if (error) { 3372 if (error == -EINVAL) 3373 error = 0; 3374 break; 3375 } 3376 if (folio) { 3377 folio_unlock(folio); 3378 3379 page = folio_file_page(folio, index); 3380 if (PageHWPoison(page)) { 3381 error = -EIO; 3382 break; 3383 } 3384 3385 if (folio_test_large(folio) && 3386 folio_test_has_hwpoisoned(folio)) 3387 fallback_page_splice = true; 3388 } 3389 3390 /* 3391 * i_size must be checked after we know the pages are Uptodate. 3392 * 3393 * Checking i_size after the check allows us to calculate 3394 * the correct value for "nr", which means the zero-filled 3395 * part of the page is not copied back to userspace (unless 3396 * another truncate extends the file - this is desired though). 3397 */ 3398 isize = i_size_read(inode); 3399 if (unlikely(*ppos >= isize)) 3400 break; 3401 /* 3402 * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned 3403 * pages. 3404 */ 3405 size = len; 3406 if (unlikely(fallback_page_splice)) { 3407 size_t offset = *ppos & ~PAGE_MASK; 3408 3409 size = umin(size, PAGE_SIZE - offset); 3410 } 3411 part = min_t(loff_t, isize - *ppos, size); 3412 3413 if (folio) { 3414 /* 3415 * If users can be writing to this page using arbitrary 3416 * virtual addresses, take care about potential aliasing 3417 * before reading the page on the kernel side. 3418 */ 3419 if (mapping_writably_mapped(mapping)) { 3420 if (likely(!fallback_page_splice)) 3421 flush_dcache_folio(folio); 3422 else 3423 flush_dcache_page(page); 3424 } 3425 folio_mark_accessed(folio); 3426 /* 3427 * Ok, we have the page, and it's up-to-date, so we can 3428 * now splice it into the pipe. 3429 */ 3430 n = splice_folio_into_pipe(pipe, folio, *ppos, part); 3431 folio_put(folio); 3432 folio = NULL; 3433 } else { 3434 n = splice_zeropage_into_pipe(pipe, *ppos, part); 3435 } 3436 3437 if (!n) 3438 break; 3439 len -= n; 3440 total_spliced += n; 3441 *ppos += n; 3442 in->f_ra.prev_pos = *ppos; 3443 if (pipe_full(pipe->head, pipe->tail, pipe->max_usage)) 3444 break; 3445 3446 cond_resched(); 3447 } while (len); 3448 3449 if (folio) 3450 folio_put(folio); 3451 3452 file_accessed(in); 3453 return total_spliced ? total_spliced : error; 3454 } 3455 3456 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence) 3457 { 3458 struct address_space *mapping = file->f_mapping; 3459 struct inode *inode = mapping->host; 3460 3461 if (whence != SEEK_DATA && whence != SEEK_HOLE) 3462 return generic_file_llseek_size(file, offset, whence, 3463 MAX_LFS_FILESIZE, i_size_read(inode)); 3464 if (offset < 0) 3465 return -ENXIO; 3466 3467 inode_lock(inode); 3468 /* We're holding i_rwsem so we can access i_size directly */ 3469 offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence); 3470 if (offset >= 0) 3471 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE); 3472 inode_unlock(inode); 3473 return offset; 3474 } 3475 3476 static long shmem_fallocate(struct file *file, int mode, loff_t offset, 3477 loff_t len) 3478 { 3479 struct inode *inode = file_inode(file); 3480 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 3481 struct shmem_inode_info *info = SHMEM_I(inode); 3482 struct shmem_falloc shmem_falloc; 3483 pgoff_t start, index, end, undo_fallocend; 3484 int error; 3485 3486 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) 3487 return -EOPNOTSUPP; 3488 3489 inode_lock(inode); 3490 3491 if (mode & FALLOC_FL_PUNCH_HOLE) { 3492 struct address_space *mapping = file->f_mapping; 3493 loff_t unmap_start = round_up(offset, PAGE_SIZE); 3494 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1; 3495 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq); 3496 3497 /* protected by i_rwsem */ 3498 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) { 3499 error = -EPERM; 3500 goto out; 3501 } 3502 3503 shmem_falloc.waitq = &shmem_falloc_waitq; 3504 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT; 3505 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT; 3506 spin_lock(&inode->i_lock); 3507 inode->i_private = &shmem_falloc; 3508 spin_unlock(&inode->i_lock); 3509 3510 if ((u64)unmap_end > (u64)unmap_start) 3511 unmap_mapping_range(mapping, unmap_start, 3512 1 + unmap_end - unmap_start, 0); 3513 shmem_truncate_range(inode, offset, offset + len - 1); 3514 /* No need to unmap again: hole-punching leaves COWed pages */ 3515 3516 spin_lock(&inode->i_lock); 3517 inode->i_private = NULL; 3518 wake_up_all(&shmem_falloc_waitq); 3519 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head)); 3520 spin_unlock(&inode->i_lock); 3521 error = 0; 3522 goto out; 3523 } 3524 3525 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */ 3526 error = inode_newsize_ok(inode, offset + len); 3527 if (error) 3528 goto out; 3529 3530 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) { 3531 error = -EPERM; 3532 goto out; 3533 } 3534 3535 start = offset >> PAGE_SHIFT; 3536 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT; 3537 /* Try to avoid a swapstorm if len is impossible to satisfy */ 3538 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) { 3539 error = -ENOSPC; 3540 goto out; 3541 } 3542 3543 shmem_falloc.waitq = NULL; 3544 shmem_falloc.start = start; 3545 shmem_falloc.next = start; 3546 shmem_falloc.nr_falloced = 0; 3547 shmem_falloc.nr_unswapped = 0; 3548 spin_lock(&inode->i_lock); 3549 inode->i_private = &shmem_falloc; 3550 spin_unlock(&inode->i_lock); 3551 3552 /* 3553 * info->fallocend is only relevant when huge pages might be 3554 * involved: to prevent split_huge_page() freeing fallocated 3555 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size. 3556 */ 3557 undo_fallocend = info->fallocend; 3558 if (info->fallocend < end) 3559 info->fallocend = end; 3560 3561 for (index = start; index < end; ) { 3562 struct folio *folio; 3563 3564 /* 3565 * Check for fatal signal so that we abort early in OOM 3566 * situations. We don't want to abort in case of non-fatal 3567 * signals as large fallocate can take noticeable time and 3568 * e.g. periodic timers may result in fallocate constantly 3569 * restarting. 3570 */ 3571 if (fatal_signal_pending(current)) 3572 error = -EINTR; 3573 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced) 3574 error = -ENOMEM; 3575 else 3576 error = shmem_get_folio(inode, index, offset + len, 3577 &folio, SGP_FALLOC); 3578 if (error) { 3579 info->fallocend = undo_fallocend; 3580 /* Remove the !uptodate folios we added */ 3581 if (index > start) { 3582 shmem_undo_range(inode, 3583 (loff_t)start << PAGE_SHIFT, 3584 ((loff_t)index << PAGE_SHIFT) - 1, true); 3585 } 3586 goto undone; 3587 } 3588 3589 /* 3590 * Here is a more important optimization than it appears: 3591 * a second SGP_FALLOC on the same large folio will clear it, 3592 * making it uptodate and un-undoable if we fail later. 3593 */ 3594 index = folio_next_index(folio); 3595 /* Beware 32-bit wraparound */ 3596 if (!index) 3597 index--; 3598 3599 /* 3600 * Inform shmem_writepage() how far we have reached. 3601 * No need for lock or barrier: we have the page lock. 3602 */ 3603 if (!folio_test_uptodate(folio)) 3604 shmem_falloc.nr_falloced += index - shmem_falloc.next; 3605 shmem_falloc.next = index; 3606 3607 /* 3608 * If !uptodate, leave it that way so that freeable folios 3609 * can be recognized if we need to rollback on error later. 3610 * But mark it dirty so that memory pressure will swap rather 3611 * than free the folios we are allocating (and SGP_CACHE folios 3612 * might still be clean: we now need to mark those dirty too). 3613 */ 3614 folio_mark_dirty(folio); 3615 folio_unlock(folio); 3616 folio_put(folio); 3617 cond_resched(); 3618 } 3619 3620 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) 3621 i_size_write(inode, offset + len); 3622 undone: 3623 spin_lock(&inode->i_lock); 3624 inode->i_private = NULL; 3625 spin_unlock(&inode->i_lock); 3626 out: 3627 if (!error) 3628 file_modified(file); 3629 inode_unlock(inode); 3630 return error; 3631 } 3632 3633 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf) 3634 { 3635 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb); 3636 3637 buf->f_type = TMPFS_MAGIC; 3638 buf->f_bsize = PAGE_SIZE; 3639 buf->f_namelen = NAME_MAX; 3640 if (sbinfo->max_blocks) { 3641 buf->f_blocks = sbinfo->max_blocks; 3642 buf->f_bavail = 3643 buf->f_bfree = sbinfo->max_blocks - 3644 percpu_counter_sum(&sbinfo->used_blocks); 3645 } 3646 if (sbinfo->max_inodes) { 3647 buf->f_files = sbinfo->max_inodes; 3648 buf->f_ffree = sbinfo->free_ispace / BOGO_INODE_SIZE; 3649 } 3650 /* else leave those fields 0 like simple_statfs */ 3651 3652 buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b); 3653 3654 return 0; 3655 } 3656 3657 /* 3658 * File creation. Allocate an inode, and we're done.. 3659 */ 3660 static int 3661 shmem_mknod(struct mnt_idmap *idmap, struct inode *dir, 3662 struct dentry *dentry, umode_t mode, dev_t dev) 3663 { 3664 struct inode *inode; 3665 int error; 3666 3667 if (!generic_ci_validate_strict_name(dir, &dentry->d_name)) 3668 return -EINVAL; 3669 3670 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, dev, VM_NORESERVE); 3671 if (IS_ERR(inode)) 3672 return PTR_ERR(inode); 3673 3674 error = simple_acl_create(dir, inode); 3675 if (error) 3676 goto out_iput; 3677 error = security_inode_init_security(inode, dir, &dentry->d_name, 3678 shmem_initxattrs, NULL); 3679 if (error && error != -EOPNOTSUPP) 3680 goto out_iput; 3681 3682 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3683 if (error) 3684 goto out_iput; 3685 3686 dir->i_size += BOGO_DIRENT_SIZE; 3687 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir)); 3688 inode_inc_iversion(dir); 3689 3690 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3691 d_add(dentry, inode); 3692 else 3693 d_instantiate(dentry, inode); 3694 3695 dget(dentry); /* Extra count - pin the dentry in core */ 3696 return error; 3697 3698 out_iput: 3699 iput(inode); 3700 return error; 3701 } 3702 3703 static int 3704 shmem_tmpfile(struct mnt_idmap *idmap, struct inode *dir, 3705 struct file *file, umode_t mode) 3706 { 3707 struct inode *inode; 3708 int error; 3709 3710 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, 0, VM_NORESERVE); 3711 if (IS_ERR(inode)) { 3712 error = PTR_ERR(inode); 3713 goto err_out; 3714 } 3715 error = security_inode_init_security(inode, dir, NULL, 3716 shmem_initxattrs, NULL); 3717 if (error && error != -EOPNOTSUPP) 3718 goto out_iput; 3719 error = simple_acl_create(dir, inode); 3720 if (error) 3721 goto out_iput; 3722 d_tmpfile(file, inode); 3723 3724 err_out: 3725 return finish_open_simple(file, error); 3726 out_iput: 3727 iput(inode); 3728 return error; 3729 } 3730 3731 static int shmem_mkdir(struct mnt_idmap *idmap, struct inode *dir, 3732 struct dentry *dentry, umode_t mode) 3733 { 3734 int error; 3735 3736 error = shmem_mknod(idmap, dir, dentry, mode | S_IFDIR, 0); 3737 if (error) 3738 return error; 3739 inc_nlink(dir); 3740 return 0; 3741 } 3742 3743 static int shmem_create(struct mnt_idmap *idmap, struct inode *dir, 3744 struct dentry *dentry, umode_t mode, bool excl) 3745 { 3746 return shmem_mknod(idmap, dir, dentry, mode | S_IFREG, 0); 3747 } 3748 3749 /* 3750 * Link a file.. 3751 */ 3752 static int shmem_link(struct dentry *old_dentry, struct inode *dir, 3753 struct dentry *dentry) 3754 { 3755 struct inode *inode = d_inode(old_dentry); 3756 int ret = 0; 3757 3758 /* 3759 * No ordinary (disk based) filesystem counts links as inodes; 3760 * but each new link needs a new dentry, pinning lowmem, and 3761 * tmpfs dentries cannot be pruned until they are unlinked. 3762 * But if an O_TMPFILE file is linked into the tmpfs, the 3763 * first link must skip that, to get the accounting right. 3764 */ 3765 if (inode->i_nlink) { 3766 ret = shmem_reserve_inode(inode->i_sb, NULL); 3767 if (ret) 3768 goto out; 3769 } 3770 3771 ret = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3772 if (ret) { 3773 if (inode->i_nlink) 3774 shmem_free_inode(inode->i_sb, 0); 3775 goto out; 3776 } 3777 3778 dir->i_size += BOGO_DIRENT_SIZE; 3779 inode_set_mtime_to_ts(dir, 3780 inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode))); 3781 inode_inc_iversion(dir); 3782 inc_nlink(inode); 3783 ihold(inode); /* New dentry reference */ 3784 dget(dentry); /* Extra pinning count for the created dentry */ 3785 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3786 d_add(dentry, inode); 3787 else 3788 d_instantiate(dentry, inode); 3789 out: 3790 return ret; 3791 } 3792 3793 static int shmem_unlink(struct inode *dir, struct dentry *dentry) 3794 { 3795 struct inode *inode = d_inode(dentry); 3796 3797 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode)) 3798 shmem_free_inode(inode->i_sb, 0); 3799 3800 simple_offset_remove(shmem_get_offset_ctx(dir), dentry); 3801 3802 dir->i_size -= BOGO_DIRENT_SIZE; 3803 inode_set_mtime_to_ts(dir, 3804 inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode))); 3805 inode_inc_iversion(dir); 3806 drop_nlink(inode); 3807 dput(dentry); /* Undo the count from "create" - does all the work */ 3808 3809 /* 3810 * For now, VFS can't deal with case-insensitive negative dentries, so 3811 * we invalidate them 3812 */ 3813 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3814 d_invalidate(dentry); 3815 3816 return 0; 3817 } 3818 3819 static int shmem_rmdir(struct inode *dir, struct dentry *dentry) 3820 { 3821 if (!simple_offset_empty(dentry)) 3822 return -ENOTEMPTY; 3823 3824 drop_nlink(d_inode(dentry)); 3825 drop_nlink(dir); 3826 return shmem_unlink(dir, dentry); 3827 } 3828 3829 static int shmem_whiteout(struct mnt_idmap *idmap, 3830 struct inode *old_dir, struct dentry *old_dentry) 3831 { 3832 struct dentry *whiteout; 3833 int error; 3834 3835 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name); 3836 if (!whiteout) 3837 return -ENOMEM; 3838 3839 error = shmem_mknod(idmap, old_dir, whiteout, 3840 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV); 3841 dput(whiteout); 3842 if (error) 3843 return error; 3844 3845 /* 3846 * Cheat and hash the whiteout while the old dentry is still in 3847 * place, instead of playing games with FS_RENAME_DOES_D_MOVE. 3848 * 3849 * d_lookup() will consistently find one of them at this point, 3850 * not sure which one, but that isn't even important. 3851 */ 3852 d_rehash(whiteout); 3853 return 0; 3854 } 3855 3856 /* 3857 * The VFS layer already does all the dentry stuff for rename, 3858 * we just have to decrement the usage count for the target if 3859 * it exists so that the VFS layer correctly free's it when it 3860 * gets overwritten. 3861 */ 3862 static int shmem_rename2(struct mnt_idmap *idmap, 3863 struct inode *old_dir, struct dentry *old_dentry, 3864 struct inode *new_dir, struct dentry *new_dentry, 3865 unsigned int flags) 3866 { 3867 struct inode *inode = d_inode(old_dentry); 3868 int they_are_dirs = S_ISDIR(inode->i_mode); 3869 int error; 3870 3871 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) 3872 return -EINVAL; 3873 3874 if (flags & RENAME_EXCHANGE) 3875 return simple_offset_rename_exchange(old_dir, old_dentry, 3876 new_dir, new_dentry); 3877 3878 if (!simple_offset_empty(new_dentry)) 3879 return -ENOTEMPTY; 3880 3881 if (flags & RENAME_WHITEOUT) { 3882 error = shmem_whiteout(idmap, old_dir, old_dentry); 3883 if (error) 3884 return error; 3885 } 3886 3887 error = simple_offset_rename(old_dir, old_dentry, new_dir, new_dentry); 3888 if (error) 3889 return error; 3890 3891 if (d_really_is_positive(new_dentry)) { 3892 (void) shmem_unlink(new_dir, new_dentry); 3893 if (they_are_dirs) { 3894 drop_nlink(d_inode(new_dentry)); 3895 drop_nlink(old_dir); 3896 } 3897 } else if (they_are_dirs) { 3898 drop_nlink(old_dir); 3899 inc_nlink(new_dir); 3900 } 3901 3902 old_dir->i_size -= BOGO_DIRENT_SIZE; 3903 new_dir->i_size += BOGO_DIRENT_SIZE; 3904 simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry); 3905 inode_inc_iversion(old_dir); 3906 inode_inc_iversion(new_dir); 3907 return 0; 3908 } 3909 3910 static int shmem_symlink(struct mnt_idmap *idmap, struct inode *dir, 3911 struct dentry *dentry, const char *symname) 3912 { 3913 int error; 3914 int len; 3915 struct inode *inode; 3916 struct folio *folio; 3917 3918 len = strlen(symname) + 1; 3919 if (len > PAGE_SIZE) 3920 return -ENAMETOOLONG; 3921 3922 inode = shmem_get_inode(idmap, dir->i_sb, dir, S_IFLNK | 0777, 0, 3923 VM_NORESERVE); 3924 if (IS_ERR(inode)) 3925 return PTR_ERR(inode); 3926 3927 error = security_inode_init_security(inode, dir, &dentry->d_name, 3928 shmem_initxattrs, NULL); 3929 if (error && error != -EOPNOTSUPP) 3930 goto out_iput; 3931 3932 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3933 if (error) 3934 goto out_iput; 3935 3936 inode->i_size = len-1; 3937 if (len <= SHORT_SYMLINK_LEN) { 3938 inode->i_link = kmemdup(symname, len, GFP_KERNEL); 3939 if (!inode->i_link) { 3940 error = -ENOMEM; 3941 goto out_remove_offset; 3942 } 3943 inode->i_op = &shmem_short_symlink_operations; 3944 } else { 3945 inode_nohighmem(inode); 3946 inode->i_mapping->a_ops = &shmem_aops; 3947 error = shmem_get_folio(inode, 0, 0, &folio, SGP_WRITE); 3948 if (error) 3949 goto out_remove_offset; 3950 inode->i_op = &shmem_symlink_inode_operations; 3951 memcpy(folio_address(folio), symname, len); 3952 folio_mark_uptodate(folio); 3953 folio_mark_dirty(folio); 3954 folio_unlock(folio); 3955 folio_put(folio); 3956 } 3957 dir->i_size += BOGO_DIRENT_SIZE; 3958 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir)); 3959 inode_inc_iversion(dir); 3960 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3961 d_add(dentry, inode); 3962 else 3963 d_instantiate(dentry, inode); 3964 dget(dentry); 3965 return 0; 3966 3967 out_remove_offset: 3968 simple_offset_remove(shmem_get_offset_ctx(dir), dentry); 3969 out_iput: 3970 iput(inode); 3971 return error; 3972 } 3973 3974 static void shmem_put_link(void *arg) 3975 { 3976 folio_mark_accessed(arg); 3977 folio_put(arg); 3978 } 3979 3980 static const char *shmem_get_link(struct dentry *dentry, struct inode *inode, 3981 struct delayed_call *done) 3982 { 3983 struct folio *folio = NULL; 3984 int error; 3985 3986 if (!dentry) { 3987 folio = filemap_get_folio(inode->i_mapping, 0); 3988 if (IS_ERR(folio)) 3989 return ERR_PTR(-ECHILD); 3990 if (PageHWPoison(folio_page(folio, 0)) || 3991 !folio_test_uptodate(folio)) { 3992 folio_put(folio); 3993 return ERR_PTR(-ECHILD); 3994 } 3995 } else { 3996 error = shmem_get_folio(inode, 0, 0, &folio, SGP_READ); 3997 if (error) 3998 return ERR_PTR(error); 3999 if (!folio) 4000 return ERR_PTR(-ECHILD); 4001 if (PageHWPoison(folio_page(folio, 0))) { 4002 folio_unlock(folio); 4003 folio_put(folio); 4004 return ERR_PTR(-ECHILD); 4005 } 4006 folio_unlock(folio); 4007 } 4008 set_delayed_call(done, shmem_put_link, folio); 4009 return folio_address(folio); 4010 } 4011 4012 #ifdef CONFIG_TMPFS_XATTR 4013 4014 static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa) 4015 { 4016 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4017 4018 fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE); 4019 4020 return 0; 4021 } 4022 4023 static int shmem_fileattr_set(struct mnt_idmap *idmap, 4024 struct dentry *dentry, struct fileattr *fa) 4025 { 4026 struct inode *inode = d_inode(dentry); 4027 struct shmem_inode_info *info = SHMEM_I(inode); 4028 int ret, flags; 4029 4030 if (fileattr_has_fsx(fa)) 4031 return -EOPNOTSUPP; 4032 if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE) 4033 return -EOPNOTSUPP; 4034 4035 flags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) | 4036 (fa->flags & SHMEM_FL_USER_MODIFIABLE); 4037 4038 ret = shmem_set_inode_flags(inode, flags, dentry); 4039 4040 if (ret) 4041 return ret; 4042 4043 info->fsflags = flags; 4044 4045 inode_set_ctime_current(inode); 4046 inode_inc_iversion(inode); 4047 return 0; 4048 } 4049 4050 /* 4051 * Superblocks without xattr inode operations may get some security.* xattr 4052 * support from the LSM "for free". As soon as we have any other xattrs 4053 * like ACLs, we also need to implement the security.* handlers at 4054 * filesystem level, though. 4055 */ 4056 4057 /* 4058 * Callback for security_inode_init_security() for acquiring xattrs. 4059 */ 4060 static int shmem_initxattrs(struct inode *inode, 4061 const struct xattr *xattr_array, void *fs_info) 4062 { 4063 struct shmem_inode_info *info = SHMEM_I(inode); 4064 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4065 const struct xattr *xattr; 4066 struct simple_xattr *new_xattr; 4067 size_t ispace = 0; 4068 size_t len; 4069 4070 if (sbinfo->max_inodes) { 4071 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4072 ispace += simple_xattr_space(xattr->name, 4073 xattr->value_len + XATTR_SECURITY_PREFIX_LEN); 4074 } 4075 if (ispace) { 4076 raw_spin_lock(&sbinfo->stat_lock); 4077 if (sbinfo->free_ispace < ispace) 4078 ispace = 0; 4079 else 4080 sbinfo->free_ispace -= ispace; 4081 raw_spin_unlock(&sbinfo->stat_lock); 4082 if (!ispace) 4083 return -ENOSPC; 4084 } 4085 } 4086 4087 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4088 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len); 4089 if (!new_xattr) 4090 break; 4091 4092 len = strlen(xattr->name) + 1; 4093 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len, 4094 GFP_KERNEL_ACCOUNT); 4095 if (!new_xattr->name) { 4096 kvfree(new_xattr); 4097 break; 4098 } 4099 4100 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX, 4101 XATTR_SECURITY_PREFIX_LEN); 4102 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN, 4103 xattr->name, len); 4104 4105 simple_xattr_add(&info->xattrs, new_xattr); 4106 } 4107 4108 if (xattr->name != NULL) { 4109 if (ispace) { 4110 raw_spin_lock(&sbinfo->stat_lock); 4111 sbinfo->free_ispace += ispace; 4112 raw_spin_unlock(&sbinfo->stat_lock); 4113 } 4114 simple_xattrs_free(&info->xattrs, NULL); 4115 return -ENOMEM; 4116 } 4117 4118 return 0; 4119 } 4120 4121 static int shmem_xattr_handler_get(const struct xattr_handler *handler, 4122 struct dentry *unused, struct inode *inode, 4123 const char *name, void *buffer, size_t size) 4124 { 4125 struct shmem_inode_info *info = SHMEM_I(inode); 4126 4127 name = xattr_full_name(handler, name); 4128 return simple_xattr_get(&info->xattrs, name, buffer, size); 4129 } 4130 4131 static int shmem_xattr_handler_set(const struct xattr_handler *handler, 4132 struct mnt_idmap *idmap, 4133 struct dentry *unused, struct inode *inode, 4134 const char *name, const void *value, 4135 size_t size, int flags) 4136 { 4137 struct shmem_inode_info *info = SHMEM_I(inode); 4138 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4139 struct simple_xattr *old_xattr; 4140 size_t ispace = 0; 4141 4142 name = xattr_full_name(handler, name); 4143 if (value && sbinfo->max_inodes) { 4144 ispace = simple_xattr_space(name, size); 4145 raw_spin_lock(&sbinfo->stat_lock); 4146 if (sbinfo->free_ispace < ispace) 4147 ispace = 0; 4148 else 4149 sbinfo->free_ispace -= ispace; 4150 raw_spin_unlock(&sbinfo->stat_lock); 4151 if (!ispace) 4152 return -ENOSPC; 4153 } 4154 4155 old_xattr = simple_xattr_set(&info->xattrs, name, value, size, flags); 4156 if (!IS_ERR(old_xattr)) { 4157 ispace = 0; 4158 if (old_xattr && sbinfo->max_inodes) 4159 ispace = simple_xattr_space(old_xattr->name, 4160 old_xattr->size); 4161 simple_xattr_free(old_xattr); 4162 old_xattr = NULL; 4163 inode_set_ctime_current(inode); 4164 inode_inc_iversion(inode); 4165 } 4166 if (ispace) { 4167 raw_spin_lock(&sbinfo->stat_lock); 4168 sbinfo->free_ispace += ispace; 4169 raw_spin_unlock(&sbinfo->stat_lock); 4170 } 4171 return PTR_ERR(old_xattr); 4172 } 4173 4174 static const struct xattr_handler shmem_security_xattr_handler = { 4175 .prefix = XATTR_SECURITY_PREFIX, 4176 .get = shmem_xattr_handler_get, 4177 .set = shmem_xattr_handler_set, 4178 }; 4179 4180 static const struct xattr_handler shmem_trusted_xattr_handler = { 4181 .prefix = XATTR_TRUSTED_PREFIX, 4182 .get = shmem_xattr_handler_get, 4183 .set = shmem_xattr_handler_set, 4184 }; 4185 4186 static const struct xattr_handler shmem_user_xattr_handler = { 4187 .prefix = XATTR_USER_PREFIX, 4188 .get = shmem_xattr_handler_get, 4189 .set = shmem_xattr_handler_set, 4190 }; 4191 4192 static const struct xattr_handler * const shmem_xattr_handlers[] = { 4193 &shmem_security_xattr_handler, 4194 &shmem_trusted_xattr_handler, 4195 &shmem_user_xattr_handler, 4196 NULL 4197 }; 4198 4199 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size) 4200 { 4201 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4202 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size); 4203 } 4204 #endif /* CONFIG_TMPFS_XATTR */ 4205 4206 static const struct inode_operations shmem_short_symlink_operations = { 4207 .getattr = shmem_getattr, 4208 .setattr = shmem_setattr, 4209 .get_link = simple_get_link, 4210 #ifdef CONFIG_TMPFS_XATTR 4211 .listxattr = shmem_listxattr, 4212 #endif 4213 }; 4214 4215 static const struct inode_operations shmem_symlink_inode_operations = { 4216 .getattr = shmem_getattr, 4217 .setattr = shmem_setattr, 4218 .get_link = shmem_get_link, 4219 #ifdef CONFIG_TMPFS_XATTR 4220 .listxattr = shmem_listxattr, 4221 #endif 4222 }; 4223 4224 static struct dentry *shmem_get_parent(struct dentry *child) 4225 { 4226 return ERR_PTR(-ESTALE); 4227 } 4228 4229 static int shmem_match(struct inode *ino, void *vfh) 4230 { 4231 __u32 *fh = vfh; 4232 __u64 inum = fh[2]; 4233 inum = (inum << 32) | fh[1]; 4234 return ino->i_ino == inum && fh[0] == ino->i_generation; 4235 } 4236 4237 /* Find any alias of inode, but prefer a hashed alias */ 4238 static struct dentry *shmem_find_alias(struct inode *inode) 4239 { 4240 struct dentry *alias = d_find_alias(inode); 4241 4242 return alias ?: d_find_any_alias(inode); 4243 } 4244 4245 static struct dentry *shmem_fh_to_dentry(struct super_block *sb, 4246 struct fid *fid, int fh_len, int fh_type) 4247 { 4248 struct inode *inode; 4249 struct dentry *dentry = NULL; 4250 u64 inum; 4251 4252 if (fh_len < 3) 4253 return NULL; 4254 4255 inum = fid->raw[2]; 4256 inum = (inum << 32) | fid->raw[1]; 4257 4258 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]), 4259 shmem_match, fid->raw); 4260 if (inode) { 4261 dentry = shmem_find_alias(inode); 4262 iput(inode); 4263 } 4264 4265 return dentry; 4266 } 4267 4268 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len, 4269 struct inode *parent) 4270 { 4271 if (*len < 3) { 4272 *len = 3; 4273 return FILEID_INVALID; 4274 } 4275 4276 if (inode_unhashed(inode)) { 4277 /* Unfortunately insert_inode_hash is not idempotent, 4278 * so as we hash inodes here rather than at creation 4279 * time, we need a lock to ensure we only try 4280 * to do it once 4281 */ 4282 static DEFINE_SPINLOCK(lock); 4283 spin_lock(&lock); 4284 if (inode_unhashed(inode)) 4285 __insert_inode_hash(inode, 4286 inode->i_ino + inode->i_generation); 4287 spin_unlock(&lock); 4288 } 4289 4290 fh[0] = inode->i_generation; 4291 fh[1] = inode->i_ino; 4292 fh[2] = ((__u64)inode->i_ino) >> 32; 4293 4294 *len = 3; 4295 return 1; 4296 } 4297 4298 static const struct export_operations shmem_export_ops = { 4299 .get_parent = shmem_get_parent, 4300 .encode_fh = shmem_encode_fh, 4301 .fh_to_dentry = shmem_fh_to_dentry, 4302 }; 4303 4304 enum shmem_param { 4305 Opt_gid, 4306 Opt_huge, 4307 Opt_mode, 4308 Opt_mpol, 4309 Opt_nr_blocks, 4310 Opt_nr_inodes, 4311 Opt_size, 4312 Opt_uid, 4313 Opt_inode32, 4314 Opt_inode64, 4315 Opt_noswap, 4316 Opt_quota, 4317 Opt_usrquota, 4318 Opt_grpquota, 4319 Opt_usrquota_block_hardlimit, 4320 Opt_usrquota_inode_hardlimit, 4321 Opt_grpquota_block_hardlimit, 4322 Opt_grpquota_inode_hardlimit, 4323 Opt_casefold_version, 4324 Opt_casefold, 4325 Opt_strict_encoding, 4326 }; 4327 4328 static const struct constant_table shmem_param_enums_huge[] = { 4329 {"never", SHMEM_HUGE_NEVER }, 4330 {"always", SHMEM_HUGE_ALWAYS }, 4331 {"within_size", SHMEM_HUGE_WITHIN_SIZE }, 4332 {"advise", SHMEM_HUGE_ADVISE }, 4333 {} 4334 }; 4335 4336 const struct fs_parameter_spec shmem_fs_parameters[] = { 4337 fsparam_gid ("gid", Opt_gid), 4338 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge), 4339 fsparam_u32oct("mode", Opt_mode), 4340 fsparam_string("mpol", Opt_mpol), 4341 fsparam_string("nr_blocks", Opt_nr_blocks), 4342 fsparam_string("nr_inodes", Opt_nr_inodes), 4343 fsparam_string("size", Opt_size), 4344 fsparam_uid ("uid", Opt_uid), 4345 fsparam_flag ("inode32", Opt_inode32), 4346 fsparam_flag ("inode64", Opt_inode64), 4347 fsparam_flag ("noswap", Opt_noswap), 4348 #ifdef CONFIG_TMPFS_QUOTA 4349 fsparam_flag ("quota", Opt_quota), 4350 fsparam_flag ("usrquota", Opt_usrquota), 4351 fsparam_flag ("grpquota", Opt_grpquota), 4352 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit), 4353 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit), 4354 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit), 4355 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit), 4356 #endif 4357 fsparam_string("casefold", Opt_casefold_version), 4358 fsparam_flag ("casefold", Opt_casefold), 4359 fsparam_flag ("strict_encoding", Opt_strict_encoding), 4360 {} 4361 }; 4362 4363 #if IS_ENABLED(CONFIG_UNICODE) 4364 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4365 bool latest_version) 4366 { 4367 struct shmem_options *ctx = fc->fs_private; 4368 unsigned int version = UTF8_LATEST; 4369 struct unicode_map *encoding; 4370 char *version_str = param->string + 5; 4371 4372 if (!latest_version) { 4373 if (strncmp(param->string, "utf8-", 5)) 4374 return invalfc(fc, "Only UTF-8 encodings are supported " 4375 "in the format: utf8-<version number>"); 4376 4377 version = utf8_parse_version(version_str); 4378 if (version < 0) 4379 return invalfc(fc, "Invalid UTF-8 version: %s", version_str); 4380 } 4381 4382 encoding = utf8_load(version); 4383 4384 if (IS_ERR(encoding)) { 4385 return invalfc(fc, "Failed loading UTF-8 version: utf8-%u.%u.%u\n", 4386 unicode_major(version), unicode_minor(version), 4387 unicode_rev(version)); 4388 } 4389 4390 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n", 4391 unicode_major(version), unicode_minor(version), unicode_rev(version)); 4392 4393 ctx->encoding = encoding; 4394 4395 return 0; 4396 } 4397 #else 4398 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4399 bool latest_version) 4400 { 4401 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4402 } 4403 #endif 4404 4405 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param) 4406 { 4407 struct shmem_options *ctx = fc->fs_private; 4408 struct fs_parse_result result; 4409 unsigned long long size; 4410 char *rest; 4411 int opt; 4412 kuid_t kuid; 4413 kgid_t kgid; 4414 4415 opt = fs_parse(fc, shmem_fs_parameters, param, &result); 4416 if (opt < 0) 4417 return opt; 4418 4419 switch (opt) { 4420 case Opt_size: 4421 size = memparse(param->string, &rest); 4422 if (*rest == '%') { 4423 size <<= PAGE_SHIFT; 4424 size *= totalram_pages(); 4425 do_div(size, 100); 4426 rest++; 4427 } 4428 if (*rest) 4429 goto bad_value; 4430 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE); 4431 ctx->seen |= SHMEM_SEEN_BLOCKS; 4432 break; 4433 case Opt_nr_blocks: 4434 ctx->blocks = memparse(param->string, &rest); 4435 if (*rest || ctx->blocks > LONG_MAX) 4436 goto bad_value; 4437 ctx->seen |= SHMEM_SEEN_BLOCKS; 4438 break; 4439 case Opt_nr_inodes: 4440 ctx->inodes = memparse(param->string, &rest); 4441 if (*rest || ctx->inodes > ULONG_MAX / BOGO_INODE_SIZE) 4442 goto bad_value; 4443 ctx->seen |= SHMEM_SEEN_INODES; 4444 break; 4445 case Opt_mode: 4446 ctx->mode = result.uint_32 & 07777; 4447 break; 4448 case Opt_uid: 4449 kuid = result.uid; 4450 4451 /* 4452 * The requested uid must be representable in the 4453 * filesystem's idmapping. 4454 */ 4455 if (!kuid_has_mapping(fc->user_ns, kuid)) 4456 goto bad_value; 4457 4458 ctx->uid = kuid; 4459 break; 4460 case Opt_gid: 4461 kgid = result.gid; 4462 4463 /* 4464 * The requested gid must be representable in the 4465 * filesystem's idmapping. 4466 */ 4467 if (!kgid_has_mapping(fc->user_ns, kgid)) 4468 goto bad_value; 4469 4470 ctx->gid = kgid; 4471 break; 4472 case Opt_huge: 4473 ctx->huge = result.uint_32; 4474 if (ctx->huge != SHMEM_HUGE_NEVER && 4475 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && 4476 has_transparent_hugepage())) 4477 goto unsupported_parameter; 4478 ctx->seen |= SHMEM_SEEN_HUGE; 4479 break; 4480 case Opt_mpol: 4481 if (IS_ENABLED(CONFIG_NUMA)) { 4482 mpol_put(ctx->mpol); 4483 ctx->mpol = NULL; 4484 if (mpol_parse_str(param->string, &ctx->mpol)) 4485 goto bad_value; 4486 break; 4487 } 4488 goto unsupported_parameter; 4489 case Opt_inode32: 4490 ctx->full_inums = false; 4491 ctx->seen |= SHMEM_SEEN_INUMS; 4492 break; 4493 case Opt_inode64: 4494 if (sizeof(ino_t) < 8) { 4495 return invalfc(fc, 4496 "Cannot use inode64 with <64bit inums in kernel\n"); 4497 } 4498 ctx->full_inums = true; 4499 ctx->seen |= SHMEM_SEEN_INUMS; 4500 break; 4501 case Opt_noswap: 4502 if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) { 4503 return invalfc(fc, 4504 "Turning off swap in unprivileged tmpfs mounts unsupported"); 4505 } 4506 ctx->noswap = true; 4507 ctx->seen |= SHMEM_SEEN_NOSWAP; 4508 break; 4509 case Opt_quota: 4510 if (fc->user_ns != &init_user_ns) 4511 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4512 ctx->seen |= SHMEM_SEEN_QUOTA; 4513 ctx->quota_types |= (QTYPE_MASK_USR | QTYPE_MASK_GRP); 4514 break; 4515 case Opt_usrquota: 4516 if (fc->user_ns != &init_user_ns) 4517 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4518 ctx->seen |= SHMEM_SEEN_QUOTA; 4519 ctx->quota_types |= QTYPE_MASK_USR; 4520 break; 4521 case Opt_grpquota: 4522 if (fc->user_ns != &init_user_ns) 4523 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4524 ctx->seen |= SHMEM_SEEN_QUOTA; 4525 ctx->quota_types |= QTYPE_MASK_GRP; 4526 break; 4527 case Opt_usrquota_block_hardlimit: 4528 size = memparse(param->string, &rest); 4529 if (*rest || !size) 4530 goto bad_value; 4531 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4532 return invalfc(fc, 4533 "User quota block hardlimit too large."); 4534 ctx->qlimits.usrquota_bhardlimit = size; 4535 break; 4536 case Opt_grpquota_block_hardlimit: 4537 size = memparse(param->string, &rest); 4538 if (*rest || !size) 4539 goto bad_value; 4540 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4541 return invalfc(fc, 4542 "Group quota block hardlimit too large."); 4543 ctx->qlimits.grpquota_bhardlimit = size; 4544 break; 4545 case Opt_usrquota_inode_hardlimit: 4546 size = memparse(param->string, &rest); 4547 if (*rest || !size) 4548 goto bad_value; 4549 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4550 return invalfc(fc, 4551 "User quota inode hardlimit too large."); 4552 ctx->qlimits.usrquota_ihardlimit = size; 4553 break; 4554 case Opt_grpquota_inode_hardlimit: 4555 size = memparse(param->string, &rest); 4556 if (*rest || !size) 4557 goto bad_value; 4558 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4559 return invalfc(fc, 4560 "Group quota inode hardlimit too large."); 4561 ctx->qlimits.grpquota_ihardlimit = size; 4562 break; 4563 case Opt_casefold_version: 4564 return shmem_parse_opt_casefold(fc, param, false); 4565 case Opt_casefold: 4566 return shmem_parse_opt_casefold(fc, param, true); 4567 case Opt_strict_encoding: 4568 #if IS_ENABLED(CONFIG_UNICODE) 4569 ctx->strict_encoding = true; 4570 break; 4571 #else 4572 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4573 #endif 4574 } 4575 return 0; 4576 4577 unsupported_parameter: 4578 return invalfc(fc, "Unsupported parameter '%s'", param->key); 4579 bad_value: 4580 return invalfc(fc, "Bad value for '%s'", param->key); 4581 } 4582 4583 static int shmem_parse_options(struct fs_context *fc, void *data) 4584 { 4585 char *options = data; 4586 4587 if (options) { 4588 int err = security_sb_eat_lsm_opts(options, &fc->security); 4589 if (err) 4590 return err; 4591 } 4592 4593 while (options != NULL) { 4594 char *this_char = options; 4595 for (;;) { 4596 /* 4597 * NUL-terminate this option: unfortunately, 4598 * mount options form a comma-separated list, 4599 * but mpol's nodelist may also contain commas. 4600 */ 4601 options = strchr(options, ','); 4602 if (options == NULL) 4603 break; 4604 options++; 4605 if (!isdigit(*options)) { 4606 options[-1] = '\0'; 4607 break; 4608 } 4609 } 4610 if (*this_char) { 4611 char *value = strchr(this_char, '='); 4612 size_t len = 0; 4613 int err; 4614 4615 if (value) { 4616 *value++ = '\0'; 4617 len = strlen(value); 4618 } 4619 err = vfs_parse_fs_string(fc, this_char, value, len); 4620 if (err < 0) 4621 return err; 4622 } 4623 } 4624 return 0; 4625 } 4626 4627 /* 4628 * Reconfigure a shmem filesystem. 4629 */ 4630 static int shmem_reconfigure(struct fs_context *fc) 4631 { 4632 struct shmem_options *ctx = fc->fs_private; 4633 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb); 4634 unsigned long used_isp; 4635 struct mempolicy *mpol = NULL; 4636 const char *err; 4637 4638 raw_spin_lock(&sbinfo->stat_lock); 4639 used_isp = sbinfo->max_inodes * BOGO_INODE_SIZE - sbinfo->free_ispace; 4640 4641 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) { 4642 if (!sbinfo->max_blocks) { 4643 err = "Cannot retroactively limit size"; 4644 goto out; 4645 } 4646 if (percpu_counter_compare(&sbinfo->used_blocks, 4647 ctx->blocks) > 0) { 4648 err = "Too small a size for current use"; 4649 goto out; 4650 } 4651 } 4652 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) { 4653 if (!sbinfo->max_inodes) { 4654 err = "Cannot retroactively limit inodes"; 4655 goto out; 4656 } 4657 if (ctx->inodes * BOGO_INODE_SIZE < used_isp) { 4658 err = "Too few inodes for current use"; 4659 goto out; 4660 } 4661 } 4662 4663 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums && 4664 sbinfo->next_ino > UINT_MAX) { 4665 err = "Current inum too high to switch to 32-bit inums"; 4666 goto out; 4667 } 4668 if ((ctx->seen & SHMEM_SEEN_NOSWAP) && ctx->noswap && !sbinfo->noswap) { 4669 err = "Cannot disable swap on remount"; 4670 goto out; 4671 } 4672 if (!(ctx->seen & SHMEM_SEEN_NOSWAP) && !ctx->noswap && sbinfo->noswap) { 4673 err = "Cannot enable swap on remount if it was disabled on first mount"; 4674 goto out; 4675 } 4676 4677 if (ctx->seen & SHMEM_SEEN_QUOTA && 4678 !sb_any_quota_loaded(fc->root->d_sb)) { 4679 err = "Cannot enable quota on remount"; 4680 goto out; 4681 } 4682 4683 #ifdef CONFIG_TMPFS_QUOTA 4684 #define CHANGED_LIMIT(name) \ 4685 (ctx->qlimits.name## hardlimit && \ 4686 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit)) 4687 4688 if (CHANGED_LIMIT(usrquota_b) || CHANGED_LIMIT(usrquota_i) || 4689 CHANGED_LIMIT(grpquota_b) || CHANGED_LIMIT(grpquota_i)) { 4690 err = "Cannot change global quota limit on remount"; 4691 goto out; 4692 } 4693 #endif /* CONFIG_TMPFS_QUOTA */ 4694 4695 if (ctx->seen & SHMEM_SEEN_HUGE) 4696 sbinfo->huge = ctx->huge; 4697 if (ctx->seen & SHMEM_SEEN_INUMS) 4698 sbinfo->full_inums = ctx->full_inums; 4699 if (ctx->seen & SHMEM_SEEN_BLOCKS) 4700 sbinfo->max_blocks = ctx->blocks; 4701 if (ctx->seen & SHMEM_SEEN_INODES) { 4702 sbinfo->max_inodes = ctx->inodes; 4703 sbinfo->free_ispace = ctx->inodes * BOGO_INODE_SIZE - used_isp; 4704 } 4705 4706 /* 4707 * Preserve previous mempolicy unless mpol remount option was specified. 4708 */ 4709 if (ctx->mpol) { 4710 mpol = sbinfo->mpol; 4711 sbinfo->mpol = ctx->mpol; /* transfers initial ref */ 4712 ctx->mpol = NULL; 4713 } 4714 4715 if (ctx->noswap) 4716 sbinfo->noswap = true; 4717 4718 raw_spin_unlock(&sbinfo->stat_lock); 4719 mpol_put(mpol); 4720 return 0; 4721 out: 4722 raw_spin_unlock(&sbinfo->stat_lock); 4723 return invalfc(fc, "%s", err); 4724 } 4725 4726 static int shmem_show_options(struct seq_file *seq, struct dentry *root) 4727 { 4728 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb); 4729 struct mempolicy *mpol; 4730 4731 if (sbinfo->max_blocks != shmem_default_max_blocks()) 4732 seq_printf(seq, ",size=%luk", K(sbinfo->max_blocks)); 4733 if (sbinfo->max_inodes != shmem_default_max_inodes()) 4734 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes); 4735 if (sbinfo->mode != (0777 | S_ISVTX)) 4736 seq_printf(seq, ",mode=%03ho", sbinfo->mode); 4737 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID)) 4738 seq_printf(seq, ",uid=%u", 4739 from_kuid_munged(&init_user_ns, sbinfo->uid)); 4740 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID)) 4741 seq_printf(seq, ",gid=%u", 4742 from_kgid_munged(&init_user_ns, sbinfo->gid)); 4743 4744 /* 4745 * Showing inode{64,32} might be useful even if it's the system default, 4746 * since then people don't have to resort to checking both here and 4747 * /proc/config.gz to confirm 64-bit inums were successfully applied 4748 * (which may not even exist if IKCONFIG_PROC isn't enabled). 4749 * 4750 * We hide it when inode64 isn't the default and we are using 32-bit 4751 * inodes, since that probably just means the feature isn't even under 4752 * consideration. 4753 * 4754 * As such: 4755 * 4756 * +-----------------+-----------------+ 4757 * | TMPFS_INODE64=y | TMPFS_INODE64=n | 4758 * +------------------+-----------------+-----------------+ 4759 * | full_inums=true | show | show | 4760 * | full_inums=false | show | hide | 4761 * +------------------+-----------------+-----------------+ 4762 * 4763 */ 4764 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums) 4765 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32)); 4766 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4767 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */ 4768 if (sbinfo->huge) 4769 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge)); 4770 #endif 4771 mpol = shmem_get_sbmpol(sbinfo); 4772 shmem_show_mpol(seq, mpol); 4773 mpol_put(mpol); 4774 if (sbinfo->noswap) 4775 seq_printf(seq, ",noswap"); 4776 #ifdef CONFIG_TMPFS_QUOTA 4777 if (sb_has_quota_active(root->d_sb, USRQUOTA)) 4778 seq_printf(seq, ",usrquota"); 4779 if (sb_has_quota_active(root->d_sb, GRPQUOTA)) 4780 seq_printf(seq, ",grpquota"); 4781 if (sbinfo->qlimits.usrquota_bhardlimit) 4782 seq_printf(seq, ",usrquota_block_hardlimit=%lld", 4783 sbinfo->qlimits.usrquota_bhardlimit); 4784 if (sbinfo->qlimits.grpquota_bhardlimit) 4785 seq_printf(seq, ",grpquota_block_hardlimit=%lld", 4786 sbinfo->qlimits.grpquota_bhardlimit); 4787 if (sbinfo->qlimits.usrquota_ihardlimit) 4788 seq_printf(seq, ",usrquota_inode_hardlimit=%lld", 4789 sbinfo->qlimits.usrquota_ihardlimit); 4790 if (sbinfo->qlimits.grpquota_ihardlimit) 4791 seq_printf(seq, ",grpquota_inode_hardlimit=%lld", 4792 sbinfo->qlimits.grpquota_ihardlimit); 4793 #endif 4794 return 0; 4795 } 4796 4797 #endif /* CONFIG_TMPFS */ 4798 4799 static void shmem_put_super(struct super_block *sb) 4800 { 4801 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 4802 4803 #if IS_ENABLED(CONFIG_UNICODE) 4804 if (sb->s_encoding) 4805 utf8_unload(sb->s_encoding); 4806 #endif 4807 4808 #ifdef CONFIG_TMPFS_QUOTA 4809 shmem_disable_quotas(sb); 4810 #endif 4811 free_percpu(sbinfo->ino_batch); 4812 percpu_counter_destroy(&sbinfo->used_blocks); 4813 mpol_put(sbinfo->mpol); 4814 kfree(sbinfo); 4815 sb->s_fs_info = NULL; 4816 } 4817 4818 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS) 4819 static const struct dentry_operations shmem_ci_dentry_ops = { 4820 .d_hash = generic_ci_d_hash, 4821 .d_compare = generic_ci_d_compare, 4822 .d_delete = always_delete_dentry, 4823 }; 4824 #endif 4825 4826 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc) 4827 { 4828 struct shmem_options *ctx = fc->fs_private; 4829 struct inode *inode; 4830 struct shmem_sb_info *sbinfo; 4831 int error = -ENOMEM; 4832 4833 /* Round up to L1_CACHE_BYTES to resist false sharing */ 4834 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info), 4835 L1_CACHE_BYTES), GFP_KERNEL); 4836 if (!sbinfo) 4837 return error; 4838 4839 sb->s_fs_info = sbinfo; 4840 4841 #ifdef CONFIG_TMPFS 4842 /* 4843 * Per default we only allow half of the physical ram per 4844 * tmpfs instance, limiting inodes to one per page of lowmem; 4845 * but the internal instance is left unlimited. 4846 */ 4847 if (!(sb->s_flags & SB_KERNMOUNT)) { 4848 if (!(ctx->seen & SHMEM_SEEN_BLOCKS)) 4849 ctx->blocks = shmem_default_max_blocks(); 4850 if (!(ctx->seen & SHMEM_SEEN_INODES)) 4851 ctx->inodes = shmem_default_max_inodes(); 4852 if (!(ctx->seen & SHMEM_SEEN_INUMS)) 4853 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64); 4854 sbinfo->noswap = ctx->noswap; 4855 } else { 4856 sb->s_flags |= SB_NOUSER; 4857 } 4858 sb->s_export_op = &shmem_export_ops; 4859 sb->s_flags |= SB_NOSEC | SB_I_VERSION; 4860 4861 #if IS_ENABLED(CONFIG_UNICODE) 4862 if (!ctx->encoding && ctx->strict_encoding) { 4863 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n"); 4864 error = -EINVAL; 4865 goto failed; 4866 } 4867 4868 if (ctx->encoding) { 4869 sb->s_encoding = ctx->encoding; 4870 sb->s_d_op = &shmem_ci_dentry_ops; 4871 if (ctx->strict_encoding) 4872 sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL; 4873 } 4874 #endif 4875 4876 #else 4877 sb->s_flags |= SB_NOUSER; 4878 #endif /* CONFIG_TMPFS */ 4879 sbinfo->max_blocks = ctx->blocks; 4880 sbinfo->max_inodes = ctx->inodes; 4881 sbinfo->free_ispace = sbinfo->max_inodes * BOGO_INODE_SIZE; 4882 if (sb->s_flags & SB_KERNMOUNT) { 4883 sbinfo->ino_batch = alloc_percpu(ino_t); 4884 if (!sbinfo->ino_batch) 4885 goto failed; 4886 } 4887 sbinfo->uid = ctx->uid; 4888 sbinfo->gid = ctx->gid; 4889 sbinfo->full_inums = ctx->full_inums; 4890 sbinfo->mode = ctx->mode; 4891 sbinfo->huge = ctx->huge; 4892 sbinfo->mpol = ctx->mpol; 4893 ctx->mpol = NULL; 4894 4895 raw_spin_lock_init(&sbinfo->stat_lock); 4896 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL)) 4897 goto failed; 4898 spin_lock_init(&sbinfo->shrinklist_lock); 4899 INIT_LIST_HEAD(&sbinfo->shrinklist); 4900 4901 sb->s_maxbytes = MAX_LFS_FILESIZE; 4902 sb->s_blocksize = PAGE_SIZE; 4903 sb->s_blocksize_bits = PAGE_SHIFT; 4904 sb->s_magic = TMPFS_MAGIC; 4905 sb->s_op = &shmem_ops; 4906 sb->s_time_gran = 1; 4907 #ifdef CONFIG_TMPFS_XATTR 4908 sb->s_xattr = shmem_xattr_handlers; 4909 #endif 4910 #ifdef CONFIG_TMPFS_POSIX_ACL 4911 sb->s_flags |= SB_POSIXACL; 4912 #endif 4913 uuid_t uuid; 4914 uuid_gen(&uuid); 4915 super_set_uuid(sb, uuid.b, sizeof(uuid)); 4916 4917 #ifdef CONFIG_TMPFS_QUOTA 4918 if (ctx->seen & SHMEM_SEEN_QUOTA) { 4919 sb->dq_op = &shmem_quota_operations; 4920 sb->s_qcop = &dquot_quotactl_sysfile_ops; 4921 sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP; 4922 4923 /* Copy the default limits from ctx into sbinfo */ 4924 memcpy(&sbinfo->qlimits, &ctx->qlimits, 4925 sizeof(struct shmem_quota_limits)); 4926 4927 if (shmem_enable_quotas(sb, ctx->quota_types)) 4928 goto failed; 4929 } 4930 #endif /* CONFIG_TMPFS_QUOTA */ 4931 4932 inode = shmem_get_inode(&nop_mnt_idmap, sb, NULL, 4933 S_IFDIR | sbinfo->mode, 0, VM_NORESERVE); 4934 if (IS_ERR(inode)) { 4935 error = PTR_ERR(inode); 4936 goto failed; 4937 } 4938 inode->i_uid = sbinfo->uid; 4939 inode->i_gid = sbinfo->gid; 4940 sb->s_root = d_make_root(inode); 4941 if (!sb->s_root) 4942 goto failed; 4943 return 0; 4944 4945 failed: 4946 shmem_put_super(sb); 4947 return error; 4948 } 4949 4950 static int shmem_get_tree(struct fs_context *fc) 4951 { 4952 return get_tree_nodev(fc, shmem_fill_super); 4953 } 4954 4955 static void shmem_free_fc(struct fs_context *fc) 4956 { 4957 struct shmem_options *ctx = fc->fs_private; 4958 4959 if (ctx) { 4960 mpol_put(ctx->mpol); 4961 kfree(ctx); 4962 } 4963 } 4964 4965 static const struct fs_context_operations shmem_fs_context_ops = { 4966 .free = shmem_free_fc, 4967 .get_tree = shmem_get_tree, 4968 #ifdef CONFIG_TMPFS 4969 .parse_monolithic = shmem_parse_options, 4970 .parse_param = shmem_parse_one, 4971 .reconfigure = shmem_reconfigure, 4972 #endif 4973 }; 4974 4975 static struct kmem_cache *shmem_inode_cachep __ro_after_init; 4976 4977 static struct inode *shmem_alloc_inode(struct super_block *sb) 4978 { 4979 struct shmem_inode_info *info; 4980 info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL); 4981 if (!info) 4982 return NULL; 4983 return &info->vfs_inode; 4984 } 4985 4986 static void shmem_free_in_core_inode(struct inode *inode) 4987 { 4988 if (S_ISLNK(inode->i_mode)) 4989 kfree(inode->i_link); 4990 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode)); 4991 } 4992 4993 static void shmem_destroy_inode(struct inode *inode) 4994 { 4995 if (S_ISREG(inode->i_mode)) 4996 mpol_free_shared_policy(&SHMEM_I(inode)->policy); 4997 if (S_ISDIR(inode->i_mode)) 4998 simple_offset_destroy(shmem_get_offset_ctx(inode)); 4999 } 5000 5001 static void shmem_init_inode(void *foo) 5002 { 5003 struct shmem_inode_info *info = foo; 5004 inode_init_once(&info->vfs_inode); 5005 } 5006 5007 static void __init shmem_init_inodecache(void) 5008 { 5009 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache", 5010 sizeof(struct shmem_inode_info), 5011 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode); 5012 } 5013 5014 static void __init shmem_destroy_inodecache(void) 5015 { 5016 kmem_cache_destroy(shmem_inode_cachep); 5017 } 5018 5019 /* Keep the page in page cache instead of truncating it */ 5020 static int shmem_error_remove_folio(struct address_space *mapping, 5021 struct folio *folio) 5022 { 5023 return 0; 5024 } 5025 5026 static const struct address_space_operations shmem_aops = { 5027 .writepage = shmem_writepage, 5028 .dirty_folio = noop_dirty_folio, 5029 #ifdef CONFIG_TMPFS 5030 .write_begin = shmem_write_begin, 5031 .write_end = shmem_write_end, 5032 #endif 5033 #ifdef CONFIG_MIGRATION 5034 .migrate_folio = migrate_folio, 5035 #endif 5036 .error_remove_folio = shmem_error_remove_folio, 5037 }; 5038 5039 static const struct file_operations shmem_file_operations = { 5040 .mmap = shmem_mmap, 5041 .open = shmem_file_open, 5042 .get_unmapped_area = shmem_get_unmapped_area, 5043 #ifdef CONFIG_TMPFS 5044 .llseek = shmem_file_llseek, 5045 .read_iter = shmem_file_read_iter, 5046 .write_iter = shmem_file_write_iter, 5047 .fsync = noop_fsync, 5048 .splice_read = shmem_file_splice_read, 5049 .splice_write = iter_file_splice_write, 5050 .fallocate = shmem_fallocate, 5051 #endif 5052 }; 5053 5054 static const struct inode_operations shmem_inode_operations = { 5055 .getattr = shmem_getattr, 5056 .setattr = shmem_setattr, 5057 #ifdef CONFIG_TMPFS_XATTR 5058 .listxattr = shmem_listxattr, 5059 .set_acl = simple_set_acl, 5060 .fileattr_get = shmem_fileattr_get, 5061 .fileattr_set = shmem_fileattr_set, 5062 #endif 5063 }; 5064 5065 static const struct inode_operations shmem_dir_inode_operations = { 5066 #ifdef CONFIG_TMPFS 5067 .getattr = shmem_getattr, 5068 .create = shmem_create, 5069 .lookup = simple_lookup, 5070 .link = shmem_link, 5071 .unlink = shmem_unlink, 5072 .symlink = shmem_symlink, 5073 .mkdir = shmem_mkdir, 5074 .rmdir = shmem_rmdir, 5075 .mknod = shmem_mknod, 5076 .rename = shmem_rename2, 5077 .tmpfile = shmem_tmpfile, 5078 .get_offset_ctx = shmem_get_offset_ctx, 5079 #endif 5080 #ifdef CONFIG_TMPFS_XATTR 5081 .listxattr = shmem_listxattr, 5082 .fileattr_get = shmem_fileattr_get, 5083 .fileattr_set = shmem_fileattr_set, 5084 #endif 5085 #ifdef CONFIG_TMPFS_POSIX_ACL 5086 .setattr = shmem_setattr, 5087 .set_acl = simple_set_acl, 5088 #endif 5089 }; 5090 5091 static const struct inode_operations shmem_special_inode_operations = { 5092 .getattr = shmem_getattr, 5093 #ifdef CONFIG_TMPFS_XATTR 5094 .listxattr = shmem_listxattr, 5095 #endif 5096 #ifdef CONFIG_TMPFS_POSIX_ACL 5097 .setattr = shmem_setattr, 5098 .set_acl = simple_set_acl, 5099 #endif 5100 }; 5101 5102 static const struct super_operations shmem_ops = { 5103 .alloc_inode = shmem_alloc_inode, 5104 .free_inode = shmem_free_in_core_inode, 5105 .destroy_inode = shmem_destroy_inode, 5106 #ifdef CONFIG_TMPFS 5107 .statfs = shmem_statfs, 5108 .show_options = shmem_show_options, 5109 #endif 5110 #ifdef CONFIG_TMPFS_QUOTA 5111 .get_dquots = shmem_get_dquots, 5112 #endif 5113 .evict_inode = shmem_evict_inode, 5114 .drop_inode = generic_delete_inode, 5115 .put_super = shmem_put_super, 5116 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5117 .nr_cached_objects = shmem_unused_huge_count, 5118 .free_cached_objects = shmem_unused_huge_scan, 5119 #endif 5120 }; 5121 5122 static const struct vm_operations_struct shmem_vm_ops = { 5123 .fault = shmem_fault, 5124 .map_pages = filemap_map_pages, 5125 #ifdef CONFIG_NUMA 5126 .set_policy = shmem_set_policy, 5127 .get_policy = shmem_get_policy, 5128 #endif 5129 }; 5130 5131 static const struct vm_operations_struct shmem_anon_vm_ops = { 5132 .fault = shmem_fault, 5133 .map_pages = filemap_map_pages, 5134 #ifdef CONFIG_NUMA 5135 .set_policy = shmem_set_policy, 5136 .get_policy = shmem_get_policy, 5137 #endif 5138 }; 5139 5140 int shmem_init_fs_context(struct fs_context *fc) 5141 { 5142 struct shmem_options *ctx; 5143 5144 ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL); 5145 if (!ctx) 5146 return -ENOMEM; 5147 5148 ctx->mode = 0777 | S_ISVTX; 5149 ctx->uid = current_fsuid(); 5150 ctx->gid = current_fsgid(); 5151 5152 #if IS_ENABLED(CONFIG_UNICODE) 5153 ctx->encoding = NULL; 5154 #endif 5155 5156 fc->fs_private = ctx; 5157 fc->ops = &shmem_fs_context_ops; 5158 return 0; 5159 } 5160 5161 static struct file_system_type shmem_fs_type = { 5162 .owner = THIS_MODULE, 5163 .name = "tmpfs", 5164 .init_fs_context = shmem_init_fs_context, 5165 #ifdef CONFIG_TMPFS 5166 .parameters = shmem_fs_parameters, 5167 #endif 5168 .kill_sb = kill_litter_super, 5169 .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME, 5170 }; 5171 5172 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5173 5174 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \ 5175 { \ 5176 .attr = { .name = __stringify(_name), .mode = _mode }, \ 5177 .show = _show, \ 5178 .store = _store, \ 5179 } 5180 5181 #define TMPFS_ATTR_W(_name, _store) \ 5182 static struct kobj_attribute tmpfs_attr_##_name = \ 5183 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store) 5184 5185 #define TMPFS_ATTR_RW(_name, _show, _store) \ 5186 static struct kobj_attribute tmpfs_attr_##_name = \ 5187 __INIT_KOBJ_ATTR(_name, 0644, _show, _store) 5188 5189 #define TMPFS_ATTR_RO(_name, _show) \ 5190 static struct kobj_attribute tmpfs_attr_##_name = \ 5191 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL) 5192 5193 #if IS_ENABLED(CONFIG_UNICODE) 5194 static ssize_t casefold_show(struct kobject *kobj, struct kobj_attribute *a, 5195 char *buf) 5196 { 5197 return sysfs_emit(buf, "supported\n"); 5198 } 5199 TMPFS_ATTR_RO(casefold, casefold_show); 5200 #endif 5201 5202 static struct attribute *tmpfs_attributes[] = { 5203 #if IS_ENABLED(CONFIG_UNICODE) 5204 &tmpfs_attr_casefold.attr, 5205 #endif 5206 NULL 5207 }; 5208 5209 static const struct attribute_group tmpfs_attribute_group = { 5210 .attrs = tmpfs_attributes, 5211 .name = "features" 5212 }; 5213 5214 static struct kobject *tmpfs_kobj; 5215 5216 static int __init tmpfs_sysfs_init(void) 5217 { 5218 int ret; 5219 5220 tmpfs_kobj = kobject_create_and_add("tmpfs", fs_kobj); 5221 if (!tmpfs_kobj) 5222 return -ENOMEM; 5223 5224 ret = sysfs_create_group(tmpfs_kobj, &tmpfs_attribute_group); 5225 if (ret) 5226 kobject_put(tmpfs_kobj); 5227 5228 return ret; 5229 } 5230 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */ 5231 5232 void __init shmem_init(void) 5233 { 5234 int error; 5235 5236 shmem_init_inodecache(); 5237 5238 #ifdef CONFIG_TMPFS_QUOTA 5239 register_quota_format(&shmem_quota_format); 5240 #endif 5241 5242 error = register_filesystem(&shmem_fs_type); 5243 if (error) { 5244 pr_err("Could not register tmpfs\n"); 5245 goto out2; 5246 } 5247 5248 shm_mnt = kern_mount(&shmem_fs_type); 5249 if (IS_ERR(shm_mnt)) { 5250 error = PTR_ERR(shm_mnt); 5251 pr_err("Could not kern_mount tmpfs\n"); 5252 goto out1; 5253 } 5254 5255 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5256 error = tmpfs_sysfs_init(); 5257 if (error) { 5258 pr_err("Could not init tmpfs sysfs\n"); 5259 goto out1; 5260 } 5261 #endif 5262 5263 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5264 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY) 5265 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5266 else 5267 shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */ 5268 5269 /* 5270 * Default to setting PMD-sized THP to inherit the global setting and 5271 * disable all other multi-size THPs. 5272 */ 5273 if (!shmem_orders_configured) 5274 huge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER); 5275 #endif 5276 return; 5277 5278 out1: 5279 unregister_filesystem(&shmem_fs_type); 5280 out2: 5281 #ifdef CONFIG_TMPFS_QUOTA 5282 unregister_quota_format(&shmem_quota_format); 5283 #endif 5284 shmem_destroy_inodecache(); 5285 shm_mnt = ERR_PTR(error); 5286 } 5287 5288 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS) 5289 static ssize_t shmem_enabled_show(struct kobject *kobj, 5290 struct kobj_attribute *attr, char *buf) 5291 { 5292 static const int values[] = { 5293 SHMEM_HUGE_ALWAYS, 5294 SHMEM_HUGE_WITHIN_SIZE, 5295 SHMEM_HUGE_ADVISE, 5296 SHMEM_HUGE_NEVER, 5297 SHMEM_HUGE_DENY, 5298 SHMEM_HUGE_FORCE, 5299 }; 5300 int len = 0; 5301 int i; 5302 5303 for (i = 0; i < ARRAY_SIZE(values); i++) { 5304 len += sysfs_emit_at(buf, len, 5305 shmem_huge == values[i] ? "%s[%s]" : "%s%s", 5306 i ? " " : "", shmem_format_huge(values[i])); 5307 } 5308 len += sysfs_emit_at(buf, len, "\n"); 5309 5310 return len; 5311 } 5312 5313 static ssize_t shmem_enabled_store(struct kobject *kobj, 5314 struct kobj_attribute *attr, const char *buf, size_t count) 5315 { 5316 char tmp[16]; 5317 int huge, err; 5318 5319 if (count + 1 > sizeof(tmp)) 5320 return -EINVAL; 5321 memcpy(tmp, buf, count); 5322 tmp[count] = '\0'; 5323 if (count && tmp[count - 1] == '\n') 5324 tmp[count - 1] = '\0'; 5325 5326 huge = shmem_parse_huge(tmp); 5327 if (huge == -EINVAL) 5328 return huge; 5329 5330 shmem_huge = huge; 5331 if (shmem_huge > SHMEM_HUGE_DENY) 5332 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5333 5334 err = start_stop_khugepaged(); 5335 return err ? err : count; 5336 } 5337 5338 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled); 5339 static DEFINE_SPINLOCK(huge_shmem_orders_lock); 5340 5341 static ssize_t thpsize_shmem_enabled_show(struct kobject *kobj, 5342 struct kobj_attribute *attr, char *buf) 5343 { 5344 int order = to_thpsize(kobj)->order; 5345 const char *output; 5346 5347 if (test_bit(order, &huge_shmem_orders_always)) 5348 output = "[always] inherit within_size advise never"; 5349 else if (test_bit(order, &huge_shmem_orders_inherit)) 5350 output = "always [inherit] within_size advise never"; 5351 else if (test_bit(order, &huge_shmem_orders_within_size)) 5352 output = "always inherit [within_size] advise never"; 5353 else if (test_bit(order, &huge_shmem_orders_madvise)) 5354 output = "always inherit within_size [advise] never"; 5355 else 5356 output = "always inherit within_size advise [never]"; 5357 5358 return sysfs_emit(buf, "%s\n", output); 5359 } 5360 5361 static ssize_t thpsize_shmem_enabled_store(struct kobject *kobj, 5362 struct kobj_attribute *attr, 5363 const char *buf, size_t count) 5364 { 5365 int order = to_thpsize(kobj)->order; 5366 ssize_t ret = count; 5367 5368 if (sysfs_streq(buf, "always")) { 5369 spin_lock(&huge_shmem_orders_lock); 5370 clear_bit(order, &huge_shmem_orders_inherit); 5371 clear_bit(order, &huge_shmem_orders_madvise); 5372 clear_bit(order, &huge_shmem_orders_within_size); 5373 set_bit(order, &huge_shmem_orders_always); 5374 spin_unlock(&huge_shmem_orders_lock); 5375 } else if (sysfs_streq(buf, "inherit")) { 5376 /* Do not override huge allocation policy with non-PMD sized mTHP */ 5377 if (shmem_huge == SHMEM_HUGE_FORCE && 5378 order != HPAGE_PMD_ORDER) 5379 return -EINVAL; 5380 5381 spin_lock(&huge_shmem_orders_lock); 5382 clear_bit(order, &huge_shmem_orders_always); 5383 clear_bit(order, &huge_shmem_orders_madvise); 5384 clear_bit(order, &huge_shmem_orders_within_size); 5385 set_bit(order, &huge_shmem_orders_inherit); 5386 spin_unlock(&huge_shmem_orders_lock); 5387 } else if (sysfs_streq(buf, "within_size")) { 5388 spin_lock(&huge_shmem_orders_lock); 5389 clear_bit(order, &huge_shmem_orders_always); 5390 clear_bit(order, &huge_shmem_orders_inherit); 5391 clear_bit(order, &huge_shmem_orders_madvise); 5392 set_bit(order, &huge_shmem_orders_within_size); 5393 spin_unlock(&huge_shmem_orders_lock); 5394 } else if (sysfs_streq(buf, "advise")) { 5395 spin_lock(&huge_shmem_orders_lock); 5396 clear_bit(order, &huge_shmem_orders_always); 5397 clear_bit(order, &huge_shmem_orders_inherit); 5398 clear_bit(order, &huge_shmem_orders_within_size); 5399 set_bit(order, &huge_shmem_orders_madvise); 5400 spin_unlock(&huge_shmem_orders_lock); 5401 } else if (sysfs_streq(buf, "never")) { 5402 spin_lock(&huge_shmem_orders_lock); 5403 clear_bit(order, &huge_shmem_orders_always); 5404 clear_bit(order, &huge_shmem_orders_inherit); 5405 clear_bit(order, &huge_shmem_orders_within_size); 5406 clear_bit(order, &huge_shmem_orders_madvise); 5407 spin_unlock(&huge_shmem_orders_lock); 5408 } else { 5409 ret = -EINVAL; 5410 } 5411 5412 if (ret > 0) { 5413 int err = start_stop_khugepaged(); 5414 5415 if (err) 5416 ret = err; 5417 } 5418 return ret; 5419 } 5420 5421 struct kobj_attribute thpsize_shmem_enabled_attr = 5422 __ATTR(shmem_enabled, 0644, thpsize_shmem_enabled_show, thpsize_shmem_enabled_store); 5423 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */ 5424 5425 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) 5426 5427 static int __init setup_transparent_hugepage_shmem(char *str) 5428 { 5429 int huge; 5430 5431 huge = shmem_parse_huge(str); 5432 if (huge == -EINVAL) { 5433 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n"); 5434 return huge; 5435 } 5436 5437 shmem_huge = huge; 5438 return 1; 5439 } 5440 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem); 5441 5442 static char str_dup[PAGE_SIZE] __initdata; 5443 static int __init setup_thp_shmem(char *str) 5444 { 5445 char *token, *range, *policy, *subtoken; 5446 unsigned long always, inherit, madvise, within_size; 5447 char *start_size, *end_size; 5448 int start, end, nr; 5449 char *p; 5450 5451 if (!str || strlen(str) + 1 > PAGE_SIZE) 5452 goto err; 5453 strscpy(str_dup, str); 5454 5455 always = huge_shmem_orders_always; 5456 inherit = huge_shmem_orders_inherit; 5457 madvise = huge_shmem_orders_madvise; 5458 within_size = huge_shmem_orders_within_size; 5459 p = str_dup; 5460 while ((token = strsep(&p, ";")) != NULL) { 5461 range = strsep(&token, ":"); 5462 policy = token; 5463 5464 if (!policy) 5465 goto err; 5466 5467 while ((subtoken = strsep(&range, ",")) != NULL) { 5468 if (strchr(subtoken, '-')) { 5469 start_size = strsep(&subtoken, "-"); 5470 end_size = subtoken; 5471 5472 start = get_order_from_str(start_size, 5473 THP_ORDERS_ALL_FILE_DEFAULT); 5474 end = get_order_from_str(end_size, 5475 THP_ORDERS_ALL_FILE_DEFAULT); 5476 } else { 5477 start_size = end_size = subtoken; 5478 start = end = get_order_from_str(subtoken, 5479 THP_ORDERS_ALL_FILE_DEFAULT); 5480 } 5481 5482 if (start == -EINVAL) { 5483 pr_err("invalid size %s in thp_shmem boot parameter\n", 5484 start_size); 5485 goto err; 5486 } 5487 5488 if (end == -EINVAL) { 5489 pr_err("invalid size %s in thp_shmem boot parameter\n", 5490 end_size); 5491 goto err; 5492 } 5493 5494 if (start < 0 || end < 0 || start > end) 5495 goto err; 5496 5497 nr = end - start + 1; 5498 if (!strcmp(policy, "always")) { 5499 bitmap_set(&always, start, nr); 5500 bitmap_clear(&inherit, start, nr); 5501 bitmap_clear(&madvise, start, nr); 5502 bitmap_clear(&within_size, start, nr); 5503 } else if (!strcmp(policy, "advise")) { 5504 bitmap_set(&madvise, start, nr); 5505 bitmap_clear(&inherit, start, nr); 5506 bitmap_clear(&always, start, nr); 5507 bitmap_clear(&within_size, start, nr); 5508 } else if (!strcmp(policy, "inherit")) { 5509 bitmap_set(&inherit, start, nr); 5510 bitmap_clear(&madvise, start, nr); 5511 bitmap_clear(&always, start, nr); 5512 bitmap_clear(&within_size, start, nr); 5513 } else if (!strcmp(policy, "within_size")) { 5514 bitmap_set(&within_size, start, nr); 5515 bitmap_clear(&inherit, start, nr); 5516 bitmap_clear(&madvise, start, nr); 5517 bitmap_clear(&always, start, nr); 5518 } else if (!strcmp(policy, "never")) { 5519 bitmap_clear(&inherit, start, nr); 5520 bitmap_clear(&madvise, start, nr); 5521 bitmap_clear(&always, start, nr); 5522 bitmap_clear(&within_size, start, nr); 5523 } else { 5524 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy); 5525 goto err; 5526 } 5527 } 5528 } 5529 5530 huge_shmem_orders_always = always; 5531 huge_shmem_orders_madvise = madvise; 5532 huge_shmem_orders_inherit = inherit; 5533 huge_shmem_orders_within_size = within_size; 5534 shmem_orders_configured = true; 5535 return 1; 5536 5537 err: 5538 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str); 5539 return 0; 5540 } 5541 __setup("thp_shmem=", setup_thp_shmem); 5542 5543 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 5544 5545 #else /* !CONFIG_SHMEM */ 5546 5547 /* 5548 * tiny-shmem: simple shmemfs and tmpfs using ramfs code 5549 * 5550 * This is intended for small system where the benefits of the full 5551 * shmem code (swap-backed and resource-limited) are outweighed by 5552 * their complexity. On systems without swap this code should be 5553 * effectively equivalent, but much lighter weight. 5554 */ 5555 5556 static struct file_system_type shmem_fs_type = { 5557 .name = "tmpfs", 5558 .init_fs_context = ramfs_init_fs_context, 5559 .parameters = ramfs_fs_parameters, 5560 .kill_sb = ramfs_kill_sb, 5561 .fs_flags = FS_USERNS_MOUNT, 5562 }; 5563 5564 void __init shmem_init(void) 5565 { 5566 BUG_ON(register_filesystem(&shmem_fs_type) != 0); 5567 5568 shm_mnt = kern_mount(&shmem_fs_type); 5569 BUG_ON(IS_ERR(shm_mnt)); 5570 } 5571 5572 int shmem_unuse(unsigned int type) 5573 { 5574 return 0; 5575 } 5576 5577 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 5578 { 5579 return 0; 5580 } 5581 5582 void shmem_unlock_mapping(struct address_space *mapping) 5583 { 5584 } 5585 5586 #ifdef CONFIG_MMU 5587 unsigned long shmem_get_unmapped_area(struct file *file, 5588 unsigned long addr, unsigned long len, 5589 unsigned long pgoff, unsigned long flags) 5590 { 5591 return mm_get_unmapped_area(current->mm, file, addr, len, pgoff, flags); 5592 } 5593 #endif 5594 5595 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 5596 { 5597 truncate_inode_pages_range(inode->i_mapping, lstart, lend); 5598 } 5599 EXPORT_SYMBOL_GPL(shmem_truncate_range); 5600 5601 #define shmem_vm_ops generic_file_vm_ops 5602 #define shmem_anon_vm_ops generic_file_vm_ops 5603 #define shmem_file_operations ramfs_file_operations 5604 #define shmem_acct_size(flags, size) 0 5605 #define shmem_unacct_size(flags, size) do {} while (0) 5606 5607 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap, 5608 struct super_block *sb, struct inode *dir, 5609 umode_t mode, dev_t dev, unsigned long flags) 5610 { 5611 struct inode *inode = ramfs_get_inode(sb, dir, mode, dev); 5612 return inode ? inode : ERR_PTR(-ENOSPC); 5613 } 5614 5615 #endif /* CONFIG_SHMEM */ 5616 5617 /* common code */ 5618 5619 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, 5620 loff_t size, unsigned long flags, unsigned int i_flags) 5621 { 5622 struct inode *inode; 5623 struct file *res; 5624 5625 if (IS_ERR(mnt)) 5626 return ERR_CAST(mnt); 5627 5628 if (size < 0 || size > MAX_LFS_FILESIZE) 5629 return ERR_PTR(-EINVAL); 5630 5631 if (shmem_acct_size(flags, size)) 5632 return ERR_PTR(-ENOMEM); 5633 5634 if (is_idmapped_mnt(mnt)) 5635 return ERR_PTR(-EINVAL); 5636 5637 inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL, 5638 S_IFREG | S_IRWXUGO, 0, flags); 5639 if (IS_ERR(inode)) { 5640 shmem_unacct_size(flags, size); 5641 return ERR_CAST(inode); 5642 } 5643 inode->i_flags |= i_flags; 5644 inode->i_size = size; 5645 clear_nlink(inode); /* It is unlinked */ 5646 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size)); 5647 if (!IS_ERR(res)) 5648 res = alloc_file_pseudo(inode, mnt, name, O_RDWR, 5649 &shmem_file_operations); 5650 if (IS_ERR(res)) 5651 iput(inode); 5652 return res; 5653 } 5654 5655 /** 5656 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be 5657 * kernel internal. There will be NO LSM permission checks against the 5658 * underlying inode. So users of this interface must do LSM checks at a 5659 * higher layer. The users are the big_key and shm implementations. LSM 5660 * checks are provided at the key or shm level rather than the inode. 5661 * @name: name for dentry (to be seen in /proc/<pid>/maps 5662 * @size: size to be set for the file 5663 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5664 */ 5665 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags) 5666 { 5667 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE); 5668 } 5669 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup); 5670 5671 /** 5672 * shmem_file_setup - get an unlinked file living in tmpfs 5673 * @name: name for dentry (to be seen in /proc/<pid>/maps 5674 * @size: size to be set for the file 5675 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5676 */ 5677 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags) 5678 { 5679 return __shmem_file_setup(shm_mnt, name, size, flags, 0); 5680 } 5681 EXPORT_SYMBOL_GPL(shmem_file_setup); 5682 5683 /** 5684 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs 5685 * @mnt: the tmpfs mount where the file will be created 5686 * @name: name for dentry (to be seen in /proc/<pid>/maps 5687 * @size: size to be set for the file 5688 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5689 */ 5690 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name, 5691 loff_t size, unsigned long flags) 5692 { 5693 return __shmem_file_setup(mnt, name, size, flags, 0); 5694 } 5695 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt); 5696 5697 /** 5698 * shmem_zero_setup - setup a shared anonymous mapping 5699 * @vma: the vma to be mmapped is prepared by do_mmap 5700 */ 5701 int shmem_zero_setup(struct vm_area_struct *vma) 5702 { 5703 struct file *file; 5704 loff_t size = vma->vm_end - vma->vm_start; 5705 5706 /* 5707 * Cloning a new file under mmap_lock leads to a lock ordering conflict 5708 * between XFS directory reading and selinux: since this file is only 5709 * accessible to the user through its mapping, use S_PRIVATE flag to 5710 * bypass file security, in the same way as shmem_kernel_file_setup(). 5711 */ 5712 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags); 5713 if (IS_ERR(file)) 5714 return PTR_ERR(file); 5715 5716 if (vma->vm_file) 5717 fput(vma->vm_file); 5718 vma->vm_file = file; 5719 vma->vm_ops = &shmem_anon_vm_ops; 5720 5721 return 0; 5722 } 5723 5724 /** 5725 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags. 5726 * @mapping: the folio's address_space 5727 * @index: the folio index 5728 * @gfp: the page allocator flags to use if allocating 5729 * 5730 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)", 5731 * with any new page allocations done using the specified allocation flags. 5732 * But read_cache_page_gfp() uses the ->read_folio() method: which does not 5733 * suit tmpfs, since it may have pages in swapcache, and needs to find those 5734 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support. 5735 * 5736 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in 5737 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily. 5738 */ 5739 struct folio *shmem_read_folio_gfp(struct address_space *mapping, 5740 pgoff_t index, gfp_t gfp) 5741 { 5742 #ifdef CONFIG_SHMEM 5743 struct inode *inode = mapping->host; 5744 struct folio *folio; 5745 int error; 5746 5747 error = shmem_get_folio_gfp(inode, index, 0, &folio, SGP_CACHE, 5748 gfp, NULL, NULL); 5749 if (error) 5750 return ERR_PTR(error); 5751 5752 folio_unlock(folio); 5753 return folio; 5754 #else 5755 /* 5756 * The tiny !SHMEM case uses ramfs without swap 5757 */ 5758 return mapping_read_folio_gfp(mapping, index, gfp); 5759 #endif 5760 } 5761 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp); 5762 5763 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping, 5764 pgoff_t index, gfp_t gfp) 5765 { 5766 struct folio *folio = shmem_read_folio_gfp(mapping, index, gfp); 5767 struct page *page; 5768 5769 if (IS_ERR(folio)) 5770 return &folio->page; 5771 5772 page = folio_file_page(folio, index); 5773 if (PageHWPoison(page)) { 5774 folio_put(folio); 5775 return ERR_PTR(-EIO); 5776 } 5777 5778 return page; 5779 } 5780 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp); 5781