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