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