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