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