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