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