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 char *link; 3918 3919 len = strlen(symname) + 1; 3920 if (len > PAGE_SIZE) 3921 return -ENAMETOOLONG; 3922 3923 inode = shmem_get_inode(idmap, dir->i_sb, dir, S_IFLNK | 0777, 0, 3924 VM_NORESERVE); 3925 if (IS_ERR(inode)) 3926 return PTR_ERR(inode); 3927 3928 error = security_inode_init_security(inode, dir, &dentry->d_name, 3929 shmem_initxattrs, NULL); 3930 if (error && error != -EOPNOTSUPP) 3931 goto out_iput; 3932 3933 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3934 if (error) 3935 goto out_iput; 3936 3937 inode->i_size = len-1; 3938 if (len <= SHORT_SYMLINK_LEN) { 3939 link = kmemdup(symname, len, GFP_KERNEL); 3940 if (!link) { 3941 error = -ENOMEM; 3942 goto out_remove_offset; 3943 } 3944 inode->i_op = &shmem_short_symlink_operations; 3945 inode_set_cached_link(inode, link, len - 1); 3946 } else { 3947 inode_nohighmem(inode); 3948 inode->i_mapping->a_ops = &shmem_aops; 3949 error = shmem_get_folio(inode, 0, 0, &folio, SGP_WRITE); 3950 if (error) 3951 goto out_remove_offset; 3952 inode->i_op = &shmem_symlink_inode_operations; 3953 memcpy(folio_address(folio), symname, len); 3954 folio_mark_uptodate(folio); 3955 folio_mark_dirty(folio); 3956 folio_unlock(folio); 3957 folio_put(folio); 3958 } 3959 dir->i_size += BOGO_DIRENT_SIZE; 3960 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir)); 3961 inode_inc_iversion(dir); 3962 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3963 d_add(dentry, inode); 3964 else 3965 d_instantiate(dentry, inode); 3966 dget(dentry); 3967 return 0; 3968 3969 out_remove_offset: 3970 simple_offset_remove(shmem_get_offset_ctx(dir), dentry); 3971 out_iput: 3972 iput(inode); 3973 return error; 3974 } 3975 3976 static void shmem_put_link(void *arg) 3977 { 3978 folio_mark_accessed(arg); 3979 folio_put(arg); 3980 } 3981 3982 static const char *shmem_get_link(struct dentry *dentry, struct inode *inode, 3983 struct delayed_call *done) 3984 { 3985 struct folio *folio = NULL; 3986 int error; 3987 3988 if (!dentry) { 3989 folio = filemap_get_folio(inode->i_mapping, 0); 3990 if (IS_ERR(folio)) 3991 return ERR_PTR(-ECHILD); 3992 if (PageHWPoison(folio_page(folio, 0)) || 3993 !folio_test_uptodate(folio)) { 3994 folio_put(folio); 3995 return ERR_PTR(-ECHILD); 3996 } 3997 } else { 3998 error = shmem_get_folio(inode, 0, 0, &folio, SGP_READ); 3999 if (error) 4000 return ERR_PTR(error); 4001 if (!folio) 4002 return ERR_PTR(-ECHILD); 4003 if (PageHWPoison(folio_page(folio, 0))) { 4004 folio_unlock(folio); 4005 folio_put(folio); 4006 return ERR_PTR(-ECHILD); 4007 } 4008 folio_unlock(folio); 4009 } 4010 set_delayed_call(done, shmem_put_link, folio); 4011 return folio_address(folio); 4012 } 4013 4014 #ifdef CONFIG_TMPFS_XATTR 4015 4016 static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa) 4017 { 4018 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4019 4020 fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE); 4021 4022 return 0; 4023 } 4024 4025 static int shmem_fileattr_set(struct mnt_idmap *idmap, 4026 struct dentry *dentry, struct fileattr *fa) 4027 { 4028 struct inode *inode = d_inode(dentry); 4029 struct shmem_inode_info *info = SHMEM_I(inode); 4030 int ret, flags; 4031 4032 if (fileattr_has_fsx(fa)) 4033 return -EOPNOTSUPP; 4034 if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE) 4035 return -EOPNOTSUPP; 4036 4037 flags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) | 4038 (fa->flags & SHMEM_FL_USER_MODIFIABLE); 4039 4040 ret = shmem_set_inode_flags(inode, flags, dentry); 4041 4042 if (ret) 4043 return ret; 4044 4045 info->fsflags = flags; 4046 4047 inode_set_ctime_current(inode); 4048 inode_inc_iversion(inode); 4049 return 0; 4050 } 4051 4052 /* 4053 * Superblocks without xattr inode operations may get some security.* xattr 4054 * support from the LSM "for free". As soon as we have any other xattrs 4055 * like ACLs, we also need to implement the security.* handlers at 4056 * filesystem level, though. 4057 */ 4058 4059 /* 4060 * Callback for security_inode_init_security() for acquiring xattrs. 4061 */ 4062 static int shmem_initxattrs(struct inode *inode, 4063 const struct xattr *xattr_array, void *fs_info) 4064 { 4065 struct shmem_inode_info *info = SHMEM_I(inode); 4066 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4067 const struct xattr *xattr; 4068 struct simple_xattr *new_xattr; 4069 size_t ispace = 0; 4070 size_t len; 4071 4072 if (sbinfo->max_inodes) { 4073 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4074 ispace += simple_xattr_space(xattr->name, 4075 xattr->value_len + XATTR_SECURITY_PREFIX_LEN); 4076 } 4077 if (ispace) { 4078 raw_spin_lock(&sbinfo->stat_lock); 4079 if (sbinfo->free_ispace < ispace) 4080 ispace = 0; 4081 else 4082 sbinfo->free_ispace -= ispace; 4083 raw_spin_unlock(&sbinfo->stat_lock); 4084 if (!ispace) 4085 return -ENOSPC; 4086 } 4087 } 4088 4089 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4090 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len); 4091 if (!new_xattr) 4092 break; 4093 4094 len = strlen(xattr->name) + 1; 4095 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len, 4096 GFP_KERNEL_ACCOUNT); 4097 if (!new_xattr->name) { 4098 kvfree(new_xattr); 4099 break; 4100 } 4101 4102 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX, 4103 XATTR_SECURITY_PREFIX_LEN); 4104 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN, 4105 xattr->name, len); 4106 4107 simple_xattr_add(&info->xattrs, new_xattr); 4108 } 4109 4110 if (xattr->name != NULL) { 4111 if (ispace) { 4112 raw_spin_lock(&sbinfo->stat_lock); 4113 sbinfo->free_ispace += ispace; 4114 raw_spin_unlock(&sbinfo->stat_lock); 4115 } 4116 simple_xattrs_free(&info->xattrs, NULL); 4117 return -ENOMEM; 4118 } 4119 4120 return 0; 4121 } 4122 4123 static int shmem_xattr_handler_get(const struct xattr_handler *handler, 4124 struct dentry *unused, struct inode *inode, 4125 const char *name, void *buffer, size_t size) 4126 { 4127 struct shmem_inode_info *info = SHMEM_I(inode); 4128 4129 name = xattr_full_name(handler, name); 4130 return simple_xattr_get(&info->xattrs, name, buffer, size); 4131 } 4132 4133 static int shmem_xattr_handler_set(const struct xattr_handler *handler, 4134 struct mnt_idmap *idmap, 4135 struct dentry *unused, struct inode *inode, 4136 const char *name, const void *value, 4137 size_t size, int flags) 4138 { 4139 struct shmem_inode_info *info = SHMEM_I(inode); 4140 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4141 struct simple_xattr *old_xattr; 4142 size_t ispace = 0; 4143 4144 name = xattr_full_name(handler, name); 4145 if (value && sbinfo->max_inodes) { 4146 ispace = simple_xattr_space(name, size); 4147 raw_spin_lock(&sbinfo->stat_lock); 4148 if (sbinfo->free_ispace < ispace) 4149 ispace = 0; 4150 else 4151 sbinfo->free_ispace -= ispace; 4152 raw_spin_unlock(&sbinfo->stat_lock); 4153 if (!ispace) 4154 return -ENOSPC; 4155 } 4156 4157 old_xattr = simple_xattr_set(&info->xattrs, name, value, size, flags); 4158 if (!IS_ERR(old_xattr)) { 4159 ispace = 0; 4160 if (old_xattr && sbinfo->max_inodes) 4161 ispace = simple_xattr_space(old_xattr->name, 4162 old_xattr->size); 4163 simple_xattr_free(old_xattr); 4164 old_xattr = NULL; 4165 inode_set_ctime_current(inode); 4166 inode_inc_iversion(inode); 4167 } 4168 if (ispace) { 4169 raw_spin_lock(&sbinfo->stat_lock); 4170 sbinfo->free_ispace += ispace; 4171 raw_spin_unlock(&sbinfo->stat_lock); 4172 } 4173 return PTR_ERR(old_xattr); 4174 } 4175 4176 static const struct xattr_handler shmem_security_xattr_handler = { 4177 .prefix = XATTR_SECURITY_PREFIX, 4178 .get = shmem_xattr_handler_get, 4179 .set = shmem_xattr_handler_set, 4180 }; 4181 4182 static const struct xattr_handler shmem_trusted_xattr_handler = { 4183 .prefix = XATTR_TRUSTED_PREFIX, 4184 .get = shmem_xattr_handler_get, 4185 .set = shmem_xattr_handler_set, 4186 }; 4187 4188 static const struct xattr_handler shmem_user_xattr_handler = { 4189 .prefix = XATTR_USER_PREFIX, 4190 .get = shmem_xattr_handler_get, 4191 .set = shmem_xattr_handler_set, 4192 }; 4193 4194 static const struct xattr_handler * const shmem_xattr_handlers[] = { 4195 &shmem_security_xattr_handler, 4196 &shmem_trusted_xattr_handler, 4197 &shmem_user_xattr_handler, 4198 NULL 4199 }; 4200 4201 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size) 4202 { 4203 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4204 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size); 4205 } 4206 #endif /* CONFIG_TMPFS_XATTR */ 4207 4208 static const struct inode_operations shmem_short_symlink_operations = { 4209 .getattr = shmem_getattr, 4210 .setattr = shmem_setattr, 4211 .get_link = simple_get_link, 4212 #ifdef CONFIG_TMPFS_XATTR 4213 .listxattr = shmem_listxattr, 4214 #endif 4215 }; 4216 4217 static const struct inode_operations shmem_symlink_inode_operations = { 4218 .getattr = shmem_getattr, 4219 .setattr = shmem_setattr, 4220 .get_link = shmem_get_link, 4221 #ifdef CONFIG_TMPFS_XATTR 4222 .listxattr = shmem_listxattr, 4223 #endif 4224 }; 4225 4226 static struct dentry *shmem_get_parent(struct dentry *child) 4227 { 4228 return ERR_PTR(-ESTALE); 4229 } 4230 4231 static int shmem_match(struct inode *ino, void *vfh) 4232 { 4233 __u32 *fh = vfh; 4234 __u64 inum = fh[2]; 4235 inum = (inum << 32) | fh[1]; 4236 return ino->i_ino == inum && fh[0] == ino->i_generation; 4237 } 4238 4239 /* Find any alias of inode, but prefer a hashed alias */ 4240 static struct dentry *shmem_find_alias(struct inode *inode) 4241 { 4242 struct dentry *alias = d_find_alias(inode); 4243 4244 return alias ?: d_find_any_alias(inode); 4245 } 4246 4247 static struct dentry *shmem_fh_to_dentry(struct super_block *sb, 4248 struct fid *fid, int fh_len, int fh_type) 4249 { 4250 struct inode *inode; 4251 struct dentry *dentry = NULL; 4252 u64 inum; 4253 4254 if (fh_len < 3) 4255 return NULL; 4256 4257 inum = fid->raw[2]; 4258 inum = (inum << 32) | fid->raw[1]; 4259 4260 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]), 4261 shmem_match, fid->raw); 4262 if (inode) { 4263 dentry = shmem_find_alias(inode); 4264 iput(inode); 4265 } 4266 4267 return dentry; 4268 } 4269 4270 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len, 4271 struct inode *parent) 4272 { 4273 if (*len < 3) { 4274 *len = 3; 4275 return FILEID_INVALID; 4276 } 4277 4278 if (inode_unhashed(inode)) { 4279 /* Unfortunately insert_inode_hash is not idempotent, 4280 * so as we hash inodes here rather than at creation 4281 * time, we need a lock to ensure we only try 4282 * to do it once 4283 */ 4284 static DEFINE_SPINLOCK(lock); 4285 spin_lock(&lock); 4286 if (inode_unhashed(inode)) 4287 __insert_inode_hash(inode, 4288 inode->i_ino + inode->i_generation); 4289 spin_unlock(&lock); 4290 } 4291 4292 fh[0] = inode->i_generation; 4293 fh[1] = inode->i_ino; 4294 fh[2] = ((__u64)inode->i_ino) >> 32; 4295 4296 *len = 3; 4297 return 1; 4298 } 4299 4300 static const struct export_operations shmem_export_ops = { 4301 .get_parent = shmem_get_parent, 4302 .encode_fh = shmem_encode_fh, 4303 .fh_to_dentry = shmem_fh_to_dentry, 4304 }; 4305 4306 enum shmem_param { 4307 Opt_gid, 4308 Opt_huge, 4309 Opt_mode, 4310 Opt_mpol, 4311 Opt_nr_blocks, 4312 Opt_nr_inodes, 4313 Opt_size, 4314 Opt_uid, 4315 Opt_inode32, 4316 Opt_inode64, 4317 Opt_noswap, 4318 Opt_quota, 4319 Opt_usrquota, 4320 Opt_grpquota, 4321 Opt_usrquota_block_hardlimit, 4322 Opt_usrquota_inode_hardlimit, 4323 Opt_grpquota_block_hardlimit, 4324 Opt_grpquota_inode_hardlimit, 4325 Opt_casefold_version, 4326 Opt_casefold, 4327 Opt_strict_encoding, 4328 }; 4329 4330 static const struct constant_table shmem_param_enums_huge[] = { 4331 {"never", SHMEM_HUGE_NEVER }, 4332 {"always", SHMEM_HUGE_ALWAYS }, 4333 {"within_size", SHMEM_HUGE_WITHIN_SIZE }, 4334 {"advise", SHMEM_HUGE_ADVISE }, 4335 {} 4336 }; 4337 4338 const struct fs_parameter_spec shmem_fs_parameters[] = { 4339 fsparam_gid ("gid", Opt_gid), 4340 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge), 4341 fsparam_u32oct("mode", Opt_mode), 4342 fsparam_string("mpol", Opt_mpol), 4343 fsparam_string("nr_blocks", Opt_nr_blocks), 4344 fsparam_string("nr_inodes", Opt_nr_inodes), 4345 fsparam_string("size", Opt_size), 4346 fsparam_uid ("uid", Opt_uid), 4347 fsparam_flag ("inode32", Opt_inode32), 4348 fsparam_flag ("inode64", Opt_inode64), 4349 fsparam_flag ("noswap", Opt_noswap), 4350 #ifdef CONFIG_TMPFS_QUOTA 4351 fsparam_flag ("quota", Opt_quota), 4352 fsparam_flag ("usrquota", Opt_usrquota), 4353 fsparam_flag ("grpquota", Opt_grpquota), 4354 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit), 4355 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit), 4356 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit), 4357 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit), 4358 #endif 4359 fsparam_string("casefold", Opt_casefold_version), 4360 fsparam_flag ("casefold", Opt_casefold), 4361 fsparam_flag ("strict_encoding", Opt_strict_encoding), 4362 {} 4363 }; 4364 4365 #if IS_ENABLED(CONFIG_UNICODE) 4366 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4367 bool latest_version) 4368 { 4369 struct shmem_options *ctx = fc->fs_private; 4370 unsigned int version = UTF8_LATEST; 4371 struct unicode_map *encoding; 4372 char *version_str = param->string + 5; 4373 4374 if (!latest_version) { 4375 if (strncmp(param->string, "utf8-", 5)) 4376 return invalfc(fc, "Only UTF-8 encodings are supported " 4377 "in the format: utf8-<version number>"); 4378 4379 version = utf8_parse_version(version_str); 4380 if (version < 0) 4381 return invalfc(fc, "Invalid UTF-8 version: %s", version_str); 4382 } 4383 4384 encoding = utf8_load(version); 4385 4386 if (IS_ERR(encoding)) { 4387 return invalfc(fc, "Failed loading UTF-8 version: utf8-%u.%u.%u\n", 4388 unicode_major(version), unicode_minor(version), 4389 unicode_rev(version)); 4390 } 4391 4392 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n", 4393 unicode_major(version), unicode_minor(version), unicode_rev(version)); 4394 4395 ctx->encoding = encoding; 4396 4397 return 0; 4398 } 4399 #else 4400 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4401 bool latest_version) 4402 { 4403 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4404 } 4405 #endif 4406 4407 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param) 4408 { 4409 struct shmem_options *ctx = fc->fs_private; 4410 struct fs_parse_result result; 4411 unsigned long long size; 4412 char *rest; 4413 int opt; 4414 kuid_t kuid; 4415 kgid_t kgid; 4416 4417 opt = fs_parse(fc, shmem_fs_parameters, param, &result); 4418 if (opt < 0) 4419 return opt; 4420 4421 switch (opt) { 4422 case Opt_size: 4423 size = memparse(param->string, &rest); 4424 if (*rest == '%') { 4425 size <<= PAGE_SHIFT; 4426 size *= totalram_pages(); 4427 do_div(size, 100); 4428 rest++; 4429 } 4430 if (*rest) 4431 goto bad_value; 4432 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE); 4433 ctx->seen |= SHMEM_SEEN_BLOCKS; 4434 break; 4435 case Opt_nr_blocks: 4436 ctx->blocks = memparse(param->string, &rest); 4437 if (*rest || ctx->blocks > LONG_MAX) 4438 goto bad_value; 4439 ctx->seen |= SHMEM_SEEN_BLOCKS; 4440 break; 4441 case Opt_nr_inodes: 4442 ctx->inodes = memparse(param->string, &rest); 4443 if (*rest || ctx->inodes > ULONG_MAX / BOGO_INODE_SIZE) 4444 goto bad_value; 4445 ctx->seen |= SHMEM_SEEN_INODES; 4446 break; 4447 case Opt_mode: 4448 ctx->mode = result.uint_32 & 07777; 4449 break; 4450 case Opt_uid: 4451 kuid = result.uid; 4452 4453 /* 4454 * The requested uid must be representable in the 4455 * filesystem's idmapping. 4456 */ 4457 if (!kuid_has_mapping(fc->user_ns, kuid)) 4458 goto bad_value; 4459 4460 ctx->uid = kuid; 4461 break; 4462 case Opt_gid: 4463 kgid = result.gid; 4464 4465 /* 4466 * The requested gid must be representable in the 4467 * filesystem's idmapping. 4468 */ 4469 if (!kgid_has_mapping(fc->user_ns, kgid)) 4470 goto bad_value; 4471 4472 ctx->gid = kgid; 4473 break; 4474 case Opt_huge: 4475 ctx->huge = result.uint_32; 4476 if (ctx->huge != SHMEM_HUGE_NEVER && 4477 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && 4478 has_transparent_hugepage())) 4479 goto unsupported_parameter; 4480 ctx->seen |= SHMEM_SEEN_HUGE; 4481 break; 4482 case Opt_mpol: 4483 if (IS_ENABLED(CONFIG_NUMA)) { 4484 mpol_put(ctx->mpol); 4485 ctx->mpol = NULL; 4486 if (mpol_parse_str(param->string, &ctx->mpol)) 4487 goto bad_value; 4488 break; 4489 } 4490 goto unsupported_parameter; 4491 case Opt_inode32: 4492 ctx->full_inums = false; 4493 ctx->seen |= SHMEM_SEEN_INUMS; 4494 break; 4495 case Opt_inode64: 4496 if (sizeof(ino_t) < 8) { 4497 return invalfc(fc, 4498 "Cannot use inode64 with <64bit inums in kernel\n"); 4499 } 4500 ctx->full_inums = true; 4501 ctx->seen |= SHMEM_SEEN_INUMS; 4502 break; 4503 case Opt_noswap: 4504 if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) { 4505 return invalfc(fc, 4506 "Turning off swap in unprivileged tmpfs mounts unsupported"); 4507 } 4508 ctx->noswap = true; 4509 ctx->seen |= SHMEM_SEEN_NOSWAP; 4510 break; 4511 case Opt_quota: 4512 if (fc->user_ns != &init_user_ns) 4513 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4514 ctx->seen |= SHMEM_SEEN_QUOTA; 4515 ctx->quota_types |= (QTYPE_MASK_USR | QTYPE_MASK_GRP); 4516 break; 4517 case Opt_usrquota: 4518 if (fc->user_ns != &init_user_ns) 4519 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4520 ctx->seen |= SHMEM_SEEN_QUOTA; 4521 ctx->quota_types |= QTYPE_MASK_USR; 4522 break; 4523 case Opt_grpquota: 4524 if (fc->user_ns != &init_user_ns) 4525 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4526 ctx->seen |= SHMEM_SEEN_QUOTA; 4527 ctx->quota_types |= QTYPE_MASK_GRP; 4528 break; 4529 case Opt_usrquota_block_hardlimit: 4530 size = memparse(param->string, &rest); 4531 if (*rest || !size) 4532 goto bad_value; 4533 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4534 return invalfc(fc, 4535 "User quota block hardlimit too large."); 4536 ctx->qlimits.usrquota_bhardlimit = size; 4537 break; 4538 case Opt_grpquota_block_hardlimit: 4539 size = memparse(param->string, &rest); 4540 if (*rest || !size) 4541 goto bad_value; 4542 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4543 return invalfc(fc, 4544 "Group quota block hardlimit too large."); 4545 ctx->qlimits.grpquota_bhardlimit = size; 4546 break; 4547 case Opt_usrquota_inode_hardlimit: 4548 size = memparse(param->string, &rest); 4549 if (*rest || !size) 4550 goto bad_value; 4551 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4552 return invalfc(fc, 4553 "User quota inode hardlimit too large."); 4554 ctx->qlimits.usrquota_ihardlimit = size; 4555 break; 4556 case Opt_grpquota_inode_hardlimit: 4557 size = memparse(param->string, &rest); 4558 if (*rest || !size) 4559 goto bad_value; 4560 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4561 return invalfc(fc, 4562 "Group quota inode hardlimit too large."); 4563 ctx->qlimits.grpquota_ihardlimit = size; 4564 break; 4565 case Opt_casefold_version: 4566 return shmem_parse_opt_casefold(fc, param, false); 4567 case Opt_casefold: 4568 return shmem_parse_opt_casefold(fc, param, true); 4569 case Opt_strict_encoding: 4570 #if IS_ENABLED(CONFIG_UNICODE) 4571 ctx->strict_encoding = true; 4572 break; 4573 #else 4574 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4575 #endif 4576 } 4577 return 0; 4578 4579 unsupported_parameter: 4580 return invalfc(fc, "Unsupported parameter '%s'", param->key); 4581 bad_value: 4582 return invalfc(fc, "Bad value for '%s'", param->key); 4583 } 4584 4585 static int shmem_parse_options(struct fs_context *fc, void *data) 4586 { 4587 char *options = data; 4588 4589 if (options) { 4590 int err = security_sb_eat_lsm_opts(options, &fc->security); 4591 if (err) 4592 return err; 4593 } 4594 4595 while (options != NULL) { 4596 char *this_char = options; 4597 for (;;) { 4598 /* 4599 * NUL-terminate this option: unfortunately, 4600 * mount options form a comma-separated list, 4601 * but mpol's nodelist may also contain commas. 4602 */ 4603 options = strchr(options, ','); 4604 if (options == NULL) 4605 break; 4606 options++; 4607 if (!isdigit(*options)) { 4608 options[-1] = '\0'; 4609 break; 4610 } 4611 } 4612 if (*this_char) { 4613 char *value = strchr(this_char, '='); 4614 size_t len = 0; 4615 int err; 4616 4617 if (value) { 4618 *value++ = '\0'; 4619 len = strlen(value); 4620 } 4621 err = vfs_parse_fs_string(fc, this_char, value, len); 4622 if (err < 0) 4623 return err; 4624 } 4625 } 4626 return 0; 4627 } 4628 4629 /* 4630 * Reconfigure a shmem filesystem. 4631 */ 4632 static int shmem_reconfigure(struct fs_context *fc) 4633 { 4634 struct shmem_options *ctx = fc->fs_private; 4635 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb); 4636 unsigned long used_isp; 4637 struct mempolicy *mpol = NULL; 4638 const char *err; 4639 4640 raw_spin_lock(&sbinfo->stat_lock); 4641 used_isp = sbinfo->max_inodes * BOGO_INODE_SIZE - sbinfo->free_ispace; 4642 4643 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) { 4644 if (!sbinfo->max_blocks) { 4645 err = "Cannot retroactively limit size"; 4646 goto out; 4647 } 4648 if (percpu_counter_compare(&sbinfo->used_blocks, 4649 ctx->blocks) > 0) { 4650 err = "Too small a size for current use"; 4651 goto out; 4652 } 4653 } 4654 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) { 4655 if (!sbinfo->max_inodes) { 4656 err = "Cannot retroactively limit inodes"; 4657 goto out; 4658 } 4659 if (ctx->inodes * BOGO_INODE_SIZE < used_isp) { 4660 err = "Too few inodes for current use"; 4661 goto out; 4662 } 4663 } 4664 4665 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums && 4666 sbinfo->next_ino > UINT_MAX) { 4667 err = "Current inum too high to switch to 32-bit inums"; 4668 goto out; 4669 } 4670 if ((ctx->seen & SHMEM_SEEN_NOSWAP) && ctx->noswap && !sbinfo->noswap) { 4671 err = "Cannot disable swap on remount"; 4672 goto out; 4673 } 4674 if (!(ctx->seen & SHMEM_SEEN_NOSWAP) && !ctx->noswap && sbinfo->noswap) { 4675 err = "Cannot enable swap on remount if it was disabled on first mount"; 4676 goto out; 4677 } 4678 4679 if (ctx->seen & SHMEM_SEEN_QUOTA && 4680 !sb_any_quota_loaded(fc->root->d_sb)) { 4681 err = "Cannot enable quota on remount"; 4682 goto out; 4683 } 4684 4685 #ifdef CONFIG_TMPFS_QUOTA 4686 #define CHANGED_LIMIT(name) \ 4687 (ctx->qlimits.name## hardlimit && \ 4688 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit)) 4689 4690 if (CHANGED_LIMIT(usrquota_b) || CHANGED_LIMIT(usrquota_i) || 4691 CHANGED_LIMIT(grpquota_b) || CHANGED_LIMIT(grpquota_i)) { 4692 err = "Cannot change global quota limit on remount"; 4693 goto out; 4694 } 4695 #endif /* CONFIG_TMPFS_QUOTA */ 4696 4697 if (ctx->seen & SHMEM_SEEN_HUGE) 4698 sbinfo->huge = ctx->huge; 4699 if (ctx->seen & SHMEM_SEEN_INUMS) 4700 sbinfo->full_inums = ctx->full_inums; 4701 if (ctx->seen & SHMEM_SEEN_BLOCKS) 4702 sbinfo->max_blocks = ctx->blocks; 4703 if (ctx->seen & SHMEM_SEEN_INODES) { 4704 sbinfo->max_inodes = ctx->inodes; 4705 sbinfo->free_ispace = ctx->inodes * BOGO_INODE_SIZE - used_isp; 4706 } 4707 4708 /* 4709 * Preserve previous mempolicy unless mpol remount option was specified. 4710 */ 4711 if (ctx->mpol) { 4712 mpol = sbinfo->mpol; 4713 sbinfo->mpol = ctx->mpol; /* transfers initial ref */ 4714 ctx->mpol = NULL; 4715 } 4716 4717 if (ctx->noswap) 4718 sbinfo->noswap = true; 4719 4720 raw_spin_unlock(&sbinfo->stat_lock); 4721 mpol_put(mpol); 4722 return 0; 4723 out: 4724 raw_spin_unlock(&sbinfo->stat_lock); 4725 return invalfc(fc, "%s", err); 4726 } 4727 4728 static int shmem_show_options(struct seq_file *seq, struct dentry *root) 4729 { 4730 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb); 4731 struct mempolicy *mpol; 4732 4733 if (sbinfo->max_blocks != shmem_default_max_blocks()) 4734 seq_printf(seq, ",size=%luk", K(sbinfo->max_blocks)); 4735 if (sbinfo->max_inodes != shmem_default_max_inodes()) 4736 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes); 4737 if (sbinfo->mode != (0777 | S_ISVTX)) 4738 seq_printf(seq, ",mode=%03ho", sbinfo->mode); 4739 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID)) 4740 seq_printf(seq, ",uid=%u", 4741 from_kuid_munged(&init_user_ns, sbinfo->uid)); 4742 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID)) 4743 seq_printf(seq, ",gid=%u", 4744 from_kgid_munged(&init_user_ns, sbinfo->gid)); 4745 4746 /* 4747 * Showing inode{64,32} might be useful even if it's the system default, 4748 * since then people don't have to resort to checking both here and 4749 * /proc/config.gz to confirm 64-bit inums were successfully applied 4750 * (which may not even exist if IKCONFIG_PROC isn't enabled). 4751 * 4752 * We hide it when inode64 isn't the default and we are using 32-bit 4753 * inodes, since that probably just means the feature isn't even under 4754 * consideration. 4755 * 4756 * As such: 4757 * 4758 * +-----------------+-----------------+ 4759 * | TMPFS_INODE64=y | TMPFS_INODE64=n | 4760 * +------------------+-----------------+-----------------+ 4761 * | full_inums=true | show | show | 4762 * | full_inums=false | show | hide | 4763 * +------------------+-----------------+-----------------+ 4764 * 4765 */ 4766 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums) 4767 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32)); 4768 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4769 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */ 4770 if (sbinfo->huge) 4771 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge)); 4772 #endif 4773 mpol = shmem_get_sbmpol(sbinfo); 4774 shmem_show_mpol(seq, mpol); 4775 mpol_put(mpol); 4776 if (sbinfo->noswap) 4777 seq_printf(seq, ",noswap"); 4778 #ifdef CONFIG_TMPFS_QUOTA 4779 if (sb_has_quota_active(root->d_sb, USRQUOTA)) 4780 seq_printf(seq, ",usrquota"); 4781 if (sb_has_quota_active(root->d_sb, GRPQUOTA)) 4782 seq_printf(seq, ",grpquota"); 4783 if (sbinfo->qlimits.usrquota_bhardlimit) 4784 seq_printf(seq, ",usrquota_block_hardlimit=%lld", 4785 sbinfo->qlimits.usrquota_bhardlimit); 4786 if (sbinfo->qlimits.grpquota_bhardlimit) 4787 seq_printf(seq, ",grpquota_block_hardlimit=%lld", 4788 sbinfo->qlimits.grpquota_bhardlimit); 4789 if (sbinfo->qlimits.usrquota_ihardlimit) 4790 seq_printf(seq, ",usrquota_inode_hardlimit=%lld", 4791 sbinfo->qlimits.usrquota_ihardlimit); 4792 if (sbinfo->qlimits.grpquota_ihardlimit) 4793 seq_printf(seq, ",grpquota_inode_hardlimit=%lld", 4794 sbinfo->qlimits.grpquota_ihardlimit); 4795 #endif 4796 return 0; 4797 } 4798 4799 #endif /* CONFIG_TMPFS */ 4800 4801 static void shmem_put_super(struct super_block *sb) 4802 { 4803 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 4804 4805 #if IS_ENABLED(CONFIG_UNICODE) 4806 if (sb->s_encoding) 4807 utf8_unload(sb->s_encoding); 4808 #endif 4809 4810 #ifdef CONFIG_TMPFS_QUOTA 4811 shmem_disable_quotas(sb); 4812 #endif 4813 free_percpu(sbinfo->ino_batch); 4814 percpu_counter_destroy(&sbinfo->used_blocks); 4815 mpol_put(sbinfo->mpol); 4816 kfree(sbinfo); 4817 sb->s_fs_info = NULL; 4818 } 4819 4820 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS) 4821 static const struct dentry_operations shmem_ci_dentry_ops = { 4822 .d_hash = generic_ci_d_hash, 4823 .d_compare = generic_ci_d_compare, 4824 .d_delete = always_delete_dentry, 4825 }; 4826 #endif 4827 4828 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc) 4829 { 4830 struct shmem_options *ctx = fc->fs_private; 4831 struct inode *inode; 4832 struct shmem_sb_info *sbinfo; 4833 int error = -ENOMEM; 4834 4835 /* Round up to L1_CACHE_BYTES to resist false sharing */ 4836 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info), 4837 L1_CACHE_BYTES), GFP_KERNEL); 4838 if (!sbinfo) 4839 return error; 4840 4841 sb->s_fs_info = sbinfo; 4842 4843 #ifdef CONFIG_TMPFS 4844 /* 4845 * Per default we only allow half of the physical ram per 4846 * tmpfs instance, limiting inodes to one per page of lowmem; 4847 * but the internal instance is left unlimited. 4848 */ 4849 if (!(sb->s_flags & SB_KERNMOUNT)) { 4850 if (!(ctx->seen & SHMEM_SEEN_BLOCKS)) 4851 ctx->blocks = shmem_default_max_blocks(); 4852 if (!(ctx->seen & SHMEM_SEEN_INODES)) 4853 ctx->inodes = shmem_default_max_inodes(); 4854 if (!(ctx->seen & SHMEM_SEEN_INUMS)) 4855 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64); 4856 sbinfo->noswap = ctx->noswap; 4857 } else { 4858 sb->s_flags |= SB_NOUSER; 4859 } 4860 sb->s_export_op = &shmem_export_ops; 4861 sb->s_flags |= SB_NOSEC | SB_I_VERSION; 4862 4863 #if IS_ENABLED(CONFIG_UNICODE) 4864 if (!ctx->encoding && ctx->strict_encoding) { 4865 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n"); 4866 error = -EINVAL; 4867 goto failed; 4868 } 4869 4870 if (ctx->encoding) { 4871 sb->s_encoding = ctx->encoding; 4872 sb->s_d_op = &shmem_ci_dentry_ops; 4873 if (ctx->strict_encoding) 4874 sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL; 4875 } 4876 #endif 4877 4878 #else 4879 sb->s_flags |= SB_NOUSER; 4880 #endif /* CONFIG_TMPFS */ 4881 sbinfo->max_blocks = ctx->blocks; 4882 sbinfo->max_inodes = ctx->inodes; 4883 sbinfo->free_ispace = sbinfo->max_inodes * BOGO_INODE_SIZE; 4884 if (sb->s_flags & SB_KERNMOUNT) { 4885 sbinfo->ino_batch = alloc_percpu(ino_t); 4886 if (!sbinfo->ino_batch) 4887 goto failed; 4888 } 4889 sbinfo->uid = ctx->uid; 4890 sbinfo->gid = ctx->gid; 4891 sbinfo->full_inums = ctx->full_inums; 4892 sbinfo->mode = ctx->mode; 4893 sbinfo->huge = ctx->huge; 4894 sbinfo->mpol = ctx->mpol; 4895 ctx->mpol = NULL; 4896 4897 raw_spin_lock_init(&sbinfo->stat_lock); 4898 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL)) 4899 goto failed; 4900 spin_lock_init(&sbinfo->shrinklist_lock); 4901 INIT_LIST_HEAD(&sbinfo->shrinklist); 4902 4903 sb->s_maxbytes = MAX_LFS_FILESIZE; 4904 sb->s_blocksize = PAGE_SIZE; 4905 sb->s_blocksize_bits = PAGE_SHIFT; 4906 sb->s_magic = TMPFS_MAGIC; 4907 sb->s_op = &shmem_ops; 4908 sb->s_time_gran = 1; 4909 #ifdef CONFIG_TMPFS_XATTR 4910 sb->s_xattr = shmem_xattr_handlers; 4911 #endif 4912 #ifdef CONFIG_TMPFS_POSIX_ACL 4913 sb->s_flags |= SB_POSIXACL; 4914 #endif 4915 uuid_t uuid; 4916 uuid_gen(&uuid); 4917 super_set_uuid(sb, uuid.b, sizeof(uuid)); 4918 4919 #ifdef CONFIG_TMPFS_QUOTA 4920 if (ctx->seen & SHMEM_SEEN_QUOTA) { 4921 sb->dq_op = &shmem_quota_operations; 4922 sb->s_qcop = &dquot_quotactl_sysfile_ops; 4923 sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP; 4924 4925 /* Copy the default limits from ctx into sbinfo */ 4926 memcpy(&sbinfo->qlimits, &ctx->qlimits, 4927 sizeof(struct shmem_quota_limits)); 4928 4929 if (shmem_enable_quotas(sb, ctx->quota_types)) 4930 goto failed; 4931 } 4932 #endif /* CONFIG_TMPFS_QUOTA */ 4933 4934 inode = shmem_get_inode(&nop_mnt_idmap, sb, NULL, 4935 S_IFDIR | sbinfo->mode, 0, VM_NORESERVE); 4936 if (IS_ERR(inode)) { 4937 error = PTR_ERR(inode); 4938 goto failed; 4939 } 4940 inode->i_uid = sbinfo->uid; 4941 inode->i_gid = sbinfo->gid; 4942 sb->s_root = d_make_root(inode); 4943 if (!sb->s_root) 4944 goto failed; 4945 return 0; 4946 4947 failed: 4948 shmem_put_super(sb); 4949 return error; 4950 } 4951 4952 static int shmem_get_tree(struct fs_context *fc) 4953 { 4954 return get_tree_nodev(fc, shmem_fill_super); 4955 } 4956 4957 static void shmem_free_fc(struct fs_context *fc) 4958 { 4959 struct shmem_options *ctx = fc->fs_private; 4960 4961 if (ctx) { 4962 mpol_put(ctx->mpol); 4963 kfree(ctx); 4964 } 4965 } 4966 4967 static const struct fs_context_operations shmem_fs_context_ops = { 4968 .free = shmem_free_fc, 4969 .get_tree = shmem_get_tree, 4970 #ifdef CONFIG_TMPFS 4971 .parse_monolithic = shmem_parse_options, 4972 .parse_param = shmem_parse_one, 4973 .reconfigure = shmem_reconfigure, 4974 #endif 4975 }; 4976 4977 static struct kmem_cache *shmem_inode_cachep __ro_after_init; 4978 4979 static struct inode *shmem_alloc_inode(struct super_block *sb) 4980 { 4981 struct shmem_inode_info *info; 4982 info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL); 4983 if (!info) 4984 return NULL; 4985 return &info->vfs_inode; 4986 } 4987 4988 static void shmem_free_in_core_inode(struct inode *inode) 4989 { 4990 if (S_ISLNK(inode->i_mode)) 4991 kfree(inode->i_link); 4992 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode)); 4993 } 4994 4995 static void shmem_destroy_inode(struct inode *inode) 4996 { 4997 if (S_ISREG(inode->i_mode)) 4998 mpol_free_shared_policy(&SHMEM_I(inode)->policy); 4999 if (S_ISDIR(inode->i_mode)) 5000 simple_offset_destroy(shmem_get_offset_ctx(inode)); 5001 } 5002 5003 static void shmem_init_inode(void *foo) 5004 { 5005 struct shmem_inode_info *info = foo; 5006 inode_init_once(&info->vfs_inode); 5007 } 5008 5009 static void __init shmem_init_inodecache(void) 5010 { 5011 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache", 5012 sizeof(struct shmem_inode_info), 5013 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode); 5014 } 5015 5016 static void __init shmem_destroy_inodecache(void) 5017 { 5018 kmem_cache_destroy(shmem_inode_cachep); 5019 } 5020 5021 /* Keep the page in page cache instead of truncating it */ 5022 static int shmem_error_remove_folio(struct address_space *mapping, 5023 struct folio *folio) 5024 { 5025 return 0; 5026 } 5027 5028 static const struct address_space_operations shmem_aops = { 5029 .writepage = shmem_writepage, 5030 .dirty_folio = noop_dirty_folio, 5031 #ifdef CONFIG_TMPFS 5032 .write_begin = shmem_write_begin, 5033 .write_end = shmem_write_end, 5034 #endif 5035 #ifdef CONFIG_MIGRATION 5036 .migrate_folio = migrate_folio, 5037 #endif 5038 .error_remove_folio = shmem_error_remove_folio, 5039 }; 5040 5041 static const struct file_operations shmem_file_operations = { 5042 .mmap = shmem_mmap, 5043 .open = shmem_file_open, 5044 .get_unmapped_area = shmem_get_unmapped_area, 5045 #ifdef CONFIG_TMPFS 5046 .llseek = shmem_file_llseek, 5047 .read_iter = shmem_file_read_iter, 5048 .write_iter = shmem_file_write_iter, 5049 .fsync = noop_fsync, 5050 .splice_read = shmem_file_splice_read, 5051 .splice_write = iter_file_splice_write, 5052 .fallocate = shmem_fallocate, 5053 #endif 5054 }; 5055 5056 static const struct inode_operations shmem_inode_operations = { 5057 .getattr = shmem_getattr, 5058 .setattr = shmem_setattr, 5059 #ifdef CONFIG_TMPFS_XATTR 5060 .listxattr = shmem_listxattr, 5061 .set_acl = simple_set_acl, 5062 .fileattr_get = shmem_fileattr_get, 5063 .fileattr_set = shmem_fileattr_set, 5064 #endif 5065 }; 5066 5067 static const struct inode_operations shmem_dir_inode_operations = { 5068 #ifdef CONFIG_TMPFS 5069 .getattr = shmem_getattr, 5070 .create = shmem_create, 5071 .lookup = simple_lookup, 5072 .link = shmem_link, 5073 .unlink = shmem_unlink, 5074 .symlink = shmem_symlink, 5075 .mkdir = shmem_mkdir, 5076 .rmdir = shmem_rmdir, 5077 .mknod = shmem_mknod, 5078 .rename = shmem_rename2, 5079 .tmpfile = shmem_tmpfile, 5080 .get_offset_ctx = shmem_get_offset_ctx, 5081 #endif 5082 #ifdef CONFIG_TMPFS_XATTR 5083 .listxattr = shmem_listxattr, 5084 .fileattr_get = shmem_fileattr_get, 5085 .fileattr_set = shmem_fileattr_set, 5086 #endif 5087 #ifdef CONFIG_TMPFS_POSIX_ACL 5088 .setattr = shmem_setattr, 5089 .set_acl = simple_set_acl, 5090 #endif 5091 }; 5092 5093 static const struct inode_operations shmem_special_inode_operations = { 5094 .getattr = shmem_getattr, 5095 #ifdef CONFIG_TMPFS_XATTR 5096 .listxattr = shmem_listxattr, 5097 #endif 5098 #ifdef CONFIG_TMPFS_POSIX_ACL 5099 .setattr = shmem_setattr, 5100 .set_acl = simple_set_acl, 5101 #endif 5102 }; 5103 5104 static const struct super_operations shmem_ops = { 5105 .alloc_inode = shmem_alloc_inode, 5106 .free_inode = shmem_free_in_core_inode, 5107 .destroy_inode = shmem_destroy_inode, 5108 #ifdef CONFIG_TMPFS 5109 .statfs = shmem_statfs, 5110 .show_options = shmem_show_options, 5111 #endif 5112 #ifdef CONFIG_TMPFS_QUOTA 5113 .get_dquots = shmem_get_dquots, 5114 #endif 5115 .evict_inode = shmem_evict_inode, 5116 .drop_inode = generic_delete_inode, 5117 .put_super = shmem_put_super, 5118 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5119 .nr_cached_objects = shmem_unused_huge_count, 5120 .free_cached_objects = shmem_unused_huge_scan, 5121 #endif 5122 }; 5123 5124 static const struct vm_operations_struct shmem_vm_ops = { 5125 .fault = shmem_fault, 5126 .map_pages = filemap_map_pages, 5127 #ifdef CONFIG_NUMA 5128 .set_policy = shmem_set_policy, 5129 .get_policy = shmem_get_policy, 5130 #endif 5131 }; 5132 5133 static const struct vm_operations_struct shmem_anon_vm_ops = { 5134 .fault = shmem_fault, 5135 .map_pages = filemap_map_pages, 5136 #ifdef CONFIG_NUMA 5137 .set_policy = shmem_set_policy, 5138 .get_policy = shmem_get_policy, 5139 #endif 5140 }; 5141 5142 int shmem_init_fs_context(struct fs_context *fc) 5143 { 5144 struct shmem_options *ctx; 5145 5146 ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL); 5147 if (!ctx) 5148 return -ENOMEM; 5149 5150 ctx->mode = 0777 | S_ISVTX; 5151 ctx->uid = current_fsuid(); 5152 ctx->gid = current_fsgid(); 5153 5154 #if IS_ENABLED(CONFIG_UNICODE) 5155 ctx->encoding = NULL; 5156 #endif 5157 5158 fc->fs_private = ctx; 5159 fc->ops = &shmem_fs_context_ops; 5160 return 0; 5161 } 5162 5163 static struct file_system_type shmem_fs_type = { 5164 .owner = THIS_MODULE, 5165 .name = "tmpfs", 5166 .init_fs_context = shmem_init_fs_context, 5167 #ifdef CONFIG_TMPFS 5168 .parameters = shmem_fs_parameters, 5169 #endif 5170 .kill_sb = kill_litter_super, 5171 .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME, 5172 }; 5173 5174 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5175 5176 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \ 5177 { \ 5178 .attr = { .name = __stringify(_name), .mode = _mode }, \ 5179 .show = _show, \ 5180 .store = _store, \ 5181 } 5182 5183 #define TMPFS_ATTR_W(_name, _store) \ 5184 static struct kobj_attribute tmpfs_attr_##_name = \ 5185 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store) 5186 5187 #define TMPFS_ATTR_RW(_name, _show, _store) \ 5188 static struct kobj_attribute tmpfs_attr_##_name = \ 5189 __INIT_KOBJ_ATTR(_name, 0644, _show, _store) 5190 5191 #define TMPFS_ATTR_RO(_name, _show) \ 5192 static struct kobj_attribute tmpfs_attr_##_name = \ 5193 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL) 5194 5195 #if IS_ENABLED(CONFIG_UNICODE) 5196 static ssize_t casefold_show(struct kobject *kobj, struct kobj_attribute *a, 5197 char *buf) 5198 { 5199 return sysfs_emit(buf, "supported\n"); 5200 } 5201 TMPFS_ATTR_RO(casefold, casefold_show); 5202 #endif 5203 5204 static struct attribute *tmpfs_attributes[] = { 5205 #if IS_ENABLED(CONFIG_UNICODE) 5206 &tmpfs_attr_casefold.attr, 5207 #endif 5208 NULL 5209 }; 5210 5211 static const struct attribute_group tmpfs_attribute_group = { 5212 .attrs = tmpfs_attributes, 5213 .name = "features" 5214 }; 5215 5216 static struct kobject *tmpfs_kobj; 5217 5218 static int __init tmpfs_sysfs_init(void) 5219 { 5220 int ret; 5221 5222 tmpfs_kobj = kobject_create_and_add("tmpfs", fs_kobj); 5223 if (!tmpfs_kobj) 5224 return -ENOMEM; 5225 5226 ret = sysfs_create_group(tmpfs_kobj, &tmpfs_attribute_group); 5227 if (ret) 5228 kobject_put(tmpfs_kobj); 5229 5230 return ret; 5231 } 5232 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */ 5233 5234 void __init shmem_init(void) 5235 { 5236 int error; 5237 5238 shmem_init_inodecache(); 5239 5240 #ifdef CONFIG_TMPFS_QUOTA 5241 register_quota_format(&shmem_quota_format); 5242 #endif 5243 5244 error = register_filesystem(&shmem_fs_type); 5245 if (error) { 5246 pr_err("Could not register tmpfs\n"); 5247 goto out2; 5248 } 5249 5250 shm_mnt = kern_mount(&shmem_fs_type); 5251 if (IS_ERR(shm_mnt)) { 5252 error = PTR_ERR(shm_mnt); 5253 pr_err("Could not kern_mount tmpfs\n"); 5254 goto out1; 5255 } 5256 5257 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5258 error = tmpfs_sysfs_init(); 5259 if (error) { 5260 pr_err("Could not init tmpfs sysfs\n"); 5261 goto out1; 5262 } 5263 #endif 5264 5265 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5266 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY) 5267 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5268 else 5269 shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */ 5270 5271 /* 5272 * Default to setting PMD-sized THP to inherit the global setting and 5273 * disable all other multi-size THPs. 5274 */ 5275 if (!shmem_orders_configured) 5276 huge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER); 5277 #endif 5278 return; 5279 5280 out1: 5281 unregister_filesystem(&shmem_fs_type); 5282 out2: 5283 #ifdef CONFIG_TMPFS_QUOTA 5284 unregister_quota_format(&shmem_quota_format); 5285 #endif 5286 shmem_destroy_inodecache(); 5287 shm_mnt = ERR_PTR(error); 5288 } 5289 5290 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS) 5291 static ssize_t shmem_enabled_show(struct kobject *kobj, 5292 struct kobj_attribute *attr, char *buf) 5293 { 5294 static const int values[] = { 5295 SHMEM_HUGE_ALWAYS, 5296 SHMEM_HUGE_WITHIN_SIZE, 5297 SHMEM_HUGE_ADVISE, 5298 SHMEM_HUGE_NEVER, 5299 SHMEM_HUGE_DENY, 5300 SHMEM_HUGE_FORCE, 5301 }; 5302 int len = 0; 5303 int i; 5304 5305 for (i = 0; i < ARRAY_SIZE(values); i++) { 5306 len += sysfs_emit_at(buf, len, 5307 shmem_huge == values[i] ? "%s[%s]" : "%s%s", 5308 i ? " " : "", shmem_format_huge(values[i])); 5309 } 5310 len += sysfs_emit_at(buf, len, "\n"); 5311 5312 return len; 5313 } 5314 5315 static ssize_t shmem_enabled_store(struct kobject *kobj, 5316 struct kobj_attribute *attr, const char *buf, size_t count) 5317 { 5318 char tmp[16]; 5319 int huge, err; 5320 5321 if (count + 1 > sizeof(tmp)) 5322 return -EINVAL; 5323 memcpy(tmp, buf, count); 5324 tmp[count] = '\0'; 5325 if (count && tmp[count - 1] == '\n') 5326 tmp[count - 1] = '\0'; 5327 5328 huge = shmem_parse_huge(tmp); 5329 if (huge == -EINVAL) 5330 return huge; 5331 5332 shmem_huge = huge; 5333 if (shmem_huge > SHMEM_HUGE_DENY) 5334 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5335 5336 err = start_stop_khugepaged(); 5337 return err ? err : count; 5338 } 5339 5340 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled); 5341 static DEFINE_SPINLOCK(huge_shmem_orders_lock); 5342 5343 static ssize_t thpsize_shmem_enabled_show(struct kobject *kobj, 5344 struct kobj_attribute *attr, char *buf) 5345 { 5346 int order = to_thpsize(kobj)->order; 5347 const char *output; 5348 5349 if (test_bit(order, &huge_shmem_orders_always)) 5350 output = "[always] inherit within_size advise never"; 5351 else if (test_bit(order, &huge_shmem_orders_inherit)) 5352 output = "always [inherit] within_size advise never"; 5353 else if (test_bit(order, &huge_shmem_orders_within_size)) 5354 output = "always inherit [within_size] advise never"; 5355 else if (test_bit(order, &huge_shmem_orders_madvise)) 5356 output = "always inherit within_size [advise] never"; 5357 else 5358 output = "always inherit within_size advise [never]"; 5359 5360 return sysfs_emit(buf, "%s\n", output); 5361 } 5362 5363 static ssize_t thpsize_shmem_enabled_store(struct kobject *kobj, 5364 struct kobj_attribute *attr, 5365 const char *buf, size_t count) 5366 { 5367 int order = to_thpsize(kobj)->order; 5368 ssize_t ret = count; 5369 5370 if (sysfs_streq(buf, "always")) { 5371 spin_lock(&huge_shmem_orders_lock); 5372 clear_bit(order, &huge_shmem_orders_inherit); 5373 clear_bit(order, &huge_shmem_orders_madvise); 5374 clear_bit(order, &huge_shmem_orders_within_size); 5375 set_bit(order, &huge_shmem_orders_always); 5376 spin_unlock(&huge_shmem_orders_lock); 5377 } else if (sysfs_streq(buf, "inherit")) { 5378 /* Do not override huge allocation policy with non-PMD sized mTHP */ 5379 if (shmem_huge == SHMEM_HUGE_FORCE && 5380 order != HPAGE_PMD_ORDER) 5381 return -EINVAL; 5382 5383 spin_lock(&huge_shmem_orders_lock); 5384 clear_bit(order, &huge_shmem_orders_always); 5385 clear_bit(order, &huge_shmem_orders_madvise); 5386 clear_bit(order, &huge_shmem_orders_within_size); 5387 set_bit(order, &huge_shmem_orders_inherit); 5388 spin_unlock(&huge_shmem_orders_lock); 5389 } else if (sysfs_streq(buf, "within_size")) { 5390 spin_lock(&huge_shmem_orders_lock); 5391 clear_bit(order, &huge_shmem_orders_always); 5392 clear_bit(order, &huge_shmem_orders_inherit); 5393 clear_bit(order, &huge_shmem_orders_madvise); 5394 set_bit(order, &huge_shmem_orders_within_size); 5395 spin_unlock(&huge_shmem_orders_lock); 5396 } else if (sysfs_streq(buf, "advise")) { 5397 spin_lock(&huge_shmem_orders_lock); 5398 clear_bit(order, &huge_shmem_orders_always); 5399 clear_bit(order, &huge_shmem_orders_inherit); 5400 clear_bit(order, &huge_shmem_orders_within_size); 5401 set_bit(order, &huge_shmem_orders_madvise); 5402 spin_unlock(&huge_shmem_orders_lock); 5403 } else if (sysfs_streq(buf, "never")) { 5404 spin_lock(&huge_shmem_orders_lock); 5405 clear_bit(order, &huge_shmem_orders_always); 5406 clear_bit(order, &huge_shmem_orders_inherit); 5407 clear_bit(order, &huge_shmem_orders_within_size); 5408 clear_bit(order, &huge_shmem_orders_madvise); 5409 spin_unlock(&huge_shmem_orders_lock); 5410 } else { 5411 ret = -EINVAL; 5412 } 5413 5414 if (ret > 0) { 5415 int err = start_stop_khugepaged(); 5416 5417 if (err) 5418 ret = err; 5419 } 5420 return ret; 5421 } 5422 5423 struct kobj_attribute thpsize_shmem_enabled_attr = 5424 __ATTR(shmem_enabled, 0644, thpsize_shmem_enabled_show, thpsize_shmem_enabled_store); 5425 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */ 5426 5427 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) 5428 5429 static int __init setup_transparent_hugepage_shmem(char *str) 5430 { 5431 int huge; 5432 5433 huge = shmem_parse_huge(str); 5434 if (huge == -EINVAL) { 5435 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n"); 5436 return huge; 5437 } 5438 5439 shmem_huge = huge; 5440 return 1; 5441 } 5442 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem); 5443 5444 static char str_dup[PAGE_SIZE] __initdata; 5445 static int __init setup_thp_shmem(char *str) 5446 { 5447 char *token, *range, *policy, *subtoken; 5448 unsigned long always, inherit, madvise, within_size; 5449 char *start_size, *end_size; 5450 int start, end, nr; 5451 char *p; 5452 5453 if (!str || strlen(str) + 1 > PAGE_SIZE) 5454 goto err; 5455 strscpy(str_dup, str); 5456 5457 always = huge_shmem_orders_always; 5458 inherit = huge_shmem_orders_inherit; 5459 madvise = huge_shmem_orders_madvise; 5460 within_size = huge_shmem_orders_within_size; 5461 p = str_dup; 5462 while ((token = strsep(&p, ";")) != NULL) { 5463 range = strsep(&token, ":"); 5464 policy = token; 5465 5466 if (!policy) 5467 goto err; 5468 5469 while ((subtoken = strsep(&range, ",")) != NULL) { 5470 if (strchr(subtoken, '-')) { 5471 start_size = strsep(&subtoken, "-"); 5472 end_size = subtoken; 5473 5474 start = get_order_from_str(start_size, 5475 THP_ORDERS_ALL_FILE_DEFAULT); 5476 end = get_order_from_str(end_size, 5477 THP_ORDERS_ALL_FILE_DEFAULT); 5478 } else { 5479 start_size = end_size = subtoken; 5480 start = end = get_order_from_str(subtoken, 5481 THP_ORDERS_ALL_FILE_DEFAULT); 5482 } 5483 5484 if (start == -EINVAL) { 5485 pr_err("invalid size %s in thp_shmem boot parameter\n", 5486 start_size); 5487 goto err; 5488 } 5489 5490 if (end == -EINVAL) { 5491 pr_err("invalid size %s in thp_shmem boot parameter\n", 5492 end_size); 5493 goto err; 5494 } 5495 5496 if (start < 0 || end < 0 || start > end) 5497 goto err; 5498 5499 nr = end - start + 1; 5500 if (!strcmp(policy, "always")) { 5501 bitmap_set(&always, start, nr); 5502 bitmap_clear(&inherit, start, nr); 5503 bitmap_clear(&madvise, start, nr); 5504 bitmap_clear(&within_size, start, nr); 5505 } else if (!strcmp(policy, "advise")) { 5506 bitmap_set(&madvise, start, nr); 5507 bitmap_clear(&inherit, start, nr); 5508 bitmap_clear(&always, start, nr); 5509 bitmap_clear(&within_size, start, nr); 5510 } else if (!strcmp(policy, "inherit")) { 5511 bitmap_set(&inherit, start, nr); 5512 bitmap_clear(&madvise, start, nr); 5513 bitmap_clear(&always, start, nr); 5514 bitmap_clear(&within_size, start, nr); 5515 } else if (!strcmp(policy, "within_size")) { 5516 bitmap_set(&within_size, start, nr); 5517 bitmap_clear(&inherit, start, nr); 5518 bitmap_clear(&madvise, start, nr); 5519 bitmap_clear(&always, start, nr); 5520 } else if (!strcmp(policy, "never")) { 5521 bitmap_clear(&inherit, start, nr); 5522 bitmap_clear(&madvise, start, nr); 5523 bitmap_clear(&always, start, nr); 5524 bitmap_clear(&within_size, start, nr); 5525 } else { 5526 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy); 5527 goto err; 5528 } 5529 } 5530 } 5531 5532 huge_shmem_orders_always = always; 5533 huge_shmem_orders_madvise = madvise; 5534 huge_shmem_orders_inherit = inherit; 5535 huge_shmem_orders_within_size = within_size; 5536 shmem_orders_configured = true; 5537 return 1; 5538 5539 err: 5540 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str); 5541 return 0; 5542 } 5543 __setup("thp_shmem=", setup_thp_shmem); 5544 5545 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 5546 5547 #else /* !CONFIG_SHMEM */ 5548 5549 /* 5550 * tiny-shmem: simple shmemfs and tmpfs using ramfs code 5551 * 5552 * This is intended for small system where the benefits of the full 5553 * shmem code (swap-backed and resource-limited) are outweighed by 5554 * their complexity. On systems without swap this code should be 5555 * effectively equivalent, but much lighter weight. 5556 */ 5557 5558 static struct file_system_type shmem_fs_type = { 5559 .name = "tmpfs", 5560 .init_fs_context = ramfs_init_fs_context, 5561 .parameters = ramfs_fs_parameters, 5562 .kill_sb = ramfs_kill_sb, 5563 .fs_flags = FS_USERNS_MOUNT, 5564 }; 5565 5566 void __init shmem_init(void) 5567 { 5568 BUG_ON(register_filesystem(&shmem_fs_type) != 0); 5569 5570 shm_mnt = kern_mount(&shmem_fs_type); 5571 BUG_ON(IS_ERR(shm_mnt)); 5572 } 5573 5574 int shmem_unuse(unsigned int type) 5575 { 5576 return 0; 5577 } 5578 5579 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 5580 { 5581 return 0; 5582 } 5583 5584 void shmem_unlock_mapping(struct address_space *mapping) 5585 { 5586 } 5587 5588 #ifdef CONFIG_MMU 5589 unsigned long shmem_get_unmapped_area(struct file *file, 5590 unsigned long addr, unsigned long len, 5591 unsigned long pgoff, unsigned long flags) 5592 { 5593 return mm_get_unmapped_area(current->mm, file, addr, len, pgoff, flags); 5594 } 5595 #endif 5596 5597 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 5598 { 5599 truncate_inode_pages_range(inode->i_mapping, lstart, lend); 5600 } 5601 EXPORT_SYMBOL_GPL(shmem_truncate_range); 5602 5603 #define shmem_vm_ops generic_file_vm_ops 5604 #define shmem_anon_vm_ops generic_file_vm_ops 5605 #define shmem_file_operations ramfs_file_operations 5606 #define shmem_acct_size(flags, size) 0 5607 #define shmem_unacct_size(flags, size) do {} while (0) 5608 5609 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap, 5610 struct super_block *sb, struct inode *dir, 5611 umode_t mode, dev_t dev, unsigned long flags) 5612 { 5613 struct inode *inode = ramfs_get_inode(sb, dir, mode, dev); 5614 return inode ? inode : ERR_PTR(-ENOSPC); 5615 } 5616 5617 #endif /* CONFIG_SHMEM */ 5618 5619 /* common code */ 5620 5621 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, 5622 loff_t size, unsigned long flags, unsigned int i_flags) 5623 { 5624 struct inode *inode; 5625 struct file *res; 5626 5627 if (IS_ERR(mnt)) 5628 return ERR_CAST(mnt); 5629 5630 if (size < 0 || size > MAX_LFS_FILESIZE) 5631 return ERR_PTR(-EINVAL); 5632 5633 if (shmem_acct_size(flags, size)) 5634 return ERR_PTR(-ENOMEM); 5635 5636 if (is_idmapped_mnt(mnt)) 5637 return ERR_PTR(-EINVAL); 5638 5639 inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL, 5640 S_IFREG | S_IRWXUGO, 0, flags); 5641 if (IS_ERR(inode)) { 5642 shmem_unacct_size(flags, size); 5643 return ERR_CAST(inode); 5644 } 5645 inode->i_flags |= i_flags; 5646 inode->i_size = size; 5647 clear_nlink(inode); /* It is unlinked */ 5648 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size)); 5649 if (!IS_ERR(res)) 5650 res = alloc_file_pseudo(inode, mnt, name, O_RDWR, 5651 &shmem_file_operations); 5652 if (IS_ERR(res)) 5653 iput(inode); 5654 return res; 5655 } 5656 5657 /** 5658 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be 5659 * kernel internal. There will be NO LSM permission checks against the 5660 * underlying inode. So users of this interface must do LSM checks at a 5661 * higher layer. The users are the big_key and shm implementations. LSM 5662 * checks are provided at the key or shm level rather than the inode. 5663 * @name: name for dentry (to be seen in /proc/<pid>/maps 5664 * @size: size to be set for the file 5665 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5666 */ 5667 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags) 5668 { 5669 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE); 5670 } 5671 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup); 5672 5673 /** 5674 * shmem_file_setup - get an unlinked file living in tmpfs 5675 * @name: name for dentry (to be seen in /proc/<pid>/maps 5676 * @size: size to be set for the file 5677 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5678 */ 5679 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags) 5680 { 5681 return __shmem_file_setup(shm_mnt, name, size, flags, 0); 5682 } 5683 EXPORT_SYMBOL_GPL(shmem_file_setup); 5684 5685 /** 5686 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs 5687 * @mnt: the tmpfs mount where the file will be created 5688 * @name: name for dentry (to be seen in /proc/<pid>/maps 5689 * @size: size to be set for the file 5690 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5691 */ 5692 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name, 5693 loff_t size, unsigned long flags) 5694 { 5695 return __shmem_file_setup(mnt, name, size, flags, 0); 5696 } 5697 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt); 5698 5699 /** 5700 * shmem_zero_setup - setup a shared anonymous mapping 5701 * @vma: the vma to be mmapped is prepared by do_mmap 5702 */ 5703 int shmem_zero_setup(struct vm_area_struct *vma) 5704 { 5705 struct file *file; 5706 loff_t size = vma->vm_end - vma->vm_start; 5707 5708 /* 5709 * Cloning a new file under mmap_lock leads to a lock ordering conflict 5710 * between XFS directory reading and selinux: since this file is only 5711 * accessible to the user through its mapping, use S_PRIVATE flag to 5712 * bypass file security, in the same way as shmem_kernel_file_setup(). 5713 */ 5714 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags); 5715 if (IS_ERR(file)) 5716 return PTR_ERR(file); 5717 5718 if (vma->vm_file) 5719 fput(vma->vm_file); 5720 vma->vm_file = file; 5721 vma->vm_ops = &shmem_anon_vm_ops; 5722 5723 return 0; 5724 } 5725 5726 /** 5727 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags. 5728 * @mapping: the folio's address_space 5729 * @index: the folio index 5730 * @gfp: the page allocator flags to use if allocating 5731 * 5732 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)", 5733 * with any new page allocations done using the specified allocation flags. 5734 * But read_cache_page_gfp() uses the ->read_folio() method: which does not 5735 * suit tmpfs, since it may have pages in swapcache, and needs to find those 5736 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support. 5737 * 5738 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in 5739 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily. 5740 */ 5741 struct folio *shmem_read_folio_gfp(struct address_space *mapping, 5742 pgoff_t index, gfp_t gfp) 5743 { 5744 #ifdef CONFIG_SHMEM 5745 struct inode *inode = mapping->host; 5746 struct folio *folio; 5747 int error; 5748 5749 error = shmem_get_folio_gfp(inode, index, 0, &folio, SGP_CACHE, 5750 gfp, NULL, NULL); 5751 if (error) 5752 return ERR_PTR(error); 5753 5754 folio_unlock(folio); 5755 return folio; 5756 #else 5757 /* 5758 * The tiny !SHMEM case uses ramfs without swap 5759 */ 5760 return mapping_read_folio_gfp(mapping, index, gfp); 5761 #endif 5762 } 5763 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp); 5764 5765 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping, 5766 pgoff_t index, gfp_t gfp) 5767 { 5768 struct folio *folio = shmem_read_folio_gfp(mapping, index, gfp); 5769 struct page *page; 5770 5771 if (IS_ERR(folio)) 5772 return &folio->page; 5773 5774 page = folio_file_page(folio, index); 5775 if (PageHWPoison(page)) { 5776 folio_put(folio); 5777 return ERR_PTR(-EIO); 5778 } 5779 5780 return page; 5781 } 5782 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp); 5783