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