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 pgoff_t index; 1537 int nr_pages; 1538 bool split = false; 1539 1540 /* 1541 * Our capabilities prevent regular writeback or sync from ever calling 1542 * shmem_writepage; but a stacking filesystem might use ->writepage of 1543 * its underlying filesystem, in which case tmpfs should write out to 1544 * swap only in response to memory pressure, and not for the writeback 1545 * threads or sync. 1546 */ 1547 if (WARN_ON_ONCE(!wbc->for_reclaim)) 1548 goto redirty; 1549 1550 if ((info->flags & VM_LOCKED) || sbinfo->noswap) 1551 goto redirty; 1552 1553 if (!total_swap_pages) 1554 goto redirty; 1555 1556 /* 1557 * If CONFIG_THP_SWAP is not enabled, the large folio should be 1558 * split when swapping. 1559 * 1560 * And shrinkage of pages beyond i_size does not split swap, so 1561 * swapout of a large folio crossing i_size needs to split too 1562 * (unless fallocate has been used to preallocate beyond EOF). 1563 */ 1564 if (folio_test_large(folio)) { 1565 index = shmem_fallocend(inode, 1566 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE)); 1567 if ((index > folio->index && index < folio_next_index(folio)) || 1568 !IS_ENABLED(CONFIG_THP_SWAP)) 1569 split = true; 1570 } 1571 1572 if (split) { 1573 try_split: 1574 /* Ensure the subpages are still dirty */ 1575 folio_test_set_dirty(folio); 1576 if (split_huge_page_to_list_to_order(page, wbc->list, 0)) 1577 goto redirty; 1578 folio = page_folio(page); 1579 folio_clear_dirty(folio); 1580 } 1581 1582 index = folio->index; 1583 nr_pages = folio_nr_pages(folio); 1584 1585 /* 1586 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC 1587 * value into swapfile.c, the only way we can correctly account for a 1588 * fallocated folio arriving here is now to initialize it and write it. 1589 * 1590 * That's okay for a folio already fallocated earlier, but if we have 1591 * not yet completed the fallocation, then (a) we want to keep track 1592 * of this folio in case we have to undo it, and (b) it may not be a 1593 * good idea to continue anyway, once we're pushing into swap. So 1594 * reactivate the folio, and let shmem_fallocate() quit when too many. 1595 */ 1596 if (!folio_test_uptodate(folio)) { 1597 if (inode->i_private) { 1598 struct shmem_falloc *shmem_falloc; 1599 spin_lock(&inode->i_lock); 1600 shmem_falloc = inode->i_private; 1601 if (shmem_falloc && 1602 !shmem_falloc->waitq && 1603 index >= shmem_falloc->start && 1604 index < shmem_falloc->next) 1605 shmem_falloc->nr_unswapped += nr_pages; 1606 else 1607 shmem_falloc = NULL; 1608 spin_unlock(&inode->i_lock); 1609 if (shmem_falloc) 1610 goto redirty; 1611 } 1612 folio_zero_range(folio, 0, folio_size(folio)); 1613 flush_dcache_folio(folio); 1614 folio_mark_uptodate(folio); 1615 } 1616 1617 /* 1618 * Add inode to shmem_unuse()'s list of swapped-out inodes, 1619 * if it's not already there. Do it now before the folio is 1620 * moved to swap cache, when its pagelock no longer protects 1621 * the inode from eviction. But don't unlock the mutex until 1622 * we've incremented swapped, because shmem_unuse_inode() will 1623 * prune a !swapped inode from the swaplist under this mutex. 1624 */ 1625 mutex_lock(&shmem_swaplist_mutex); 1626 if (list_empty(&info->swaplist)) 1627 list_add(&info->swaplist, &shmem_swaplist); 1628 1629 if (!folio_alloc_swap(folio, __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN)) { 1630 shmem_recalc_inode(inode, 0, nr_pages); 1631 swap_shmem_alloc(folio->swap, nr_pages); 1632 shmem_delete_from_page_cache(folio, swp_to_radix_entry(folio->swap)); 1633 1634 mutex_unlock(&shmem_swaplist_mutex); 1635 BUG_ON(folio_mapped(folio)); 1636 return swap_writepage(&folio->page, wbc); 1637 } 1638 1639 list_del_init(&info->swaplist); 1640 mutex_unlock(&shmem_swaplist_mutex); 1641 if (nr_pages > 1) 1642 goto try_split; 1643 redirty: 1644 folio_mark_dirty(folio); 1645 if (wbc->for_reclaim) 1646 return AOP_WRITEPAGE_ACTIVATE; /* Return with folio locked */ 1647 folio_unlock(folio); 1648 return 0; 1649 } 1650 1651 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS) 1652 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1653 { 1654 char buffer[64]; 1655 1656 if (!mpol || mpol->mode == MPOL_DEFAULT) 1657 return; /* show nothing */ 1658 1659 mpol_to_str(buffer, sizeof(buffer), mpol); 1660 1661 seq_printf(seq, ",mpol=%s", buffer); 1662 } 1663 1664 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1665 { 1666 struct mempolicy *mpol = NULL; 1667 if (sbinfo->mpol) { 1668 raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */ 1669 mpol = sbinfo->mpol; 1670 mpol_get(mpol); 1671 raw_spin_unlock(&sbinfo->stat_lock); 1672 } 1673 return mpol; 1674 } 1675 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */ 1676 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1677 { 1678 } 1679 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1680 { 1681 return NULL; 1682 } 1683 #endif /* CONFIG_NUMA && CONFIG_TMPFS */ 1684 1685 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 1686 pgoff_t index, unsigned int order, pgoff_t *ilx); 1687 1688 static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp, 1689 struct shmem_inode_info *info, pgoff_t index) 1690 { 1691 struct mempolicy *mpol; 1692 pgoff_t ilx; 1693 struct folio *folio; 1694 1695 mpol = shmem_get_pgoff_policy(info, index, 0, &ilx); 1696 folio = swap_cluster_readahead(swap, gfp, mpol, ilx); 1697 mpol_cond_put(mpol); 1698 1699 return folio; 1700 } 1701 1702 /* 1703 * Make sure huge_gfp is always more limited than limit_gfp. 1704 * Some of the flags set permissions, while others set limitations. 1705 */ 1706 static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp) 1707 { 1708 gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM; 1709 gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY; 1710 gfp_t zoneflags = limit_gfp & GFP_ZONEMASK; 1711 gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK); 1712 1713 /* Allow allocations only from the originally specified zones. */ 1714 result |= zoneflags; 1715 1716 /* 1717 * Minimize the result gfp by taking the union with the deny flags, 1718 * and the intersection of the allow flags. 1719 */ 1720 result |= (limit_gfp & denyflags); 1721 result |= (huge_gfp & limit_gfp) & allowflags; 1722 1723 return result; 1724 } 1725 1726 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1727 bool shmem_hpage_pmd_enabled(void) 1728 { 1729 if (shmem_huge == SHMEM_HUGE_DENY) 1730 return false; 1731 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always)) 1732 return true; 1733 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise)) 1734 return true; 1735 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size)) 1736 return true; 1737 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) && 1738 shmem_huge != SHMEM_HUGE_NEVER) 1739 return true; 1740 1741 return false; 1742 } 1743 1744 unsigned long shmem_allowable_huge_orders(struct inode *inode, 1745 struct vm_area_struct *vma, pgoff_t index, 1746 loff_t write_end, bool shmem_huge_force) 1747 { 1748 unsigned long mask = READ_ONCE(huge_shmem_orders_always); 1749 unsigned long within_size_orders = READ_ONCE(huge_shmem_orders_within_size); 1750 unsigned long vm_flags = vma ? vma->vm_flags : 0; 1751 pgoff_t aligned_index; 1752 unsigned int global_orders; 1753 loff_t i_size; 1754 int order; 1755 1756 if (thp_disabled_by_hw() || (vma && vma_thp_disabled(vma, vm_flags))) 1757 return 0; 1758 1759 global_orders = shmem_huge_global_enabled(inode, index, write_end, 1760 shmem_huge_force, vma, vm_flags); 1761 /* Tmpfs huge pages allocation */ 1762 if (!vma || !vma_is_anon_shmem(vma)) 1763 return global_orders; 1764 1765 /* 1766 * Following the 'deny' semantics of the top level, force the huge 1767 * option off from all mounts. 1768 */ 1769 if (shmem_huge == SHMEM_HUGE_DENY) 1770 return 0; 1771 1772 /* 1773 * Only allow inherit orders if the top-level value is 'force', which 1774 * means non-PMD sized THP can not override 'huge' mount option now. 1775 */ 1776 if (shmem_huge == SHMEM_HUGE_FORCE) 1777 return READ_ONCE(huge_shmem_orders_inherit); 1778 1779 /* Allow mTHP that will be fully within i_size. */ 1780 order = highest_order(within_size_orders); 1781 while (within_size_orders) { 1782 aligned_index = round_up(index + 1, 1 << order); 1783 i_size = round_up(i_size_read(inode), PAGE_SIZE); 1784 if (i_size >> PAGE_SHIFT >= aligned_index) { 1785 mask |= within_size_orders; 1786 break; 1787 } 1788 1789 order = next_order(&within_size_orders, order); 1790 } 1791 1792 if (vm_flags & VM_HUGEPAGE) 1793 mask |= READ_ONCE(huge_shmem_orders_madvise); 1794 1795 if (global_orders > 0) 1796 mask |= READ_ONCE(huge_shmem_orders_inherit); 1797 1798 return THP_ORDERS_ALL_FILE_DEFAULT & mask; 1799 } 1800 1801 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf, 1802 struct address_space *mapping, pgoff_t index, 1803 unsigned long orders) 1804 { 1805 struct vm_area_struct *vma = vmf ? vmf->vma : NULL; 1806 pgoff_t aligned_index; 1807 unsigned long pages; 1808 int order; 1809 1810 if (vma) { 1811 orders = thp_vma_suitable_orders(vma, vmf->address, orders); 1812 if (!orders) 1813 return 0; 1814 } 1815 1816 /* Find the highest order that can add into the page cache */ 1817 order = highest_order(orders); 1818 while (orders) { 1819 pages = 1UL << order; 1820 aligned_index = round_down(index, pages); 1821 /* 1822 * Check for conflict before waiting on a huge allocation. 1823 * Conflict might be that a huge page has just been allocated 1824 * and added to page cache by a racing thread, or that there 1825 * is already at least one small page in the huge extent. 1826 * Be careful to retry when appropriate, but not forever! 1827 * Elsewhere -EEXIST would be the right code, but not here. 1828 */ 1829 if (!xa_find(&mapping->i_pages, &aligned_index, 1830 aligned_index + pages - 1, XA_PRESENT)) 1831 break; 1832 order = next_order(&orders, order); 1833 } 1834 1835 return orders; 1836 } 1837 #else 1838 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf, 1839 struct address_space *mapping, pgoff_t index, 1840 unsigned long orders) 1841 { 1842 return 0; 1843 } 1844 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 1845 1846 static struct folio *shmem_alloc_folio(gfp_t gfp, int order, 1847 struct shmem_inode_info *info, pgoff_t index) 1848 { 1849 struct mempolicy *mpol; 1850 pgoff_t ilx; 1851 struct folio *folio; 1852 1853 mpol = shmem_get_pgoff_policy(info, index, order, &ilx); 1854 folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id()); 1855 mpol_cond_put(mpol); 1856 1857 return folio; 1858 } 1859 1860 static struct folio *shmem_alloc_and_add_folio(struct vm_fault *vmf, 1861 gfp_t gfp, struct inode *inode, pgoff_t index, 1862 struct mm_struct *fault_mm, unsigned long orders) 1863 { 1864 struct address_space *mapping = inode->i_mapping; 1865 struct shmem_inode_info *info = SHMEM_I(inode); 1866 unsigned long suitable_orders = 0; 1867 struct folio *folio = NULL; 1868 long pages; 1869 int error, order; 1870 1871 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 1872 orders = 0; 1873 1874 if (orders > 0) { 1875 suitable_orders = shmem_suitable_orders(inode, vmf, 1876 mapping, index, orders); 1877 1878 order = highest_order(suitable_orders); 1879 while (suitable_orders) { 1880 pages = 1UL << order; 1881 index = round_down(index, pages); 1882 folio = shmem_alloc_folio(gfp, order, info, index); 1883 if (folio) 1884 goto allocated; 1885 1886 if (pages == HPAGE_PMD_NR) 1887 count_vm_event(THP_FILE_FALLBACK); 1888 count_mthp_stat(order, MTHP_STAT_SHMEM_FALLBACK); 1889 order = next_order(&suitable_orders, order); 1890 } 1891 } else { 1892 pages = 1; 1893 folio = shmem_alloc_folio(gfp, 0, info, index); 1894 } 1895 if (!folio) 1896 return ERR_PTR(-ENOMEM); 1897 1898 allocated: 1899 __folio_set_locked(folio); 1900 __folio_set_swapbacked(folio); 1901 1902 gfp &= GFP_RECLAIM_MASK; 1903 error = mem_cgroup_charge(folio, fault_mm, gfp); 1904 if (error) { 1905 if (xa_find(&mapping->i_pages, &index, 1906 index + pages - 1, XA_PRESENT)) { 1907 error = -EEXIST; 1908 } else if (pages > 1) { 1909 if (pages == HPAGE_PMD_NR) { 1910 count_vm_event(THP_FILE_FALLBACK); 1911 count_vm_event(THP_FILE_FALLBACK_CHARGE); 1912 } 1913 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK); 1914 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK_CHARGE); 1915 } 1916 goto unlock; 1917 } 1918 1919 error = shmem_add_to_page_cache(folio, mapping, index, NULL, gfp); 1920 if (error) 1921 goto unlock; 1922 1923 error = shmem_inode_acct_blocks(inode, pages); 1924 if (error) { 1925 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 1926 long freed; 1927 /* 1928 * Try to reclaim some space by splitting a few 1929 * large folios beyond i_size on the filesystem. 1930 */ 1931 shmem_unused_huge_shrink(sbinfo, NULL, pages); 1932 /* 1933 * And do a shmem_recalc_inode() to account for freed pages: 1934 * except our folio is there in cache, so not quite balanced. 1935 */ 1936 spin_lock(&info->lock); 1937 freed = pages + info->alloced - info->swapped - 1938 READ_ONCE(mapping->nrpages); 1939 if (freed > 0) 1940 info->alloced -= freed; 1941 spin_unlock(&info->lock); 1942 if (freed > 0) 1943 shmem_inode_unacct_blocks(inode, freed); 1944 error = shmem_inode_acct_blocks(inode, pages); 1945 if (error) { 1946 filemap_remove_folio(folio); 1947 goto unlock; 1948 } 1949 } 1950 1951 shmem_recalc_inode(inode, pages, 0); 1952 folio_add_lru(folio); 1953 return folio; 1954 1955 unlock: 1956 folio_unlock(folio); 1957 folio_put(folio); 1958 return ERR_PTR(error); 1959 } 1960 1961 static struct folio *shmem_swap_alloc_folio(struct inode *inode, 1962 struct vm_area_struct *vma, pgoff_t index, 1963 swp_entry_t entry, int order, gfp_t gfp) 1964 { 1965 struct shmem_inode_info *info = SHMEM_I(inode); 1966 struct folio *new; 1967 void *shadow; 1968 int nr_pages; 1969 1970 /* 1971 * We have arrived here because our zones are constrained, so don't 1972 * limit chance of success with further cpuset and node constraints. 1973 */ 1974 gfp &= ~GFP_CONSTRAINT_MASK; 1975 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && order > 0) { 1976 gfp_t huge_gfp = vma_thp_gfp_mask(vma); 1977 1978 gfp = limit_gfp_mask(huge_gfp, gfp); 1979 } 1980 1981 new = shmem_alloc_folio(gfp, order, info, index); 1982 if (!new) 1983 return ERR_PTR(-ENOMEM); 1984 1985 nr_pages = folio_nr_pages(new); 1986 if (mem_cgroup_swapin_charge_folio(new, vma ? vma->vm_mm : NULL, 1987 gfp, entry)) { 1988 folio_put(new); 1989 return ERR_PTR(-ENOMEM); 1990 } 1991 1992 /* 1993 * Prevent parallel swapin from proceeding with the swap cache flag. 1994 * 1995 * Of course there is another possible concurrent scenario as well, 1996 * that is to say, the swap cache flag of a large folio has already 1997 * been set by swapcache_prepare(), while another thread may have 1998 * already split the large swap entry stored in the shmem mapping. 1999 * In this case, shmem_add_to_page_cache() will help identify the 2000 * concurrent swapin and return -EEXIST. 2001 */ 2002 if (swapcache_prepare(entry, nr_pages)) { 2003 folio_put(new); 2004 return ERR_PTR(-EEXIST); 2005 } 2006 2007 __folio_set_locked(new); 2008 __folio_set_swapbacked(new); 2009 new->swap = entry; 2010 2011 memcg1_swapin(entry, nr_pages); 2012 shadow = get_shadow_from_swap_cache(entry); 2013 if (shadow) 2014 workingset_refault(new, shadow); 2015 folio_add_lru(new); 2016 swap_read_folio(new, NULL); 2017 return new; 2018 } 2019 2020 /* 2021 * When a page is moved from swapcache to shmem filecache (either by the 2022 * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of 2023 * shmem_unuse_inode()), it may have been read in earlier from swap, in 2024 * ignorance of the mapping it belongs to. If that mapping has special 2025 * constraints (like the gma500 GEM driver, which requires RAM below 4GB), 2026 * we may need to copy to a suitable page before moving to filecache. 2027 * 2028 * In a future release, this may well be extended to respect cpuset and 2029 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page(); 2030 * but for now it is a simple matter of zone. 2031 */ 2032 static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp) 2033 { 2034 return folio_zonenum(folio) > gfp_zone(gfp); 2035 } 2036 2037 static int shmem_replace_folio(struct folio **foliop, gfp_t gfp, 2038 struct shmem_inode_info *info, pgoff_t index, 2039 struct vm_area_struct *vma) 2040 { 2041 struct folio *new, *old = *foliop; 2042 swp_entry_t entry = old->swap; 2043 struct address_space *swap_mapping = swap_address_space(entry); 2044 pgoff_t swap_index = swap_cache_index(entry); 2045 XA_STATE(xas, &swap_mapping->i_pages, swap_index); 2046 int nr_pages = folio_nr_pages(old); 2047 int error = 0, i; 2048 2049 /* 2050 * We have arrived here because our zones are constrained, so don't 2051 * limit chance of success by further cpuset and node constraints. 2052 */ 2053 gfp &= ~GFP_CONSTRAINT_MASK; 2054 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2055 if (nr_pages > 1) { 2056 gfp_t huge_gfp = vma_thp_gfp_mask(vma); 2057 2058 gfp = limit_gfp_mask(huge_gfp, gfp); 2059 } 2060 #endif 2061 2062 new = shmem_alloc_folio(gfp, folio_order(old), info, index); 2063 if (!new) 2064 return -ENOMEM; 2065 2066 folio_ref_add(new, nr_pages); 2067 folio_copy(new, old); 2068 flush_dcache_folio(new); 2069 2070 __folio_set_locked(new); 2071 __folio_set_swapbacked(new); 2072 folio_mark_uptodate(new); 2073 new->swap = entry; 2074 folio_set_swapcache(new); 2075 2076 /* Swap cache still stores N entries instead of a high-order entry */ 2077 xa_lock_irq(&swap_mapping->i_pages); 2078 for (i = 0; i < nr_pages; i++) { 2079 void *item = xas_load(&xas); 2080 2081 if (item != old) { 2082 error = -ENOENT; 2083 break; 2084 } 2085 2086 xas_store(&xas, new); 2087 xas_next(&xas); 2088 } 2089 if (!error) { 2090 mem_cgroup_replace_folio(old, new); 2091 shmem_update_stats(new, nr_pages); 2092 shmem_update_stats(old, -nr_pages); 2093 } 2094 xa_unlock_irq(&swap_mapping->i_pages); 2095 2096 if (unlikely(error)) { 2097 /* 2098 * Is this possible? I think not, now that our callers 2099 * check both the swapcache flag and folio->private 2100 * after getting the folio lock; but be defensive. 2101 * Reverse old to newpage for clear and free. 2102 */ 2103 old = new; 2104 } else { 2105 folio_add_lru(new); 2106 *foliop = new; 2107 } 2108 2109 folio_clear_swapcache(old); 2110 old->private = NULL; 2111 2112 folio_unlock(old); 2113 /* 2114 * The old folio are removed from swap cache, drop the 'nr_pages' 2115 * reference, as well as one temporary reference getting from swap 2116 * cache. 2117 */ 2118 folio_put_refs(old, nr_pages + 1); 2119 return error; 2120 } 2121 2122 static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index, 2123 struct folio *folio, swp_entry_t swap, 2124 bool skip_swapcache) 2125 { 2126 struct address_space *mapping = inode->i_mapping; 2127 swp_entry_t swapin_error; 2128 void *old; 2129 int nr_pages; 2130 2131 swapin_error = make_poisoned_swp_entry(); 2132 old = xa_cmpxchg_irq(&mapping->i_pages, index, 2133 swp_to_radix_entry(swap), 2134 swp_to_radix_entry(swapin_error), 0); 2135 if (old != swp_to_radix_entry(swap)) 2136 return; 2137 2138 nr_pages = folio_nr_pages(folio); 2139 folio_wait_writeback(folio); 2140 if (!skip_swapcache) 2141 delete_from_swap_cache(folio); 2142 /* 2143 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks 2144 * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks) 2145 * in shmem_evict_inode(). 2146 */ 2147 shmem_recalc_inode(inode, -nr_pages, -nr_pages); 2148 swap_free_nr(swap, nr_pages); 2149 } 2150 2151 static int shmem_split_large_entry(struct inode *inode, pgoff_t index, 2152 swp_entry_t swap, gfp_t gfp) 2153 { 2154 struct address_space *mapping = inode->i_mapping; 2155 XA_STATE_ORDER(xas, &mapping->i_pages, index, 0); 2156 void *alloced_shadow = NULL; 2157 int alloced_order = 0, i; 2158 2159 /* Convert user data gfp flags to xarray node gfp flags */ 2160 gfp &= GFP_RECLAIM_MASK; 2161 2162 for (;;) { 2163 int order = -1, split_order = 0; 2164 void *old = NULL; 2165 2166 xas_lock_irq(&xas); 2167 old = xas_load(&xas); 2168 if (!xa_is_value(old) || swp_to_radix_entry(swap) != old) { 2169 xas_set_err(&xas, -EEXIST); 2170 goto unlock; 2171 } 2172 2173 order = xas_get_order(&xas); 2174 2175 /* Swap entry may have changed before we re-acquire the lock */ 2176 if (alloced_order && 2177 (old != alloced_shadow || order != alloced_order)) { 2178 xas_destroy(&xas); 2179 alloced_order = 0; 2180 } 2181 2182 /* Try to split large swap entry in pagecache */ 2183 if (order > 0) { 2184 if (!alloced_order) { 2185 split_order = order; 2186 goto unlock; 2187 } 2188 xas_split(&xas, old, order); 2189 2190 /* 2191 * Re-set the swap entry after splitting, and the swap 2192 * offset of the original large entry must be continuous. 2193 */ 2194 for (i = 0; i < 1 << order; i++) { 2195 pgoff_t aligned_index = round_down(index, 1 << order); 2196 swp_entry_t tmp; 2197 2198 tmp = swp_entry(swp_type(swap), swp_offset(swap) + i); 2199 __xa_store(&mapping->i_pages, aligned_index + i, 2200 swp_to_radix_entry(tmp), 0); 2201 } 2202 } 2203 2204 unlock: 2205 xas_unlock_irq(&xas); 2206 2207 /* split needed, alloc here and retry. */ 2208 if (split_order) { 2209 xas_split_alloc(&xas, old, split_order, gfp); 2210 if (xas_error(&xas)) 2211 goto error; 2212 alloced_shadow = old; 2213 alloced_order = split_order; 2214 xas_reset(&xas); 2215 continue; 2216 } 2217 2218 if (!xas_nomem(&xas, gfp)) 2219 break; 2220 } 2221 2222 error: 2223 if (xas_error(&xas)) 2224 return xas_error(&xas); 2225 2226 return alloced_order; 2227 } 2228 2229 /* 2230 * Swap in the folio pointed to by *foliop. 2231 * Caller has to make sure that *foliop contains a valid swapped folio. 2232 * Returns 0 and the folio in foliop if success. On failure, returns the 2233 * error code and NULL in *foliop. 2234 */ 2235 static int shmem_swapin_folio(struct inode *inode, pgoff_t index, 2236 struct folio **foliop, enum sgp_type sgp, 2237 gfp_t gfp, struct vm_area_struct *vma, 2238 vm_fault_t *fault_type) 2239 { 2240 struct address_space *mapping = inode->i_mapping; 2241 struct mm_struct *fault_mm = vma ? vma->vm_mm : NULL; 2242 struct shmem_inode_info *info = SHMEM_I(inode); 2243 struct swap_info_struct *si; 2244 struct folio *folio = NULL; 2245 bool skip_swapcache = false; 2246 swp_entry_t swap; 2247 int error, nr_pages, order, split_order; 2248 2249 VM_BUG_ON(!*foliop || !xa_is_value(*foliop)); 2250 swap = radix_to_swp_entry(*foliop); 2251 *foliop = NULL; 2252 2253 if (is_poisoned_swp_entry(swap)) 2254 return -EIO; 2255 2256 si = get_swap_device(swap); 2257 if (!si) { 2258 if (!shmem_confirm_swap(mapping, index, swap)) 2259 return -EEXIST; 2260 else 2261 return -EINVAL; 2262 } 2263 2264 /* Look it up and read it in.. */ 2265 folio = swap_cache_get_folio(swap, NULL, 0); 2266 order = xa_get_order(&mapping->i_pages, index); 2267 if (!folio) { 2268 bool fallback_order0 = false; 2269 2270 /* Or update major stats only when swapin succeeds?? */ 2271 if (fault_type) { 2272 *fault_type |= VM_FAULT_MAJOR; 2273 count_vm_event(PGMAJFAULT); 2274 count_memcg_event_mm(fault_mm, PGMAJFAULT); 2275 } 2276 2277 /* 2278 * If uffd is active for the vma, we need per-page fault 2279 * fidelity to maintain the uffd semantics, then fallback 2280 * to swapin order-0 folio, as well as for zswap case. 2281 */ 2282 if (order > 0 && ((vma && unlikely(userfaultfd_armed(vma))) || 2283 !zswap_never_enabled())) 2284 fallback_order0 = true; 2285 2286 /* Skip swapcache for synchronous device. */ 2287 if (!fallback_order0 && data_race(si->flags & SWP_SYNCHRONOUS_IO)) { 2288 folio = shmem_swap_alloc_folio(inode, vma, index, swap, order, gfp); 2289 if (!IS_ERR(folio)) { 2290 skip_swapcache = true; 2291 goto alloced; 2292 } 2293 2294 /* 2295 * Fallback to swapin order-0 folio unless the swap entry 2296 * already exists. 2297 */ 2298 error = PTR_ERR(folio); 2299 folio = NULL; 2300 if (error == -EEXIST) 2301 goto failed; 2302 } 2303 2304 /* 2305 * Now swap device can only swap in order 0 folio, then we 2306 * should split the large swap entry stored in the pagecache 2307 * if necessary. 2308 */ 2309 split_order = shmem_split_large_entry(inode, index, swap, gfp); 2310 if (split_order < 0) { 2311 error = split_order; 2312 goto failed; 2313 } 2314 2315 /* 2316 * If the large swap entry has already been split, it is 2317 * necessary to recalculate the new swap entry based on 2318 * the old order alignment. 2319 */ 2320 if (split_order > 0) { 2321 pgoff_t offset = index - round_down(index, 1 << split_order); 2322 2323 swap = swp_entry(swp_type(swap), swp_offset(swap) + offset); 2324 } 2325 2326 /* Here we actually start the io */ 2327 folio = shmem_swapin_cluster(swap, gfp, info, index); 2328 if (!folio) { 2329 error = -ENOMEM; 2330 goto failed; 2331 } 2332 } else if (order != folio_order(folio)) { 2333 /* 2334 * Swap readahead may swap in order 0 folios into swapcache 2335 * asynchronously, while the shmem mapping can still stores 2336 * large swap entries. In such cases, we should split the 2337 * large swap entry to prevent possible data corruption. 2338 */ 2339 split_order = shmem_split_large_entry(inode, index, swap, gfp); 2340 if (split_order < 0) { 2341 error = split_order; 2342 goto failed; 2343 } 2344 2345 /* 2346 * If the large swap entry has already been split, it is 2347 * necessary to recalculate the new swap entry based on 2348 * the old order alignment. 2349 */ 2350 if (split_order > 0) { 2351 pgoff_t offset = index - round_down(index, 1 << split_order); 2352 2353 swap = swp_entry(swp_type(swap), swp_offset(swap) + offset); 2354 } 2355 } 2356 2357 alloced: 2358 /* We have to do this with folio locked to prevent races */ 2359 folio_lock(folio); 2360 if ((!skip_swapcache && !folio_test_swapcache(folio)) || 2361 folio->swap.val != swap.val || 2362 !shmem_confirm_swap(mapping, index, swap) || 2363 xa_get_order(&mapping->i_pages, index) != folio_order(folio)) { 2364 error = -EEXIST; 2365 goto unlock; 2366 } 2367 if (!folio_test_uptodate(folio)) { 2368 error = -EIO; 2369 goto failed; 2370 } 2371 folio_wait_writeback(folio); 2372 nr_pages = folio_nr_pages(folio); 2373 2374 /* 2375 * Some architectures may have to restore extra metadata to the 2376 * folio after reading from swap. 2377 */ 2378 arch_swap_restore(folio_swap(swap, folio), folio); 2379 2380 if (shmem_should_replace_folio(folio, gfp)) { 2381 error = shmem_replace_folio(&folio, gfp, info, index, vma); 2382 if (error) 2383 goto failed; 2384 } 2385 2386 error = shmem_add_to_page_cache(folio, mapping, 2387 round_down(index, nr_pages), 2388 swp_to_radix_entry(swap), gfp); 2389 if (error) 2390 goto failed; 2391 2392 shmem_recalc_inode(inode, 0, -nr_pages); 2393 2394 if (sgp == SGP_WRITE) 2395 folio_mark_accessed(folio); 2396 2397 if (skip_swapcache) { 2398 folio->swap.val = 0; 2399 swapcache_clear(si, swap, nr_pages); 2400 } else { 2401 delete_from_swap_cache(folio); 2402 } 2403 folio_mark_dirty(folio); 2404 swap_free_nr(swap, nr_pages); 2405 put_swap_device(si); 2406 2407 *foliop = folio; 2408 return 0; 2409 failed: 2410 if (!shmem_confirm_swap(mapping, index, swap)) 2411 error = -EEXIST; 2412 if (error == -EIO) 2413 shmem_set_folio_swapin_error(inode, index, folio, swap, 2414 skip_swapcache); 2415 unlock: 2416 if (skip_swapcache) 2417 swapcache_clear(si, swap, folio_nr_pages(folio)); 2418 if (folio) { 2419 folio_unlock(folio); 2420 folio_put(folio); 2421 } 2422 put_swap_device(si); 2423 2424 return error; 2425 } 2426 2427 /* 2428 * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate 2429 * 2430 * If we allocate a new one we do not mark it dirty. That's up to the 2431 * vm. If we swap it in we mark it dirty since we also free the swap 2432 * entry since a page cannot live in both the swap and page cache. 2433 * 2434 * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL. 2435 */ 2436 static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index, 2437 loff_t write_end, struct folio **foliop, enum sgp_type sgp, 2438 gfp_t gfp, struct vm_fault *vmf, vm_fault_t *fault_type) 2439 { 2440 struct vm_area_struct *vma = vmf ? vmf->vma : NULL; 2441 struct mm_struct *fault_mm; 2442 struct folio *folio; 2443 int error; 2444 bool alloced; 2445 unsigned long orders = 0; 2446 2447 if (WARN_ON_ONCE(!shmem_mapping(inode->i_mapping))) 2448 return -EINVAL; 2449 2450 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT)) 2451 return -EFBIG; 2452 repeat: 2453 if (sgp <= SGP_CACHE && 2454 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) 2455 return -EINVAL; 2456 2457 alloced = false; 2458 fault_mm = vma ? vma->vm_mm : NULL; 2459 2460 folio = filemap_get_entry(inode->i_mapping, index); 2461 if (folio && vma && userfaultfd_minor(vma)) { 2462 if (!xa_is_value(folio)) 2463 folio_put(folio); 2464 *fault_type = handle_userfault(vmf, VM_UFFD_MINOR); 2465 return 0; 2466 } 2467 2468 if (xa_is_value(folio)) { 2469 error = shmem_swapin_folio(inode, index, &folio, 2470 sgp, gfp, vma, fault_type); 2471 if (error == -EEXIST) 2472 goto repeat; 2473 2474 *foliop = folio; 2475 return error; 2476 } 2477 2478 if (folio) { 2479 folio_lock(folio); 2480 2481 /* Has the folio been truncated or swapped out? */ 2482 if (unlikely(folio->mapping != inode->i_mapping)) { 2483 folio_unlock(folio); 2484 folio_put(folio); 2485 goto repeat; 2486 } 2487 if (sgp == SGP_WRITE) 2488 folio_mark_accessed(folio); 2489 if (folio_test_uptodate(folio)) 2490 goto out; 2491 /* fallocated folio */ 2492 if (sgp != SGP_READ) 2493 goto clear; 2494 folio_unlock(folio); 2495 folio_put(folio); 2496 } 2497 2498 /* 2499 * SGP_READ: succeed on hole, with NULL folio, letting caller zero. 2500 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail. 2501 */ 2502 *foliop = NULL; 2503 if (sgp == SGP_READ) 2504 return 0; 2505 if (sgp == SGP_NOALLOC) 2506 return -ENOENT; 2507 2508 /* 2509 * Fast cache lookup and swap lookup did not find it: allocate. 2510 */ 2511 2512 if (vma && userfaultfd_missing(vma)) { 2513 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING); 2514 return 0; 2515 } 2516 2517 /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */ 2518 orders = shmem_allowable_huge_orders(inode, vma, index, write_end, false); 2519 if (orders > 0) { 2520 gfp_t huge_gfp; 2521 2522 huge_gfp = vma_thp_gfp_mask(vma); 2523 huge_gfp = limit_gfp_mask(huge_gfp, gfp); 2524 folio = shmem_alloc_and_add_folio(vmf, huge_gfp, 2525 inode, index, fault_mm, orders); 2526 if (!IS_ERR(folio)) { 2527 if (folio_test_pmd_mappable(folio)) 2528 count_vm_event(THP_FILE_ALLOC); 2529 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_ALLOC); 2530 goto alloced; 2531 } 2532 if (PTR_ERR(folio) == -EEXIST) 2533 goto repeat; 2534 } 2535 2536 folio = shmem_alloc_and_add_folio(vmf, gfp, inode, index, fault_mm, 0); 2537 if (IS_ERR(folio)) { 2538 error = PTR_ERR(folio); 2539 if (error == -EEXIST) 2540 goto repeat; 2541 folio = NULL; 2542 goto unlock; 2543 } 2544 2545 alloced: 2546 alloced = true; 2547 if (folio_test_large(folio) && 2548 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) < 2549 folio_next_index(folio)) { 2550 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 2551 struct shmem_inode_info *info = SHMEM_I(inode); 2552 /* 2553 * Part of the large folio is beyond i_size: subject 2554 * to shrink under memory pressure. 2555 */ 2556 spin_lock(&sbinfo->shrinklist_lock); 2557 /* 2558 * _careful to defend against unlocked access to 2559 * ->shrink_list in shmem_unused_huge_shrink() 2560 */ 2561 if (list_empty_careful(&info->shrinklist)) { 2562 list_add_tail(&info->shrinklist, 2563 &sbinfo->shrinklist); 2564 sbinfo->shrinklist_len++; 2565 } 2566 spin_unlock(&sbinfo->shrinklist_lock); 2567 } 2568 2569 if (sgp == SGP_WRITE) 2570 folio_set_referenced(folio); 2571 /* 2572 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio. 2573 */ 2574 if (sgp == SGP_FALLOC) 2575 sgp = SGP_WRITE; 2576 clear: 2577 /* 2578 * Let SGP_WRITE caller clear ends if write does not fill folio; 2579 * but SGP_FALLOC on a folio fallocated earlier must initialize 2580 * it now, lest undo on failure cancel our earlier guarantee. 2581 */ 2582 if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) { 2583 long i, n = folio_nr_pages(folio); 2584 2585 for (i = 0; i < n; i++) 2586 clear_highpage(folio_page(folio, i)); 2587 flush_dcache_folio(folio); 2588 folio_mark_uptodate(folio); 2589 } 2590 2591 /* Perhaps the file has been truncated since we checked */ 2592 if (sgp <= SGP_CACHE && 2593 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) { 2594 error = -EINVAL; 2595 goto unlock; 2596 } 2597 out: 2598 *foliop = folio; 2599 return 0; 2600 2601 /* 2602 * Error recovery. 2603 */ 2604 unlock: 2605 if (alloced) 2606 filemap_remove_folio(folio); 2607 shmem_recalc_inode(inode, 0, 0); 2608 if (folio) { 2609 folio_unlock(folio); 2610 folio_put(folio); 2611 } 2612 return error; 2613 } 2614 2615 /** 2616 * shmem_get_folio - find, and lock a shmem folio. 2617 * @inode: inode to search 2618 * @index: the page index. 2619 * @write_end: end of a write, could extend inode size 2620 * @foliop: pointer to the folio if found 2621 * @sgp: SGP_* flags to control behavior 2622 * 2623 * Looks up the page cache entry at @inode & @index. If a folio is 2624 * present, it is returned locked with an increased refcount. 2625 * 2626 * If the caller modifies data in the folio, it must call folio_mark_dirty() 2627 * before unlocking the folio to ensure that the folio is not reclaimed. 2628 * There is no need to reserve space before calling folio_mark_dirty(). 2629 * 2630 * When no folio is found, the behavior depends on @sgp: 2631 * - for SGP_READ, *@foliop is %NULL and 0 is returned 2632 * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned 2633 * - for all other flags a new folio is allocated, inserted into the 2634 * page cache and returned locked in @foliop. 2635 * 2636 * Context: May sleep. 2637 * Return: 0 if successful, else a negative error code. 2638 */ 2639 int shmem_get_folio(struct inode *inode, pgoff_t index, loff_t write_end, 2640 struct folio **foliop, enum sgp_type sgp) 2641 { 2642 return shmem_get_folio_gfp(inode, index, write_end, foliop, sgp, 2643 mapping_gfp_mask(inode->i_mapping), NULL, NULL); 2644 } 2645 EXPORT_SYMBOL_GPL(shmem_get_folio); 2646 2647 /* 2648 * This is like autoremove_wake_function, but it removes the wait queue 2649 * entry unconditionally - even if something else had already woken the 2650 * target. 2651 */ 2652 static int synchronous_wake_function(wait_queue_entry_t *wait, 2653 unsigned int mode, int sync, void *key) 2654 { 2655 int ret = default_wake_function(wait, mode, sync, key); 2656 list_del_init(&wait->entry); 2657 return ret; 2658 } 2659 2660 /* 2661 * Trinity finds that probing a hole which tmpfs is punching can 2662 * prevent the hole-punch from ever completing: which in turn 2663 * locks writers out with its hold on i_rwsem. So refrain from 2664 * faulting pages into the hole while it's being punched. Although 2665 * shmem_undo_range() does remove the additions, it may be unable to 2666 * keep up, as each new page needs its own unmap_mapping_range() call, 2667 * and the i_mmap tree grows ever slower to scan if new vmas are added. 2668 * 2669 * It does not matter if we sometimes reach this check just before the 2670 * hole-punch begins, so that one fault then races with the punch: 2671 * we just need to make racing faults a rare case. 2672 * 2673 * The implementation below would be much simpler if we just used a 2674 * standard mutex or completion: but we cannot take i_rwsem in fault, 2675 * and bloating every shmem inode for this unlikely case would be sad. 2676 */ 2677 static vm_fault_t shmem_falloc_wait(struct vm_fault *vmf, struct inode *inode) 2678 { 2679 struct shmem_falloc *shmem_falloc; 2680 struct file *fpin = NULL; 2681 vm_fault_t ret = 0; 2682 2683 spin_lock(&inode->i_lock); 2684 shmem_falloc = inode->i_private; 2685 if (shmem_falloc && 2686 shmem_falloc->waitq && 2687 vmf->pgoff >= shmem_falloc->start && 2688 vmf->pgoff < shmem_falloc->next) { 2689 wait_queue_head_t *shmem_falloc_waitq; 2690 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function); 2691 2692 ret = VM_FAULT_NOPAGE; 2693 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 2694 shmem_falloc_waitq = shmem_falloc->waitq; 2695 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait, 2696 TASK_UNINTERRUPTIBLE); 2697 spin_unlock(&inode->i_lock); 2698 schedule(); 2699 2700 /* 2701 * shmem_falloc_waitq points into the shmem_fallocate() 2702 * stack of the hole-punching task: shmem_falloc_waitq 2703 * is usually invalid by the time we reach here, but 2704 * finish_wait() does not dereference it in that case; 2705 * though i_lock needed lest racing with wake_up_all(). 2706 */ 2707 spin_lock(&inode->i_lock); 2708 finish_wait(shmem_falloc_waitq, &shmem_fault_wait); 2709 } 2710 spin_unlock(&inode->i_lock); 2711 if (fpin) { 2712 fput(fpin); 2713 ret = VM_FAULT_RETRY; 2714 } 2715 return ret; 2716 } 2717 2718 static vm_fault_t shmem_fault(struct vm_fault *vmf) 2719 { 2720 struct inode *inode = file_inode(vmf->vma->vm_file); 2721 gfp_t gfp = mapping_gfp_mask(inode->i_mapping); 2722 struct folio *folio = NULL; 2723 vm_fault_t ret = 0; 2724 int err; 2725 2726 /* 2727 * Trinity finds that probing a hole which tmpfs is punching can 2728 * prevent the hole-punch from ever completing: noted in i_private. 2729 */ 2730 if (unlikely(inode->i_private)) { 2731 ret = shmem_falloc_wait(vmf, inode); 2732 if (ret) 2733 return ret; 2734 } 2735 2736 WARN_ON_ONCE(vmf->page != NULL); 2737 err = shmem_get_folio_gfp(inode, vmf->pgoff, 0, &folio, SGP_CACHE, 2738 gfp, vmf, &ret); 2739 if (err) 2740 return vmf_error(err); 2741 if (folio) { 2742 vmf->page = folio_file_page(folio, vmf->pgoff); 2743 ret |= VM_FAULT_LOCKED; 2744 } 2745 return ret; 2746 } 2747 2748 unsigned long shmem_get_unmapped_area(struct file *file, 2749 unsigned long uaddr, unsigned long len, 2750 unsigned long pgoff, unsigned long flags) 2751 { 2752 unsigned long addr; 2753 unsigned long offset; 2754 unsigned long inflated_len; 2755 unsigned long inflated_addr; 2756 unsigned long inflated_offset; 2757 unsigned long hpage_size; 2758 2759 if (len > TASK_SIZE) 2760 return -ENOMEM; 2761 2762 addr = mm_get_unmapped_area(current->mm, file, uaddr, len, pgoff, 2763 flags); 2764 2765 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 2766 return addr; 2767 if (IS_ERR_VALUE(addr)) 2768 return addr; 2769 if (addr & ~PAGE_MASK) 2770 return addr; 2771 if (addr > TASK_SIZE - len) 2772 return addr; 2773 2774 if (shmem_huge == SHMEM_HUGE_DENY) 2775 return addr; 2776 if (flags & MAP_FIXED) 2777 return addr; 2778 /* 2779 * Our priority is to support MAP_SHARED mapped hugely; 2780 * and support MAP_PRIVATE mapped hugely too, until it is COWed. 2781 * But if caller specified an address hint and we allocated area there 2782 * successfully, respect that as before. 2783 */ 2784 if (uaddr == addr) 2785 return addr; 2786 2787 hpage_size = HPAGE_PMD_SIZE; 2788 if (shmem_huge != SHMEM_HUGE_FORCE) { 2789 struct super_block *sb; 2790 unsigned long __maybe_unused hpage_orders; 2791 int order = 0; 2792 2793 if (file) { 2794 VM_BUG_ON(file->f_op != &shmem_file_operations); 2795 sb = file_inode(file)->i_sb; 2796 } else { 2797 /* 2798 * Called directly from mm/mmap.c, or drivers/char/mem.c 2799 * for "/dev/zero", to create a shared anonymous object. 2800 */ 2801 if (IS_ERR(shm_mnt)) 2802 return addr; 2803 sb = shm_mnt->mnt_sb; 2804 2805 /* 2806 * Find the highest mTHP order used for anonymous shmem to 2807 * provide a suitable alignment address. 2808 */ 2809 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2810 hpage_orders = READ_ONCE(huge_shmem_orders_always); 2811 hpage_orders |= READ_ONCE(huge_shmem_orders_within_size); 2812 hpage_orders |= READ_ONCE(huge_shmem_orders_madvise); 2813 if (SHMEM_SB(sb)->huge != SHMEM_HUGE_NEVER) 2814 hpage_orders |= READ_ONCE(huge_shmem_orders_inherit); 2815 2816 if (hpage_orders > 0) { 2817 order = highest_order(hpage_orders); 2818 hpage_size = PAGE_SIZE << order; 2819 } 2820 #endif 2821 } 2822 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER && !order) 2823 return addr; 2824 } 2825 2826 if (len < hpage_size) 2827 return addr; 2828 2829 offset = (pgoff << PAGE_SHIFT) & (hpage_size - 1); 2830 if (offset && offset + len < 2 * hpage_size) 2831 return addr; 2832 if ((addr & (hpage_size - 1)) == offset) 2833 return addr; 2834 2835 inflated_len = len + hpage_size - PAGE_SIZE; 2836 if (inflated_len > TASK_SIZE) 2837 return addr; 2838 if (inflated_len < len) 2839 return addr; 2840 2841 inflated_addr = mm_get_unmapped_area(current->mm, NULL, uaddr, 2842 inflated_len, 0, flags); 2843 if (IS_ERR_VALUE(inflated_addr)) 2844 return addr; 2845 if (inflated_addr & ~PAGE_MASK) 2846 return addr; 2847 2848 inflated_offset = inflated_addr & (hpage_size - 1); 2849 inflated_addr += offset - inflated_offset; 2850 if (inflated_offset > offset) 2851 inflated_addr += hpage_size; 2852 2853 if (inflated_addr > TASK_SIZE - len) 2854 return addr; 2855 return inflated_addr; 2856 } 2857 2858 #ifdef CONFIG_NUMA 2859 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol) 2860 { 2861 struct inode *inode = file_inode(vma->vm_file); 2862 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol); 2863 } 2864 2865 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma, 2866 unsigned long addr, pgoff_t *ilx) 2867 { 2868 struct inode *inode = file_inode(vma->vm_file); 2869 pgoff_t index; 2870 2871 /* 2872 * Bias interleave by inode number to distribute better across nodes; 2873 * but this interface is independent of which page order is used, so 2874 * supplies only that bias, letting caller apply the offset (adjusted 2875 * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()). 2876 */ 2877 *ilx = inode->i_ino; 2878 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; 2879 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index); 2880 } 2881 2882 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 2883 pgoff_t index, unsigned int order, pgoff_t *ilx) 2884 { 2885 struct mempolicy *mpol; 2886 2887 /* Bias interleave by inode number to distribute better across nodes */ 2888 *ilx = info->vfs_inode.i_ino + (index >> order); 2889 2890 mpol = mpol_shared_policy_lookup(&info->policy, index); 2891 return mpol ? mpol : get_task_policy(current); 2892 } 2893 #else 2894 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info, 2895 pgoff_t index, unsigned int order, pgoff_t *ilx) 2896 { 2897 *ilx = 0; 2898 return NULL; 2899 } 2900 #endif /* CONFIG_NUMA */ 2901 2902 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 2903 { 2904 struct inode *inode = file_inode(file); 2905 struct shmem_inode_info *info = SHMEM_I(inode); 2906 int retval = -ENOMEM; 2907 2908 /* 2909 * What serializes the accesses to info->flags? 2910 * ipc_lock_object() when called from shmctl_do_lock(), 2911 * no serialization needed when called from shm_destroy(). 2912 */ 2913 if (lock && !(info->flags & VM_LOCKED)) { 2914 if (!user_shm_lock(inode->i_size, ucounts)) 2915 goto out_nomem; 2916 info->flags |= VM_LOCKED; 2917 mapping_set_unevictable(file->f_mapping); 2918 } 2919 if (!lock && (info->flags & VM_LOCKED) && ucounts) { 2920 user_shm_unlock(inode->i_size, ucounts); 2921 info->flags &= ~VM_LOCKED; 2922 mapping_clear_unevictable(file->f_mapping); 2923 } 2924 retval = 0; 2925 2926 out_nomem: 2927 return retval; 2928 } 2929 2930 static int shmem_mmap(struct file *file, struct vm_area_struct *vma) 2931 { 2932 struct inode *inode = file_inode(file); 2933 2934 file_accessed(file); 2935 /* This is anonymous shared memory if it is unlinked at the time of mmap */ 2936 if (inode->i_nlink) 2937 vma->vm_ops = &shmem_vm_ops; 2938 else 2939 vma->vm_ops = &shmem_anon_vm_ops; 2940 return 0; 2941 } 2942 2943 static int shmem_file_open(struct inode *inode, struct file *file) 2944 { 2945 file->f_mode |= FMODE_CAN_ODIRECT; 2946 return generic_file_open(inode, file); 2947 } 2948 2949 #ifdef CONFIG_TMPFS_XATTR 2950 static int shmem_initxattrs(struct inode *, const struct xattr *, void *); 2951 2952 #if IS_ENABLED(CONFIG_UNICODE) 2953 /* 2954 * shmem_inode_casefold_flags - Deal with casefold file attribute flag 2955 * 2956 * The casefold file attribute needs some special checks. I can just be added to 2957 * an empty dir, and can't be removed from a non-empty dir. 2958 */ 2959 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags, 2960 struct dentry *dentry, unsigned int *i_flags) 2961 { 2962 unsigned int old = inode->i_flags; 2963 struct super_block *sb = inode->i_sb; 2964 2965 if (fsflags & FS_CASEFOLD_FL) { 2966 if (!(old & S_CASEFOLD)) { 2967 if (!sb->s_encoding) 2968 return -EOPNOTSUPP; 2969 2970 if (!S_ISDIR(inode->i_mode)) 2971 return -ENOTDIR; 2972 2973 if (dentry && !simple_empty(dentry)) 2974 return -ENOTEMPTY; 2975 } 2976 2977 *i_flags = *i_flags | S_CASEFOLD; 2978 } else if (old & S_CASEFOLD) { 2979 if (dentry && !simple_empty(dentry)) 2980 return -ENOTEMPTY; 2981 } 2982 2983 return 0; 2984 } 2985 #else 2986 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags, 2987 struct dentry *dentry, unsigned int *i_flags) 2988 { 2989 if (fsflags & FS_CASEFOLD_FL) 2990 return -EOPNOTSUPP; 2991 2992 return 0; 2993 } 2994 #endif 2995 2996 /* 2997 * chattr's fsflags are unrelated to extended attributes, 2998 * but tmpfs has chosen to enable them under the same config option. 2999 */ 3000 static int shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry) 3001 { 3002 unsigned int i_flags = 0; 3003 int ret; 3004 3005 ret = shmem_inode_casefold_flags(inode, fsflags, dentry, &i_flags); 3006 if (ret) 3007 return ret; 3008 3009 if (fsflags & FS_NOATIME_FL) 3010 i_flags |= S_NOATIME; 3011 if (fsflags & FS_APPEND_FL) 3012 i_flags |= S_APPEND; 3013 if (fsflags & FS_IMMUTABLE_FL) 3014 i_flags |= S_IMMUTABLE; 3015 /* 3016 * But FS_NODUMP_FL does not require any action in i_flags. 3017 */ 3018 inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE | S_CASEFOLD); 3019 3020 return 0; 3021 } 3022 #else 3023 static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry) 3024 { 3025 } 3026 #define shmem_initxattrs NULL 3027 #endif 3028 3029 static struct offset_ctx *shmem_get_offset_ctx(struct inode *inode) 3030 { 3031 return &SHMEM_I(inode)->dir_offsets; 3032 } 3033 3034 static struct inode *__shmem_get_inode(struct mnt_idmap *idmap, 3035 struct super_block *sb, 3036 struct inode *dir, umode_t mode, 3037 dev_t dev, unsigned long flags) 3038 { 3039 struct inode *inode; 3040 struct shmem_inode_info *info; 3041 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 3042 ino_t ino; 3043 int err; 3044 3045 err = shmem_reserve_inode(sb, &ino); 3046 if (err) 3047 return ERR_PTR(err); 3048 3049 inode = new_inode(sb); 3050 if (!inode) { 3051 shmem_free_inode(sb, 0); 3052 return ERR_PTR(-ENOSPC); 3053 } 3054 3055 inode->i_ino = ino; 3056 inode_init_owner(idmap, inode, dir, mode); 3057 inode->i_blocks = 0; 3058 simple_inode_init_ts(inode); 3059 inode->i_generation = get_random_u32(); 3060 info = SHMEM_I(inode); 3061 memset(info, 0, (char *)inode - (char *)info); 3062 spin_lock_init(&info->lock); 3063 atomic_set(&info->stop_eviction, 0); 3064 info->seals = F_SEAL_SEAL; 3065 info->flags = flags & VM_NORESERVE; 3066 info->i_crtime = inode_get_mtime(inode); 3067 info->fsflags = (dir == NULL) ? 0 : 3068 SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED; 3069 if (info->fsflags) 3070 shmem_set_inode_flags(inode, info->fsflags, NULL); 3071 INIT_LIST_HEAD(&info->shrinklist); 3072 INIT_LIST_HEAD(&info->swaplist); 3073 simple_xattrs_init(&info->xattrs); 3074 cache_no_acl(inode); 3075 if (sbinfo->noswap) 3076 mapping_set_unevictable(inode->i_mapping); 3077 3078 /* Don't consider 'deny' for emergencies and 'force' for testing */ 3079 if (sbinfo->huge) 3080 mapping_set_large_folios(inode->i_mapping); 3081 3082 switch (mode & S_IFMT) { 3083 default: 3084 inode->i_op = &shmem_special_inode_operations; 3085 init_special_inode(inode, mode, dev); 3086 break; 3087 case S_IFREG: 3088 inode->i_mapping->a_ops = &shmem_aops; 3089 inode->i_op = &shmem_inode_operations; 3090 inode->i_fop = &shmem_file_operations; 3091 mpol_shared_policy_init(&info->policy, 3092 shmem_get_sbmpol(sbinfo)); 3093 break; 3094 case S_IFDIR: 3095 inc_nlink(inode); 3096 /* Some things misbehave if size == 0 on a directory */ 3097 inode->i_size = 2 * BOGO_DIRENT_SIZE; 3098 inode->i_op = &shmem_dir_inode_operations; 3099 inode->i_fop = &simple_offset_dir_operations; 3100 simple_offset_init(shmem_get_offset_ctx(inode)); 3101 break; 3102 case S_IFLNK: 3103 /* 3104 * Must not load anything in the rbtree, 3105 * mpol_free_shared_policy will not be called. 3106 */ 3107 mpol_shared_policy_init(&info->policy, NULL); 3108 break; 3109 } 3110 3111 lockdep_annotate_inode_mutex_key(inode); 3112 return inode; 3113 } 3114 3115 #ifdef CONFIG_TMPFS_QUOTA 3116 static struct inode *shmem_get_inode(struct mnt_idmap *idmap, 3117 struct super_block *sb, struct inode *dir, 3118 umode_t mode, dev_t dev, unsigned long flags) 3119 { 3120 int err; 3121 struct inode *inode; 3122 3123 inode = __shmem_get_inode(idmap, sb, dir, mode, dev, flags); 3124 if (IS_ERR(inode)) 3125 return inode; 3126 3127 err = dquot_initialize(inode); 3128 if (err) 3129 goto errout; 3130 3131 err = dquot_alloc_inode(inode); 3132 if (err) { 3133 dquot_drop(inode); 3134 goto errout; 3135 } 3136 return inode; 3137 3138 errout: 3139 inode->i_flags |= S_NOQUOTA; 3140 iput(inode); 3141 return ERR_PTR(err); 3142 } 3143 #else 3144 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap, 3145 struct super_block *sb, struct inode *dir, 3146 umode_t mode, dev_t dev, unsigned long flags) 3147 { 3148 return __shmem_get_inode(idmap, sb, dir, mode, dev, flags); 3149 } 3150 #endif /* CONFIG_TMPFS_QUOTA */ 3151 3152 #ifdef CONFIG_USERFAULTFD 3153 int shmem_mfill_atomic_pte(pmd_t *dst_pmd, 3154 struct vm_area_struct *dst_vma, 3155 unsigned long dst_addr, 3156 unsigned long src_addr, 3157 uffd_flags_t flags, 3158 struct folio **foliop) 3159 { 3160 struct inode *inode = file_inode(dst_vma->vm_file); 3161 struct shmem_inode_info *info = SHMEM_I(inode); 3162 struct address_space *mapping = inode->i_mapping; 3163 gfp_t gfp = mapping_gfp_mask(mapping); 3164 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr); 3165 void *page_kaddr; 3166 struct folio *folio; 3167 int ret; 3168 pgoff_t max_off; 3169 3170 if (shmem_inode_acct_blocks(inode, 1)) { 3171 /* 3172 * We may have got a page, returned -ENOENT triggering a retry, 3173 * and now we find ourselves with -ENOMEM. Release the page, to 3174 * avoid a BUG_ON in our caller. 3175 */ 3176 if (unlikely(*foliop)) { 3177 folio_put(*foliop); 3178 *foliop = NULL; 3179 } 3180 return -ENOMEM; 3181 } 3182 3183 if (!*foliop) { 3184 ret = -ENOMEM; 3185 folio = shmem_alloc_folio(gfp, 0, info, pgoff); 3186 if (!folio) 3187 goto out_unacct_blocks; 3188 3189 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY)) { 3190 page_kaddr = kmap_local_folio(folio, 0); 3191 /* 3192 * The read mmap_lock is held here. Despite the 3193 * mmap_lock being read recursive a deadlock is still 3194 * possible if a writer has taken a lock. For example: 3195 * 3196 * process A thread 1 takes read lock on own mmap_lock 3197 * process A thread 2 calls mmap, blocks taking write lock 3198 * process B thread 1 takes page fault, read lock on own mmap lock 3199 * process B thread 2 calls mmap, blocks taking write lock 3200 * process A thread 1 blocks taking read lock on process B 3201 * process B thread 1 blocks taking read lock on process A 3202 * 3203 * Disable page faults to prevent potential deadlock 3204 * and retry the copy outside the mmap_lock. 3205 */ 3206 pagefault_disable(); 3207 ret = copy_from_user(page_kaddr, 3208 (const void __user *)src_addr, 3209 PAGE_SIZE); 3210 pagefault_enable(); 3211 kunmap_local(page_kaddr); 3212 3213 /* fallback to copy_from_user outside mmap_lock */ 3214 if (unlikely(ret)) { 3215 *foliop = folio; 3216 ret = -ENOENT; 3217 /* don't free the page */ 3218 goto out_unacct_blocks; 3219 } 3220 3221 flush_dcache_folio(folio); 3222 } else { /* ZEROPAGE */ 3223 clear_user_highpage(&folio->page, dst_addr); 3224 } 3225 } else { 3226 folio = *foliop; 3227 VM_BUG_ON_FOLIO(folio_test_large(folio), folio); 3228 *foliop = NULL; 3229 } 3230 3231 VM_BUG_ON(folio_test_locked(folio)); 3232 VM_BUG_ON(folio_test_swapbacked(folio)); 3233 __folio_set_locked(folio); 3234 __folio_set_swapbacked(folio); 3235 __folio_mark_uptodate(folio); 3236 3237 ret = -EFAULT; 3238 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 3239 if (unlikely(pgoff >= max_off)) 3240 goto out_release; 3241 3242 ret = mem_cgroup_charge(folio, dst_vma->vm_mm, gfp); 3243 if (ret) 3244 goto out_release; 3245 ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL, gfp); 3246 if (ret) 3247 goto out_release; 3248 3249 ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr, 3250 &folio->page, true, flags); 3251 if (ret) 3252 goto out_delete_from_cache; 3253 3254 shmem_recalc_inode(inode, 1, 0); 3255 folio_unlock(folio); 3256 return 0; 3257 out_delete_from_cache: 3258 filemap_remove_folio(folio); 3259 out_release: 3260 folio_unlock(folio); 3261 folio_put(folio); 3262 out_unacct_blocks: 3263 shmem_inode_unacct_blocks(inode, 1); 3264 return ret; 3265 } 3266 #endif /* CONFIG_USERFAULTFD */ 3267 3268 #ifdef CONFIG_TMPFS 3269 static const struct inode_operations shmem_symlink_inode_operations; 3270 static const struct inode_operations shmem_short_symlink_operations; 3271 3272 static int 3273 shmem_write_begin(struct file *file, struct address_space *mapping, 3274 loff_t pos, unsigned len, 3275 struct folio **foliop, void **fsdata) 3276 { 3277 struct inode *inode = mapping->host; 3278 struct shmem_inode_info *info = SHMEM_I(inode); 3279 pgoff_t index = pos >> PAGE_SHIFT; 3280 struct folio *folio; 3281 int ret = 0; 3282 3283 /* i_rwsem is held by caller */ 3284 if (unlikely(info->seals & (F_SEAL_GROW | 3285 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) { 3286 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) 3287 return -EPERM; 3288 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size) 3289 return -EPERM; 3290 } 3291 3292 ret = shmem_get_folio(inode, index, pos + len, &folio, SGP_WRITE); 3293 if (ret) 3294 return ret; 3295 3296 if (folio_test_hwpoison(folio) || 3297 (folio_test_large(folio) && folio_test_has_hwpoisoned(folio))) { 3298 folio_unlock(folio); 3299 folio_put(folio); 3300 return -EIO; 3301 } 3302 3303 *foliop = folio; 3304 return 0; 3305 } 3306 3307 static int 3308 shmem_write_end(struct file *file, struct address_space *mapping, 3309 loff_t pos, unsigned len, unsigned copied, 3310 struct folio *folio, void *fsdata) 3311 { 3312 struct inode *inode = mapping->host; 3313 3314 if (pos + copied > inode->i_size) 3315 i_size_write(inode, pos + copied); 3316 3317 if (!folio_test_uptodate(folio)) { 3318 if (copied < folio_size(folio)) { 3319 size_t from = offset_in_folio(folio, pos); 3320 folio_zero_segments(folio, 0, from, 3321 from + copied, folio_size(folio)); 3322 } 3323 folio_mark_uptodate(folio); 3324 } 3325 folio_mark_dirty(folio); 3326 folio_unlock(folio); 3327 folio_put(folio); 3328 3329 return copied; 3330 } 3331 3332 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) 3333 { 3334 struct file *file = iocb->ki_filp; 3335 struct inode *inode = file_inode(file); 3336 struct address_space *mapping = inode->i_mapping; 3337 pgoff_t index; 3338 unsigned long offset; 3339 int error = 0; 3340 ssize_t retval = 0; 3341 3342 for (;;) { 3343 struct folio *folio = NULL; 3344 struct page *page = NULL; 3345 unsigned long nr, ret; 3346 loff_t end_offset, i_size = i_size_read(inode); 3347 bool fallback_page_copy = false; 3348 size_t fsize; 3349 3350 if (unlikely(iocb->ki_pos >= i_size)) 3351 break; 3352 3353 index = iocb->ki_pos >> PAGE_SHIFT; 3354 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ); 3355 if (error) { 3356 if (error == -EINVAL) 3357 error = 0; 3358 break; 3359 } 3360 if (folio) { 3361 folio_unlock(folio); 3362 3363 page = folio_file_page(folio, index); 3364 if (PageHWPoison(page)) { 3365 folio_put(folio); 3366 error = -EIO; 3367 break; 3368 } 3369 3370 if (folio_test_large(folio) && 3371 folio_test_has_hwpoisoned(folio)) 3372 fallback_page_copy = true; 3373 } 3374 3375 /* 3376 * We must evaluate after, since reads (unlike writes) 3377 * are called without i_rwsem protection against truncate 3378 */ 3379 i_size = i_size_read(inode); 3380 if (unlikely(iocb->ki_pos >= i_size)) { 3381 if (folio) 3382 folio_put(folio); 3383 break; 3384 } 3385 end_offset = min_t(loff_t, i_size, iocb->ki_pos + to->count); 3386 if (folio && likely(!fallback_page_copy)) 3387 fsize = folio_size(folio); 3388 else 3389 fsize = PAGE_SIZE; 3390 offset = iocb->ki_pos & (fsize - 1); 3391 nr = min_t(loff_t, end_offset - iocb->ki_pos, fsize - offset); 3392 3393 if (folio) { 3394 /* 3395 * If users can be writing to this page using arbitrary 3396 * virtual addresses, take care about potential aliasing 3397 * before reading the page on the kernel side. 3398 */ 3399 if (mapping_writably_mapped(mapping)) { 3400 if (likely(!fallback_page_copy)) 3401 flush_dcache_folio(folio); 3402 else 3403 flush_dcache_page(page); 3404 } 3405 3406 /* 3407 * Mark the folio accessed if we read the beginning. 3408 */ 3409 if (!offset) 3410 folio_mark_accessed(folio); 3411 /* 3412 * Ok, we have the page, and it's up-to-date, so 3413 * now we can copy it to user space... 3414 */ 3415 if (likely(!fallback_page_copy)) 3416 ret = copy_folio_to_iter(folio, offset, nr, to); 3417 else 3418 ret = copy_page_to_iter(page, offset, nr, to); 3419 folio_put(folio); 3420 } else if (user_backed_iter(to)) { 3421 /* 3422 * Copy to user tends to be so well optimized, but 3423 * clear_user() not so much, that it is noticeably 3424 * faster to copy the zero page instead of clearing. 3425 */ 3426 ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to); 3427 } else { 3428 /* 3429 * But submitting the same page twice in a row to 3430 * splice() - or others? - can result in confusion: 3431 * so don't attempt that optimization on pipes etc. 3432 */ 3433 ret = iov_iter_zero(nr, to); 3434 } 3435 3436 retval += ret; 3437 iocb->ki_pos += ret; 3438 3439 if (!iov_iter_count(to)) 3440 break; 3441 if (ret < nr) { 3442 error = -EFAULT; 3443 break; 3444 } 3445 cond_resched(); 3446 } 3447 3448 file_accessed(file); 3449 return retval ? retval : error; 3450 } 3451 3452 static ssize_t shmem_file_write_iter(struct kiocb *iocb, struct iov_iter *from) 3453 { 3454 struct file *file = iocb->ki_filp; 3455 struct inode *inode = file->f_mapping->host; 3456 ssize_t ret; 3457 3458 inode_lock(inode); 3459 ret = generic_write_checks(iocb, from); 3460 if (ret <= 0) 3461 goto unlock; 3462 ret = file_remove_privs(file); 3463 if (ret) 3464 goto unlock; 3465 ret = file_update_time(file); 3466 if (ret) 3467 goto unlock; 3468 ret = generic_perform_write(iocb, from); 3469 unlock: 3470 inode_unlock(inode); 3471 return ret; 3472 } 3473 3474 static bool zero_pipe_buf_get(struct pipe_inode_info *pipe, 3475 struct pipe_buffer *buf) 3476 { 3477 return true; 3478 } 3479 3480 static void zero_pipe_buf_release(struct pipe_inode_info *pipe, 3481 struct pipe_buffer *buf) 3482 { 3483 } 3484 3485 static bool zero_pipe_buf_try_steal(struct pipe_inode_info *pipe, 3486 struct pipe_buffer *buf) 3487 { 3488 return false; 3489 } 3490 3491 static const struct pipe_buf_operations zero_pipe_buf_ops = { 3492 .release = zero_pipe_buf_release, 3493 .try_steal = zero_pipe_buf_try_steal, 3494 .get = zero_pipe_buf_get, 3495 }; 3496 3497 static size_t splice_zeropage_into_pipe(struct pipe_inode_info *pipe, 3498 loff_t fpos, size_t size) 3499 { 3500 size_t offset = fpos & ~PAGE_MASK; 3501 3502 size = min_t(size_t, size, PAGE_SIZE - offset); 3503 3504 if (!pipe_is_full(pipe)) { 3505 struct pipe_buffer *buf = pipe_head_buf(pipe); 3506 3507 *buf = (struct pipe_buffer) { 3508 .ops = &zero_pipe_buf_ops, 3509 .page = ZERO_PAGE(0), 3510 .offset = offset, 3511 .len = size, 3512 }; 3513 pipe->head++; 3514 } 3515 3516 return size; 3517 } 3518 3519 static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos, 3520 struct pipe_inode_info *pipe, 3521 size_t len, unsigned int flags) 3522 { 3523 struct inode *inode = file_inode(in); 3524 struct address_space *mapping = inode->i_mapping; 3525 struct folio *folio = NULL; 3526 size_t total_spliced = 0, used, npages, n, part; 3527 loff_t isize; 3528 int error = 0; 3529 3530 /* Work out how much data we can actually add into the pipe */ 3531 used = pipe_buf_usage(pipe); 3532 npages = max_t(ssize_t, pipe->max_usage - used, 0); 3533 len = min_t(size_t, len, npages * PAGE_SIZE); 3534 3535 do { 3536 bool fallback_page_splice = false; 3537 struct page *page = NULL; 3538 pgoff_t index; 3539 size_t size; 3540 3541 if (*ppos >= i_size_read(inode)) 3542 break; 3543 3544 index = *ppos >> PAGE_SHIFT; 3545 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ); 3546 if (error) { 3547 if (error == -EINVAL) 3548 error = 0; 3549 break; 3550 } 3551 if (folio) { 3552 folio_unlock(folio); 3553 3554 page = folio_file_page(folio, index); 3555 if (PageHWPoison(page)) { 3556 error = -EIO; 3557 break; 3558 } 3559 3560 if (folio_test_large(folio) && 3561 folio_test_has_hwpoisoned(folio)) 3562 fallback_page_splice = true; 3563 } 3564 3565 /* 3566 * i_size must be checked after we know the pages are Uptodate. 3567 * 3568 * Checking i_size after the check allows us to calculate 3569 * the correct value for "nr", which means the zero-filled 3570 * part of the page is not copied back to userspace (unless 3571 * another truncate extends the file - this is desired though). 3572 */ 3573 isize = i_size_read(inode); 3574 if (unlikely(*ppos >= isize)) 3575 break; 3576 /* 3577 * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned 3578 * pages. 3579 */ 3580 size = len; 3581 if (unlikely(fallback_page_splice)) { 3582 size_t offset = *ppos & ~PAGE_MASK; 3583 3584 size = umin(size, PAGE_SIZE - offset); 3585 } 3586 part = min_t(loff_t, isize - *ppos, size); 3587 3588 if (folio) { 3589 /* 3590 * If users can be writing to this page using arbitrary 3591 * virtual addresses, take care about potential aliasing 3592 * before reading the page on the kernel side. 3593 */ 3594 if (mapping_writably_mapped(mapping)) { 3595 if (likely(!fallback_page_splice)) 3596 flush_dcache_folio(folio); 3597 else 3598 flush_dcache_page(page); 3599 } 3600 folio_mark_accessed(folio); 3601 /* 3602 * Ok, we have the page, and it's up-to-date, so we can 3603 * now splice it into the pipe. 3604 */ 3605 n = splice_folio_into_pipe(pipe, folio, *ppos, part); 3606 folio_put(folio); 3607 folio = NULL; 3608 } else { 3609 n = splice_zeropage_into_pipe(pipe, *ppos, part); 3610 } 3611 3612 if (!n) 3613 break; 3614 len -= n; 3615 total_spliced += n; 3616 *ppos += n; 3617 in->f_ra.prev_pos = *ppos; 3618 if (pipe_is_full(pipe)) 3619 break; 3620 3621 cond_resched(); 3622 } while (len); 3623 3624 if (folio) 3625 folio_put(folio); 3626 3627 file_accessed(in); 3628 return total_spliced ? total_spliced : error; 3629 } 3630 3631 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence) 3632 { 3633 struct address_space *mapping = file->f_mapping; 3634 struct inode *inode = mapping->host; 3635 3636 if (whence != SEEK_DATA && whence != SEEK_HOLE) 3637 return generic_file_llseek_size(file, offset, whence, 3638 MAX_LFS_FILESIZE, i_size_read(inode)); 3639 if (offset < 0) 3640 return -ENXIO; 3641 3642 inode_lock(inode); 3643 /* We're holding i_rwsem so we can access i_size directly */ 3644 offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence); 3645 if (offset >= 0) 3646 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE); 3647 inode_unlock(inode); 3648 return offset; 3649 } 3650 3651 static long shmem_fallocate(struct file *file, int mode, loff_t offset, 3652 loff_t len) 3653 { 3654 struct inode *inode = file_inode(file); 3655 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 3656 struct shmem_inode_info *info = SHMEM_I(inode); 3657 struct shmem_falloc shmem_falloc; 3658 pgoff_t start, index, end, undo_fallocend; 3659 int error; 3660 3661 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) 3662 return -EOPNOTSUPP; 3663 3664 inode_lock(inode); 3665 3666 if (mode & FALLOC_FL_PUNCH_HOLE) { 3667 struct address_space *mapping = file->f_mapping; 3668 loff_t unmap_start = round_up(offset, PAGE_SIZE); 3669 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1; 3670 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq); 3671 3672 /* protected by i_rwsem */ 3673 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) { 3674 error = -EPERM; 3675 goto out; 3676 } 3677 3678 shmem_falloc.waitq = &shmem_falloc_waitq; 3679 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT; 3680 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT; 3681 spin_lock(&inode->i_lock); 3682 inode->i_private = &shmem_falloc; 3683 spin_unlock(&inode->i_lock); 3684 3685 if ((u64)unmap_end > (u64)unmap_start) 3686 unmap_mapping_range(mapping, unmap_start, 3687 1 + unmap_end - unmap_start, 0); 3688 shmem_truncate_range(inode, offset, offset + len - 1); 3689 /* No need to unmap again: hole-punching leaves COWed pages */ 3690 3691 spin_lock(&inode->i_lock); 3692 inode->i_private = NULL; 3693 wake_up_all(&shmem_falloc_waitq); 3694 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head)); 3695 spin_unlock(&inode->i_lock); 3696 error = 0; 3697 goto out; 3698 } 3699 3700 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */ 3701 error = inode_newsize_ok(inode, offset + len); 3702 if (error) 3703 goto out; 3704 3705 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) { 3706 error = -EPERM; 3707 goto out; 3708 } 3709 3710 start = offset >> PAGE_SHIFT; 3711 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT; 3712 /* Try to avoid a swapstorm if len is impossible to satisfy */ 3713 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) { 3714 error = -ENOSPC; 3715 goto out; 3716 } 3717 3718 shmem_falloc.waitq = NULL; 3719 shmem_falloc.start = start; 3720 shmem_falloc.next = start; 3721 shmem_falloc.nr_falloced = 0; 3722 shmem_falloc.nr_unswapped = 0; 3723 spin_lock(&inode->i_lock); 3724 inode->i_private = &shmem_falloc; 3725 spin_unlock(&inode->i_lock); 3726 3727 /* 3728 * info->fallocend is only relevant when huge pages might be 3729 * involved: to prevent split_huge_page() freeing fallocated 3730 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size. 3731 */ 3732 undo_fallocend = info->fallocend; 3733 if (info->fallocend < end) 3734 info->fallocend = end; 3735 3736 for (index = start; index < end; ) { 3737 struct folio *folio; 3738 3739 /* 3740 * Check for fatal signal so that we abort early in OOM 3741 * situations. We don't want to abort in case of non-fatal 3742 * signals as large fallocate can take noticeable time and 3743 * e.g. periodic timers may result in fallocate constantly 3744 * restarting. 3745 */ 3746 if (fatal_signal_pending(current)) 3747 error = -EINTR; 3748 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced) 3749 error = -ENOMEM; 3750 else 3751 error = shmem_get_folio(inode, index, offset + len, 3752 &folio, SGP_FALLOC); 3753 if (error) { 3754 info->fallocend = undo_fallocend; 3755 /* Remove the !uptodate folios we added */ 3756 if (index > start) { 3757 shmem_undo_range(inode, 3758 (loff_t)start << PAGE_SHIFT, 3759 ((loff_t)index << PAGE_SHIFT) - 1, true); 3760 } 3761 goto undone; 3762 } 3763 3764 /* 3765 * Here is a more important optimization than it appears: 3766 * a second SGP_FALLOC on the same large folio will clear it, 3767 * making it uptodate and un-undoable if we fail later. 3768 */ 3769 index = folio_next_index(folio); 3770 /* Beware 32-bit wraparound */ 3771 if (!index) 3772 index--; 3773 3774 /* 3775 * Inform shmem_writepage() how far we have reached. 3776 * No need for lock or barrier: we have the page lock. 3777 */ 3778 if (!folio_test_uptodate(folio)) 3779 shmem_falloc.nr_falloced += index - shmem_falloc.next; 3780 shmem_falloc.next = index; 3781 3782 /* 3783 * If !uptodate, leave it that way so that freeable folios 3784 * can be recognized if we need to rollback on error later. 3785 * But mark it dirty so that memory pressure will swap rather 3786 * than free the folios we are allocating (and SGP_CACHE folios 3787 * might still be clean: we now need to mark those dirty too). 3788 */ 3789 folio_mark_dirty(folio); 3790 folio_unlock(folio); 3791 folio_put(folio); 3792 cond_resched(); 3793 } 3794 3795 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) 3796 i_size_write(inode, offset + len); 3797 undone: 3798 spin_lock(&inode->i_lock); 3799 inode->i_private = NULL; 3800 spin_unlock(&inode->i_lock); 3801 out: 3802 if (!error) 3803 file_modified(file); 3804 inode_unlock(inode); 3805 return error; 3806 } 3807 3808 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf) 3809 { 3810 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb); 3811 3812 buf->f_type = TMPFS_MAGIC; 3813 buf->f_bsize = PAGE_SIZE; 3814 buf->f_namelen = NAME_MAX; 3815 if (sbinfo->max_blocks) { 3816 buf->f_blocks = sbinfo->max_blocks; 3817 buf->f_bavail = 3818 buf->f_bfree = sbinfo->max_blocks - 3819 percpu_counter_sum(&sbinfo->used_blocks); 3820 } 3821 if (sbinfo->max_inodes) { 3822 buf->f_files = sbinfo->max_inodes; 3823 buf->f_ffree = sbinfo->free_ispace / BOGO_INODE_SIZE; 3824 } 3825 /* else leave those fields 0 like simple_statfs */ 3826 3827 buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b); 3828 3829 return 0; 3830 } 3831 3832 /* 3833 * File creation. Allocate an inode, and we're done.. 3834 */ 3835 static int 3836 shmem_mknod(struct mnt_idmap *idmap, struct inode *dir, 3837 struct dentry *dentry, umode_t mode, dev_t dev) 3838 { 3839 struct inode *inode; 3840 int error; 3841 3842 if (!generic_ci_validate_strict_name(dir, &dentry->d_name)) 3843 return -EINVAL; 3844 3845 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, dev, VM_NORESERVE); 3846 if (IS_ERR(inode)) 3847 return PTR_ERR(inode); 3848 3849 error = simple_acl_create(dir, inode); 3850 if (error) 3851 goto out_iput; 3852 error = security_inode_init_security(inode, dir, &dentry->d_name, 3853 shmem_initxattrs, NULL); 3854 if (error && error != -EOPNOTSUPP) 3855 goto out_iput; 3856 3857 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3858 if (error) 3859 goto out_iput; 3860 3861 dir->i_size += BOGO_DIRENT_SIZE; 3862 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir)); 3863 inode_inc_iversion(dir); 3864 3865 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3866 d_add(dentry, inode); 3867 else 3868 d_instantiate(dentry, inode); 3869 3870 dget(dentry); /* Extra count - pin the dentry in core */ 3871 return error; 3872 3873 out_iput: 3874 iput(inode); 3875 return error; 3876 } 3877 3878 static int 3879 shmem_tmpfile(struct mnt_idmap *idmap, struct inode *dir, 3880 struct file *file, umode_t mode) 3881 { 3882 struct inode *inode; 3883 int error; 3884 3885 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, 0, VM_NORESERVE); 3886 if (IS_ERR(inode)) { 3887 error = PTR_ERR(inode); 3888 goto err_out; 3889 } 3890 error = security_inode_init_security(inode, dir, NULL, 3891 shmem_initxattrs, NULL); 3892 if (error && error != -EOPNOTSUPP) 3893 goto out_iput; 3894 error = simple_acl_create(dir, inode); 3895 if (error) 3896 goto out_iput; 3897 d_tmpfile(file, inode); 3898 3899 err_out: 3900 return finish_open_simple(file, error); 3901 out_iput: 3902 iput(inode); 3903 return error; 3904 } 3905 3906 static int shmem_mkdir(struct mnt_idmap *idmap, struct inode *dir, 3907 struct dentry *dentry, umode_t mode) 3908 { 3909 int error; 3910 3911 error = shmem_mknod(idmap, dir, dentry, mode | S_IFDIR, 0); 3912 if (error) 3913 return error; 3914 inc_nlink(dir); 3915 return 0; 3916 } 3917 3918 static int shmem_create(struct mnt_idmap *idmap, struct inode *dir, 3919 struct dentry *dentry, umode_t mode, bool excl) 3920 { 3921 return shmem_mknod(idmap, dir, dentry, mode | S_IFREG, 0); 3922 } 3923 3924 /* 3925 * Link a file.. 3926 */ 3927 static int shmem_link(struct dentry *old_dentry, struct inode *dir, 3928 struct dentry *dentry) 3929 { 3930 struct inode *inode = d_inode(old_dentry); 3931 int ret = 0; 3932 3933 /* 3934 * No ordinary (disk based) filesystem counts links as inodes; 3935 * but each new link needs a new dentry, pinning lowmem, and 3936 * tmpfs dentries cannot be pruned until they are unlinked. 3937 * But if an O_TMPFILE file is linked into the tmpfs, the 3938 * first link must skip that, to get the accounting right. 3939 */ 3940 if (inode->i_nlink) { 3941 ret = shmem_reserve_inode(inode->i_sb, NULL); 3942 if (ret) 3943 goto out; 3944 } 3945 3946 ret = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 3947 if (ret) { 3948 if (inode->i_nlink) 3949 shmem_free_inode(inode->i_sb, 0); 3950 goto out; 3951 } 3952 3953 dir->i_size += BOGO_DIRENT_SIZE; 3954 inode_set_mtime_to_ts(dir, 3955 inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode))); 3956 inode_inc_iversion(dir); 3957 inc_nlink(inode); 3958 ihold(inode); /* New dentry reference */ 3959 dget(dentry); /* Extra pinning count for the created dentry */ 3960 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3961 d_add(dentry, inode); 3962 else 3963 d_instantiate(dentry, inode); 3964 out: 3965 return ret; 3966 } 3967 3968 static int shmem_unlink(struct inode *dir, struct dentry *dentry) 3969 { 3970 struct inode *inode = d_inode(dentry); 3971 3972 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode)) 3973 shmem_free_inode(inode->i_sb, 0); 3974 3975 simple_offset_remove(shmem_get_offset_ctx(dir), dentry); 3976 3977 dir->i_size -= BOGO_DIRENT_SIZE; 3978 inode_set_mtime_to_ts(dir, 3979 inode_set_ctime_to_ts(dir, inode_set_ctime_current(inode))); 3980 inode_inc_iversion(dir); 3981 drop_nlink(inode); 3982 dput(dentry); /* Undo the count from "create" - does all the work */ 3983 3984 /* 3985 * For now, VFS can't deal with case-insensitive negative dentries, so 3986 * we invalidate them 3987 */ 3988 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 3989 d_invalidate(dentry); 3990 3991 return 0; 3992 } 3993 3994 static int shmem_rmdir(struct inode *dir, struct dentry *dentry) 3995 { 3996 if (!simple_empty(dentry)) 3997 return -ENOTEMPTY; 3998 3999 drop_nlink(d_inode(dentry)); 4000 drop_nlink(dir); 4001 return shmem_unlink(dir, dentry); 4002 } 4003 4004 static int shmem_whiteout(struct mnt_idmap *idmap, 4005 struct inode *old_dir, struct dentry *old_dentry) 4006 { 4007 struct dentry *whiteout; 4008 int error; 4009 4010 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name); 4011 if (!whiteout) 4012 return -ENOMEM; 4013 4014 error = shmem_mknod(idmap, old_dir, whiteout, 4015 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV); 4016 dput(whiteout); 4017 if (error) 4018 return error; 4019 4020 /* 4021 * Cheat and hash the whiteout while the old dentry is still in 4022 * place, instead of playing games with FS_RENAME_DOES_D_MOVE. 4023 * 4024 * d_lookup() will consistently find one of them at this point, 4025 * not sure which one, but that isn't even important. 4026 */ 4027 d_rehash(whiteout); 4028 return 0; 4029 } 4030 4031 /* 4032 * The VFS layer already does all the dentry stuff for rename, 4033 * we just have to decrement the usage count for the target if 4034 * it exists so that the VFS layer correctly free's it when it 4035 * gets overwritten. 4036 */ 4037 static int shmem_rename2(struct mnt_idmap *idmap, 4038 struct inode *old_dir, struct dentry *old_dentry, 4039 struct inode *new_dir, struct dentry *new_dentry, 4040 unsigned int flags) 4041 { 4042 struct inode *inode = d_inode(old_dentry); 4043 int they_are_dirs = S_ISDIR(inode->i_mode); 4044 int error; 4045 4046 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) 4047 return -EINVAL; 4048 4049 if (flags & RENAME_EXCHANGE) 4050 return simple_offset_rename_exchange(old_dir, old_dentry, 4051 new_dir, new_dentry); 4052 4053 if (!simple_empty(new_dentry)) 4054 return -ENOTEMPTY; 4055 4056 if (flags & RENAME_WHITEOUT) { 4057 error = shmem_whiteout(idmap, old_dir, old_dentry); 4058 if (error) 4059 return error; 4060 } 4061 4062 error = simple_offset_rename(old_dir, old_dentry, new_dir, new_dentry); 4063 if (error) 4064 return error; 4065 4066 if (d_really_is_positive(new_dentry)) { 4067 (void) shmem_unlink(new_dir, new_dentry); 4068 if (they_are_dirs) { 4069 drop_nlink(d_inode(new_dentry)); 4070 drop_nlink(old_dir); 4071 } 4072 } else if (they_are_dirs) { 4073 drop_nlink(old_dir); 4074 inc_nlink(new_dir); 4075 } 4076 4077 old_dir->i_size -= BOGO_DIRENT_SIZE; 4078 new_dir->i_size += BOGO_DIRENT_SIZE; 4079 simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry); 4080 inode_inc_iversion(old_dir); 4081 inode_inc_iversion(new_dir); 4082 return 0; 4083 } 4084 4085 static int shmem_symlink(struct mnt_idmap *idmap, struct inode *dir, 4086 struct dentry *dentry, const char *symname) 4087 { 4088 int error; 4089 int len; 4090 struct inode *inode; 4091 struct folio *folio; 4092 char *link; 4093 4094 len = strlen(symname) + 1; 4095 if (len > PAGE_SIZE) 4096 return -ENAMETOOLONG; 4097 4098 inode = shmem_get_inode(idmap, dir->i_sb, dir, S_IFLNK | 0777, 0, 4099 VM_NORESERVE); 4100 if (IS_ERR(inode)) 4101 return PTR_ERR(inode); 4102 4103 error = security_inode_init_security(inode, dir, &dentry->d_name, 4104 shmem_initxattrs, NULL); 4105 if (error && error != -EOPNOTSUPP) 4106 goto out_iput; 4107 4108 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry); 4109 if (error) 4110 goto out_iput; 4111 4112 inode->i_size = len-1; 4113 if (len <= SHORT_SYMLINK_LEN) { 4114 link = kmemdup(symname, len, GFP_KERNEL); 4115 if (!link) { 4116 error = -ENOMEM; 4117 goto out_remove_offset; 4118 } 4119 inode->i_op = &shmem_short_symlink_operations; 4120 inode_set_cached_link(inode, link, len - 1); 4121 } else { 4122 inode_nohighmem(inode); 4123 inode->i_mapping->a_ops = &shmem_aops; 4124 error = shmem_get_folio(inode, 0, 0, &folio, SGP_WRITE); 4125 if (error) 4126 goto out_remove_offset; 4127 inode->i_op = &shmem_symlink_inode_operations; 4128 memcpy(folio_address(folio), symname, len); 4129 folio_mark_uptodate(folio); 4130 folio_mark_dirty(folio); 4131 folio_unlock(folio); 4132 folio_put(folio); 4133 } 4134 dir->i_size += BOGO_DIRENT_SIZE; 4135 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir)); 4136 inode_inc_iversion(dir); 4137 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir)) 4138 d_add(dentry, inode); 4139 else 4140 d_instantiate(dentry, inode); 4141 dget(dentry); 4142 return 0; 4143 4144 out_remove_offset: 4145 simple_offset_remove(shmem_get_offset_ctx(dir), dentry); 4146 out_iput: 4147 iput(inode); 4148 return error; 4149 } 4150 4151 static void shmem_put_link(void *arg) 4152 { 4153 folio_mark_accessed(arg); 4154 folio_put(arg); 4155 } 4156 4157 static const char *shmem_get_link(struct dentry *dentry, struct inode *inode, 4158 struct delayed_call *done) 4159 { 4160 struct folio *folio = NULL; 4161 int error; 4162 4163 if (!dentry) { 4164 folio = filemap_get_folio(inode->i_mapping, 0); 4165 if (IS_ERR(folio)) 4166 return ERR_PTR(-ECHILD); 4167 if (PageHWPoison(folio_page(folio, 0)) || 4168 !folio_test_uptodate(folio)) { 4169 folio_put(folio); 4170 return ERR_PTR(-ECHILD); 4171 } 4172 } else { 4173 error = shmem_get_folio(inode, 0, 0, &folio, SGP_READ); 4174 if (error) 4175 return ERR_PTR(error); 4176 if (!folio) 4177 return ERR_PTR(-ECHILD); 4178 if (PageHWPoison(folio_page(folio, 0))) { 4179 folio_unlock(folio); 4180 folio_put(folio); 4181 return ERR_PTR(-ECHILD); 4182 } 4183 folio_unlock(folio); 4184 } 4185 set_delayed_call(done, shmem_put_link, folio); 4186 return folio_address(folio); 4187 } 4188 4189 #ifdef CONFIG_TMPFS_XATTR 4190 4191 static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa) 4192 { 4193 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4194 4195 fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE); 4196 4197 return 0; 4198 } 4199 4200 static int shmem_fileattr_set(struct mnt_idmap *idmap, 4201 struct dentry *dentry, struct fileattr *fa) 4202 { 4203 struct inode *inode = d_inode(dentry); 4204 struct shmem_inode_info *info = SHMEM_I(inode); 4205 int ret, flags; 4206 4207 if (fileattr_has_fsx(fa)) 4208 return -EOPNOTSUPP; 4209 if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE) 4210 return -EOPNOTSUPP; 4211 4212 flags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) | 4213 (fa->flags & SHMEM_FL_USER_MODIFIABLE); 4214 4215 ret = shmem_set_inode_flags(inode, flags, dentry); 4216 4217 if (ret) 4218 return ret; 4219 4220 info->fsflags = flags; 4221 4222 inode_set_ctime_current(inode); 4223 inode_inc_iversion(inode); 4224 return 0; 4225 } 4226 4227 /* 4228 * Superblocks without xattr inode operations may get some security.* xattr 4229 * support from the LSM "for free". As soon as we have any other xattrs 4230 * like ACLs, we also need to implement the security.* handlers at 4231 * filesystem level, though. 4232 */ 4233 4234 /* 4235 * Callback for security_inode_init_security() for acquiring xattrs. 4236 */ 4237 static int shmem_initxattrs(struct inode *inode, 4238 const struct xattr *xattr_array, void *fs_info) 4239 { 4240 struct shmem_inode_info *info = SHMEM_I(inode); 4241 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4242 const struct xattr *xattr; 4243 struct simple_xattr *new_xattr; 4244 size_t ispace = 0; 4245 size_t len; 4246 4247 if (sbinfo->max_inodes) { 4248 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4249 ispace += simple_xattr_space(xattr->name, 4250 xattr->value_len + XATTR_SECURITY_PREFIX_LEN); 4251 } 4252 if (ispace) { 4253 raw_spin_lock(&sbinfo->stat_lock); 4254 if (sbinfo->free_ispace < ispace) 4255 ispace = 0; 4256 else 4257 sbinfo->free_ispace -= ispace; 4258 raw_spin_unlock(&sbinfo->stat_lock); 4259 if (!ispace) 4260 return -ENOSPC; 4261 } 4262 } 4263 4264 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 4265 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len); 4266 if (!new_xattr) 4267 break; 4268 4269 len = strlen(xattr->name) + 1; 4270 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len, 4271 GFP_KERNEL_ACCOUNT); 4272 if (!new_xattr->name) { 4273 kvfree(new_xattr); 4274 break; 4275 } 4276 4277 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX, 4278 XATTR_SECURITY_PREFIX_LEN); 4279 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN, 4280 xattr->name, len); 4281 4282 simple_xattr_add(&info->xattrs, new_xattr); 4283 } 4284 4285 if (xattr->name != NULL) { 4286 if (ispace) { 4287 raw_spin_lock(&sbinfo->stat_lock); 4288 sbinfo->free_ispace += ispace; 4289 raw_spin_unlock(&sbinfo->stat_lock); 4290 } 4291 simple_xattrs_free(&info->xattrs, NULL); 4292 return -ENOMEM; 4293 } 4294 4295 return 0; 4296 } 4297 4298 static int shmem_xattr_handler_get(const struct xattr_handler *handler, 4299 struct dentry *unused, struct inode *inode, 4300 const char *name, void *buffer, size_t size) 4301 { 4302 struct shmem_inode_info *info = SHMEM_I(inode); 4303 4304 name = xattr_full_name(handler, name); 4305 return simple_xattr_get(&info->xattrs, name, buffer, size); 4306 } 4307 4308 static int shmem_xattr_handler_set(const struct xattr_handler *handler, 4309 struct mnt_idmap *idmap, 4310 struct dentry *unused, struct inode *inode, 4311 const char *name, const void *value, 4312 size_t size, int flags) 4313 { 4314 struct shmem_inode_info *info = SHMEM_I(inode); 4315 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 4316 struct simple_xattr *old_xattr; 4317 size_t ispace = 0; 4318 4319 name = xattr_full_name(handler, name); 4320 if (value && sbinfo->max_inodes) { 4321 ispace = simple_xattr_space(name, size); 4322 raw_spin_lock(&sbinfo->stat_lock); 4323 if (sbinfo->free_ispace < ispace) 4324 ispace = 0; 4325 else 4326 sbinfo->free_ispace -= ispace; 4327 raw_spin_unlock(&sbinfo->stat_lock); 4328 if (!ispace) 4329 return -ENOSPC; 4330 } 4331 4332 old_xattr = simple_xattr_set(&info->xattrs, name, value, size, flags); 4333 if (!IS_ERR(old_xattr)) { 4334 ispace = 0; 4335 if (old_xattr && sbinfo->max_inodes) 4336 ispace = simple_xattr_space(old_xattr->name, 4337 old_xattr->size); 4338 simple_xattr_free(old_xattr); 4339 old_xattr = NULL; 4340 inode_set_ctime_current(inode); 4341 inode_inc_iversion(inode); 4342 } 4343 if (ispace) { 4344 raw_spin_lock(&sbinfo->stat_lock); 4345 sbinfo->free_ispace += ispace; 4346 raw_spin_unlock(&sbinfo->stat_lock); 4347 } 4348 return PTR_ERR(old_xattr); 4349 } 4350 4351 static const struct xattr_handler shmem_security_xattr_handler = { 4352 .prefix = XATTR_SECURITY_PREFIX, 4353 .get = shmem_xattr_handler_get, 4354 .set = shmem_xattr_handler_set, 4355 }; 4356 4357 static const struct xattr_handler shmem_trusted_xattr_handler = { 4358 .prefix = XATTR_TRUSTED_PREFIX, 4359 .get = shmem_xattr_handler_get, 4360 .set = shmem_xattr_handler_set, 4361 }; 4362 4363 static const struct xattr_handler shmem_user_xattr_handler = { 4364 .prefix = XATTR_USER_PREFIX, 4365 .get = shmem_xattr_handler_get, 4366 .set = shmem_xattr_handler_set, 4367 }; 4368 4369 static const struct xattr_handler * const shmem_xattr_handlers[] = { 4370 &shmem_security_xattr_handler, 4371 &shmem_trusted_xattr_handler, 4372 &shmem_user_xattr_handler, 4373 NULL 4374 }; 4375 4376 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size) 4377 { 4378 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 4379 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size); 4380 } 4381 #endif /* CONFIG_TMPFS_XATTR */ 4382 4383 static const struct inode_operations shmem_short_symlink_operations = { 4384 .getattr = shmem_getattr, 4385 .setattr = shmem_setattr, 4386 .get_link = simple_get_link, 4387 #ifdef CONFIG_TMPFS_XATTR 4388 .listxattr = shmem_listxattr, 4389 #endif 4390 }; 4391 4392 static const struct inode_operations shmem_symlink_inode_operations = { 4393 .getattr = shmem_getattr, 4394 .setattr = shmem_setattr, 4395 .get_link = shmem_get_link, 4396 #ifdef CONFIG_TMPFS_XATTR 4397 .listxattr = shmem_listxattr, 4398 #endif 4399 }; 4400 4401 static struct dentry *shmem_get_parent(struct dentry *child) 4402 { 4403 return ERR_PTR(-ESTALE); 4404 } 4405 4406 static int shmem_match(struct inode *ino, void *vfh) 4407 { 4408 __u32 *fh = vfh; 4409 __u64 inum = fh[2]; 4410 inum = (inum << 32) | fh[1]; 4411 return ino->i_ino == inum && fh[0] == ino->i_generation; 4412 } 4413 4414 /* Find any alias of inode, but prefer a hashed alias */ 4415 static struct dentry *shmem_find_alias(struct inode *inode) 4416 { 4417 struct dentry *alias = d_find_alias(inode); 4418 4419 return alias ?: d_find_any_alias(inode); 4420 } 4421 4422 static struct dentry *shmem_fh_to_dentry(struct super_block *sb, 4423 struct fid *fid, int fh_len, int fh_type) 4424 { 4425 struct inode *inode; 4426 struct dentry *dentry = NULL; 4427 u64 inum; 4428 4429 if (fh_len < 3) 4430 return NULL; 4431 4432 inum = fid->raw[2]; 4433 inum = (inum << 32) | fid->raw[1]; 4434 4435 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]), 4436 shmem_match, fid->raw); 4437 if (inode) { 4438 dentry = shmem_find_alias(inode); 4439 iput(inode); 4440 } 4441 4442 return dentry; 4443 } 4444 4445 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len, 4446 struct inode *parent) 4447 { 4448 if (*len < 3) { 4449 *len = 3; 4450 return FILEID_INVALID; 4451 } 4452 4453 if (inode_unhashed(inode)) { 4454 /* Unfortunately insert_inode_hash is not idempotent, 4455 * so as we hash inodes here rather than at creation 4456 * time, we need a lock to ensure we only try 4457 * to do it once 4458 */ 4459 static DEFINE_SPINLOCK(lock); 4460 spin_lock(&lock); 4461 if (inode_unhashed(inode)) 4462 __insert_inode_hash(inode, 4463 inode->i_ino + inode->i_generation); 4464 spin_unlock(&lock); 4465 } 4466 4467 fh[0] = inode->i_generation; 4468 fh[1] = inode->i_ino; 4469 fh[2] = ((__u64)inode->i_ino) >> 32; 4470 4471 *len = 3; 4472 return 1; 4473 } 4474 4475 static const struct export_operations shmem_export_ops = { 4476 .get_parent = shmem_get_parent, 4477 .encode_fh = shmem_encode_fh, 4478 .fh_to_dentry = shmem_fh_to_dentry, 4479 }; 4480 4481 enum shmem_param { 4482 Opt_gid, 4483 Opt_huge, 4484 Opt_mode, 4485 Opt_mpol, 4486 Opt_nr_blocks, 4487 Opt_nr_inodes, 4488 Opt_size, 4489 Opt_uid, 4490 Opt_inode32, 4491 Opt_inode64, 4492 Opt_noswap, 4493 Opt_quota, 4494 Opt_usrquota, 4495 Opt_grpquota, 4496 Opt_usrquota_block_hardlimit, 4497 Opt_usrquota_inode_hardlimit, 4498 Opt_grpquota_block_hardlimit, 4499 Opt_grpquota_inode_hardlimit, 4500 Opt_casefold_version, 4501 Opt_casefold, 4502 Opt_strict_encoding, 4503 }; 4504 4505 static const struct constant_table shmem_param_enums_huge[] = { 4506 {"never", SHMEM_HUGE_NEVER }, 4507 {"always", SHMEM_HUGE_ALWAYS }, 4508 {"within_size", SHMEM_HUGE_WITHIN_SIZE }, 4509 {"advise", SHMEM_HUGE_ADVISE }, 4510 {} 4511 }; 4512 4513 const struct fs_parameter_spec shmem_fs_parameters[] = { 4514 fsparam_gid ("gid", Opt_gid), 4515 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge), 4516 fsparam_u32oct("mode", Opt_mode), 4517 fsparam_string("mpol", Opt_mpol), 4518 fsparam_string("nr_blocks", Opt_nr_blocks), 4519 fsparam_string("nr_inodes", Opt_nr_inodes), 4520 fsparam_string("size", Opt_size), 4521 fsparam_uid ("uid", Opt_uid), 4522 fsparam_flag ("inode32", Opt_inode32), 4523 fsparam_flag ("inode64", Opt_inode64), 4524 fsparam_flag ("noswap", Opt_noswap), 4525 #ifdef CONFIG_TMPFS_QUOTA 4526 fsparam_flag ("quota", Opt_quota), 4527 fsparam_flag ("usrquota", Opt_usrquota), 4528 fsparam_flag ("grpquota", Opt_grpquota), 4529 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit), 4530 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit), 4531 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit), 4532 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit), 4533 #endif 4534 fsparam_string("casefold", Opt_casefold_version), 4535 fsparam_flag ("casefold", Opt_casefold), 4536 fsparam_flag ("strict_encoding", Opt_strict_encoding), 4537 {} 4538 }; 4539 4540 #if IS_ENABLED(CONFIG_UNICODE) 4541 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4542 bool latest_version) 4543 { 4544 struct shmem_options *ctx = fc->fs_private; 4545 int version = UTF8_LATEST; 4546 struct unicode_map *encoding; 4547 char *version_str = param->string + 5; 4548 4549 if (!latest_version) { 4550 if (strncmp(param->string, "utf8-", 5)) 4551 return invalfc(fc, "Only UTF-8 encodings are supported " 4552 "in the format: utf8-<version number>"); 4553 4554 version = utf8_parse_version(version_str); 4555 if (version < 0) 4556 return invalfc(fc, "Invalid UTF-8 version: %s", version_str); 4557 } 4558 4559 encoding = utf8_load(version); 4560 4561 if (IS_ERR(encoding)) { 4562 return invalfc(fc, "Failed loading UTF-8 version: utf8-%u.%u.%u\n", 4563 unicode_major(version), unicode_minor(version), 4564 unicode_rev(version)); 4565 } 4566 4567 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n", 4568 unicode_major(version), unicode_minor(version), unicode_rev(version)); 4569 4570 ctx->encoding = encoding; 4571 4572 return 0; 4573 } 4574 #else 4575 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param, 4576 bool latest_version) 4577 { 4578 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4579 } 4580 #endif 4581 4582 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param) 4583 { 4584 struct shmem_options *ctx = fc->fs_private; 4585 struct fs_parse_result result; 4586 unsigned long long size; 4587 char *rest; 4588 int opt; 4589 kuid_t kuid; 4590 kgid_t kgid; 4591 4592 opt = fs_parse(fc, shmem_fs_parameters, param, &result); 4593 if (opt < 0) 4594 return opt; 4595 4596 switch (opt) { 4597 case Opt_size: 4598 size = memparse(param->string, &rest); 4599 if (*rest == '%') { 4600 size <<= PAGE_SHIFT; 4601 size *= totalram_pages(); 4602 do_div(size, 100); 4603 rest++; 4604 } 4605 if (*rest) 4606 goto bad_value; 4607 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE); 4608 ctx->seen |= SHMEM_SEEN_BLOCKS; 4609 break; 4610 case Opt_nr_blocks: 4611 ctx->blocks = memparse(param->string, &rest); 4612 if (*rest || ctx->blocks > LONG_MAX) 4613 goto bad_value; 4614 ctx->seen |= SHMEM_SEEN_BLOCKS; 4615 break; 4616 case Opt_nr_inodes: 4617 ctx->inodes = memparse(param->string, &rest); 4618 if (*rest || ctx->inodes > ULONG_MAX / BOGO_INODE_SIZE) 4619 goto bad_value; 4620 ctx->seen |= SHMEM_SEEN_INODES; 4621 break; 4622 case Opt_mode: 4623 ctx->mode = result.uint_32 & 07777; 4624 break; 4625 case Opt_uid: 4626 kuid = result.uid; 4627 4628 /* 4629 * The requested uid must be representable in the 4630 * filesystem's idmapping. 4631 */ 4632 if (!kuid_has_mapping(fc->user_ns, kuid)) 4633 goto bad_value; 4634 4635 ctx->uid = kuid; 4636 break; 4637 case Opt_gid: 4638 kgid = result.gid; 4639 4640 /* 4641 * The requested gid must be representable in the 4642 * filesystem's idmapping. 4643 */ 4644 if (!kgid_has_mapping(fc->user_ns, kgid)) 4645 goto bad_value; 4646 4647 ctx->gid = kgid; 4648 break; 4649 case Opt_huge: 4650 ctx->huge = result.uint_32; 4651 if (ctx->huge != SHMEM_HUGE_NEVER && 4652 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && 4653 has_transparent_hugepage())) 4654 goto unsupported_parameter; 4655 ctx->seen |= SHMEM_SEEN_HUGE; 4656 break; 4657 case Opt_mpol: 4658 if (IS_ENABLED(CONFIG_NUMA)) { 4659 mpol_put(ctx->mpol); 4660 ctx->mpol = NULL; 4661 if (mpol_parse_str(param->string, &ctx->mpol)) 4662 goto bad_value; 4663 break; 4664 } 4665 goto unsupported_parameter; 4666 case Opt_inode32: 4667 ctx->full_inums = false; 4668 ctx->seen |= SHMEM_SEEN_INUMS; 4669 break; 4670 case Opt_inode64: 4671 if (sizeof(ino_t) < 8) { 4672 return invalfc(fc, 4673 "Cannot use inode64 with <64bit inums in kernel\n"); 4674 } 4675 ctx->full_inums = true; 4676 ctx->seen |= SHMEM_SEEN_INUMS; 4677 break; 4678 case Opt_noswap: 4679 if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) { 4680 return invalfc(fc, 4681 "Turning off swap in unprivileged tmpfs mounts unsupported"); 4682 } 4683 ctx->noswap = true; 4684 ctx->seen |= SHMEM_SEEN_NOSWAP; 4685 break; 4686 case Opt_quota: 4687 if (fc->user_ns != &init_user_ns) 4688 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4689 ctx->seen |= SHMEM_SEEN_QUOTA; 4690 ctx->quota_types |= (QTYPE_MASK_USR | QTYPE_MASK_GRP); 4691 break; 4692 case Opt_usrquota: 4693 if (fc->user_ns != &init_user_ns) 4694 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4695 ctx->seen |= SHMEM_SEEN_QUOTA; 4696 ctx->quota_types |= QTYPE_MASK_USR; 4697 break; 4698 case Opt_grpquota: 4699 if (fc->user_ns != &init_user_ns) 4700 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported"); 4701 ctx->seen |= SHMEM_SEEN_QUOTA; 4702 ctx->quota_types |= QTYPE_MASK_GRP; 4703 break; 4704 case Opt_usrquota_block_hardlimit: 4705 size = memparse(param->string, &rest); 4706 if (*rest || !size) 4707 goto bad_value; 4708 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4709 return invalfc(fc, 4710 "User quota block hardlimit too large."); 4711 ctx->qlimits.usrquota_bhardlimit = size; 4712 break; 4713 case Opt_grpquota_block_hardlimit: 4714 size = memparse(param->string, &rest); 4715 if (*rest || !size) 4716 goto bad_value; 4717 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT) 4718 return invalfc(fc, 4719 "Group quota block hardlimit too large."); 4720 ctx->qlimits.grpquota_bhardlimit = size; 4721 break; 4722 case Opt_usrquota_inode_hardlimit: 4723 size = memparse(param->string, &rest); 4724 if (*rest || !size) 4725 goto bad_value; 4726 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4727 return invalfc(fc, 4728 "User quota inode hardlimit too large."); 4729 ctx->qlimits.usrquota_ihardlimit = size; 4730 break; 4731 case Opt_grpquota_inode_hardlimit: 4732 size = memparse(param->string, &rest); 4733 if (*rest || !size) 4734 goto bad_value; 4735 if (size > SHMEM_QUOTA_MAX_INO_LIMIT) 4736 return invalfc(fc, 4737 "Group quota inode hardlimit too large."); 4738 ctx->qlimits.grpquota_ihardlimit = size; 4739 break; 4740 case Opt_casefold_version: 4741 return shmem_parse_opt_casefold(fc, param, false); 4742 case Opt_casefold: 4743 return shmem_parse_opt_casefold(fc, param, true); 4744 case Opt_strict_encoding: 4745 #if IS_ENABLED(CONFIG_UNICODE) 4746 ctx->strict_encoding = true; 4747 break; 4748 #else 4749 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n"); 4750 #endif 4751 } 4752 return 0; 4753 4754 unsupported_parameter: 4755 return invalfc(fc, "Unsupported parameter '%s'", param->key); 4756 bad_value: 4757 return invalfc(fc, "Bad value for '%s'", param->key); 4758 } 4759 4760 static char *shmem_next_opt(char **s) 4761 { 4762 char *sbegin = *s; 4763 char *p; 4764 4765 if (sbegin == NULL) 4766 return NULL; 4767 4768 /* 4769 * NUL-terminate this option: unfortunately, 4770 * mount options form a comma-separated list, 4771 * but mpol's nodelist may also contain commas. 4772 */ 4773 for (;;) { 4774 p = strchr(*s, ','); 4775 if (p == NULL) 4776 break; 4777 *s = p + 1; 4778 if (!isdigit(*(p+1))) { 4779 *p = '\0'; 4780 return sbegin; 4781 } 4782 } 4783 4784 *s = NULL; 4785 return sbegin; 4786 } 4787 4788 static int shmem_parse_monolithic(struct fs_context *fc, void *data) 4789 { 4790 return vfs_parse_monolithic_sep(fc, data, shmem_next_opt); 4791 } 4792 4793 /* 4794 * Reconfigure a shmem filesystem. 4795 */ 4796 static int shmem_reconfigure(struct fs_context *fc) 4797 { 4798 struct shmem_options *ctx = fc->fs_private; 4799 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb); 4800 unsigned long used_isp; 4801 struct mempolicy *mpol = NULL; 4802 const char *err; 4803 4804 raw_spin_lock(&sbinfo->stat_lock); 4805 used_isp = sbinfo->max_inodes * BOGO_INODE_SIZE - sbinfo->free_ispace; 4806 4807 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) { 4808 if (!sbinfo->max_blocks) { 4809 err = "Cannot retroactively limit size"; 4810 goto out; 4811 } 4812 if (percpu_counter_compare(&sbinfo->used_blocks, 4813 ctx->blocks) > 0) { 4814 err = "Too small a size for current use"; 4815 goto out; 4816 } 4817 } 4818 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) { 4819 if (!sbinfo->max_inodes) { 4820 err = "Cannot retroactively limit inodes"; 4821 goto out; 4822 } 4823 if (ctx->inodes * BOGO_INODE_SIZE < used_isp) { 4824 err = "Too few inodes for current use"; 4825 goto out; 4826 } 4827 } 4828 4829 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums && 4830 sbinfo->next_ino > UINT_MAX) { 4831 err = "Current inum too high to switch to 32-bit inums"; 4832 goto out; 4833 } 4834 if ((ctx->seen & SHMEM_SEEN_NOSWAP) && ctx->noswap && !sbinfo->noswap) { 4835 err = "Cannot disable swap on remount"; 4836 goto out; 4837 } 4838 if (!(ctx->seen & SHMEM_SEEN_NOSWAP) && !ctx->noswap && sbinfo->noswap) { 4839 err = "Cannot enable swap on remount if it was disabled on first mount"; 4840 goto out; 4841 } 4842 4843 if (ctx->seen & SHMEM_SEEN_QUOTA && 4844 !sb_any_quota_loaded(fc->root->d_sb)) { 4845 err = "Cannot enable quota on remount"; 4846 goto out; 4847 } 4848 4849 #ifdef CONFIG_TMPFS_QUOTA 4850 #define CHANGED_LIMIT(name) \ 4851 (ctx->qlimits.name## hardlimit && \ 4852 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit)) 4853 4854 if (CHANGED_LIMIT(usrquota_b) || CHANGED_LIMIT(usrquota_i) || 4855 CHANGED_LIMIT(grpquota_b) || CHANGED_LIMIT(grpquota_i)) { 4856 err = "Cannot change global quota limit on remount"; 4857 goto out; 4858 } 4859 #endif /* CONFIG_TMPFS_QUOTA */ 4860 4861 if (ctx->seen & SHMEM_SEEN_HUGE) 4862 sbinfo->huge = ctx->huge; 4863 if (ctx->seen & SHMEM_SEEN_INUMS) 4864 sbinfo->full_inums = ctx->full_inums; 4865 if (ctx->seen & SHMEM_SEEN_BLOCKS) 4866 sbinfo->max_blocks = ctx->blocks; 4867 if (ctx->seen & SHMEM_SEEN_INODES) { 4868 sbinfo->max_inodes = ctx->inodes; 4869 sbinfo->free_ispace = ctx->inodes * BOGO_INODE_SIZE - used_isp; 4870 } 4871 4872 /* 4873 * Preserve previous mempolicy unless mpol remount option was specified. 4874 */ 4875 if (ctx->mpol) { 4876 mpol = sbinfo->mpol; 4877 sbinfo->mpol = ctx->mpol; /* transfers initial ref */ 4878 ctx->mpol = NULL; 4879 } 4880 4881 if (ctx->noswap) 4882 sbinfo->noswap = true; 4883 4884 raw_spin_unlock(&sbinfo->stat_lock); 4885 mpol_put(mpol); 4886 return 0; 4887 out: 4888 raw_spin_unlock(&sbinfo->stat_lock); 4889 return invalfc(fc, "%s", err); 4890 } 4891 4892 static int shmem_show_options(struct seq_file *seq, struct dentry *root) 4893 { 4894 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb); 4895 struct mempolicy *mpol; 4896 4897 if (sbinfo->max_blocks != shmem_default_max_blocks()) 4898 seq_printf(seq, ",size=%luk", K(sbinfo->max_blocks)); 4899 if (sbinfo->max_inodes != shmem_default_max_inodes()) 4900 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes); 4901 if (sbinfo->mode != (0777 | S_ISVTX)) 4902 seq_printf(seq, ",mode=%03ho", sbinfo->mode); 4903 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID)) 4904 seq_printf(seq, ",uid=%u", 4905 from_kuid_munged(&init_user_ns, sbinfo->uid)); 4906 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID)) 4907 seq_printf(seq, ",gid=%u", 4908 from_kgid_munged(&init_user_ns, sbinfo->gid)); 4909 4910 /* 4911 * Showing inode{64,32} might be useful even if it's the system default, 4912 * since then people don't have to resort to checking both here and 4913 * /proc/config.gz to confirm 64-bit inums were successfully applied 4914 * (which may not even exist if IKCONFIG_PROC isn't enabled). 4915 * 4916 * We hide it when inode64 isn't the default and we are using 32-bit 4917 * inodes, since that probably just means the feature isn't even under 4918 * consideration. 4919 * 4920 * As such: 4921 * 4922 * +-----------------+-----------------+ 4923 * | TMPFS_INODE64=y | TMPFS_INODE64=n | 4924 * +------------------+-----------------+-----------------+ 4925 * | full_inums=true | show | show | 4926 * | full_inums=false | show | hide | 4927 * +------------------+-----------------+-----------------+ 4928 * 4929 */ 4930 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums) 4931 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32)); 4932 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4933 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */ 4934 if (sbinfo->huge) 4935 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge)); 4936 #endif 4937 mpol = shmem_get_sbmpol(sbinfo); 4938 shmem_show_mpol(seq, mpol); 4939 mpol_put(mpol); 4940 if (sbinfo->noswap) 4941 seq_printf(seq, ",noswap"); 4942 #ifdef CONFIG_TMPFS_QUOTA 4943 if (sb_has_quota_active(root->d_sb, USRQUOTA)) 4944 seq_printf(seq, ",usrquota"); 4945 if (sb_has_quota_active(root->d_sb, GRPQUOTA)) 4946 seq_printf(seq, ",grpquota"); 4947 if (sbinfo->qlimits.usrquota_bhardlimit) 4948 seq_printf(seq, ",usrquota_block_hardlimit=%lld", 4949 sbinfo->qlimits.usrquota_bhardlimit); 4950 if (sbinfo->qlimits.grpquota_bhardlimit) 4951 seq_printf(seq, ",grpquota_block_hardlimit=%lld", 4952 sbinfo->qlimits.grpquota_bhardlimit); 4953 if (sbinfo->qlimits.usrquota_ihardlimit) 4954 seq_printf(seq, ",usrquota_inode_hardlimit=%lld", 4955 sbinfo->qlimits.usrquota_ihardlimit); 4956 if (sbinfo->qlimits.grpquota_ihardlimit) 4957 seq_printf(seq, ",grpquota_inode_hardlimit=%lld", 4958 sbinfo->qlimits.grpquota_ihardlimit); 4959 #endif 4960 return 0; 4961 } 4962 4963 #endif /* CONFIG_TMPFS */ 4964 4965 static void shmem_put_super(struct super_block *sb) 4966 { 4967 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 4968 4969 #if IS_ENABLED(CONFIG_UNICODE) 4970 if (sb->s_encoding) 4971 utf8_unload(sb->s_encoding); 4972 #endif 4973 4974 #ifdef CONFIG_TMPFS_QUOTA 4975 shmem_disable_quotas(sb); 4976 #endif 4977 free_percpu(sbinfo->ino_batch); 4978 percpu_counter_destroy(&sbinfo->used_blocks); 4979 mpol_put(sbinfo->mpol); 4980 kfree(sbinfo); 4981 sb->s_fs_info = NULL; 4982 } 4983 4984 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS) 4985 static const struct dentry_operations shmem_ci_dentry_ops = { 4986 .d_hash = generic_ci_d_hash, 4987 .d_compare = generic_ci_d_compare, 4988 .d_delete = always_delete_dentry, 4989 }; 4990 #endif 4991 4992 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc) 4993 { 4994 struct shmem_options *ctx = fc->fs_private; 4995 struct inode *inode; 4996 struct shmem_sb_info *sbinfo; 4997 int error = -ENOMEM; 4998 4999 /* Round up to L1_CACHE_BYTES to resist false sharing */ 5000 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info), 5001 L1_CACHE_BYTES), GFP_KERNEL); 5002 if (!sbinfo) 5003 return error; 5004 5005 sb->s_fs_info = sbinfo; 5006 5007 #ifdef CONFIG_TMPFS 5008 /* 5009 * Per default we only allow half of the physical ram per 5010 * tmpfs instance, limiting inodes to one per page of lowmem; 5011 * but the internal instance is left unlimited. 5012 */ 5013 if (!(sb->s_flags & SB_KERNMOUNT)) { 5014 if (!(ctx->seen & SHMEM_SEEN_BLOCKS)) 5015 ctx->blocks = shmem_default_max_blocks(); 5016 if (!(ctx->seen & SHMEM_SEEN_INODES)) 5017 ctx->inodes = shmem_default_max_inodes(); 5018 if (!(ctx->seen & SHMEM_SEEN_INUMS)) 5019 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64); 5020 sbinfo->noswap = ctx->noswap; 5021 } else { 5022 sb->s_flags |= SB_NOUSER; 5023 } 5024 sb->s_export_op = &shmem_export_ops; 5025 sb->s_flags |= SB_NOSEC | SB_I_VERSION; 5026 5027 #if IS_ENABLED(CONFIG_UNICODE) 5028 if (!ctx->encoding && ctx->strict_encoding) { 5029 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n"); 5030 error = -EINVAL; 5031 goto failed; 5032 } 5033 5034 if (ctx->encoding) { 5035 sb->s_encoding = ctx->encoding; 5036 sb->s_d_op = &shmem_ci_dentry_ops; 5037 if (ctx->strict_encoding) 5038 sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL; 5039 } 5040 #endif 5041 5042 #else 5043 sb->s_flags |= SB_NOUSER; 5044 #endif /* CONFIG_TMPFS */ 5045 sbinfo->max_blocks = ctx->blocks; 5046 sbinfo->max_inodes = ctx->inodes; 5047 sbinfo->free_ispace = sbinfo->max_inodes * BOGO_INODE_SIZE; 5048 if (sb->s_flags & SB_KERNMOUNT) { 5049 sbinfo->ino_batch = alloc_percpu(ino_t); 5050 if (!sbinfo->ino_batch) 5051 goto failed; 5052 } 5053 sbinfo->uid = ctx->uid; 5054 sbinfo->gid = ctx->gid; 5055 sbinfo->full_inums = ctx->full_inums; 5056 sbinfo->mode = ctx->mode; 5057 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5058 if (ctx->seen & SHMEM_SEEN_HUGE) 5059 sbinfo->huge = ctx->huge; 5060 else 5061 sbinfo->huge = tmpfs_huge; 5062 #endif 5063 sbinfo->mpol = ctx->mpol; 5064 ctx->mpol = NULL; 5065 5066 raw_spin_lock_init(&sbinfo->stat_lock); 5067 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL)) 5068 goto failed; 5069 spin_lock_init(&sbinfo->shrinklist_lock); 5070 INIT_LIST_HEAD(&sbinfo->shrinklist); 5071 5072 sb->s_maxbytes = MAX_LFS_FILESIZE; 5073 sb->s_blocksize = PAGE_SIZE; 5074 sb->s_blocksize_bits = PAGE_SHIFT; 5075 sb->s_magic = TMPFS_MAGIC; 5076 sb->s_op = &shmem_ops; 5077 sb->s_time_gran = 1; 5078 #ifdef CONFIG_TMPFS_XATTR 5079 sb->s_xattr = shmem_xattr_handlers; 5080 #endif 5081 #ifdef CONFIG_TMPFS_POSIX_ACL 5082 sb->s_flags |= SB_POSIXACL; 5083 #endif 5084 uuid_t uuid; 5085 uuid_gen(&uuid); 5086 super_set_uuid(sb, uuid.b, sizeof(uuid)); 5087 5088 #ifdef CONFIG_TMPFS_QUOTA 5089 if (ctx->seen & SHMEM_SEEN_QUOTA) { 5090 sb->dq_op = &shmem_quota_operations; 5091 sb->s_qcop = &dquot_quotactl_sysfile_ops; 5092 sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP; 5093 5094 /* Copy the default limits from ctx into sbinfo */ 5095 memcpy(&sbinfo->qlimits, &ctx->qlimits, 5096 sizeof(struct shmem_quota_limits)); 5097 5098 if (shmem_enable_quotas(sb, ctx->quota_types)) 5099 goto failed; 5100 } 5101 #endif /* CONFIG_TMPFS_QUOTA */ 5102 5103 inode = shmem_get_inode(&nop_mnt_idmap, sb, NULL, 5104 S_IFDIR | sbinfo->mode, 0, VM_NORESERVE); 5105 if (IS_ERR(inode)) { 5106 error = PTR_ERR(inode); 5107 goto failed; 5108 } 5109 inode->i_uid = sbinfo->uid; 5110 inode->i_gid = sbinfo->gid; 5111 sb->s_root = d_make_root(inode); 5112 if (!sb->s_root) 5113 goto failed; 5114 return 0; 5115 5116 failed: 5117 shmem_put_super(sb); 5118 return error; 5119 } 5120 5121 static int shmem_get_tree(struct fs_context *fc) 5122 { 5123 return get_tree_nodev(fc, shmem_fill_super); 5124 } 5125 5126 static void shmem_free_fc(struct fs_context *fc) 5127 { 5128 struct shmem_options *ctx = fc->fs_private; 5129 5130 if (ctx) { 5131 mpol_put(ctx->mpol); 5132 kfree(ctx); 5133 } 5134 } 5135 5136 static const struct fs_context_operations shmem_fs_context_ops = { 5137 .free = shmem_free_fc, 5138 .get_tree = shmem_get_tree, 5139 #ifdef CONFIG_TMPFS 5140 .parse_monolithic = shmem_parse_monolithic, 5141 .parse_param = shmem_parse_one, 5142 .reconfigure = shmem_reconfigure, 5143 #endif 5144 }; 5145 5146 static struct kmem_cache *shmem_inode_cachep __ro_after_init; 5147 5148 static struct inode *shmem_alloc_inode(struct super_block *sb) 5149 { 5150 struct shmem_inode_info *info; 5151 info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL); 5152 if (!info) 5153 return NULL; 5154 return &info->vfs_inode; 5155 } 5156 5157 static void shmem_free_in_core_inode(struct inode *inode) 5158 { 5159 if (S_ISLNK(inode->i_mode)) 5160 kfree(inode->i_link); 5161 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode)); 5162 } 5163 5164 static void shmem_destroy_inode(struct inode *inode) 5165 { 5166 if (S_ISREG(inode->i_mode)) 5167 mpol_free_shared_policy(&SHMEM_I(inode)->policy); 5168 if (S_ISDIR(inode->i_mode)) 5169 simple_offset_destroy(shmem_get_offset_ctx(inode)); 5170 } 5171 5172 static void shmem_init_inode(void *foo) 5173 { 5174 struct shmem_inode_info *info = foo; 5175 inode_init_once(&info->vfs_inode); 5176 } 5177 5178 static void __init shmem_init_inodecache(void) 5179 { 5180 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache", 5181 sizeof(struct shmem_inode_info), 5182 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode); 5183 } 5184 5185 static void __init shmem_destroy_inodecache(void) 5186 { 5187 kmem_cache_destroy(shmem_inode_cachep); 5188 } 5189 5190 /* Keep the page in page cache instead of truncating it */ 5191 static int shmem_error_remove_folio(struct address_space *mapping, 5192 struct folio *folio) 5193 { 5194 return 0; 5195 } 5196 5197 static const struct address_space_operations shmem_aops = { 5198 .writepage = shmem_writepage, 5199 .dirty_folio = noop_dirty_folio, 5200 #ifdef CONFIG_TMPFS 5201 .write_begin = shmem_write_begin, 5202 .write_end = shmem_write_end, 5203 #endif 5204 #ifdef CONFIG_MIGRATION 5205 .migrate_folio = migrate_folio, 5206 #endif 5207 .error_remove_folio = shmem_error_remove_folio, 5208 }; 5209 5210 static const struct file_operations shmem_file_operations = { 5211 .mmap = shmem_mmap, 5212 .open = shmem_file_open, 5213 .get_unmapped_area = shmem_get_unmapped_area, 5214 #ifdef CONFIG_TMPFS 5215 .llseek = shmem_file_llseek, 5216 .read_iter = shmem_file_read_iter, 5217 .write_iter = shmem_file_write_iter, 5218 .fsync = noop_fsync, 5219 .splice_read = shmem_file_splice_read, 5220 .splice_write = iter_file_splice_write, 5221 .fallocate = shmem_fallocate, 5222 #endif 5223 }; 5224 5225 static const struct inode_operations shmem_inode_operations = { 5226 .getattr = shmem_getattr, 5227 .setattr = shmem_setattr, 5228 #ifdef CONFIG_TMPFS_XATTR 5229 .listxattr = shmem_listxattr, 5230 .set_acl = simple_set_acl, 5231 .fileattr_get = shmem_fileattr_get, 5232 .fileattr_set = shmem_fileattr_set, 5233 #endif 5234 }; 5235 5236 static const struct inode_operations shmem_dir_inode_operations = { 5237 #ifdef CONFIG_TMPFS 5238 .getattr = shmem_getattr, 5239 .create = shmem_create, 5240 .lookup = simple_lookup, 5241 .link = shmem_link, 5242 .unlink = shmem_unlink, 5243 .symlink = shmem_symlink, 5244 .mkdir = shmem_mkdir, 5245 .rmdir = shmem_rmdir, 5246 .mknod = shmem_mknod, 5247 .rename = shmem_rename2, 5248 .tmpfile = shmem_tmpfile, 5249 .get_offset_ctx = shmem_get_offset_ctx, 5250 #endif 5251 #ifdef CONFIG_TMPFS_XATTR 5252 .listxattr = shmem_listxattr, 5253 .fileattr_get = shmem_fileattr_get, 5254 .fileattr_set = shmem_fileattr_set, 5255 #endif 5256 #ifdef CONFIG_TMPFS_POSIX_ACL 5257 .setattr = shmem_setattr, 5258 .set_acl = simple_set_acl, 5259 #endif 5260 }; 5261 5262 static const struct inode_operations shmem_special_inode_operations = { 5263 .getattr = shmem_getattr, 5264 #ifdef CONFIG_TMPFS_XATTR 5265 .listxattr = shmem_listxattr, 5266 #endif 5267 #ifdef CONFIG_TMPFS_POSIX_ACL 5268 .setattr = shmem_setattr, 5269 .set_acl = simple_set_acl, 5270 #endif 5271 }; 5272 5273 static const struct super_operations shmem_ops = { 5274 .alloc_inode = shmem_alloc_inode, 5275 .free_inode = shmem_free_in_core_inode, 5276 .destroy_inode = shmem_destroy_inode, 5277 #ifdef CONFIG_TMPFS 5278 .statfs = shmem_statfs, 5279 .show_options = shmem_show_options, 5280 #endif 5281 #ifdef CONFIG_TMPFS_QUOTA 5282 .get_dquots = shmem_get_dquots, 5283 #endif 5284 .evict_inode = shmem_evict_inode, 5285 .drop_inode = generic_delete_inode, 5286 .put_super = shmem_put_super, 5287 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5288 .nr_cached_objects = shmem_unused_huge_count, 5289 .free_cached_objects = shmem_unused_huge_scan, 5290 #endif 5291 }; 5292 5293 static const struct vm_operations_struct shmem_vm_ops = { 5294 .fault = shmem_fault, 5295 .map_pages = filemap_map_pages, 5296 #ifdef CONFIG_NUMA 5297 .set_policy = shmem_set_policy, 5298 .get_policy = shmem_get_policy, 5299 #endif 5300 }; 5301 5302 static const struct vm_operations_struct shmem_anon_vm_ops = { 5303 .fault = shmem_fault, 5304 .map_pages = filemap_map_pages, 5305 #ifdef CONFIG_NUMA 5306 .set_policy = shmem_set_policy, 5307 .get_policy = shmem_get_policy, 5308 #endif 5309 }; 5310 5311 int shmem_init_fs_context(struct fs_context *fc) 5312 { 5313 struct shmem_options *ctx; 5314 5315 ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL); 5316 if (!ctx) 5317 return -ENOMEM; 5318 5319 ctx->mode = 0777 | S_ISVTX; 5320 ctx->uid = current_fsuid(); 5321 ctx->gid = current_fsgid(); 5322 5323 #if IS_ENABLED(CONFIG_UNICODE) 5324 ctx->encoding = NULL; 5325 #endif 5326 5327 fc->fs_private = ctx; 5328 fc->ops = &shmem_fs_context_ops; 5329 return 0; 5330 } 5331 5332 static struct file_system_type shmem_fs_type = { 5333 .owner = THIS_MODULE, 5334 .name = "tmpfs", 5335 .init_fs_context = shmem_init_fs_context, 5336 #ifdef CONFIG_TMPFS 5337 .parameters = shmem_fs_parameters, 5338 #endif 5339 .kill_sb = kill_litter_super, 5340 .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME, 5341 }; 5342 5343 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5344 5345 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \ 5346 { \ 5347 .attr = { .name = __stringify(_name), .mode = _mode }, \ 5348 .show = _show, \ 5349 .store = _store, \ 5350 } 5351 5352 #define TMPFS_ATTR_W(_name, _store) \ 5353 static struct kobj_attribute tmpfs_attr_##_name = \ 5354 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store) 5355 5356 #define TMPFS_ATTR_RW(_name, _show, _store) \ 5357 static struct kobj_attribute tmpfs_attr_##_name = \ 5358 __INIT_KOBJ_ATTR(_name, 0644, _show, _store) 5359 5360 #define TMPFS_ATTR_RO(_name, _show) \ 5361 static struct kobj_attribute tmpfs_attr_##_name = \ 5362 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL) 5363 5364 #if IS_ENABLED(CONFIG_UNICODE) 5365 static ssize_t casefold_show(struct kobject *kobj, struct kobj_attribute *a, 5366 char *buf) 5367 { 5368 return sysfs_emit(buf, "supported\n"); 5369 } 5370 TMPFS_ATTR_RO(casefold, casefold_show); 5371 #endif 5372 5373 static struct attribute *tmpfs_attributes[] = { 5374 #if IS_ENABLED(CONFIG_UNICODE) 5375 &tmpfs_attr_casefold.attr, 5376 #endif 5377 NULL 5378 }; 5379 5380 static const struct attribute_group tmpfs_attribute_group = { 5381 .attrs = tmpfs_attributes, 5382 .name = "features" 5383 }; 5384 5385 static struct kobject *tmpfs_kobj; 5386 5387 static int __init tmpfs_sysfs_init(void) 5388 { 5389 int ret; 5390 5391 tmpfs_kobj = kobject_create_and_add("tmpfs", fs_kobj); 5392 if (!tmpfs_kobj) 5393 return -ENOMEM; 5394 5395 ret = sysfs_create_group(tmpfs_kobj, &tmpfs_attribute_group); 5396 if (ret) 5397 kobject_put(tmpfs_kobj); 5398 5399 return ret; 5400 } 5401 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */ 5402 5403 void __init shmem_init(void) 5404 { 5405 int error; 5406 5407 shmem_init_inodecache(); 5408 5409 #ifdef CONFIG_TMPFS_QUOTA 5410 register_quota_format(&shmem_quota_format); 5411 #endif 5412 5413 error = register_filesystem(&shmem_fs_type); 5414 if (error) { 5415 pr_err("Could not register tmpfs\n"); 5416 goto out2; 5417 } 5418 5419 shm_mnt = kern_mount(&shmem_fs_type); 5420 if (IS_ERR(shm_mnt)) { 5421 error = PTR_ERR(shm_mnt); 5422 pr_err("Could not kern_mount tmpfs\n"); 5423 goto out1; 5424 } 5425 5426 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS) 5427 error = tmpfs_sysfs_init(); 5428 if (error) { 5429 pr_err("Could not init tmpfs sysfs\n"); 5430 goto out1; 5431 } 5432 #endif 5433 5434 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 5435 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY) 5436 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5437 else 5438 shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */ 5439 5440 /* 5441 * Default to setting PMD-sized THP to inherit the global setting and 5442 * disable all other multi-size THPs. 5443 */ 5444 if (!shmem_orders_configured) 5445 huge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER); 5446 #endif 5447 return; 5448 5449 out1: 5450 unregister_filesystem(&shmem_fs_type); 5451 out2: 5452 #ifdef CONFIG_TMPFS_QUOTA 5453 unregister_quota_format(&shmem_quota_format); 5454 #endif 5455 shmem_destroy_inodecache(); 5456 shm_mnt = ERR_PTR(error); 5457 } 5458 5459 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS) 5460 static ssize_t shmem_enabled_show(struct kobject *kobj, 5461 struct kobj_attribute *attr, char *buf) 5462 { 5463 static const int values[] = { 5464 SHMEM_HUGE_ALWAYS, 5465 SHMEM_HUGE_WITHIN_SIZE, 5466 SHMEM_HUGE_ADVISE, 5467 SHMEM_HUGE_NEVER, 5468 SHMEM_HUGE_DENY, 5469 SHMEM_HUGE_FORCE, 5470 }; 5471 int len = 0; 5472 int i; 5473 5474 for (i = 0; i < ARRAY_SIZE(values); i++) { 5475 len += sysfs_emit_at(buf, len, 5476 shmem_huge == values[i] ? "%s[%s]" : "%s%s", 5477 i ? " " : "", shmem_format_huge(values[i])); 5478 } 5479 len += sysfs_emit_at(buf, len, "\n"); 5480 5481 return len; 5482 } 5483 5484 static ssize_t shmem_enabled_store(struct kobject *kobj, 5485 struct kobj_attribute *attr, const char *buf, size_t count) 5486 { 5487 char tmp[16]; 5488 int huge, err; 5489 5490 if (count + 1 > sizeof(tmp)) 5491 return -EINVAL; 5492 memcpy(tmp, buf, count); 5493 tmp[count] = '\0'; 5494 if (count && tmp[count - 1] == '\n') 5495 tmp[count - 1] = '\0'; 5496 5497 huge = shmem_parse_huge(tmp); 5498 if (huge == -EINVAL) 5499 return huge; 5500 5501 shmem_huge = huge; 5502 if (shmem_huge > SHMEM_HUGE_DENY) 5503 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 5504 5505 err = start_stop_khugepaged(); 5506 return err ? err : count; 5507 } 5508 5509 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled); 5510 static DEFINE_SPINLOCK(huge_shmem_orders_lock); 5511 5512 static ssize_t thpsize_shmem_enabled_show(struct kobject *kobj, 5513 struct kobj_attribute *attr, char *buf) 5514 { 5515 int order = to_thpsize(kobj)->order; 5516 const char *output; 5517 5518 if (test_bit(order, &huge_shmem_orders_always)) 5519 output = "[always] inherit within_size advise never"; 5520 else if (test_bit(order, &huge_shmem_orders_inherit)) 5521 output = "always [inherit] within_size advise never"; 5522 else if (test_bit(order, &huge_shmem_orders_within_size)) 5523 output = "always inherit [within_size] advise never"; 5524 else if (test_bit(order, &huge_shmem_orders_madvise)) 5525 output = "always inherit within_size [advise] never"; 5526 else 5527 output = "always inherit within_size advise [never]"; 5528 5529 return sysfs_emit(buf, "%s\n", output); 5530 } 5531 5532 static ssize_t thpsize_shmem_enabled_store(struct kobject *kobj, 5533 struct kobj_attribute *attr, 5534 const char *buf, size_t count) 5535 { 5536 int order = to_thpsize(kobj)->order; 5537 ssize_t ret = count; 5538 5539 if (sysfs_streq(buf, "always")) { 5540 spin_lock(&huge_shmem_orders_lock); 5541 clear_bit(order, &huge_shmem_orders_inherit); 5542 clear_bit(order, &huge_shmem_orders_madvise); 5543 clear_bit(order, &huge_shmem_orders_within_size); 5544 set_bit(order, &huge_shmem_orders_always); 5545 spin_unlock(&huge_shmem_orders_lock); 5546 } else if (sysfs_streq(buf, "inherit")) { 5547 /* Do not override huge allocation policy with non-PMD sized mTHP */ 5548 if (shmem_huge == SHMEM_HUGE_FORCE && 5549 order != HPAGE_PMD_ORDER) 5550 return -EINVAL; 5551 5552 spin_lock(&huge_shmem_orders_lock); 5553 clear_bit(order, &huge_shmem_orders_always); 5554 clear_bit(order, &huge_shmem_orders_madvise); 5555 clear_bit(order, &huge_shmem_orders_within_size); 5556 set_bit(order, &huge_shmem_orders_inherit); 5557 spin_unlock(&huge_shmem_orders_lock); 5558 } else if (sysfs_streq(buf, "within_size")) { 5559 spin_lock(&huge_shmem_orders_lock); 5560 clear_bit(order, &huge_shmem_orders_always); 5561 clear_bit(order, &huge_shmem_orders_inherit); 5562 clear_bit(order, &huge_shmem_orders_madvise); 5563 set_bit(order, &huge_shmem_orders_within_size); 5564 spin_unlock(&huge_shmem_orders_lock); 5565 } else if (sysfs_streq(buf, "advise")) { 5566 spin_lock(&huge_shmem_orders_lock); 5567 clear_bit(order, &huge_shmem_orders_always); 5568 clear_bit(order, &huge_shmem_orders_inherit); 5569 clear_bit(order, &huge_shmem_orders_within_size); 5570 set_bit(order, &huge_shmem_orders_madvise); 5571 spin_unlock(&huge_shmem_orders_lock); 5572 } else if (sysfs_streq(buf, "never")) { 5573 spin_lock(&huge_shmem_orders_lock); 5574 clear_bit(order, &huge_shmem_orders_always); 5575 clear_bit(order, &huge_shmem_orders_inherit); 5576 clear_bit(order, &huge_shmem_orders_within_size); 5577 clear_bit(order, &huge_shmem_orders_madvise); 5578 spin_unlock(&huge_shmem_orders_lock); 5579 } else { 5580 ret = -EINVAL; 5581 } 5582 5583 if (ret > 0) { 5584 int err = start_stop_khugepaged(); 5585 5586 if (err) 5587 ret = err; 5588 } 5589 return ret; 5590 } 5591 5592 struct kobj_attribute thpsize_shmem_enabled_attr = 5593 __ATTR(shmem_enabled, 0644, thpsize_shmem_enabled_show, thpsize_shmem_enabled_store); 5594 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */ 5595 5596 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) 5597 5598 static int __init setup_transparent_hugepage_shmem(char *str) 5599 { 5600 int huge; 5601 5602 huge = shmem_parse_huge(str); 5603 if (huge == -EINVAL) { 5604 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n"); 5605 return huge; 5606 } 5607 5608 shmem_huge = huge; 5609 return 1; 5610 } 5611 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem); 5612 5613 static int __init setup_transparent_hugepage_tmpfs(char *str) 5614 { 5615 int huge; 5616 5617 huge = shmem_parse_huge(str); 5618 if (huge < 0) { 5619 pr_warn("transparent_hugepage_tmpfs= cannot parse, ignored\n"); 5620 return huge; 5621 } 5622 5623 tmpfs_huge = huge; 5624 return 1; 5625 } 5626 __setup("transparent_hugepage_tmpfs=", setup_transparent_hugepage_tmpfs); 5627 5628 static char str_dup[PAGE_SIZE] __initdata; 5629 static int __init setup_thp_shmem(char *str) 5630 { 5631 char *token, *range, *policy, *subtoken; 5632 unsigned long always, inherit, madvise, within_size; 5633 char *start_size, *end_size; 5634 int start, end, nr; 5635 char *p; 5636 5637 if (!str || strlen(str) + 1 > PAGE_SIZE) 5638 goto err; 5639 strscpy(str_dup, str); 5640 5641 always = huge_shmem_orders_always; 5642 inherit = huge_shmem_orders_inherit; 5643 madvise = huge_shmem_orders_madvise; 5644 within_size = huge_shmem_orders_within_size; 5645 p = str_dup; 5646 while ((token = strsep(&p, ";")) != NULL) { 5647 range = strsep(&token, ":"); 5648 policy = token; 5649 5650 if (!policy) 5651 goto err; 5652 5653 while ((subtoken = strsep(&range, ",")) != NULL) { 5654 if (strchr(subtoken, '-')) { 5655 start_size = strsep(&subtoken, "-"); 5656 end_size = subtoken; 5657 5658 start = get_order_from_str(start_size, 5659 THP_ORDERS_ALL_FILE_DEFAULT); 5660 end = get_order_from_str(end_size, 5661 THP_ORDERS_ALL_FILE_DEFAULT); 5662 } else { 5663 start_size = end_size = subtoken; 5664 start = end = get_order_from_str(subtoken, 5665 THP_ORDERS_ALL_FILE_DEFAULT); 5666 } 5667 5668 if (start == -EINVAL) { 5669 pr_err("invalid size %s in thp_shmem boot parameter\n", 5670 start_size); 5671 goto err; 5672 } 5673 5674 if (end == -EINVAL) { 5675 pr_err("invalid size %s in thp_shmem boot parameter\n", 5676 end_size); 5677 goto err; 5678 } 5679 5680 if (start < 0 || end < 0 || start > end) 5681 goto err; 5682 5683 nr = end - start + 1; 5684 if (!strcmp(policy, "always")) { 5685 bitmap_set(&always, start, nr); 5686 bitmap_clear(&inherit, start, nr); 5687 bitmap_clear(&madvise, start, nr); 5688 bitmap_clear(&within_size, start, nr); 5689 } else if (!strcmp(policy, "advise")) { 5690 bitmap_set(&madvise, start, nr); 5691 bitmap_clear(&inherit, start, nr); 5692 bitmap_clear(&always, start, nr); 5693 bitmap_clear(&within_size, start, nr); 5694 } else if (!strcmp(policy, "inherit")) { 5695 bitmap_set(&inherit, start, nr); 5696 bitmap_clear(&madvise, start, nr); 5697 bitmap_clear(&always, start, nr); 5698 bitmap_clear(&within_size, start, nr); 5699 } else if (!strcmp(policy, "within_size")) { 5700 bitmap_set(&within_size, start, nr); 5701 bitmap_clear(&inherit, start, nr); 5702 bitmap_clear(&madvise, start, nr); 5703 bitmap_clear(&always, start, nr); 5704 } else if (!strcmp(policy, "never")) { 5705 bitmap_clear(&inherit, start, nr); 5706 bitmap_clear(&madvise, start, nr); 5707 bitmap_clear(&always, start, nr); 5708 bitmap_clear(&within_size, start, nr); 5709 } else { 5710 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy); 5711 goto err; 5712 } 5713 } 5714 } 5715 5716 huge_shmem_orders_always = always; 5717 huge_shmem_orders_madvise = madvise; 5718 huge_shmem_orders_inherit = inherit; 5719 huge_shmem_orders_within_size = within_size; 5720 shmem_orders_configured = true; 5721 return 1; 5722 5723 err: 5724 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str); 5725 return 0; 5726 } 5727 __setup("thp_shmem=", setup_thp_shmem); 5728 5729 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 5730 5731 #else /* !CONFIG_SHMEM */ 5732 5733 /* 5734 * tiny-shmem: simple shmemfs and tmpfs using ramfs code 5735 * 5736 * This is intended for small system where the benefits of the full 5737 * shmem code (swap-backed and resource-limited) are outweighed by 5738 * their complexity. On systems without swap this code should be 5739 * effectively equivalent, but much lighter weight. 5740 */ 5741 5742 static struct file_system_type shmem_fs_type = { 5743 .name = "tmpfs", 5744 .init_fs_context = ramfs_init_fs_context, 5745 .parameters = ramfs_fs_parameters, 5746 .kill_sb = ramfs_kill_sb, 5747 .fs_flags = FS_USERNS_MOUNT, 5748 }; 5749 5750 void __init shmem_init(void) 5751 { 5752 BUG_ON(register_filesystem(&shmem_fs_type) != 0); 5753 5754 shm_mnt = kern_mount(&shmem_fs_type); 5755 BUG_ON(IS_ERR(shm_mnt)); 5756 } 5757 5758 int shmem_unuse(unsigned int type) 5759 { 5760 return 0; 5761 } 5762 5763 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 5764 { 5765 return 0; 5766 } 5767 5768 void shmem_unlock_mapping(struct address_space *mapping) 5769 { 5770 } 5771 5772 #ifdef CONFIG_MMU 5773 unsigned long shmem_get_unmapped_area(struct file *file, 5774 unsigned long addr, unsigned long len, 5775 unsigned long pgoff, unsigned long flags) 5776 { 5777 return mm_get_unmapped_area(current->mm, file, addr, len, pgoff, flags); 5778 } 5779 #endif 5780 5781 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 5782 { 5783 truncate_inode_pages_range(inode->i_mapping, lstart, lend); 5784 } 5785 EXPORT_SYMBOL_GPL(shmem_truncate_range); 5786 5787 #define shmem_vm_ops generic_file_vm_ops 5788 #define shmem_anon_vm_ops generic_file_vm_ops 5789 #define shmem_file_operations ramfs_file_operations 5790 #define shmem_acct_size(flags, size) 0 5791 #define shmem_unacct_size(flags, size) do {} while (0) 5792 5793 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap, 5794 struct super_block *sb, struct inode *dir, 5795 umode_t mode, dev_t dev, unsigned long flags) 5796 { 5797 struct inode *inode = ramfs_get_inode(sb, dir, mode, dev); 5798 return inode ? inode : ERR_PTR(-ENOSPC); 5799 } 5800 5801 #endif /* CONFIG_SHMEM */ 5802 5803 /* common code */ 5804 5805 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, 5806 loff_t size, unsigned long flags, unsigned int i_flags) 5807 { 5808 struct inode *inode; 5809 struct file *res; 5810 5811 if (IS_ERR(mnt)) 5812 return ERR_CAST(mnt); 5813 5814 if (size < 0 || size > MAX_LFS_FILESIZE) 5815 return ERR_PTR(-EINVAL); 5816 5817 if (shmem_acct_size(flags, size)) 5818 return ERR_PTR(-ENOMEM); 5819 5820 if (is_idmapped_mnt(mnt)) 5821 return ERR_PTR(-EINVAL); 5822 5823 inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL, 5824 S_IFREG | S_IRWXUGO, 0, flags); 5825 if (IS_ERR(inode)) { 5826 shmem_unacct_size(flags, size); 5827 return ERR_CAST(inode); 5828 } 5829 inode->i_flags |= i_flags; 5830 inode->i_size = size; 5831 clear_nlink(inode); /* It is unlinked */ 5832 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size)); 5833 if (!IS_ERR(res)) 5834 res = alloc_file_pseudo(inode, mnt, name, O_RDWR, 5835 &shmem_file_operations); 5836 if (IS_ERR(res)) 5837 iput(inode); 5838 return res; 5839 } 5840 5841 /** 5842 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be 5843 * kernel internal. There will be NO LSM permission checks against the 5844 * underlying inode. So users of this interface must do LSM checks at a 5845 * higher layer. The users are the big_key and shm implementations. LSM 5846 * checks are provided at the key or shm level rather than the inode. 5847 * @name: name for dentry (to be seen in /proc/<pid>/maps 5848 * @size: size to be set for the file 5849 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5850 */ 5851 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags) 5852 { 5853 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE); 5854 } 5855 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup); 5856 5857 /** 5858 * shmem_file_setup - get an unlinked file living in tmpfs 5859 * @name: name for dentry (to be seen in /proc/<pid>/maps 5860 * @size: size to be set for the file 5861 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5862 */ 5863 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags) 5864 { 5865 return __shmem_file_setup(shm_mnt, name, size, flags, 0); 5866 } 5867 EXPORT_SYMBOL_GPL(shmem_file_setup); 5868 5869 /** 5870 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs 5871 * @mnt: the tmpfs mount where the file will be created 5872 * @name: name for dentry (to be seen in /proc/<pid>/maps 5873 * @size: size to be set for the file 5874 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 5875 */ 5876 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name, 5877 loff_t size, unsigned long flags) 5878 { 5879 return __shmem_file_setup(mnt, name, size, flags, 0); 5880 } 5881 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt); 5882 5883 /** 5884 * shmem_zero_setup - setup a shared anonymous mapping 5885 * @vma: the vma to be mmapped is prepared by do_mmap 5886 */ 5887 int shmem_zero_setup(struct vm_area_struct *vma) 5888 { 5889 struct file *file; 5890 loff_t size = vma->vm_end - vma->vm_start; 5891 5892 /* 5893 * Cloning a new file under mmap_lock leads to a lock ordering conflict 5894 * between XFS directory reading and selinux: since this file is only 5895 * accessible to the user through its mapping, use S_PRIVATE flag to 5896 * bypass file security, in the same way as shmem_kernel_file_setup(). 5897 */ 5898 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags); 5899 if (IS_ERR(file)) 5900 return PTR_ERR(file); 5901 5902 if (vma->vm_file) 5903 fput(vma->vm_file); 5904 vma->vm_file = file; 5905 vma->vm_ops = &shmem_anon_vm_ops; 5906 5907 return 0; 5908 } 5909 5910 /** 5911 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags. 5912 * @mapping: the folio's address_space 5913 * @index: the folio index 5914 * @gfp: the page allocator flags to use if allocating 5915 * 5916 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)", 5917 * with any new page allocations done using the specified allocation flags. 5918 * But read_cache_page_gfp() uses the ->read_folio() method: which does not 5919 * suit tmpfs, since it may have pages in swapcache, and needs to find those 5920 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support. 5921 * 5922 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in 5923 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily. 5924 */ 5925 struct folio *shmem_read_folio_gfp(struct address_space *mapping, 5926 pgoff_t index, gfp_t gfp) 5927 { 5928 #ifdef CONFIG_SHMEM 5929 struct inode *inode = mapping->host; 5930 struct folio *folio; 5931 int error; 5932 5933 error = shmem_get_folio_gfp(inode, index, 0, &folio, SGP_CACHE, 5934 gfp, NULL, NULL); 5935 if (error) 5936 return ERR_PTR(error); 5937 5938 folio_unlock(folio); 5939 return folio; 5940 #else 5941 /* 5942 * The tiny !SHMEM case uses ramfs without swap 5943 */ 5944 return mapping_read_folio_gfp(mapping, index, gfp); 5945 #endif 5946 } 5947 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp); 5948 5949 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping, 5950 pgoff_t index, gfp_t gfp) 5951 { 5952 struct folio *folio = shmem_read_folio_gfp(mapping, index, gfp); 5953 struct page *page; 5954 5955 if (IS_ERR(folio)) 5956 return &folio->page; 5957 5958 page = folio_file_page(folio, index); 5959 if (PageHWPoison(page)) { 5960 folio_put(folio); 5961 return ERR_PTR(-EIO); 5962 } 5963 5964 return page; 5965 } 5966 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp); 5967