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