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/swap.h> 37 #include <linux/uio.h> 38 #include <linux/hugetlb.h> 39 #include <linux/fs_parser.h> 40 #include <linux/swapfile.h> 41 #include "swap.h" 42 43 static struct vfsmount *shm_mnt; 44 45 #ifdef CONFIG_SHMEM 46 /* 47 * This virtual memory filesystem is heavily based on the ramfs. It 48 * extends ramfs by the ability to use swap and honor resource limits 49 * which makes it a completely usable filesystem. 50 */ 51 52 #include <linux/xattr.h> 53 #include <linux/exportfs.h> 54 #include <linux/posix_acl.h> 55 #include <linux/posix_acl_xattr.h> 56 #include <linux/mman.h> 57 #include <linux/string.h> 58 #include <linux/slab.h> 59 #include <linux/backing-dev.h> 60 #include <linux/shmem_fs.h> 61 #include <linux/writeback.h> 62 #include <linux/pagevec.h> 63 #include <linux/percpu_counter.h> 64 #include <linux/falloc.h> 65 #include <linux/splice.h> 66 #include <linux/security.h> 67 #include <linux/swapops.h> 68 #include <linux/mempolicy.h> 69 #include <linux/namei.h> 70 #include <linux/ctype.h> 71 #include <linux/migrate.h> 72 #include <linux/highmem.h> 73 #include <linux/seq_file.h> 74 #include <linux/magic.h> 75 #include <linux/syscalls.h> 76 #include <linux/fcntl.h> 77 #include <uapi/linux/memfd.h> 78 #include <linux/userfaultfd_k.h> 79 #include <linux/rmap.h> 80 #include <linux/uuid.h> 81 82 #include <linux/uaccess.h> 83 84 #include "internal.h" 85 86 #define BLOCKS_PER_PAGE (PAGE_SIZE/512) 87 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT) 88 89 /* Pretend that each entry is of this size in directory's i_size */ 90 #define BOGO_DIRENT_SIZE 20 91 92 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */ 93 #define SHORT_SYMLINK_LEN 128 94 95 /* 96 * shmem_fallocate communicates with shmem_fault or shmem_writepage via 97 * inode->i_private (with i_rwsem making sure that it has only one user at 98 * a time): we would prefer not to enlarge the shmem inode just for that. 99 */ 100 struct shmem_falloc { 101 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */ 102 pgoff_t start; /* start of range currently being fallocated */ 103 pgoff_t next; /* the next page offset to be fallocated */ 104 pgoff_t nr_falloced; /* how many new pages have been fallocated */ 105 pgoff_t nr_unswapped; /* how often writepage refused to swap out */ 106 }; 107 108 struct shmem_options { 109 unsigned long long blocks; 110 unsigned long long inodes; 111 struct mempolicy *mpol; 112 kuid_t uid; 113 kgid_t gid; 114 umode_t mode; 115 bool full_inums; 116 int huge; 117 int seen; 118 #define SHMEM_SEEN_BLOCKS 1 119 #define SHMEM_SEEN_INODES 2 120 #define SHMEM_SEEN_HUGE 4 121 #define SHMEM_SEEN_INUMS 8 122 }; 123 124 #ifdef CONFIG_TMPFS 125 static unsigned long shmem_default_max_blocks(void) 126 { 127 return totalram_pages() / 2; 128 } 129 130 static unsigned long shmem_default_max_inodes(void) 131 { 132 unsigned long nr_pages = totalram_pages(); 133 134 return min(nr_pages - totalhigh_pages(), nr_pages / 2); 135 } 136 #endif 137 138 static int shmem_swapin_folio(struct inode *inode, pgoff_t index, 139 struct folio **foliop, enum sgp_type sgp, 140 gfp_t gfp, struct vm_area_struct *vma, 141 vm_fault_t *fault_type); 142 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index, 143 struct page **pagep, enum sgp_type sgp, 144 gfp_t gfp, struct vm_area_struct *vma, 145 struct vm_fault *vmf, vm_fault_t *fault_type); 146 147 int shmem_getpage(struct inode *inode, pgoff_t index, 148 struct page **pagep, enum sgp_type sgp) 149 { 150 return shmem_getpage_gfp(inode, index, pagep, sgp, 151 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL); 152 } 153 154 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb) 155 { 156 return sb->s_fs_info; 157 } 158 159 /* 160 * shmem_file_setup pre-accounts the whole fixed size of a VM object, 161 * for shared memory and for shared anonymous (/dev/zero) mappings 162 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1), 163 * consistent with the pre-accounting of private mappings ... 164 */ 165 static inline int shmem_acct_size(unsigned long flags, loff_t size) 166 { 167 return (flags & VM_NORESERVE) ? 168 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size)); 169 } 170 171 static inline void shmem_unacct_size(unsigned long flags, loff_t size) 172 { 173 if (!(flags & VM_NORESERVE)) 174 vm_unacct_memory(VM_ACCT(size)); 175 } 176 177 static inline int shmem_reacct_size(unsigned long flags, 178 loff_t oldsize, loff_t newsize) 179 { 180 if (!(flags & VM_NORESERVE)) { 181 if (VM_ACCT(newsize) > VM_ACCT(oldsize)) 182 return security_vm_enough_memory_mm(current->mm, 183 VM_ACCT(newsize) - VM_ACCT(oldsize)); 184 else if (VM_ACCT(newsize) < VM_ACCT(oldsize)) 185 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize)); 186 } 187 return 0; 188 } 189 190 /* 191 * ... whereas tmpfs objects are accounted incrementally as 192 * pages are allocated, in order to allow large sparse files. 193 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM, 194 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM. 195 */ 196 static inline int shmem_acct_block(unsigned long flags, long pages) 197 { 198 if (!(flags & VM_NORESERVE)) 199 return 0; 200 201 return security_vm_enough_memory_mm(current->mm, 202 pages * VM_ACCT(PAGE_SIZE)); 203 } 204 205 static inline void shmem_unacct_blocks(unsigned long flags, long pages) 206 { 207 if (flags & VM_NORESERVE) 208 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE)); 209 } 210 211 static inline bool shmem_inode_acct_block(struct inode *inode, long pages) 212 { 213 struct shmem_inode_info *info = SHMEM_I(inode); 214 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 215 216 if (shmem_acct_block(info->flags, pages)) 217 return false; 218 219 if (sbinfo->max_blocks) { 220 if (percpu_counter_compare(&sbinfo->used_blocks, 221 sbinfo->max_blocks - pages) > 0) 222 goto unacct; 223 percpu_counter_add(&sbinfo->used_blocks, pages); 224 } 225 226 return true; 227 228 unacct: 229 shmem_unacct_blocks(info->flags, pages); 230 return false; 231 } 232 233 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages) 234 { 235 struct shmem_inode_info *info = SHMEM_I(inode); 236 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 237 238 if (sbinfo->max_blocks) 239 percpu_counter_sub(&sbinfo->used_blocks, pages); 240 shmem_unacct_blocks(info->flags, pages); 241 } 242 243 static const struct super_operations shmem_ops; 244 const struct address_space_operations shmem_aops; 245 static const struct file_operations shmem_file_operations; 246 static const struct inode_operations shmem_inode_operations; 247 static const struct inode_operations shmem_dir_inode_operations; 248 static const struct inode_operations shmem_special_inode_operations; 249 static const struct vm_operations_struct shmem_vm_ops; 250 static struct file_system_type shmem_fs_type; 251 252 bool vma_is_shmem(struct vm_area_struct *vma) 253 { 254 return vma->vm_ops == &shmem_vm_ops; 255 } 256 257 static LIST_HEAD(shmem_swaplist); 258 static DEFINE_MUTEX(shmem_swaplist_mutex); 259 260 /* 261 * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and 262 * produces a novel ino for the newly allocated inode. 263 * 264 * It may also be called when making a hard link to permit the space needed by 265 * each dentry. However, in that case, no new inode number is needed since that 266 * internally draws from another pool of inode numbers (currently global 267 * get_next_ino()). This case is indicated by passing NULL as inop. 268 */ 269 #define SHMEM_INO_BATCH 1024 270 static int shmem_reserve_inode(struct super_block *sb, ino_t *inop) 271 { 272 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 273 ino_t ino; 274 275 if (!(sb->s_flags & SB_KERNMOUNT)) { 276 raw_spin_lock(&sbinfo->stat_lock); 277 if (sbinfo->max_inodes) { 278 if (!sbinfo->free_inodes) { 279 raw_spin_unlock(&sbinfo->stat_lock); 280 return -ENOSPC; 281 } 282 sbinfo->free_inodes--; 283 } 284 if (inop) { 285 ino = sbinfo->next_ino++; 286 if (unlikely(is_zero_ino(ino))) 287 ino = sbinfo->next_ino++; 288 if (unlikely(!sbinfo->full_inums && 289 ino > UINT_MAX)) { 290 /* 291 * Emulate get_next_ino uint wraparound for 292 * compatibility 293 */ 294 if (IS_ENABLED(CONFIG_64BIT)) 295 pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n", 296 __func__, MINOR(sb->s_dev)); 297 sbinfo->next_ino = 1; 298 ino = sbinfo->next_ino++; 299 } 300 *inop = ino; 301 } 302 raw_spin_unlock(&sbinfo->stat_lock); 303 } else if (inop) { 304 /* 305 * __shmem_file_setup, one of our callers, is lock-free: it 306 * doesn't hold stat_lock in shmem_reserve_inode since 307 * max_inodes is always 0, and is called from potentially 308 * unknown contexts. As such, use a per-cpu batched allocator 309 * which doesn't require the per-sb stat_lock unless we are at 310 * the batch boundary. 311 * 312 * We don't need to worry about inode{32,64} since SB_KERNMOUNT 313 * shmem mounts are not exposed to userspace, so we don't need 314 * to worry about things like glibc compatibility. 315 */ 316 ino_t *next_ino; 317 318 next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu()); 319 ino = *next_ino; 320 if (unlikely(ino % SHMEM_INO_BATCH == 0)) { 321 raw_spin_lock(&sbinfo->stat_lock); 322 ino = sbinfo->next_ino; 323 sbinfo->next_ino += SHMEM_INO_BATCH; 324 raw_spin_unlock(&sbinfo->stat_lock); 325 if (unlikely(is_zero_ino(ino))) 326 ino++; 327 } 328 *inop = ino; 329 *next_ino = ++ino; 330 put_cpu(); 331 } 332 333 return 0; 334 } 335 336 static void shmem_free_inode(struct super_block *sb) 337 { 338 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 339 if (sbinfo->max_inodes) { 340 raw_spin_lock(&sbinfo->stat_lock); 341 sbinfo->free_inodes++; 342 raw_spin_unlock(&sbinfo->stat_lock); 343 } 344 } 345 346 /** 347 * shmem_recalc_inode - recalculate the block usage of an inode 348 * @inode: inode to recalc 349 * 350 * We have to calculate the free blocks since the mm can drop 351 * undirtied hole pages behind our back. 352 * 353 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped 354 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped) 355 * 356 * It has to be called with the spinlock held. 357 */ 358 static void shmem_recalc_inode(struct inode *inode) 359 { 360 struct shmem_inode_info *info = SHMEM_I(inode); 361 long freed; 362 363 freed = info->alloced - info->swapped - inode->i_mapping->nrpages; 364 if (freed > 0) { 365 info->alloced -= freed; 366 inode->i_blocks -= freed * BLOCKS_PER_PAGE; 367 shmem_inode_unacct_blocks(inode, freed); 368 } 369 } 370 371 bool shmem_charge(struct inode *inode, long pages) 372 { 373 struct shmem_inode_info *info = SHMEM_I(inode); 374 unsigned long flags; 375 376 if (!shmem_inode_acct_block(inode, pages)) 377 return false; 378 379 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */ 380 inode->i_mapping->nrpages += pages; 381 382 spin_lock_irqsave(&info->lock, flags); 383 info->alloced += pages; 384 inode->i_blocks += pages * BLOCKS_PER_PAGE; 385 shmem_recalc_inode(inode); 386 spin_unlock_irqrestore(&info->lock, flags); 387 388 return true; 389 } 390 391 void shmem_uncharge(struct inode *inode, long pages) 392 { 393 struct shmem_inode_info *info = SHMEM_I(inode); 394 unsigned long flags; 395 396 /* nrpages adjustment done by __delete_from_page_cache() or caller */ 397 398 spin_lock_irqsave(&info->lock, flags); 399 info->alloced -= pages; 400 inode->i_blocks -= pages * BLOCKS_PER_PAGE; 401 shmem_recalc_inode(inode); 402 spin_unlock_irqrestore(&info->lock, flags); 403 404 shmem_inode_unacct_blocks(inode, pages); 405 } 406 407 /* 408 * Replace item expected in xarray by a new item, while holding xa_lock. 409 */ 410 static int shmem_replace_entry(struct address_space *mapping, 411 pgoff_t index, void *expected, void *replacement) 412 { 413 XA_STATE(xas, &mapping->i_pages, index); 414 void *item; 415 416 VM_BUG_ON(!expected); 417 VM_BUG_ON(!replacement); 418 item = xas_load(&xas); 419 if (item != expected) 420 return -ENOENT; 421 xas_store(&xas, replacement); 422 return 0; 423 } 424 425 /* 426 * Sometimes, before we decide whether to proceed or to fail, we must check 427 * that an entry was not already brought back from swap by a racing thread. 428 * 429 * Checking page is not enough: by the time a SwapCache page is locked, it 430 * might be reused, and again be SwapCache, using the same swap as before. 431 */ 432 static bool shmem_confirm_swap(struct address_space *mapping, 433 pgoff_t index, swp_entry_t swap) 434 { 435 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap); 436 } 437 438 /* 439 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option 440 * 441 * SHMEM_HUGE_NEVER: 442 * disables huge pages for the mount; 443 * SHMEM_HUGE_ALWAYS: 444 * enables huge pages for the mount; 445 * SHMEM_HUGE_WITHIN_SIZE: 446 * only allocate huge pages if the page will be fully within i_size, 447 * also respect fadvise()/madvise() hints; 448 * SHMEM_HUGE_ADVISE: 449 * only allocate huge pages if requested with fadvise()/madvise(); 450 */ 451 452 #define SHMEM_HUGE_NEVER 0 453 #define SHMEM_HUGE_ALWAYS 1 454 #define SHMEM_HUGE_WITHIN_SIZE 2 455 #define SHMEM_HUGE_ADVISE 3 456 457 /* 458 * Special values. 459 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled: 460 * 461 * SHMEM_HUGE_DENY: 462 * disables huge on shm_mnt and all mounts, for emergency use; 463 * SHMEM_HUGE_FORCE: 464 * enables huge on shm_mnt and all mounts, w/o needing option, for testing; 465 * 466 */ 467 #define SHMEM_HUGE_DENY (-1) 468 #define SHMEM_HUGE_FORCE (-2) 469 470 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 471 /* ifdef here to avoid bloating shmem.o when not necessary */ 472 473 static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER; 474 475 bool shmem_is_huge(struct vm_area_struct *vma, 476 struct inode *inode, pgoff_t index) 477 { 478 loff_t i_size; 479 480 if (!S_ISREG(inode->i_mode)) 481 return false; 482 if (shmem_huge == SHMEM_HUGE_DENY) 483 return false; 484 if (vma && ((vma->vm_flags & VM_NOHUGEPAGE) || 485 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))) 486 return false; 487 if (shmem_huge == SHMEM_HUGE_FORCE) 488 return true; 489 490 switch (SHMEM_SB(inode->i_sb)->huge) { 491 case SHMEM_HUGE_ALWAYS: 492 return true; 493 case SHMEM_HUGE_WITHIN_SIZE: 494 index = round_up(index + 1, HPAGE_PMD_NR); 495 i_size = round_up(i_size_read(inode), PAGE_SIZE); 496 if (i_size >> PAGE_SHIFT >= index) 497 return true; 498 fallthrough; 499 case SHMEM_HUGE_ADVISE: 500 if (vma && (vma->vm_flags & VM_HUGEPAGE)) 501 return true; 502 fallthrough; 503 default: 504 return false; 505 } 506 } 507 508 #if defined(CONFIG_SYSFS) 509 static int shmem_parse_huge(const char *str) 510 { 511 if (!strcmp(str, "never")) 512 return SHMEM_HUGE_NEVER; 513 if (!strcmp(str, "always")) 514 return SHMEM_HUGE_ALWAYS; 515 if (!strcmp(str, "within_size")) 516 return SHMEM_HUGE_WITHIN_SIZE; 517 if (!strcmp(str, "advise")) 518 return SHMEM_HUGE_ADVISE; 519 if (!strcmp(str, "deny")) 520 return SHMEM_HUGE_DENY; 521 if (!strcmp(str, "force")) 522 return SHMEM_HUGE_FORCE; 523 return -EINVAL; 524 } 525 #endif 526 527 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS) 528 static const char *shmem_format_huge(int huge) 529 { 530 switch (huge) { 531 case SHMEM_HUGE_NEVER: 532 return "never"; 533 case SHMEM_HUGE_ALWAYS: 534 return "always"; 535 case SHMEM_HUGE_WITHIN_SIZE: 536 return "within_size"; 537 case SHMEM_HUGE_ADVISE: 538 return "advise"; 539 case SHMEM_HUGE_DENY: 540 return "deny"; 541 case SHMEM_HUGE_FORCE: 542 return "force"; 543 default: 544 VM_BUG_ON(1); 545 return "bad_val"; 546 } 547 } 548 #endif 549 550 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, 551 struct shrink_control *sc, unsigned long nr_to_split) 552 { 553 LIST_HEAD(list), *pos, *next; 554 LIST_HEAD(to_remove); 555 struct inode *inode; 556 struct shmem_inode_info *info; 557 struct folio *folio; 558 unsigned long batch = sc ? sc->nr_to_scan : 128; 559 int split = 0; 560 561 if (list_empty(&sbinfo->shrinklist)) 562 return SHRINK_STOP; 563 564 spin_lock(&sbinfo->shrinklist_lock); 565 list_for_each_safe(pos, next, &sbinfo->shrinklist) { 566 info = list_entry(pos, struct shmem_inode_info, shrinklist); 567 568 /* pin the inode */ 569 inode = igrab(&info->vfs_inode); 570 571 /* inode is about to be evicted */ 572 if (!inode) { 573 list_del_init(&info->shrinklist); 574 goto next; 575 } 576 577 /* Check if there's anything to gain */ 578 if (round_up(inode->i_size, PAGE_SIZE) == 579 round_up(inode->i_size, HPAGE_PMD_SIZE)) { 580 list_move(&info->shrinklist, &to_remove); 581 goto next; 582 } 583 584 list_move(&info->shrinklist, &list); 585 next: 586 sbinfo->shrinklist_len--; 587 if (!--batch) 588 break; 589 } 590 spin_unlock(&sbinfo->shrinklist_lock); 591 592 list_for_each_safe(pos, next, &to_remove) { 593 info = list_entry(pos, struct shmem_inode_info, shrinklist); 594 inode = &info->vfs_inode; 595 list_del_init(&info->shrinklist); 596 iput(inode); 597 } 598 599 list_for_each_safe(pos, next, &list) { 600 int ret; 601 pgoff_t index; 602 603 info = list_entry(pos, struct shmem_inode_info, shrinklist); 604 inode = &info->vfs_inode; 605 606 if (nr_to_split && split >= nr_to_split) 607 goto move_back; 608 609 index = (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT; 610 folio = filemap_get_folio(inode->i_mapping, index); 611 if (!folio) 612 goto drop; 613 614 /* No huge page at the end of the file: nothing to split */ 615 if (!folio_test_large(folio)) { 616 folio_put(folio); 617 goto drop; 618 } 619 620 /* 621 * Move the inode on the list back to shrinklist if we failed 622 * to lock the page at this time. 623 * 624 * Waiting for the lock may lead to deadlock in the 625 * reclaim path. 626 */ 627 if (!folio_trylock(folio)) { 628 folio_put(folio); 629 goto move_back; 630 } 631 632 ret = split_huge_page(&folio->page); 633 folio_unlock(folio); 634 folio_put(folio); 635 636 /* If split failed move the inode on the list back to shrinklist */ 637 if (ret) 638 goto move_back; 639 640 split++; 641 drop: 642 list_del_init(&info->shrinklist); 643 goto put; 644 move_back: 645 /* 646 * Make sure the inode is either on the global list or deleted 647 * from any local list before iput() since it could be deleted 648 * in another thread once we put the inode (then the local list 649 * is corrupted). 650 */ 651 spin_lock(&sbinfo->shrinklist_lock); 652 list_move(&info->shrinklist, &sbinfo->shrinklist); 653 sbinfo->shrinklist_len++; 654 spin_unlock(&sbinfo->shrinklist_lock); 655 put: 656 iput(inode); 657 } 658 659 return split; 660 } 661 662 static long shmem_unused_huge_scan(struct super_block *sb, 663 struct shrink_control *sc) 664 { 665 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 666 667 if (!READ_ONCE(sbinfo->shrinklist_len)) 668 return SHRINK_STOP; 669 670 return shmem_unused_huge_shrink(sbinfo, sc, 0); 671 } 672 673 static long shmem_unused_huge_count(struct super_block *sb, 674 struct shrink_control *sc) 675 { 676 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 677 return READ_ONCE(sbinfo->shrinklist_len); 678 } 679 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */ 680 681 #define shmem_huge SHMEM_HUGE_DENY 682 683 bool shmem_is_huge(struct vm_area_struct *vma, 684 struct inode *inode, pgoff_t index) 685 { 686 return false; 687 } 688 689 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo, 690 struct shrink_control *sc, unsigned long nr_to_split) 691 { 692 return 0; 693 } 694 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ 695 696 /* 697 * Like add_to_page_cache_locked, but error if expected item has gone. 698 */ 699 static int shmem_add_to_page_cache(struct folio *folio, 700 struct address_space *mapping, 701 pgoff_t index, void *expected, gfp_t gfp, 702 struct mm_struct *charge_mm) 703 { 704 XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio)); 705 long nr = folio_nr_pages(folio); 706 int error; 707 708 VM_BUG_ON_FOLIO(index != round_down(index, nr), folio); 709 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 710 VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio); 711 VM_BUG_ON(expected && folio_test_large(folio)); 712 713 folio_ref_add(folio, nr); 714 folio->mapping = mapping; 715 folio->index = index; 716 717 if (!folio_test_swapcache(folio)) { 718 error = mem_cgroup_charge(folio, charge_mm, gfp); 719 if (error) { 720 if (folio_test_pmd_mappable(folio)) { 721 count_vm_event(THP_FILE_FALLBACK); 722 count_vm_event(THP_FILE_FALLBACK_CHARGE); 723 } 724 goto error; 725 } 726 } 727 folio_throttle_swaprate(folio, gfp); 728 729 do { 730 xas_lock_irq(&xas); 731 if (expected != xas_find_conflict(&xas)) { 732 xas_set_err(&xas, -EEXIST); 733 goto unlock; 734 } 735 if (expected && xas_find_conflict(&xas)) { 736 xas_set_err(&xas, -EEXIST); 737 goto unlock; 738 } 739 xas_store(&xas, folio); 740 if (xas_error(&xas)) 741 goto unlock; 742 if (folio_test_pmd_mappable(folio)) { 743 count_vm_event(THP_FILE_ALLOC); 744 __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr); 745 } 746 mapping->nrpages += nr; 747 __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr); 748 __lruvec_stat_mod_folio(folio, NR_SHMEM, nr); 749 unlock: 750 xas_unlock_irq(&xas); 751 } while (xas_nomem(&xas, gfp)); 752 753 if (xas_error(&xas)) { 754 error = xas_error(&xas); 755 goto error; 756 } 757 758 return 0; 759 error: 760 folio->mapping = NULL; 761 folio_ref_sub(folio, nr); 762 return error; 763 } 764 765 /* 766 * Like delete_from_page_cache, but substitutes swap for page. 767 */ 768 static void shmem_delete_from_page_cache(struct page *page, void *radswap) 769 { 770 struct address_space *mapping = page->mapping; 771 int error; 772 773 VM_BUG_ON_PAGE(PageCompound(page), page); 774 775 xa_lock_irq(&mapping->i_pages); 776 error = shmem_replace_entry(mapping, page->index, page, radswap); 777 page->mapping = NULL; 778 mapping->nrpages--; 779 __dec_lruvec_page_state(page, NR_FILE_PAGES); 780 __dec_lruvec_page_state(page, NR_SHMEM); 781 xa_unlock_irq(&mapping->i_pages); 782 put_page(page); 783 BUG_ON(error); 784 } 785 786 /* 787 * Remove swap entry from page cache, free the swap and its page cache. 788 */ 789 static int shmem_free_swap(struct address_space *mapping, 790 pgoff_t index, void *radswap) 791 { 792 void *old; 793 794 old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0); 795 if (old != radswap) 796 return -ENOENT; 797 free_swap_and_cache(radix_to_swp_entry(radswap)); 798 return 0; 799 } 800 801 /* 802 * Determine (in bytes) how many of the shmem object's pages mapped by the 803 * given offsets are swapped out. 804 * 805 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU, 806 * as long as the inode doesn't go away and racy results are not a problem. 807 */ 808 unsigned long shmem_partial_swap_usage(struct address_space *mapping, 809 pgoff_t start, pgoff_t end) 810 { 811 XA_STATE(xas, &mapping->i_pages, start); 812 struct page *page; 813 unsigned long swapped = 0; 814 815 rcu_read_lock(); 816 xas_for_each(&xas, page, end - 1) { 817 if (xas_retry(&xas, page)) 818 continue; 819 if (xa_is_value(page)) 820 swapped++; 821 822 if (need_resched()) { 823 xas_pause(&xas); 824 cond_resched_rcu(); 825 } 826 } 827 828 rcu_read_unlock(); 829 830 return swapped << PAGE_SHIFT; 831 } 832 833 /* 834 * Determine (in bytes) how many of the shmem object's pages mapped by the 835 * given vma is swapped out. 836 * 837 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU, 838 * as long as the inode doesn't go away and racy results are not a problem. 839 */ 840 unsigned long shmem_swap_usage(struct vm_area_struct *vma) 841 { 842 struct inode *inode = file_inode(vma->vm_file); 843 struct shmem_inode_info *info = SHMEM_I(inode); 844 struct address_space *mapping = inode->i_mapping; 845 unsigned long swapped; 846 847 /* Be careful as we don't hold info->lock */ 848 swapped = READ_ONCE(info->swapped); 849 850 /* 851 * The easier cases are when the shmem object has nothing in swap, or 852 * the vma maps it whole. Then we can simply use the stats that we 853 * already track. 854 */ 855 if (!swapped) 856 return 0; 857 858 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size) 859 return swapped << PAGE_SHIFT; 860 861 /* Here comes the more involved part */ 862 return shmem_partial_swap_usage(mapping, vma->vm_pgoff, 863 vma->vm_pgoff + vma_pages(vma)); 864 } 865 866 /* 867 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists. 868 */ 869 void shmem_unlock_mapping(struct address_space *mapping) 870 { 871 struct pagevec pvec; 872 pgoff_t index = 0; 873 874 pagevec_init(&pvec); 875 /* 876 * Minor point, but we might as well stop if someone else SHM_LOCKs it. 877 */ 878 while (!mapping_unevictable(mapping)) { 879 if (!pagevec_lookup(&pvec, mapping, &index)) 880 break; 881 check_move_unevictable_pages(&pvec); 882 pagevec_release(&pvec); 883 cond_resched(); 884 } 885 } 886 887 static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index) 888 { 889 struct folio *folio; 890 struct page *page; 891 892 /* 893 * At first avoid shmem_getpage(,,,SGP_READ): that fails 894 * beyond i_size, and reports fallocated pages as holes. 895 */ 896 folio = __filemap_get_folio(inode->i_mapping, index, 897 FGP_ENTRY | FGP_LOCK, 0); 898 if (!xa_is_value(folio)) 899 return folio; 900 /* 901 * But read a page back from swap if any of it is within i_size 902 * (although in some cases this is just a waste of time). 903 */ 904 page = NULL; 905 shmem_getpage(inode, index, &page, SGP_READ); 906 return page ? page_folio(page) : NULL; 907 } 908 909 /* 910 * Remove range of pages and swap entries from page cache, and free them. 911 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate. 912 */ 913 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend, 914 bool unfalloc) 915 { 916 struct address_space *mapping = inode->i_mapping; 917 struct shmem_inode_info *info = SHMEM_I(inode); 918 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT; 919 pgoff_t end = (lend + 1) >> PAGE_SHIFT; 920 struct folio_batch fbatch; 921 pgoff_t indices[PAGEVEC_SIZE]; 922 struct folio *folio; 923 bool same_folio; 924 long nr_swaps_freed = 0; 925 pgoff_t index; 926 int i; 927 928 if (lend == -1) 929 end = -1; /* unsigned, so actually very big */ 930 931 if (info->fallocend > start && info->fallocend <= end && !unfalloc) 932 info->fallocend = start; 933 934 folio_batch_init(&fbatch); 935 index = start; 936 while (index < end && find_lock_entries(mapping, index, end - 1, 937 &fbatch, indices)) { 938 for (i = 0; i < folio_batch_count(&fbatch); i++) { 939 folio = fbatch.folios[i]; 940 941 index = indices[i]; 942 943 if (xa_is_value(folio)) { 944 if (unfalloc) 945 continue; 946 nr_swaps_freed += !shmem_free_swap(mapping, 947 index, folio); 948 continue; 949 } 950 index += folio_nr_pages(folio) - 1; 951 952 if (!unfalloc || !folio_test_uptodate(folio)) 953 truncate_inode_folio(mapping, folio); 954 folio_unlock(folio); 955 } 956 folio_batch_remove_exceptionals(&fbatch); 957 folio_batch_release(&fbatch); 958 cond_resched(); 959 index++; 960 } 961 962 same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT); 963 folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT); 964 if (folio) { 965 same_folio = lend < folio_pos(folio) + folio_size(folio); 966 folio_mark_dirty(folio); 967 if (!truncate_inode_partial_folio(folio, lstart, lend)) { 968 start = folio->index + folio_nr_pages(folio); 969 if (same_folio) 970 end = folio->index; 971 } 972 folio_unlock(folio); 973 folio_put(folio); 974 folio = NULL; 975 } 976 977 if (!same_folio) 978 folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT); 979 if (folio) { 980 folio_mark_dirty(folio); 981 if (!truncate_inode_partial_folio(folio, lstart, lend)) 982 end = folio->index; 983 folio_unlock(folio); 984 folio_put(folio); 985 } 986 987 index = start; 988 while (index < end) { 989 cond_resched(); 990 991 if (!find_get_entries(mapping, index, end - 1, &fbatch, 992 indices)) { 993 /* If all gone or hole-punch or unfalloc, we're done */ 994 if (index == start || end != -1) 995 break; 996 /* But if truncating, restart to make sure all gone */ 997 index = start; 998 continue; 999 } 1000 for (i = 0; i < folio_batch_count(&fbatch); i++) { 1001 folio = fbatch.folios[i]; 1002 1003 index = indices[i]; 1004 if (xa_is_value(folio)) { 1005 if (unfalloc) 1006 continue; 1007 if (shmem_free_swap(mapping, index, folio)) { 1008 /* Swap was replaced by page: retry */ 1009 index--; 1010 break; 1011 } 1012 nr_swaps_freed++; 1013 continue; 1014 } 1015 1016 folio_lock(folio); 1017 1018 if (!unfalloc || !folio_test_uptodate(folio)) { 1019 if (folio_mapping(folio) != mapping) { 1020 /* Page was replaced by swap: retry */ 1021 folio_unlock(folio); 1022 index--; 1023 break; 1024 } 1025 VM_BUG_ON_FOLIO(folio_test_writeback(folio), 1026 folio); 1027 truncate_inode_folio(mapping, folio); 1028 } 1029 index = folio->index + folio_nr_pages(folio) - 1; 1030 folio_unlock(folio); 1031 } 1032 folio_batch_remove_exceptionals(&fbatch); 1033 folio_batch_release(&fbatch); 1034 index++; 1035 } 1036 1037 spin_lock_irq(&info->lock); 1038 info->swapped -= nr_swaps_freed; 1039 shmem_recalc_inode(inode); 1040 spin_unlock_irq(&info->lock); 1041 } 1042 1043 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 1044 { 1045 shmem_undo_range(inode, lstart, lend, false); 1046 inode->i_ctime = inode->i_mtime = current_time(inode); 1047 } 1048 EXPORT_SYMBOL_GPL(shmem_truncate_range); 1049 1050 static int shmem_getattr(struct user_namespace *mnt_userns, 1051 const struct path *path, struct kstat *stat, 1052 u32 request_mask, unsigned int query_flags) 1053 { 1054 struct inode *inode = path->dentry->d_inode; 1055 struct shmem_inode_info *info = SHMEM_I(inode); 1056 1057 if (info->alloced - info->swapped != inode->i_mapping->nrpages) { 1058 spin_lock_irq(&info->lock); 1059 shmem_recalc_inode(inode); 1060 spin_unlock_irq(&info->lock); 1061 } 1062 if (info->fsflags & FS_APPEND_FL) 1063 stat->attributes |= STATX_ATTR_APPEND; 1064 if (info->fsflags & FS_IMMUTABLE_FL) 1065 stat->attributes |= STATX_ATTR_IMMUTABLE; 1066 if (info->fsflags & FS_NODUMP_FL) 1067 stat->attributes |= STATX_ATTR_NODUMP; 1068 stat->attributes_mask |= (STATX_ATTR_APPEND | 1069 STATX_ATTR_IMMUTABLE | 1070 STATX_ATTR_NODUMP); 1071 generic_fillattr(&init_user_ns, inode, stat); 1072 1073 if (shmem_is_huge(NULL, inode, 0)) 1074 stat->blksize = HPAGE_PMD_SIZE; 1075 1076 if (request_mask & STATX_BTIME) { 1077 stat->result_mask |= STATX_BTIME; 1078 stat->btime.tv_sec = info->i_crtime.tv_sec; 1079 stat->btime.tv_nsec = info->i_crtime.tv_nsec; 1080 } 1081 1082 return 0; 1083 } 1084 1085 static int shmem_setattr(struct user_namespace *mnt_userns, 1086 struct dentry *dentry, struct iattr *attr) 1087 { 1088 struct inode *inode = d_inode(dentry); 1089 struct shmem_inode_info *info = SHMEM_I(inode); 1090 int error; 1091 1092 error = setattr_prepare(&init_user_ns, dentry, attr); 1093 if (error) 1094 return error; 1095 1096 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { 1097 loff_t oldsize = inode->i_size; 1098 loff_t newsize = attr->ia_size; 1099 1100 /* protected by i_rwsem */ 1101 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) || 1102 (newsize > oldsize && (info->seals & F_SEAL_GROW))) 1103 return -EPERM; 1104 1105 if (newsize != oldsize) { 1106 error = shmem_reacct_size(SHMEM_I(inode)->flags, 1107 oldsize, newsize); 1108 if (error) 1109 return error; 1110 i_size_write(inode, newsize); 1111 inode->i_ctime = inode->i_mtime = current_time(inode); 1112 } 1113 if (newsize <= oldsize) { 1114 loff_t holebegin = round_up(newsize, PAGE_SIZE); 1115 if (oldsize > holebegin) 1116 unmap_mapping_range(inode->i_mapping, 1117 holebegin, 0, 1); 1118 if (info->alloced) 1119 shmem_truncate_range(inode, 1120 newsize, (loff_t)-1); 1121 /* unmap again to remove racily COWed private pages */ 1122 if (oldsize > holebegin) 1123 unmap_mapping_range(inode->i_mapping, 1124 holebegin, 0, 1); 1125 } 1126 } 1127 1128 setattr_copy(&init_user_ns, inode, attr); 1129 if (attr->ia_valid & ATTR_MODE) 1130 error = posix_acl_chmod(&init_user_ns, inode, inode->i_mode); 1131 return error; 1132 } 1133 1134 static void shmem_evict_inode(struct inode *inode) 1135 { 1136 struct shmem_inode_info *info = SHMEM_I(inode); 1137 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 1138 1139 if (shmem_mapping(inode->i_mapping)) { 1140 shmem_unacct_size(info->flags, inode->i_size); 1141 inode->i_size = 0; 1142 mapping_set_exiting(inode->i_mapping); 1143 shmem_truncate_range(inode, 0, (loff_t)-1); 1144 if (!list_empty(&info->shrinklist)) { 1145 spin_lock(&sbinfo->shrinklist_lock); 1146 if (!list_empty(&info->shrinklist)) { 1147 list_del_init(&info->shrinklist); 1148 sbinfo->shrinklist_len--; 1149 } 1150 spin_unlock(&sbinfo->shrinklist_lock); 1151 } 1152 while (!list_empty(&info->swaplist)) { 1153 /* Wait while shmem_unuse() is scanning this inode... */ 1154 wait_var_event(&info->stop_eviction, 1155 !atomic_read(&info->stop_eviction)); 1156 mutex_lock(&shmem_swaplist_mutex); 1157 /* ...but beware of the race if we peeked too early */ 1158 if (!atomic_read(&info->stop_eviction)) 1159 list_del_init(&info->swaplist); 1160 mutex_unlock(&shmem_swaplist_mutex); 1161 } 1162 } 1163 1164 simple_xattrs_free(&info->xattrs); 1165 WARN_ON(inode->i_blocks); 1166 shmem_free_inode(inode->i_sb); 1167 clear_inode(inode); 1168 } 1169 1170 static int shmem_find_swap_entries(struct address_space *mapping, 1171 pgoff_t start, struct folio_batch *fbatch, 1172 pgoff_t *indices, unsigned int type) 1173 { 1174 XA_STATE(xas, &mapping->i_pages, start); 1175 struct folio *folio; 1176 swp_entry_t entry; 1177 1178 rcu_read_lock(); 1179 xas_for_each(&xas, folio, ULONG_MAX) { 1180 if (xas_retry(&xas, folio)) 1181 continue; 1182 1183 if (!xa_is_value(folio)) 1184 continue; 1185 1186 entry = radix_to_swp_entry(folio); 1187 /* 1188 * swapin error entries can be found in the mapping. But they're 1189 * deliberately ignored here as we've done everything we can do. 1190 */ 1191 if (swp_type(entry) != type) 1192 continue; 1193 1194 indices[folio_batch_count(fbatch)] = xas.xa_index; 1195 if (!folio_batch_add(fbatch, folio)) 1196 break; 1197 1198 if (need_resched()) { 1199 xas_pause(&xas); 1200 cond_resched_rcu(); 1201 } 1202 } 1203 rcu_read_unlock(); 1204 1205 return xas.xa_index; 1206 } 1207 1208 /* 1209 * Move the swapped pages for an inode to page cache. Returns the count 1210 * of pages swapped in, or the error in case of failure. 1211 */ 1212 static int shmem_unuse_swap_entries(struct inode *inode, 1213 struct folio_batch *fbatch, pgoff_t *indices) 1214 { 1215 int i = 0; 1216 int ret = 0; 1217 int error = 0; 1218 struct address_space *mapping = inode->i_mapping; 1219 1220 for (i = 0; i < folio_batch_count(fbatch); i++) { 1221 struct folio *folio = fbatch->folios[i]; 1222 1223 if (!xa_is_value(folio)) 1224 continue; 1225 error = shmem_swapin_folio(inode, indices[i], 1226 &folio, SGP_CACHE, 1227 mapping_gfp_mask(mapping), 1228 NULL, NULL); 1229 if (error == 0) { 1230 folio_unlock(folio); 1231 folio_put(folio); 1232 ret++; 1233 } 1234 if (error == -ENOMEM) 1235 break; 1236 error = 0; 1237 } 1238 return error ? error : ret; 1239 } 1240 1241 /* 1242 * If swap found in inode, free it and move page from swapcache to filecache. 1243 */ 1244 static int shmem_unuse_inode(struct inode *inode, unsigned int type) 1245 { 1246 struct address_space *mapping = inode->i_mapping; 1247 pgoff_t start = 0; 1248 struct folio_batch fbatch; 1249 pgoff_t indices[PAGEVEC_SIZE]; 1250 int ret = 0; 1251 1252 do { 1253 folio_batch_init(&fbatch); 1254 shmem_find_swap_entries(mapping, start, &fbatch, indices, type); 1255 if (folio_batch_count(&fbatch) == 0) { 1256 ret = 0; 1257 break; 1258 } 1259 1260 ret = shmem_unuse_swap_entries(inode, &fbatch, indices); 1261 if (ret < 0) 1262 break; 1263 1264 start = indices[folio_batch_count(&fbatch) - 1]; 1265 } while (true); 1266 1267 return ret; 1268 } 1269 1270 /* 1271 * Read all the shared memory data that resides in the swap 1272 * device 'type' back into memory, so the swap device can be 1273 * unused. 1274 */ 1275 int shmem_unuse(unsigned int type) 1276 { 1277 struct shmem_inode_info *info, *next; 1278 int error = 0; 1279 1280 if (list_empty(&shmem_swaplist)) 1281 return 0; 1282 1283 mutex_lock(&shmem_swaplist_mutex); 1284 list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) { 1285 if (!info->swapped) { 1286 list_del_init(&info->swaplist); 1287 continue; 1288 } 1289 /* 1290 * Drop the swaplist mutex while searching the inode for swap; 1291 * but before doing so, make sure shmem_evict_inode() will not 1292 * remove placeholder inode from swaplist, nor let it be freed 1293 * (igrab() would protect from unlink, but not from unmount). 1294 */ 1295 atomic_inc(&info->stop_eviction); 1296 mutex_unlock(&shmem_swaplist_mutex); 1297 1298 error = shmem_unuse_inode(&info->vfs_inode, type); 1299 cond_resched(); 1300 1301 mutex_lock(&shmem_swaplist_mutex); 1302 next = list_next_entry(info, swaplist); 1303 if (!info->swapped) 1304 list_del_init(&info->swaplist); 1305 if (atomic_dec_and_test(&info->stop_eviction)) 1306 wake_up_var(&info->stop_eviction); 1307 if (error) 1308 break; 1309 } 1310 mutex_unlock(&shmem_swaplist_mutex); 1311 1312 return error; 1313 } 1314 1315 /* 1316 * Move the page from the page cache to the swap cache. 1317 */ 1318 static int shmem_writepage(struct page *page, struct writeback_control *wbc) 1319 { 1320 struct folio *folio = page_folio(page); 1321 struct shmem_inode_info *info; 1322 struct address_space *mapping; 1323 struct inode *inode; 1324 swp_entry_t swap; 1325 pgoff_t index; 1326 1327 /* 1328 * If /sys/kernel/mm/transparent_hugepage/shmem_enabled is "always" or 1329 * "force", drivers/gpu/drm/i915/gem/i915_gem_shmem.c gets huge pages, 1330 * and its shmem_writeback() needs them to be split when swapping. 1331 */ 1332 if (PageTransCompound(page)) { 1333 /* Ensure the subpages are still dirty */ 1334 SetPageDirty(page); 1335 if (split_huge_page(page) < 0) 1336 goto redirty; 1337 ClearPageDirty(page); 1338 } 1339 1340 BUG_ON(!PageLocked(page)); 1341 mapping = page->mapping; 1342 index = page->index; 1343 inode = mapping->host; 1344 info = SHMEM_I(inode); 1345 if (info->flags & VM_LOCKED) 1346 goto redirty; 1347 if (!total_swap_pages) 1348 goto redirty; 1349 1350 /* 1351 * Our capabilities prevent regular writeback or sync from ever calling 1352 * shmem_writepage; but a stacking filesystem might use ->writepage of 1353 * its underlying filesystem, in which case tmpfs should write out to 1354 * swap only in response to memory pressure, and not for the writeback 1355 * threads or sync. 1356 */ 1357 if (!wbc->for_reclaim) { 1358 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */ 1359 goto redirty; 1360 } 1361 1362 /* 1363 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC 1364 * value into swapfile.c, the only way we can correctly account for a 1365 * fallocated page arriving here is now to initialize it and write it. 1366 * 1367 * That's okay for a page already fallocated earlier, but if we have 1368 * not yet completed the fallocation, then (a) we want to keep track 1369 * of this page in case we have to undo it, and (b) it may not be a 1370 * good idea to continue anyway, once we're pushing into swap. So 1371 * reactivate the page, and let shmem_fallocate() quit when too many. 1372 */ 1373 if (!PageUptodate(page)) { 1374 if (inode->i_private) { 1375 struct shmem_falloc *shmem_falloc; 1376 spin_lock(&inode->i_lock); 1377 shmem_falloc = inode->i_private; 1378 if (shmem_falloc && 1379 !shmem_falloc->waitq && 1380 index >= shmem_falloc->start && 1381 index < shmem_falloc->next) 1382 shmem_falloc->nr_unswapped++; 1383 else 1384 shmem_falloc = NULL; 1385 spin_unlock(&inode->i_lock); 1386 if (shmem_falloc) 1387 goto redirty; 1388 } 1389 clear_highpage(page); 1390 flush_dcache_page(page); 1391 SetPageUptodate(page); 1392 } 1393 1394 swap = folio_alloc_swap(folio); 1395 if (!swap.val) 1396 goto redirty; 1397 1398 /* 1399 * Add inode to shmem_unuse()'s list of swapped-out inodes, 1400 * if it's not already there. Do it now before the page is 1401 * moved to swap cache, when its pagelock no longer protects 1402 * the inode from eviction. But don't unlock the mutex until 1403 * we've incremented swapped, because shmem_unuse_inode() will 1404 * prune a !swapped inode from the swaplist under this mutex. 1405 */ 1406 mutex_lock(&shmem_swaplist_mutex); 1407 if (list_empty(&info->swaplist)) 1408 list_add(&info->swaplist, &shmem_swaplist); 1409 1410 if (add_to_swap_cache(page, swap, 1411 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN, 1412 NULL) == 0) { 1413 spin_lock_irq(&info->lock); 1414 shmem_recalc_inode(inode); 1415 info->swapped++; 1416 spin_unlock_irq(&info->lock); 1417 1418 swap_shmem_alloc(swap); 1419 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap)); 1420 1421 mutex_unlock(&shmem_swaplist_mutex); 1422 BUG_ON(page_mapped(page)); 1423 swap_writepage(page, wbc); 1424 return 0; 1425 } 1426 1427 mutex_unlock(&shmem_swaplist_mutex); 1428 put_swap_page(page, swap); 1429 redirty: 1430 set_page_dirty(page); 1431 if (wbc->for_reclaim) 1432 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */ 1433 unlock_page(page); 1434 return 0; 1435 } 1436 1437 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS) 1438 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1439 { 1440 char buffer[64]; 1441 1442 if (!mpol || mpol->mode == MPOL_DEFAULT) 1443 return; /* show nothing */ 1444 1445 mpol_to_str(buffer, sizeof(buffer), mpol); 1446 1447 seq_printf(seq, ",mpol=%s", buffer); 1448 } 1449 1450 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1451 { 1452 struct mempolicy *mpol = NULL; 1453 if (sbinfo->mpol) { 1454 raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */ 1455 mpol = sbinfo->mpol; 1456 mpol_get(mpol); 1457 raw_spin_unlock(&sbinfo->stat_lock); 1458 } 1459 return mpol; 1460 } 1461 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */ 1462 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol) 1463 { 1464 } 1465 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo) 1466 { 1467 return NULL; 1468 } 1469 #endif /* CONFIG_NUMA && CONFIG_TMPFS */ 1470 #ifndef CONFIG_NUMA 1471 #define vm_policy vm_private_data 1472 #endif 1473 1474 static void shmem_pseudo_vma_init(struct vm_area_struct *vma, 1475 struct shmem_inode_info *info, pgoff_t index) 1476 { 1477 /* Create a pseudo vma that just contains the policy */ 1478 vma_init(vma, NULL); 1479 /* Bias interleave by inode number to distribute better across nodes */ 1480 vma->vm_pgoff = index + info->vfs_inode.i_ino; 1481 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index); 1482 } 1483 1484 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma) 1485 { 1486 /* Drop reference taken by mpol_shared_policy_lookup() */ 1487 mpol_cond_put(vma->vm_policy); 1488 } 1489 1490 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp, 1491 struct shmem_inode_info *info, pgoff_t index) 1492 { 1493 struct vm_area_struct pvma; 1494 struct page *page; 1495 struct vm_fault vmf = { 1496 .vma = &pvma, 1497 }; 1498 1499 shmem_pseudo_vma_init(&pvma, info, index); 1500 page = swap_cluster_readahead(swap, gfp, &vmf); 1501 shmem_pseudo_vma_destroy(&pvma); 1502 1503 return page; 1504 } 1505 1506 /* 1507 * Make sure huge_gfp is always more limited than limit_gfp. 1508 * Some of the flags set permissions, while others set limitations. 1509 */ 1510 static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp) 1511 { 1512 gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM; 1513 gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY; 1514 gfp_t zoneflags = limit_gfp & GFP_ZONEMASK; 1515 gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK); 1516 1517 /* Allow allocations only from the originally specified zones. */ 1518 result |= zoneflags; 1519 1520 /* 1521 * Minimize the result gfp by taking the union with the deny flags, 1522 * and the intersection of the allow flags. 1523 */ 1524 result |= (limit_gfp & denyflags); 1525 result |= (huge_gfp & limit_gfp) & allowflags; 1526 1527 return result; 1528 } 1529 1530 static struct folio *shmem_alloc_hugefolio(gfp_t gfp, 1531 struct shmem_inode_info *info, pgoff_t index) 1532 { 1533 struct vm_area_struct pvma; 1534 struct address_space *mapping = info->vfs_inode.i_mapping; 1535 pgoff_t hindex; 1536 struct folio *folio; 1537 1538 hindex = round_down(index, HPAGE_PMD_NR); 1539 if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1, 1540 XA_PRESENT)) 1541 return NULL; 1542 1543 shmem_pseudo_vma_init(&pvma, info, hindex); 1544 folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, &pvma, 0, true); 1545 shmem_pseudo_vma_destroy(&pvma); 1546 if (!folio) 1547 count_vm_event(THP_FILE_FALLBACK); 1548 return folio; 1549 } 1550 1551 static struct folio *shmem_alloc_folio(gfp_t gfp, 1552 struct shmem_inode_info *info, pgoff_t index) 1553 { 1554 struct vm_area_struct pvma; 1555 struct folio *folio; 1556 1557 shmem_pseudo_vma_init(&pvma, info, index); 1558 folio = vma_alloc_folio(gfp, 0, &pvma, 0, false); 1559 shmem_pseudo_vma_destroy(&pvma); 1560 1561 return folio; 1562 } 1563 1564 static struct page *shmem_alloc_page(gfp_t gfp, 1565 struct shmem_inode_info *info, pgoff_t index) 1566 { 1567 return &shmem_alloc_folio(gfp, info, index)->page; 1568 } 1569 1570 static struct folio *shmem_alloc_and_acct_folio(gfp_t gfp, struct inode *inode, 1571 pgoff_t index, bool huge) 1572 { 1573 struct shmem_inode_info *info = SHMEM_I(inode); 1574 struct folio *folio; 1575 int nr; 1576 int err = -ENOSPC; 1577 1578 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 1579 huge = false; 1580 nr = huge ? HPAGE_PMD_NR : 1; 1581 1582 if (!shmem_inode_acct_block(inode, nr)) 1583 goto failed; 1584 1585 if (huge) 1586 folio = shmem_alloc_hugefolio(gfp, info, index); 1587 else 1588 folio = shmem_alloc_folio(gfp, info, index); 1589 if (folio) { 1590 __folio_set_locked(folio); 1591 __folio_set_swapbacked(folio); 1592 return folio; 1593 } 1594 1595 err = -ENOMEM; 1596 shmem_inode_unacct_blocks(inode, nr); 1597 failed: 1598 return ERR_PTR(err); 1599 } 1600 1601 /* 1602 * When a page is moved from swapcache to shmem filecache (either by the 1603 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of 1604 * shmem_unuse_inode()), it may have been read in earlier from swap, in 1605 * ignorance of the mapping it belongs to. If that mapping has special 1606 * constraints (like the gma500 GEM driver, which requires RAM below 4GB), 1607 * we may need to copy to a suitable page before moving to filecache. 1608 * 1609 * In a future release, this may well be extended to respect cpuset and 1610 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page(); 1611 * but for now it is a simple matter of zone. 1612 */ 1613 static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp) 1614 { 1615 return folio_zonenum(folio) > gfp_zone(gfp); 1616 } 1617 1618 static int shmem_replace_page(struct page **pagep, gfp_t gfp, 1619 struct shmem_inode_info *info, pgoff_t index) 1620 { 1621 struct page *oldpage, *newpage; 1622 struct folio *old, *new; 1623 struct address_space *swap_mapping; 1624 swp_entry_t entry; 1625 pgoff_t swap_index; 1626 int error; 1627 1628 oldpage = *pagep; 1629 entry.val = page_private(oldpage); 1630 swap_index = swp_offset(entry); 1631 swap_mapping = page_mapping(oldpage); 1632 1633 /* 1634 * We have arrived here because our zones are constrained, so don't 1635 * limit chance of success by further cpuset and node constraints. 1636 */ 1637 gfp &= ~GFP_CONSTRAINT_MASK; 1638 newpage = shmem_alloc_page(gfp, info, index); 1639 if (!newpage) 1640 return -ENOMEM; 1641 1642 get_page(newpage); 1643 copy_highpage(newpage, oldpage); 1644 flush_dcache_page(newpage); 1645 1646 __SetPageLocked(newpage); 1647 __SetPageSwapBacked(newpage); 1648 SetPageUptodate(newpage); 1649 set_page_private(newpage, entry.val); 1650 SetPageSwapCache(newpage); 1651 1652 /* 1653 * Our caller will very soon move newpage out of swapcache, but it's 1654 * a nice clean interface for us to replace oldpage by newpage there. 1655 */ 1656 xa_lock_irq(&swap_mapping->i_pages); 1657 error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage); 1658 if (!error) { 1659 old = page_folio(oldpage); 1660 new = page_folio(newpage); 1661 mem_cgroup_migrate(old, new); 1662 __inc_lruvec_page_state(newpage, NR_FILE_PAGES); 1663 __dec_lruvec_page_state(oldpage, NR_FILE_PAGES); 1664 } 1665 xa_unlock_irq(&swap_mapping->i_pages); 1666 1667 if (unlikely(error)) { 1668 /* 1669 * Is this possible? I think not, now that our callers check 1670 * both PageSwapCache and page_private after getting page lock; 1671 * but be defensive. Reverse old to newpage for clear and free. 1672 */ 1673 oldpage = newpage; 1674 } else { 1675 lru_cache_add(newpage); 1676 *pagep = newpage; 1677 } 1678 1679 ClearPageSwapCache(oldpage); 1680 set_page_private(oldpage, 0); 1681 1682 unlock_page(oldpage); 1683 put_page(oldpage); 1684 put_page(oldpage); 1685 return error; 1686 } 1687 1688 static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index, 1689 struct folio *folio, swp_entry_t swap) 1690 { 1691 struct address_space *mapping = inode->i_mapping; 1692 struct shmem_inode_info *info = SHMEM_I(inode); 1693 swp_entry_t swapin_error; 1694 void *old; 1695 1696 swapin_error = make_swapin_error_entry(&folio->page); 1697 old = xa_cmpxchg_irq(&mapping->i_pages, index, 1698 swp_to_radix_entry(swap), 1699 swp_to_radix_entry(swapin_error), 0); 1700 if (old != swp_to_radix_entry(swap)) 1701 return; 1702 1703 folio_wait_writeback(folio); 1704 delete_from_swap_cache(folio); 1705 spin_lock_irq(&info->lock); 1706 /* 1707 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks won't 1708 * be 0 when inode is released and thus trigger WARN_ON(inode->i_blocks) in 1709 * shmem_evict_inode. 1710 */ 1711 info->alloced--; 1712 info->swapped--; 1713 shmem_recalc_inode(inode); 1714 spin_unlock_irq(&info->lock); 1715 swap_free(swap); 1716 } 1717 1718 /* 1719 * Swap in the folio pointed to by *foliop. 1720 * Caller has to make sure that *foliop contains a valid swapped folio. 1721 * Returns 0 and the folio in foliop if success. On failure, returns the 1722 * error code and NULL in *foliop. 1723 */ 1724 static int shmem_swapin_folio(struct inode *inode, pgoff_t index, 1725 struct folio **foliop, enum sgp_type sgp, 1726 gfp_t gfp, struct vm_area_struct *vma, 1727 vm_fault_t *fault_type) 1728 { 1729 struct address_space *mapping = inode->i_mapping; 1730 struct shmem_inode_info *info = SHMEM_I(inode); 1731 struct mm_struct *charge_mm = vma ? vma->vm_mm : NULL; 1732 struct page *page; 1733 struct folio *folio = NULL; 1734 swp_entry_t swap; 1735 int error; 1736 1737 VM_BUG_ON(!*foliop || !xa_is_value(*foliop)); 1738 swap = radix_to_swp_entry(*foliop); 1739 *foliop = NULL; 1740 1741 if (is_swapin_error_entry(swap)) 1742 return -EIO; 1743 1744 /* Look it up and read it in.. */ 1745 page = lookup_swap_cache(swap, NULL, 0); 1746 if (!page) { 1747 /* Or update major stats only when swapin succeeds?? */ 1748 if (fault_type) { 1749 *fault_type |= VM_FAULT_MAJOR; 1750 count_vm_event(PGMAJFAULT); 1751 count_memcg_event_mm(charge_mm, PGMAJFAULT); 1752 } 1753 /* Here we actually start the io */ 1754 page = shmem_swapin(swap, gfp, info, index); 1755 if (!page) { 1756 error = -ENOMEM; 1757 goto failed; 1758 } 1759 } 1760 folio = page_folio(page); 1761 1762 /* We have to do this with folio locked to prevent races */ 1763 folio_lock(folio); 1764 if (!folio_test_swapcache(folio) || 1765 folio_swap_entry(folio).val != swap.val || 1766 !shmem_confirm_swap(mapping, index, swap)) { 1767 error = -EEXIST; 1768 goto unlock; 1769 } 1770 if (!folio_test_uptodate(folio)) { 1771 error = -EIO; 1772 goto failed; 1773 } 1774 folio_wait_writeback(folio); 1775 1776 /* 1777 * Some architectures may have to restore extra metadata to the 1778 * folio after reading from swap. 1779 */ 1780 arch_swap_restore(swap, folio); 1781 1782 if (shmem_should_replace_folio(folio, gfp)) { 1783 error = shmem_replace_page(&page, gfp, info, index); 1784 if (error) 1785 goto failed; 1786 } 1787 1788 error = shmem_add_to_page_cache(folio, mapping, index, 1789 swp_to_radix_entry(swap), gfp, 1790 charge_mm); 1791 if (error) 1792 goto failed; 1793 1794 spin_lock_irq(&info->lock); 1795 info->swapped--; 1796 shmem_recalc_inode(inode); 1797 spin_unlock_irq(&info->lock); 1798 1799 if (sgp == SGP_WRITE) 1800 folio_mark_accessed(folio); 1801 1802 delete_from_swap_cache(folio); 1803 folio_mark_dirty(folio); 1804 swap_free(swap); 1805 1806 *foliop = folio; 1807 return 0; 1808 failed: 1809 if (!shmem_confirm_swap(mapping, index, swap)) 1810 error = -EEXIST; 1811 if (error == -EIO) 1812 shmem_set_folio_swapin_error(inode, index, folio, swap); 1813 unlock: 1814 if (folio) { 1815 folio_unlock(folio); 1816 folio_put(folio); 1817 } 1818 1819 return error; 1820 } 1821 1822 /* 1823 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate 1824 * 1825 * If we allocate a new one we do not mark it dirty. That's up to the 1826 * vm. If we swap it in we mark it dirty since we also free the swap 1827 * entry since a page cannot live in both the swap and page cache. 1828 * 1829 * vma, vmf, and fault_type are only supplied by shmem_fault: 1830 * otherwise they are NULL. 1831 */ 1832 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index, 1833 struct page **pagep, enum sgp_type sgp, gfp_t gfp, 1834 struct vm_area_struct *vma, struct vm_fault *vmf, 1835 vm_fault_t *fault_type) 1836 { 1837 struct address_space *mapping = inode->i_mapping; 1838 struct shmem_inode_info *info = SHMEM_I(inode); 1839 struct shmem_sb_info *sbinfo; 1840 struct mm_struct *charge_mm; 1841 struct folio *folio; 1842 pgoff_t hindex = index; 1843 gfp_t huge_gfp; 1844 int error; 1845 int once = 0; 1846 int alloced = 0; 1847 1848 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT)) 1849 return -EFBIG; 1850 repeat: 1851 if (sgp <= SGP_CACHE && 1852 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) { 1853 return -EINVAL; 1854 } 1855 1856 sbinfo = SHMEM_SB(inode->i_sb); 1857 charge_mm = vma ? vma->vm_mm : NULL; 1858 1859 folio = __filemap_get_folio(mapping, index, FGP_ENTRY | FGP_LOCK, 0); 1860 if (folio && vma && userfaultfd_minor(vma)) { 1861 if (!xa_is_value(folio)) { 1862 folio_unlock(folio); 1863 folio_put(folio); 1864 } 1865 *fault_type = handle_userfault(vmf, VM_UFFD_MINOR); 1866 return 0; 1867 } 1868 1869 if (xa_is_value(folio)) { 1870 error = shmem_swapin_folio(inode, index, &folio, 1871 sgp, gfp, vma, fault_type); 1872 if (error == -EEXIST) 1873 goto repeat; 1874 1875 *pagep = &folio->page; 1876 return error; 1877 } 1878 1879 if (folio) { 1880 hindex = folio->index; 1881 if (sgp == SGP_WRITE) 1882 folio_mark_accessed(folio); 1883 if (folio_test_uptodate(folio)) 1884 goto out; 1885 /* fallocated page */ 1886 if (sgp != SGP_READ) 1887 goto clear; 1888 folio_unlock(folio); 1889 folio_put(folio); 1890 } 1891 1892 /* 1893 * SGP_READ: succeed on hole, with NULL page, letting caller zero. 1894 * SGP_NOALLOC: fail on hole, with NULL page, letting caller fail. 1895 */ 1896 *pagep = NULL; 1897 if (sgp == SGP_READ) 1898 return 0; 1899 if (sgp == SGP_NOALLOC) 1900 return -ENOENT; 1901 1902 /* 1903 * Fast cache lookup and swap lookup did not find it: allocate. 1904 */ 1905 1906 if (vma && userfaultfd_missing(vma)) { 1907 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING); 1908 return 0; 1909 } 1910 1911 if (!shmem_is_huge(vma, inode, index)) 1912 goto alloc_nohuge; 1913 1914 huge_gfp = vma_thp_gfp_mask(vma); 1915 huge_gfp = limit_gfp_mask(huge_gfp, gfp); 1916 folio = shmem_alloc_and_acct_folio(huge_gfp, inode, index, true); 1917 if (IS_ERR(folio)) { 1918 alloc_nohuge: 1919 folio = shmem_alloc_and_acct_folio(gfp, inode, index, false); 1920 } 1921 if (IS_ERR(folio)) { 1922 int retry = 5; 1923 1924 error = PTR_ERR(folio); 1925 folio = NULL; 1926 if (error != -ENOSPC) 1927 goto unlock; 1928 /* 1929 * Try to reclaim some space by splitting a huge page 1930 * beyond i_size on the filesystem. 1931 */ 1932 while (retry--) { 1933 int ret; 1934 1935 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1); 1936 if (ret == SHRINK_STOP) 1937 break; 1938 if (ret) 1939 goto alloc_nohuge; 1940 } 1941 goto unlock; 1942 } 1943 1944 hindex = round_down(index, folio_nr_pages(folio)); 1945 1946 if (sgp == SGP_WRITE) 1947 __folio_set_referenced(folio); 1948 1949 error = shmem_add_to_page_cache(folio, mapping, hindex, 1950 NULL, gfp & GFP_RECLAIM_MASK, 1951 charge_mm); 1952 if (error) 1953 goto unacct; 1954 folio_add_lru(folio); 1955 1956 spin_lock_irq(&info->lock); 1957 info->alloced += folio_nr_pages(folio); 1958 inode->i_blocks += (blkcnt_t)BLOCKS_PER_PAGE << folio_order(folio); 1959 shmem_recalc_inode(inode); 1960 spin_unlock_irq(&info->lock); 1961 alloced = true; 1962 1963 if (folio_test_pmd_mappable(folio) && 1964 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) < 1965 hindex + HPAGE_PMD_NR - 1) { 1966 /* 1967 * Part of the huge page is beyond i_size: subject 1968 * to shrink under memory pressure. 1969 */ 1970 spin_lock(&sbinfo->shrinklist_lock); 1971 /* 1972 * _careful to defend against unlocked access to 1973 * ->shrink_list in shmem_unused_huge_shrink() 1974 */ 1975 if (list_empty_careful(&info->shrinklist)) { 1976 list_add_tail(&info->shrinklist, 1977 &sbinfo->shrinklist); 1978 sbinfo->shrinklist_len++; 1979 } 1980 spin_unlock(&sbinfo->shrinklist_lock); 1981 } 1982 1983 /* 1984 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page. 1985 */ 1986 if (sgp == SGP_FALLOC) 1987 sgp = SGP_WRITE; 1988 clear: 1989 /* 1990 * Let SGP_WRITE caller clear ends if write does not fill page; 1991 * but SGP_FALLOC on a page fallocated earlier must initialize 1992 * it now, lest undo on failure cancel our earlier guarantee. 1993 */ 1994 if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) { 1995 long i, n = folio_nr_pages(folio); 1996 1997 for (i = 0; i < n; i++) 1998 clear_highpage(folio_page(folio, i)); 1999 flush_dcache_folio(folio); 2000 folio_mark_uptodate(folio); 2001 } 2002 2003 /* Perhaps the file has been truncated since we checked */ 2004 if (sgp <= SGP_CACHE && 2005 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) { 2006 if (alloced) { 2007 folio_clear_dirty(folio); 2008 filemap_remove_folio(folio); 2009 spin_lock_irq(&info->lock); 2010 shmem_recalc_inode(inode); 2011 spin_unlock_irq(&info->lock); 2012 } 2013 error = -EINVAL; 2014 goto unlock; 2015 } 2016 out: 2017 *pagep = folio_page(folio, index - hindex); 2018 return 0; 2019 2020 /* 2021 * Error recovery. 2022 */ 2023 unacct: 2024 shmem_inode_unacct_blocks(inode, folio_nr_pages(folio)); 2025 2026 if (folio_test_large(folio)) { 2027 folio_unlock(folio); 2028 folio_put(folio); 2029 goto alloc_nohuge; 2030 } 2031 unlock: 2032 if (folio) { 2033 folio_unlock(folio); 2034 folio_put(folio); 2035 } 2036 if (error == -ENOSPC && !once++) { 2037 spin_lock_irq(&info->lock); 2038 shmem_recalc_inode(inode); 2039 spin_unlock_irq(&info->lock); 2040 goto repeat; 2041 } 2042 if (error == -EEXIST) 2043 goto repeat; 2044 return error; 2045 } 2046 2047 /* 2048 * This is like autoremove_wake_function, but it removes the wait queue 2049 * entry unconditionally - even if something else had already woken the 2050 * target. 2051 */ 2052 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key) 2053 { 2054 int ret = default_wake_function(wait, mode, sync, key); 2055 list_del_init(&wait->entry); 2056 return ret; 2057 } 2058 2059 static vm_fault_t shmem_fault(struct vm_fault *vmf) 2060 { 2061 struct vm_area_struct *vma = vmf->vma; 2062 struct inode *inode = file_inode(vma->vm_file); 2063 gfp_t gfp = mapping_gfp_mask(inode->i_mapping); 2064 int err; 2065 vm_fault_t ret = VM_FAULT_LOCKED; 2066 2067 /* 2068 * Trinity finds that probing a hole which tmpfs is punching can 2069 * prevent the hole-punch from ever completing: which in turn 2070 * locks writers out with its hold on i_rwsem. So refrain from 2071 * faulting pages into the hole while it's being punched. Although 2072 * shmem_undo_range() does remove the additions, it may be unable to 2073 * keep up, as each new page needs its own unmap_mapping_range() call, 2074 * and the i_mmap tree grows ever slower to scan if new vmas are added. 2075 * 2076 * It does not matter if we sometimes reach this check just before the 2077 * hole-punch begins, so that one fault then races with the punch: 2078 * we just need to make racing faults a rare case. 2079 * 2080 * The implementation below would be much simpler if we just used a 2081 * standard mutex or completion: but we cannot take i_rwsem in fault, 2082 * and bloating every shmem inode for this unlikely case would be sad. 2083 */ 2084 if (unlikely(inode->i_private)) { 2085 struct shmem_falloc *shmem_falloc; 2086 2087 spin_lock(&inode->i_lock); 2088 shmem_falloc = inode->i_private; 2089 if (shmem_falloc && 2090 shmem_falloc->waitq && 2091 vmf->pgoff >= shmem_falloc->start && 2092 vmf->pgoff < shmem_falloc->next) { 2093 struct file *fpin; 2094 wait_queue_head_t *shmem_falloc_waitq; 2095 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function); 2096 2097 ret = VM_FAULT_NOPAGE; 2098 fpin = maybe_unlock_mmap_for_io(vmf, NULL); 2099 if (fpin) 2100 ret = VM_FAULT_RETRY; 2101 2102 shmem_falloc_waitq = shmem_falloc->waitq; 2103 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait, 2104 TASK_UNINTERRUPTIBLE); 2105 spin_unlock(&inode->i_lock); 2106 schedule(); 2107 2108 /* 2109 * shmem_falloc_waitq points into the shmem_fallocate() 2110 * stack of the hole-punching task: shmem_falloc_waitq 2111 * is usually invalid by the time we reach here, but 2112 * finish_wait() does not dereference it in that case; 2113 * though i_lock needed lest racing with wake_up_all(). 2114 */ 2115 spin_lock(&inode->i_lock); 2116 finish_wait(shmem_falloc_waitq, &shmem_fault_wait); 2117 spin_unlock(&inode->i_lock); 2118 2119 if (fpin) 2120 fput(fpin); 2121 return ret; 2122 } 2123 spin_unlock(&inode->i_lock); 2124 } 2125 2126 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, SGP_CACHE, 2127 gfp, vma, vmf, &ret); 2128 if (err) 2129 return vmf_error(err); 2130 return ret; 2131 } 2132 2133 unsigned long shmem_get_unmapped_area(struct file *file, 2134 unsigned long uaddr, unsigned long len, 2135 unsigned long pgoff, unsigned long flags) 2136 { 2137 unsigned long (*get_area)(struct file *, 2138 unsigned long, unsigned long, unsigned long, unsigned long); 2139 unsigned long addr; 2140 unsigned long offset; 2141 unsigned long inflated_len; 2142 unsigned long inflated_addr; 2143 unsigned long inflated_offset; 2144 2145 if (len > TASK_SIZE) 2146 return -ENOMEM; 2147 2148 get_area = current->mm->get_unmapped_area; 2149 addr = get_area(file, uaddr, len, pgoff, flags); 2150 2151 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) 2152 return addr; 2153 if (IS_ERR_VALUE(addr)) 2154 return addr; 2155 if (addr & ~PAGE_MASK) 2156 return addr; 2157 if (addr > TASK_SIZE - len) 2158 return addr; 2159 2160 if (shmem_huge == SHMEM_HUGE_DENY) 2161 return addr; 2162 if (len < HPAGE_PMD_SIZE) 2163 return addr; 2164 if (flags & MAP_FIXED) 2165 return addr; 2166 /* 2167 * Our priority is to support MAP_SHARED mapped hugely; 2168 * and support MAP_PRIVATE mapped hugely too, until it is COWed. 2169 * But if caller specified an address hint and we allocated area there 2170 * successfully, respect that as before. 2171 */ 2172 if (uaddr == addr) 2173 return addr; 2174 2175 if (shmem_huge != SHMEM_HUGE_FORCE) { 2176 struct super_block *sb; 2177 2178 if (file) { 2179 VM_BUG_ON(file->f_op != &shmem_file_operations); 2180 sb = file_inode(file)->i_sb; 2181 } else { 2182 /* 2183 * Called directly from mm/mmap.c, or drivers/char/mem.c 2184 * for "/dev/zero", to create a shared anonymous object. 2185 */ 2186 if (IS_ERR(shm_mnt)) 2187 return addr; 2188 sb = shm_mnt->mnt_sb; 2189 } 2190 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER) 2191 return addr; 2192 } 2193 2194 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1); 2195 if (offset && offset + len < 2 * HPAGE_PMD_SIZE) 2196 return addr; 2197 if ((addr & (HPAGE_PMD_SIZE-1)) == offset) 2198 return addr; 2199 2200 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE; 2201 if (inflated_len > TASK_SIZE) 2202 return addr; 2203 if (inflated_len < len) 2204 return addr; 2205 2206 inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags); 2207 if (IS_ERR_VALUE(inflated_addr)) 2208 return addr; 2209 if (inflated_addr & ~PAGE_MASK) 2210 return addr; 2211 2212 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1); 2213 inflated_addr += offset - inflated_offset; 2214 if (inflated_offset > offset) 2215 inflated_addr += HPAGE_PMD_SIZE; 2216 2217 if (inflated_addr > TASK_SIZE - len) 2218 return addr; 2219 return inflated_addr; 2220 } 2221 2222 #ifdef CONFIG_NUMA 2223 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol) 2224 { 2225 struct inode *inode = file_inode(vma->vm_file); 2226 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol); 2227 } 2228 2229 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma, 2230 unsigned long addr) 2231 { 2232 struct inode *inode = file_inode(vma->vm_file); 2233 pgoff_t index; 2234 2235 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; 2236 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index); 2237 } 2238 #endif 2239 2240 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 2241 { 2242 struct inode *inode = file_inode(file); 2243 struct shmem_inode_info *info = SHMEM_I(inode); 2244 int retval = -ENOMEM; 2245 2246 /* 2247 * What serializes the accesses to info->flags? 2248 * ipc_lock_object() when called from shmctl_do_lock(), 2249 * no serialization needed when called from shm_destroy(). 2250 */ 2251 if (lock && !(info->flags & VM_LOCKED)) { 2252 if (!user_shm_lock(inode->i_size, ucounts)) 2253 goto out_nomem; 2254 info->flags |= VM_LOCKED; 2255 mapping_set_unevictable(file->f_mapping); 2256 } 2257 if (!lock && (info->flags & VM_LOCKED) && ucounts) { 2258 user_shm_unlock(inode->i_size, ucounts); 2259 info->flags &= ~VM_LOCKED; 2260 mapping_clear_unevictable(file->f_mapping); 2261 } 2262 retval = 0; 2263 2264 out_nomem: 2265 return retval; 2266 } 2267 2268 static int shmem_mmap(struct file *file, struct vm_area_struct *vma) 2269 { 2270 struct shmem_inode_info *info = SHMEM_I(file_inode(file)); 2271 int ret; 2272 2273 ret = seal_check_future_write(info->seals, vma); 2274 if (ret) 2275 return ret; 2276 2277 /* arm64 - allow memory tagging on RAM-based files */ 2278 vma->vm_flags |= VM_MTE_ALLOWED; 2279 2280 file_accessed(file); 2281 vma->vm_ops = &shmem_vm_ops; 2282 return 0; 2283 } 2284 2285 /* Mask out flags that are inappropriate for the given type of inode. */ 2286 static unsigned shmem_mask_flags(umode_t mode, __u32 flags) 2287 { 2288 if (S_ISDIR(mode)) 2289 return flags; 2290 else if (S_ISREG(mode)) 2291 return flags & SHMEM_REG_FLMASK; 2292 else 2293 return flags & SHMEM_OTHER_FLMASK; 2294 } 2295 2296 static struct inode *shmem_get_inode(struct super_block *sb, struct inode *dir, 2297 umode_t mode, dev_t dev, unsigned long flags) 2298 { 2299 struct inode *inode; 2300 struct shmem_inode_info *info; 2301 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 2302 ino_t ino; 2303 2304 if (shmem_reserve_inode(sb, &ino)) 2305 return NULL; 2306 2307 inode = new_inode(sb); 2308 if (inode) { 2309 inode->i_ino = ino; 2310 inode_init_owner(&init_user_ns, inode, dir, mode); 2311 inode->i_blocks = 0; 2312 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode); 2313 inode->i_generation = prandom_u32(); 2314 info = SHMEM_I(inode); 2315 memset(info, 0, (char *)inode - (char *)info); 2316 spin_lock_init(&info->lock); 2317 atomic_set(&info->stop_eviction, 0); 2318 info->seals = F_SEAL_SEAL; 2319 info->flags = flags & VM_NORESERVE; 2320 info->i_crtime = inode->i_mtime; 2321 info->fsflags = (dir == NULL) ? 0 : 2322 SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED; 2323 info->fsflags = shmem_mask_flags(mode, info->fsflags); 2324 INIT_LIST_HEAD(&info->shrinklist); 2325 INIT_LIST_HEAD(&info->swaplist); 2326 simple_xattrs_init(&info->xattrs); 2327 cache_no_acl(inode); 2328 mapping_set_large_folios(inode->i_mapping); 2329 2330 switch (mode & S_IFMT) { 2331 default: 2332 inode->i_op = &shmem_special_inode_operations; 2333 init_special_inode(inode, mode, dev); 2334 break; 2335 case S_IFREG: 2336 inode->i_mapping->a_ops = &shmem_aops; 2337 inode->i_op = &shmem_inode_operations; 2338 inode->i_fop = &shmem_file_operations; 2339 mpol_shared_policy_init(&info->policy, 2340 shmem_get_sbmpol(sbinfo)); 2341 break; 2342 case S_IFDIR: 2343 inc_nlink(inode); 2344 /* Some things misbehave if size == 0 on a directory */ 2345 inode->i_size = 2 * BOGO_DIRENT_SIZE; 2346 inode->i_op = &shmem_dir_inode_operations; 2347 inode->i_fop = &simple_dir_operations; 2348 break; 2349 case S_IFLNK: 2350 /* 2351 * Must not load anything in the rbtree, 2352 * mpol_free_shared_policy will not be called. 2353 */ 2354 mpol_shared_policy_init(&info->policy, NULL); 2355 break; 2356 } 2357 2358 lockdep_annotate_inode_mutex_key(inode); 2359 } else 2360 shmem_free_inode(sb); 2361 return inode; 2362 } 2363 2364 #ifdef CONFIG_USERFAULTFD 2365 int shmem_mfill_atomic_pte(struct mm_struct *dst_mm, 2366 pmd_t *dst_pmd, 2367 struct vm_area_struct *dst_vma, 2368 unsigned long dst_addr, 2369 unsigned long src_addr, 2370 bool zeropage, bool wp_copy, 2371 struct page **pagep) 2372 { 2373 struct inode *inode = file_inode(dst_vma->vm_file); 2374 struct shmem_inode_info *info = SHMEM_I(inode); 2375 struct address_space *mapping = inode->i_mapping; 2376 gfp_t gfp = mapping_gfp_mask(mapping); 2377 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr); 2378 void *page_kaddr; 2379 struct folio *folio; 2380 struct page *page; 2381 int ret; 2382 pgoff_t max_off; 2383 2384 if (!shmem_inode_acct_block(inode, 1)) { 2385 /* 2386 * We may have got a page, returned -ENOENT triggering a retry, 2387 * and now we find ourselves with -ENOMEM. Release the page, to 2388 * avoid a BUG_ON in our caller. 2389 */ 2390 if (unlikely(*pagep)) { 2391 put_page(*pagep); 2392 *pagep = NULL; 2393 } 2394 return -ENOMEM; 2395 } 2396 2397 if (!*pagep) { 2398 ret = -ENOMEM; 2399 page = shmem_alloc_page(gfp, info, pgoff); 2400 if (!page) 2401 goto out_unacct_blocks; 2402 2403 if (!zeropage) { /* COPY */ 2404 page_kaddr = kmap_atomic(page); 2405 ret = copy_from_user(page_kaddr, 2406 (const void __user *)src_addr, 2407 PAGE_SIZE); 2408 kunmap_atomic(page_kaddr); 2409 2410 /* fallback to copy_from_user outside mmap_lock */ 2411 if (unlikely(ret)) { 2412 *pagep = page; 2413 ret = -ENOENT; 2414 /* don't free the page */ 2415 goto out_unacct_blocks; 2416 } 2417 2418 flush_dcache_page(page); 2419 } else { /* ZEROPAGE */ 2420 clear_user_highpage(page, dst_addr); 2421 } 2422 } else { 2423 page = *pagep; 2424 *pagep = NULL; 2425 } 2426 2427 VM_BUG_ON(PageLocked(page)); 2428 VM_BUG_ON(PageSwapBacked(page)); 2429 __SetPageLocked(page); 2430 __SetPageSwapBacked(page); 2431 __SetPageUptodate(page); 2432 2433 ret = -EFAULT; 2434 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 2435 if (unlikely(pgoff >= max_off)) 2436 goto out_release; 2437 2438 folio = page_folio(page); 2439 ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL, 2440 gfp & GFP_RECLAIM_MASK, dst_mm); 2441 if (ret) 2442 goto out_release; 2443 2444 ret = mfill_atomic_install_pte(dst_mm, dst_pmd, dst_vma, dst_addr, 2445 page, true, wp_copy); 2446 if (ret) 2447 goto out_delete_from_cache; 2448 2449 spin_lock_irq(&info->lock); 2450 info->alloced++; 2451 inode->i_blocks += BLOCKS_PER_PAGE; 2452 shmem_recalc_inode(inode); 2453 spin_unlock_irq(&info->lock); 2454 2455 unlock_page(page); 2456 return 0; 2457 out_delete_from_cache: 2458 delete_from_page_cache(page); 2459 out_release: 2460 unlock_page(page); 2461 put_page(page); 2462 out_unacct_blocks: 2463 shmem_inode_unacct_blocks(inode, 1); 2464 return ret; 2465 } 2466 #endif /* CONFIG_USERFAULTFD */ 2467 2468 #ifdef CONFIG_TMPFS 2469 static const struct inode_operations shmem_symlink_inode_operations; 2470 static const struct inode_operations shmem_short_symlink_operations; 2471 2472 #ifdef CONFIG_TMPFS_XATTR 2473 static int shmem_initxattrs(struct inode *, const struct xattr *, void *); 2474 #else 2475 #define shmem_initxattrs NULL 2476 #endif 2477 2478 static int 2479 shmem_write_begin(struct file *file, struct address_space *mapping, 2480 loff_t pos, unsigned len, 2481 struct page **pagep, void **fsdata) 2482 { 2483 struct inode *inode = mapping->host; 2484 struct shmem_inode_info *info = SHMEM_I(inode); 2485 pgoff_t index = pos >> PAGE_SHIFT; 2486 int ret = 0; 2487 2488 /* i_rwsem is held by caller */ 2489 if (unlikely(info->seals & (F_SEAL_GROW | 2490 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) { 2491 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) 2492 return -EPERM; 2493 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size) 2494 return -EPERM; 2495 } 2496 2497 ret = shmem_getpage(inode, index, pagep, SGP_WRITE); 2498 2499 if (ret) 2500 return ret; 2501 2502 if (PageHWPoison(*pagep)) { 2503 unlock_page(*pagep); 2504 put_page(*pagep); 2505 *pagep = NULL; 2506 return -EIO; 2507 } 2508 2509 return 0; 2510 } 2511 2512 static int 2513 shmem_write_end(struct file *file, struct address_space *mapping, 2514 loff_t pos, unsigned len, unsigned copied, 2515 struct page *page, void *fsdata) 2516 { 2517 struct inode *inode = mapping->host; 2518 2519 if (pos + copied > inode->i_size) 2520 i_size_write(inode, pos + copied); 2521 2522 if (!PageUptodate(page)) { 2523 struct page *head = compound_head(page); 2524 if (PageTransCompound(page)) { 2525 int i; 2526 2527 for (i = 0; i < HPAGE_PMD_NR; i++) { 2528 if (head + i == page) 2529 continue; 2530 clear_highpage(head + i); 2531 flush_dcache_page(head + i); 2532 } 2533 } 2534 if (copied < PAGE_SIZE) { 2535 unsigned from = pos & (PAGE_SIZE - 1); 2536 zero_user_segments(page, 0, from, 2537 from + copied, PAGE_SIZE); 2538 } 2539 SetPageUptodate(head); 2540 } 2541 set_page_dirty(page); 2542 unlock_page(page); 2543 put_page(page); 2544 2545 return copied; 2546 } 2547 2548 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to) 2549 { 2550 struct file *file = iocb->ki_filp; 2551 struct inode *inode = file_inode(file); 2552 struct address_space *mapping = inode->i_mapping; 2553 pgoff_t index; 2554 unsigned long offset; 2555 int error = 0; 2556 ssize_t retval = 0; 2557 loff_t *ppos = &iocb->ki_pos; 2558 2559 index = *ppos >> PAGE_SHIFT; 2560 offset = *ppos & ~PAGE_MASK; 2561 2562 for (;;) { 2563 struct page *page = NULL; 2564 pgoff_t end_index; 2565 unsigned long nr, ret; 2566 loff_t i_size = i_size_read(inode); 2567 2568 end_index = i_size >> PAGE_SHIFT; 2569 if (index > end_index) 2570 break; 2571 if (index == end_index) { 2572 nr = i_size & ~PAGE_MASK; 2573 if (nr <= offset) 2574 break; 2575 } 2576 2577 error = shmem_getpage(inode, index, &page, SGP_READ); 2578 if (error) { 2579 if (error == -EINVAL) 2580 error = 0; 2581 break; 2582 } 2583 if (page) { 2584 unlock_page(page); 2585 2586 if (PageHWPoison(page)) { 2587 put_page(page); 2588 error = -EIO; 2589 break; 2590 } 2591 } 2592 2593 /* 2594 * We must evaluate after, since reads (unlike writes) 2595 * are called without i_rwsem protection against truncate 2596 */ 2597 nr = PAGE_SIZE; 2598 i_size = i_size_read(inode); 2599 end_index = i_size >> PAGE_SHIFT; 2600 if (index == end_index) { 2601 nr = i_size & ~PAGE_MASK; 2602 if (nr <= offset) { 2603 if (page) 2604 put_page(page); 2605 break; 2606 } 2607 } 2608 nr -= offset; 2609 2610 if (page) { 2611 /* 2612 * If users can be writing to this page using arbitrary 2613 * virtual addresses, take care about potential aliasing 2614 * before reading the page on the kernel side. 2615 */ 2616 if (mapping_writably_mapped(mapping)) 2617 flush_dcache_page(page); 2618 /* 2619 * Mark the page accessed if we read the beginning. 2620 */ 2621 if (!offset) 2622 mark_page_accessed(page); 2623 /* 2624 * Ok, we have the page, and it's up-to-date, so 2625 * now we can copy it to user space... 2626 */ 2627 ret = copy_page_to_iter(page, offset, nr, to); 2628 put_page(page); 2629 2630 } else if (iter_is_iovec(to)) { 2631 /* 2632 * Copy to user tends to be so well optimized, but 2633 * clear_user() not so much, that it is noticeably 2634 * faster to copy the zero page instead of clearing. 2635 */ 2636 ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to); 2637 } else { 2638 /* 2639 * But submitting the same page twice in a row to 2640 * splice() - or others? - can result in confusion: 2641 * so don't attempt that optimization on pipes etc. 2642 */ 2643 ret = iov_iter_zero(nr, to); 2644 } 2645 2646 retval += ret; 2647 offset += ret; 2648 index += offset >> PAGE_SHIFT; 2649 offset &= ~PAGE_MASK; 2650 2651 if (!iov_iter_count(to)) 2652 break; 2653 if (ret < nr) { 2654 error = -EFAULT; 2655 break; 2656 } 2657 cond_resched(); 2658 } 2659 2660 *ppos = ((loff_t) index << PAGE_SHIFT) + offset; 2661 file_accessed(file); 2662 return retval ? retval : error; 2663 } 2664 2665 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence) 2666 { 2667 struct address_space *mapping = file->f_mapping; 2668 struct inode *inode = mapping->host; 2669 2670 if (whence != SEEK_DATA && whence != SEEK_HOLE) 2671 return generic_file_llseek_size(file, offset, whence, 2672 MAX_LFS_FILESIZE, i_size_read(inode)); 2673 if (offset < 0) 2674 return -ENXIO; 2675 2676 inode_lock(inode); 2677 /* We're holding i_rwsem so we can access i_size directly */ 2678 offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence); 2679 if (offset >= 0) 2680 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE); 2681 inode_unlock(inode); 2682 return offset; 2683 } 2684 2685 static long shmem_fallocate(struct file *file, int mode, loff_t offset, 2686 loff_t len) 2687 { 2688 struct inode *inode = file_inode(file); 2689 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb); 2690 struct shmem_inode_info *info = SHMEM_I(inode); 2691 struct shmem_falloc shmem_falloc; 2692 pgoff_t start, index, end, undo_fallocend; 2693 int error; 2694 2695 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) 2696 return -EOPNOTSUPP; 2697 2698 inode_lock(inode); 2699 2700 if (mode & FALLOC_FL_PUNCH_HOLE) { 2701 struct address_space *mapping = file->f_mapping; 2702 loff_t unmap_start = round_up(offset, PAGE_SIZE); 2703 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1; 2704 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq); 2705 2706 /* protected by i_rwsem */ 2707 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) { 2708 error = -EPERM; 2709 goto out; 2710 } 2711 2712 shmem_falloc.waitq = &shmem_falloc_waitq; 2713 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT; 2714 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT; 2715 spin_lock(&inode->i_lock); 2716 inode->i_private = &shmem_falloc; 2717 spin_unlock(&inode->i_lock); 2718 2719 if ((u64)unmap_end > (u64)unmap_start) 2720 unmap_mapping_range(mapping, unmap_start, 2721 1 + unmap_end - unmap_start, 0); 2722 shmem_truncate_range(inode, offset, offset + len - 1); 2723 /* No need to unmap again: hole-punching leaves COWed pages */ 2724 2725 spin_lock(&inode->i_lock); 2726 inode->i_private = NULL; 2727 wake_up_all(&shmem_falloc_waitq); 2728 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head)); 2729 spin_unlock(&inode->i_lock); 2730 error = 0; 2731 goto out; 2732 } 2733 2734 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */ 2735 error = inode_newsize_ok(inode, offset + len); 2736 if (error) 2737 goto out; 2738 2739 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) { 2740 error = -EPERM; 2741 goto out; 2742 } 2743 2744 start = offset >> PAGE_SHIFT; 2745 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT; 2746 /* Try to avoid a swapstorm if len is impossible to satisfy */ 2747 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) { 2748 error = -ENOSPC; 2749 goto out; 2750 } 2751 2752 shmem_falloc.waitq = NULL; 2753 shmem_falloc.start = start; 2754 shmem_falloc.next = start; 2755 shmem_falloc.nr_falloced = 0; 2756 shmem_falloc.nr_unswapped = 0; 2757 spin_lock(&inode->i_lock); 2758 inode->i_private = &shmem_falloc; 2759 spin_unlock(&inode->i_lock); 2760 2761 /* 2762 * info->fallocend is only relevant when huge pages might be 2763 * involved: to prevent split_huge_page() freeing fallocated 2764 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size. 2765 */ 2766 undo_fallocend = info->fallocend; 2767 if (info->fallocend < end) 2768 info->fallocend = end; 2769 2770 for (index = start; index < end; ) { 2771 struct page *page; 2772 2773 /* 2774 * Good, the fallocate(2) manpage permits EINTR: we may have 2775 * been interrupted because we are using up too much memory. 2776 */ 2777 if (signal_pending(current)) 2778 error = -EINTR; 2779 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced) 2780 error = -ENOMEM; 2781 else 2782 error = shmem_getpage(inode, index, &page, SGP_FALLOC); 2783 if (error) { 2784 info->fallocend = undo_fallocend; 2785 /* Remove the !PageUptodate pages we added */ 2786 if (index > start) { 2787 shmem_undo_range(inode, 2788 (loff_t)start << PAGE_SHIFT, 2789 ((loff_t)index << PAGE_SHIFT) - 1, true); 2790 } 2791 goto undone; 2792 } 2793 2794 index++; 2795 /* 2796 * Here is a more important optimization than it appears: 2797 * a second SGP_FALLOC on the same huge page will clear it, 2798 * making it PageUptodate and un-undoable if we fail later. 2799 */ 2800 if (PageTransCompound(page)) { 2801 index = round_up(index, HPAGE_PMD_NR); 2802 /* Beware 32-bit wraparound */ 2803 if (!index) 2804 index--; 2805 } 2806 2807 /* 2808 * Inform shmem_writepage() how far we have reached. 2809 * No need for lock or barrier: we have the page lock. 2810 */ 2811 if (!PageUptodate(page)) 2812 shmem_falloc.nr_falloced += index - shmem_falloc.next; 2813 shmem_falloc.next = index; 2814 2815 /* 2816 * If !PageUptodate, leave it that way so that freeable pages 2817 * can be recognized if we need to rollback on error later. 2818 * But set_page_dirty so that memory pressure will swap rather 2819 * than free the pages we are allocating (and SGP_CACHE pages 2820 * might still be clean: we now need to mark those dirty too). 2821 */ 2822 set_page_dirty(page); 2823 unlock_page(page); 2824 put_page(page); 2825 cond_resched(); 2826 } 2827 2828 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) 2829 i_size_write(inode, offset + len); 2830 inode->i_ctime = current_time(inode); 2831 undone: 2832 spin_lock(&inode->i_lock); 2833 inode->i_private = NULL; 2834 spin_unlock(&inode->i_lock); 2835 out: 2836 inode_unlock(inode); 2837 return error; 2838 } 2839 2840 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf) 2841 { 2842 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb); 2843 2844 buf->f_type = TMPFS_MAGIC; 2845 buf->f_bsize = PAGE_SIZE; 2846 buf->f_namelen = NAME_MAX; 2847 if (sbinfo->max_blocks) { 2848 buf->f_blocks = sbinfo->max_blocks; 2849 buf->f_bavail = 2850 buf->f_bfree = sbinfo->max_blocks - 2851 percpu_counter_sum(&sbinfo->used_blocks); 2852 } 2853 if (sbinfo->max_inodes) { 2854 buf->f_files = sbinfo->max_inodes; 2855 buf->f_ffree = sbinfo->free_inodes; 2856 } 2857 /* else leave those fields 0 like simple_statfs */ 2858 2859 buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b); 2860 2861 return 0; 2862 } 2863 2864 /* 2865 * File creation. Allocate an inode, and we're done.. 2866 */ 2867 static int 2868 shmem_mknod(struct user_namespace *mnt_userns, struct inode *dir, 2869 struct dentry *dentry, umode_t mode, dev_t dev) 2870 { 2871 struct inode *inode; 2872 int error = -ENOSPC; 2873 2874 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE); 2875 if (inode) { 2876 error = simple_acl_create(dir, inode); 2877 if (error) 2878 goto out_iput; 2879 error = security_inode_init_security(inode, dir, 2880 &dentry->d_name, 2881 shmem_initxattrs, NULL); 2882 if (error && error != -EOPNOTSUPP) 2883 goto out_iput; 2884 2885 error = 0; 2886 dir->i_size += BOGO_DIRENT_SIZE; 2887 dir->i_ctime = dir->i_mtime = current_time(dir); 2888 d_instantiate(dentry, inode); 2889 dget(dentry); /* Extra count - pin the dentry in core */ 2890 } 2891 return error; 2892 out_iput: 2893 iput(inode); 2894 return error; 2895 } 2896 2897 static int 2898 shmem_tmpfile(struct user_namespace *mnt_userns, struct inode *dir, 2899 struct dentry *dentry, umode_t mode) 2900 { 2901 struct inode *inode; 2902 int error = -ENOSPC; 2903 2904 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE); 2905 if (inode) { 2906 error = security_inode_init_security(inode, dir, 2907 NULL, 2908 shmem_initxattrs, NULL); 2909 if (error && error != -EOPNOTSUPP) 2910 goto out_iput; 2911 error = simple_acl_create(dir, inode); 2912 if (error) 2913 goto out_iput; 2914 d_tmpfile(dentry, inode); 2915 } 2916 return error; 2917 out_iput: 2918 iput(inode); 2919 return error; 2920 } 2921 2922 static int shmem_mkdir(struct user_namespace *mnt_userns, struct inode *dir, 2923 struct dentry *dentry, umode_t mode) 2924 { 2925 int error; 2926 2927 if ((error = shmem_mknod(&init_user_ns, dir, dentry, 2928 mode | S_IFDIR, 0))) 2929 return error; 2930 inc_nlink(dir); 2931 return 0; 2932 } 2933 2934 static int shmem_create(struct user_namespace *mnt_userns, struct inode *dir, 2935 struct dentry *dentry, umode_t mode, bool excl) 2936 { 2937 return shmem_mknod(&init_user_ns, dir, dentry, mode | S_IFREG, 0); 2938 } 2939 2940 /* 2941 * Link a file.. 2942 */ 2943 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) 2944 { 2945 struct inode *inode = d_inode(old_dentry); 2946 int ret = 0; 2947 2948 /* 2949 * No ordinary (disk based) filesystem counts links as inodes; 2950 * but each new link needs a new dentry, pinning lowmem, and 2951 * tmpfs dentries cannot be pruned until they are unlinked. 2952 * But if an O_TMPFILE file is linked into the tmpfs, the 2953 * first link must skip that, to get the accounting right. 2954 */ 2955 if (inode->i_nlink) { 2956 ret = shmem_reserve_inode(inode->i_sb, NULL); 2957 if (ret) 2958 goto out; 2959 } 2960 2961 dir->i_size += BOGO_DIRENT_SIZE; 2962 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode); 2963 inc_nlink(inode); 2964 ihold(inode); /* New dentry reference */ 2965 dget(dentry); /* Extra pinning count for the created dentry */ 2966 d_instantiate(dentry, inode); 2967 out: 2968 return ret; 2969 } 2970 2971 static int shmem_unlink(struct inode *dir, struct dentry *dentry) 2972 { 2973 struct inode *inode = d_inode(dentry); 2974 2975 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode)) 2976 shmem_free_inode(inode->i_sb); 2977 2978 dir->i_size -= BOGO_DIRENT_SIZE; 2979 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode); 2980 drop_nlink(inode); 2981 dput(dentry); /* Undo the count from "create" - this does all the work */ 2982 return 0; 2983 } 2984 2985 static int shmem_rmdir(struct inode *dir, struct dentry *dentry) 2986 { 2987 if (!simple_empty(dentry)) 2988 return -ENOTEMPTY; 2989 2990 drop_nlink(d_inode(dentry)); 2991 drop_nlink(dir); 2992 return shmem_unlink(dir, dentry); 2993 } 2994 2995 static int shmem_whiteout(struct user_namespace *mnt_userns, 2996 struct inode *old_dir, struct dentry *old_dentry) 2997 { 2998 struct dentry *whiteout; 2999 int error; 3000 3001 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name); 3002 if (!whiteout) 3003 return -ENOMEM; 3004 3005 error = shmem_mknod(&init_user_ns, old_dir, whiteout, 3006 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV); 3007 dput(whiteout); 3008 if (error) 3009 return error; 3010 3011 /* 3012 * Cheat and hash the whiteout while the old dentry is still in 3013 * place, instead of playing games with FS_RENAME_DOES_D_MOVE. 3014 * 3015 * d_lookup() will consistently find one of them at this point, 3016 * not sure which one, but that isn't even important. 3017 */ 3018 d_rehash(whiteout); 3019 return 0; 3020 } 3021 3022 /* 3023 * The VFS layer already does all the dentry stuff for rename, 3024 * we just have to decrement the usage count for the target if 3025 * it exists so that the VFS layer correctly free's it when it 3026 * gets overwritten. 3027 */ 3028 static int shmem_rename2(struct user_namespace *mnt_userns, 3029 struct inode *old_dir, struct dentry *old_dentry, 3030 struct inode *new_dir, struct dentry *new_dentry, 3031 unsigned int flags) 3032 { 3033 struct inode *inode = d_inode(old_dentry); 3034 int they_are_dirs = S_ISDIR(inode->i_mode); 3035 3036 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) 3037 return -EINVAL; 3038 3039 if (flags & RENAME_EXCHANGE) 3040 return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry); 3041 3042 if (!simple_empty(new_dentry)) 3043 return -ENOTEMPTY; 3044 3045 if (flags & RENAME_WHITEOUT) { 3046 int error; 3047 3048 error = shmem_whiteout(&init_user_ns, old_dir, old_dentry); 3049 if (error) 3050 return error; 3051 } 3052 3053 if (d_really_is_positive(new_dentry)) { 3054 (void) shmem_unlink(new_dir, new_dentry); 3055 if (they_are_dirs) { 3056 drop_nlink(d_inode(new_dentry)); 3057 drop_nlink(old_dir); 3058 } 3059 } else if (they_are_dirs) { 3060 drop_nlink(old_dir); 3061 inc_nlink(new_dir); 3062 } 3063 3064 old_dir->i_size -= BOGO_DIRENT_SIZE; 3065 new_dir->i_size += BOGO_DIRENT_SIZE; 3066 old_dir->i_ctime = old_dir->i_mtime = 3067 new_dir->i_ctime = new_dir->i_mtime = 3068 inode->i_ctime = current_time(old_dir); 3069 return 0; 3070 } 3071 3072 static int shmem_symlink(struct user_namespace *mnt_userns, struct inode *dir, 3073 struct dentry *dentry, const char *symname) 3074 { 3075 int error; 3076 int len; 3077 struct inode *inode; 3078 struct page *page; 3079 3080 len = strlen(symname) + 1; 3081 if (len > PAGE_SIZE) 3082 return -ENAMETOOLONG; 3083 3084 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0, 3085 VM_NORESERVE); 3086 if (!inode) 3087 return -ENOSPC; 3088 3089 error = security_inode_init_security(inode, dir, &dentry->d_name, 3090 shmem_initxattrs, NULL); 3091 if (error && error != -EOPNOTSUPP) { 3092 iput(inode); 3093 return error; 3094 } 3095 3096 inode->i_size = len-1; 3097 if (len <= SHORT_SYMLINK_LEN) { 3098 inode->i_link = kmemdup(symname, len, GFP_KERNEL); 3099 if (!inode->i_link) { 3100 iput(inode); 3101 return -ENOMEM; 3102 } 3103 inode->i_op = &shmem_short_symlink_operations; 3104 } else { 3105 inode_nohighmem(inode); 3106 error = shmem_getpage(inode, 0, &page, SGP_WRITE); 3107 if (error) { 3108 iput(inode); 3109 return error; 3110 } 3111 inode->i_mapping->a_ops = &shmem_aops; 3112 inode->i_op = &shmem_symlink_inode_operations; 3113 memcpy(page_address(page), symname, len); 3114 SetPageUptodate(page); 3115 set_page_dirty(page); 3116 unlock_page(page); 3117 put_page(page); 3118 } 3119 dir->i_size += BOGO_DIRENT_SIZE; 3120 dir->i_ctime = dir->i_mtime = current_time(dir); 3121 d_instantiate(dentry, inode); 3122 dget(dentry); 3123 return 0; 3124 } 3125 3126 static void shmem_put_link(void *arg) 3127 { 3128 mark_page_accessed(arg); 3129 put_page(arg); 3130 } 3131 3132 static const char *shmem_get_link(struct dentry *dentry, 3133 struct inode *inode, 3134 struct delayed_call *done) 3135 { 3136 struct page *page = NULL; 3137 int error; 3138 if (!dentry) { 3139 page = find_get_page(inode->i_mapping, 0); 3140 if (!page) 3141 return ERR_PTR(-ECHILD); 3142 if (PageHWPoison(page) || 3143 !PageUptodate(page)) { 3144 put_page(page); 3145 return ERR_PTR(-ECHILD); 3146 } 3147 } else { 3148 error = shmem_getpage(inode, 0, &page, SGP_READ); 3149 if (error) 3150 return ERR_PTR(error); 3151 if (!page) 3152 return ERR_PTR(-ECHILD); 3153 if (PageHWPoison(page)) { 3154 unlock_page(page); 3155 put_page(page); 3156 return ERR_PTR(-ECHILD); 3157 } 3158 unlock_page(page); 3159 } 3160 set_delayed_call(done, shmem_put_link, page); 3161 return page_address(page); 3162 } 3163 3164 #ifdef CONFIG_TMPFS_XATTR 3165 3166 static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa) 3167 { 3168 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 3169 3170 fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE); 3171 3172 return 0; 3173 } 3174 3175 static int shmem_fileattr_set(struct user_namespace *mnt_userns, 3176 struct dentry *dentry, struct fileattr *fa) 3177 { 3178 struct inode *inode = d_inode(dentry); 3179 struct shmem_inode_info *info = SHMEM_I(inode); 3180 3181 if (fileattr_has_fsx(fa)) 3182 return -EOPNOTSUPP; 3183 3184 info->fsflags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) | 3185 (fa->flags & SHMEM_FL_USER_MODIFIABLE); 3186 3187 inode->i_flags &= ~(S_APPEND | S_IMMUTABLE | S_NOATIME); 3188 if (info->fsflags & FS_APPEND_FL) 3189 inode->i_flags |= S_APPEND; 3190 if (info->fsflags & FS_IMMUTABLE_FL) 3191 inode->i_flags |= S_IMMUTABLE; 3192 if (info->fsflags & FS_NOATIME_FL) 3193 inode->i_flags |= S_NOATIME; 3194 3195 inode->i_ctime = current_time(inode); 3196 return 0; 3197 } 3198 3199 /* 3200 * Superblocks without xattr inode operations may get some security.* xattr 3201 * support from the LSM "for free". As soon as we have any other xattrs 3202 * like ACLs, we also need to implement the security.* handlers at 3203 * filesystem level, though. 3204 */ 3205 3206 /* 3207 * Callback for security_inode_init_security() for acquiring xattrs. 3208 */ 3209 static int shmem_initxattrs(struct inode *inode, 3210 const struct xattr *xattr_array, 3211 void *fs_info) 3212 { 3213 struct shmem_inode_info *info = SHMEM_I(inode); 3214 const struct xattr *xattr; 3215 struct simple_xattr *new_xattr; 3216 size_t len; 3217 3218 for (xattr = xattr_array; xattr->name != NULL; xattr++) { 3219 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len); 3220 if (!new_xattr) 3221 return -ENOMEM; 3222 3223 len = strlen(xattr->name) + 1; 3224 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len, 3225 GFP_KERNEL); 3226 if (!new_xattr->name) { 3227 kvfree(new_xattr); 3228 return -ENOMEM; 3229 } 3230 3231 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX, 3232 XATTR_SECURITY_PREFIX_LEN); 3233 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN, 3234 xattr->name, len); 3235 3236 simple_xattr_list_add(&info->xattrs, new_xattr); 3237 } 3238 3239 return 0; 3240 } 3241 3242 static int shmem_xattr_handler_get(const struct xattr_handler *handler, 3243 struct dentry *unused, struct inode *inode, 3244 const char *name, void *buffer, size_t size) 3245 { 3246 struct shmem_inode_info *info = SHMEM_I(inode); 3247 3248 name = xattr_full_name(handler, name); 3249 return simple_xattr_get(&info->xattrs, name, buffer, size); 3250 } 3251 3252 static int shmem_xattr_handler_set(const struct xattr_handler *handler, 3253 struct user_namespace *mnt_userns, 3254 struct dentry *unused, struct inode *inode, 3255 const char *name, const void *value, 3256 size_t size, int flags) 3257 { 3258 struct shmem_inode_info *info = SHMEM_I(inode); 3259 3260 name = xattr_full_name(handler, name); 3261 return simple_xattr_set(&info->xattrs, name, value, size, flags, NULL); 3262 } 3263 3264 static const struct xattr_handler shmem_security_xattr_handler = { 3265 .prefix = XATTR_SECURITY_PREFIX, 3266 .get = shmem_xattr_handler_get, 3267 .set = shmem_xattr_handler_set, 3268 }; 3269 3270 static const struct xattr_handler shmem_trusted_xattr_handler = { 3271 .prefix = XATTR_TRUSTED_PREFIX, 3272 .get = shmem_xattr_handler_get, 3273 .set = shmem_xattr_handler_set, 3274 }; 3275 3276 static const struct xattr_handler *shmem_xattr_handlers[] = { 3277 #ifdef CONFIG_TMPFS_POSIX_ACL 3278 &posix_acl_access_xattr_handler, 3279 &posix_acl_default_xattr_handler, 3280 #endif 3281 &shmem_security_xattr_handler, 3282 &shmem_trusted_xattr_handler, 3283 NULL 3284 }; 3285 3286 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size) 3287 { 3288 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry)); 3289 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size); 3290 } 3291 #endif /* CONFIG_TMPFS_XATTR */ 3292 3293 static const struct inode_operations shmem_short_symlink_operations = { 3294 .getattr = shmem_getattr, 3295 .get_link = simple_get_link, 3296 #ifdef CONFIG_TMPFS_XATTR 3297 .listxattr = shmem_listxattr, 3298 #endif 3299 }; 3300 3301 static const struct inode_operations shmem_symlink_inode_operations = { 3302 .getattr = shmem_getattr, 3303 .get_link = shmem_get_link, 3304 #ifdef CONFIG_TMPFS_XATTR 3305 .listxattr = shmem_listxattr, 3306 #endif 3307 }; 3308 3309 static struct dentry *shmem_get_parent(struct dentry *child) 3310 { 3311 return ERR_PTR(-ESTALE); 3312 } 3313 3314 static int shmem_match(struct inode *ino, void *vfh) 3315 { 3316 __u32 *fh = vfh; 3317 __u64 inum = fh[2]; 3318 inum = (inum << 32) | fh[1]; 3319 return ino->i_ino == inum && fh[0] == ino->i_generation; 3320 } 3321 3322 /* Find any alias of inode, but prefer a hashed alias */ 3323 static struct dentry *shmem_find_alias(struct inode *inode) 3324 { 3325 struct dentry *alias = d_find_alias(inode); 3326 3327 return alias ?: d_find_any_alias(inode); 3328 } 3329 3330 3331 static struct dentry *shmem_fh_to_dentry(struct super_block *sb, 3332 struct fid *fid, int fh_len, int fh_type) 3333 { 3334 struct inode *inode; 3335 struct dentry *dentry = NULL; 3336 u64 inum; 3337 3338 if (fh_len < 3) 3339 return NULL; 3340 3341 inum = fid->raw[2]; 3342 inum = (inum << 32) | fid->raw[1]; 3343 3344 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]), 3345 shmem_match, fid->raw); 3346 if (inode) { 3347 dentry = shmem_find_alias(inode); 3348 iput(inode); 3349 } 3350 3351 return dentry; 3352 } 3353 3354 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len, 3355 struct inode *parent) 3356 { 3357 if (*len < 3) { 3358 *len = 3; 3359 return FILEID_INVALID; 3360 } 3361 3362 if (inode_unhashed(inode)) { 3363 /* Unfortunately insert_inode_hash is not idempotent, 3364 * so as we hash inodes here rather than at creation 3365 * time, we need a lock to ensure we only try 3366 * to do it once 3367 */ 3368 static DEFINE_SPINLOCK(lock); 3369 spin_lock(&lock); 3370 if (inode_unhashed(inode)) 3371 __insert_inode_hash(inode, 3372 inode->i_ino + inode->i_generation); 3373 spin_unlock(&lock); 3374 } 3375 3376 fh[0] = inode->i_generation; 3377 fh[1] = inode->i_ino; 3378 fh[2] = ((__u64)inode->i_ino) >> 32; 3379 3380 *len = 3; 3381 return 1; 3382 } 3383 3384 static const struct export_operations shmem_export_ops = { 3385 .get_parent = shmem_get_parent, 3386 .encode_fh = shmem_encode_fh, 3387 .fh_to_dentry = shmem_fh_to_dentry, 3388 }; 3389 3390 enum shmem_param { 3391 Opt_gid, 3392 Opt_huge, 3393 Opt_mode, 3394 Opt_mpol, 3395 Opt_nr_blocks, 3396 Opt_nr_inodes, 3397 Opt_size, 3398 Opt_uid, 3399 Opt_inode32, 3400 Opt_inode64, 3401 }; 3402 3403 static const struct constant_table shmem_param_enums_huge[] = { 3404 {"never", SHMEM_HUGE_NEVER }, 3405 {"always", SHMEM_HUGE_ALWAYS }, 3406 {"within_size", SHMEM_HUGE_WITHIN_SIZE }, 3407 {"advise", SHMEM_HUGE_ADVISE }, 3408 {} 3409 }; 3410 3411 const struct fs_parameter_spec shmem_fs_parameters[] = { 3412 fsparam_u32 ("gid", Opt_gid), 3413 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge), 3414 fsparam_u32oct("mode", Opt_mode), 3415 fsparam_string("mpol", Opt_mpol), 3416 fsparam_string("nr_blocks", Opt_nr_blocks), 3417 fsparam_string("nr_inodes", Opt_nr_inodes), 3418 fsparam_string("size", Opt_size), 3419 fsparam_u32 ("uid", Opt_uid), 3420 fsparam_flag ("inode32", Opt_inode32), 3421 fsparam_flag ("inode64", Opt_inode64), 3422 {} 3423 }; 3424 3425 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param) 3426 { 3427 struct shmem_options *ctx = fc->fs_private; 3428 struct fs_parse_result result; 3429 unsigned long long size; 3430 char *rest; 3431 int opt; 3432 3433 opt = fs_parse(fc, shmem_fs_parameters, param, &result); 3434 if (opt < 0) 3435 return opt; 3436 3437 switch (opt) { 3438 case Opt_size: 3439 size = memparse(param->string, &rest); 3440 if (*rest == '%') { 3441 size <<= PAGE_SHIFT; 3442 size *= totalram_pages(); 3443 do_div(size, 100); 3444 rest++; 3445 } 3446 if (*rest) 3447 goto bad_value; 3448 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE); 3449 ctx->seen |= SHMEM_SEEN_BLOCKS; 3450 break; 3451 case Opt_nr_blocks: 3452 ctx->blocks = memparse(param->string, &rest); 3453 if (*rest) 3454 goto bad_value; 3455 ctx->seen |= SHMEM_SEEN_BLOCKS; 3456 break; 3457 case Opt_nr_inodes: 3458 ctx->inodes = memparse(param->string, &rest); 3459 if (*rest) 3460 goto bad_value; 3461 ctx->seen |= SHMEM_SEEN_INODES; 3462 break; 3463 case Opt_mode: 3464 ctx->mode = result.uint_32 & 07777; 3465 break; 3466 case Opt_uid: 3467 ctx->uid = make_kuid(current_user_ns(), result.uint_32); 3468 if (!uid_valid(ctx->uid)) 3469 goto bad_value; 3470 break; 3471 case Opt_gid: 3472 ctx->gid = make_kgid(current_user_ns(), result.uint_32); 3473 if (!gid_valid(ctx->gid)) 3474 goto bad_value; 3475 break; 3476 case Opt_huge: 3477 ctx->huge = result.uint_32; 3478 if (ctx->huge != SHMEM_HUGE_NEVER && 3479 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && 3480 has_transparent_hugepage())) 3481 goto unsupported_parameter; 3482 ctx->seen |= SHMEM_SEEN_HUGE; 3483 break; 3484 case Opt_mpol: 3485 if (IS_ENABLED(CONFIG_NUMA)) { 3486 mpol_put(ctx->mpol); 3487 ctx->mpol = NULL; 3488 if (mpol_parse_str(param->string, &ctx->mpol)) 3489 goto bad_value; 3490 break; 3491 } 3492 goto unsupported_parameter; 3493 case Opt_inode32: 3494 ctx->full_inums = false; 3495 ctx->seen |= SHMEM_SEEN_INUMS; 3496 break; 3497 case Opt_inode64: 3498 if (sizeof(ino_t) < 8) { 3499 return invalfc(fc, 3500 "Cannot use inode64 with <64bit inums in kernel\n"); 3501 } 3502 ctx->full_inums = true; 3503 ctx->seen |= SHMEM_SEEN_INUMS; 3504 break; 3505 } 3506 return 0; 3507 3508 unsupported_parameter: 3509 return invalfc(fc, "Unsupported parameter '%s'", param->key); 3510 bad_value: 3511 return invalfc(fc, "Bad value for '%s'", param->key); 3512 } 3513 3514 static int shmem_parse_options(struct fs_context *fc, void *data) 3515 { 3516 char *options = data; 3517 3518 if (options) { 3519 int err = security_sb_eat_lsm_opts(options, &fc->security); 3520 if (err) 3521 return err; 3522 } 3523 3524 while (options != NULL) { 3525 char *this_char = options; 3526 for (;;) { 3527 /* 3528 * NUL-terminate this option: unfortunately, 3529 * mount options form a comma-separated list, 3530 * but mpol's nodelist may also contain commas. 3531 */ 3532 options = strchr(options, ','); 3533 if (options == NULL) 3534 break; 3535 options++; 3536 if (!isdigit(*options)) { 3537 options[-1] = '\0'; 3538 break; 3539 } 3540 } 3541 if (*this_char) { 3542 char *value = strchr(this_char, '='); 3543 size_t len = 0; 3544 int err; 3545 3546 if (value) { 3547 *value++ = '\0'; 3548 len = strlen(value); 3549 } 3550 err = vfs_parse_fs_string(fc, this_char, value, len); 3551 if (err < 0) 3552 return err; 3553 } 3554 } 3555 return 0; 3556 } 3557 3558 /* 3559 * Reconfigure a shmem filesystem. 3560 * 3561 * Note that we disallow change from limited->unlimited blocks/inodes while any 3562 * are in use; but we must separately disallow unlimited->limited, because in 3563 * that case we have no record of how much is already in use. 3564 */ 3565 static int shmem_reconfigure(struct fs_context *fc) 3566 { 3567 struct shmem_options *ctx = fc->fs_private; 3568 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb); 3569 unsigned long inodes; 3570 struct mempolicy *mpol = NULL; 3571 const char *err; 3572 3573 raw_spin_lock(&sbinfo->stat_lock); 3574 inodes = sbinfo->max_inodes - sbinfo->free_inodes; 3575 if (ctx->blocks > S64_MAX) { 3576 err = "Number of blocks too large"; 3577 goto out; 3578 } 3579 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) { 3580 if (!sbinfo->max_blocks) { 3581 err = "Cannot retroactively limit size"; 3582 goto out; 3583 } 3584 if (percpu_counter_compare(&sbinfo->used_blocks, 3585 ctx->blocks) > 0) { 3586 err = "Too small a size for current use"; 3587 goto out; 3588 } 3589 } 3590 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) { 3591 if (!sbinfo->max_inodes) { 3592 err = "Cannot retroactively limit inodes"; 3593 goto out; 3594 } 3595 if (ctx->inodes < inodes) { 3596 err = "Too few inodes for current use"; 3597 goto out; 3598 } 3599 } 3600 3601 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums && 3602 sbinfo->next_ino > UINT_MAX) { 3603 err = "Current inum too high to switch to 32-bit inums"; 3604 goto out; 3605 } 3606 3607 if (ctx->seen & SHMEM_SEEN_HUGE) 3608 sbinfo->huge = ctx->huge; 3609 if (ctx->seen & SHMEM_SEEN_INUMS) 3610 sbinfo->full_inums = ctx->full_inums; 3611 if (ctx->seen & SHMEM_SEEN_BLOCKS) 3612 sbinfo->max_blocks = ctx->blocks; 3613 if (ctx->seen & SHMEM_SEEN_INODES) { 3614 sbinfo->max_inodes = ctx->inodes; 3615 sbinfo->free_inodes = ctx->inodes - inodes; 3616 } 3617 3618 /* 3619 * Preserve previous mempolicy unless mpol remount option was specified. 3620 */ 3621 if (ctx->mpol) { 3622 mpol = sbinfo->mpol; 3623 sbinfo->mpol = ctx->mpol; /* transfers initial ref */ 3624 ctx->mpol = NULL; 3625 } 3626 raw_spin_unlock(&sbinfo->stat_lock); 3627 mpol_put(mpol); 3628 return 0; 3629 out: 3630 raw_spin_unlock(&sbinfo->stat_lock); 3631 return invalfc(fc, "%s", err); 3632 } 3633 3634 static int shmem_show_options(struct seq_file *seq, struct dentry *root) 3635 { 3636 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb); 3637 3638 if (sbinfo->max_blocks != shmem_default_max_blocks()) 3639 seq_printf(seq, ",size=%luk", 3640 sbinfo->max_blocks << (PAGE_SHIFT - 10)); 3641 if (sbinfo->max_inodes != shmem_default_max_inodes()) 3642 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes); 3643 if (sbinfo->mode != (0777 | S_ISVTX)) 3644 seq_printf(seq, ",mode=%03ho", sbinfo->mode); 3645 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID)) 3646 seq_printf(seq, ",uid=%u", 3647 from_kuid_munged(&init_user_ns, sbinfo->uid)); 3648 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID)) 3649 seq_printf(seq, ",gid=%u", 3650 from_kgid_munged(&init_user_ns, sbinfo->gid)); 3651 3652 /* 3653 * Showing inode{64,32} might be useful even if it's the system default, 3654 * since then people don't have to resort to checking both here and 3655 * /proc/config.gz to confirm 64-bit inums were successfully applied 3656 * (which may not even exist if IKCONFIG_PROC isn't enabled). 3657 * 3658 * We hide it when inode64 isn't the default and we are using 32-bit 3659 * inodes, since that probably just means the feature isn't even under 3660 * consideration. 3661 * 3662 * As such: 3663 * 3664 * +-----------------+-----------------+ 3665 * | TMPFS_INODE64=y | TMPFS_INODE64=n | 3666 * +------------------+-----------------+-----------------+ 3667 * | full_inums=true | show | show | 3668 * | full_inums=false | show | hide | 3669 * +------------------+-----------------+-----------------+ 3670 * 3671 */ 3672 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums) 3673 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32)); 3674 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 3675 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */ 3676 if (sbinfo->huge) 3677 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge)); 3678 #endif 3679 shmem_show_mpol(seq, sbinfo->mpol); 3680 return 0; 3681 } 3682 3683 #endif /* CONFIG_TMPFS */ 3684 3685 static void shmem_put_super(struct super_block *sb) 3686 { 3687 struct shmem_sb_info *sbinfo = SHMEM_SB(sb); 3688 3689 free_percpu(sbinfo->ino_batch); 3690 percpu_counter_destroy(&sbinfo->used_blocks); 3691 mpol_put(sbinfo->mpol); 3692 kfree(sbinfo); 3693 sb->s_fs_info = NULL; 3694 } 3695 3696 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc) 3697 { 3698 struct shmem_options *ctx = fc->fs_private; 3699 struct inode *inode; 3700 struct shmem_sb_info *sbinfo; 3701 3702 /* Round up to L1_CACHE_BYTES to resist false sharing */ 3703 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info), 3704 L1_CACHE_BYTES), GFP_KERNEL); 3705 if (!sbinfo) 3706 return -ENOMEM; 3707 3708 sb->s_fs_info = sbinfo; 3709 3710 #ifdef CONFIG_TMPFS 3711 /* 3712 * Per default we only allow half of the physical ram per 3713 * tmpfs instance, limiting inodes to one per page of lowmem; 3714 * but the internal instance is left unlimited. 3715 */ 3716 if (!(sb->s_flags & SB_KERNMOUNT)) { 3717 if (!(ctx->seen & SHMEM_SEEN_BLOCKS)) 3718 ctx->blocks = shmem_default_max_blocks(); 3719 if (!(ctx->seen & SHMEM_SEEN_INODES)) 3720 ctx->inodes = shmem_default_max_inodes(); 3721 if (!(ctx->seen & SHMEM_SEEN_INUMS)) 3722 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64); 3723 } else { 3724 sb->s_flags |= SB_NOUSER; 3725 } 3726 sb->s_export_op = &shmem_export_ops; 3727 sb->s_flags |= SB_NOSEC; 3728 #else 3729 sb->s_flags |= SB_NOUSER; 3730 #endif 3731 sbinfo->max_blocks = ctx->blocks; 3732 sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes; 3733 if (sb->s_flags & SB_KERNMOUNT) { 3734 sbinfo->ino_batch = alloc_percpu(ino_t); 3735 if (!sbinfo->ino_batch) 3736 goto failed; 3737 } 3738 sbinfo->uid = ctx->uid; 3739 sbinfo->gid = ctx->gid; 3740 sbinfo->full_inums = ctx->full_inums; 3741 sbinfo->mode = ctx->mode; 3742 sbinfo->huge = ctx->huge; 3743 sbinfo->mpol = ctx->mpol; 3744 ctx->mpol = NULL; 3745 3746 raw_spin_lock_init(&sbinfo->stat_lock); 3747 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL)) 3748 goto failed; 3749 spin_lock_init(&sbinfo->shrinklist_lock); 3750 INIT_LIST_HEAD(&sbinfo->shrinklist); 3751 3752 sb->s_maxbytes = MAX_LFS_FILESIZE; 3753 sb->s_blocksize = PAGE_SIZE; 3754 sb->s_blocksize_bits = PAGE_SHIFT; 3755 sb->s_magic = TMPFS_MAGIC; 3756 sb->s_op = &shmem_ops; 3757 sb->s_time_gran = 1; 3758 #ifdef CONFIG_TMPFS_XATTR 3759 sb->s_xattr = shmem_xattr_handlers; 3760 #endif 3761 #ifdef CONFIG_TMPFS_POSIX_ACL 3762 sb->s_flags |= SB_POSIXACL; 3763 #endif 3764 uuid_gen(&sb->s_uuid); 3765 3766 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE); 3767 if (!inode) 3768 goto failed; 3769 inode->i_uid = sbinfo->uid; 3770 inode->i_gid = sbinfo->gid; 3771 sb->s_root = d_make_root(inode); 3772 if (!sb->s_root) 3773 goto failed; 3774 return 0; 3775 3776 failed: 3777 shmem_put_super(sb); 3778 return -ENOMEM; 3779 } 3780 3781 static int shmem_get_tree(struct fs_context *fc) 3782 { 3783 return get_tree_nodev(fc, shmem_fill_super); 3784 } 3785 3786 static void shmem_free_fc(struct fs_context *fc) 3787 { 3788 struct shmem_options *ctx = fc->fs_private; 3789 3790 if (ctx) { 3791 mpol_put(ctx->mpol); 3792 kfree(ctx); 3793 } 3794 } 3795 3796 static const struct fs_context_operations shmem_fs_context_ops = { 3797 .free = shmem_free_fc, 3798 .get_tree = shmem_get_tree, 3799 #ifdef CONFIG_TMPFS 3800 .parse_monolithic = shmem_parse_options, 3801 .parse_param = shmem_parse_one, 3802 .reconfigure = shmem_reconfigure, 3803 #endif 3804 }; 3805 3806 static struct kmem_cache *shmem_inode_cachep; 3807 3808 static struct inode *shmem_alloc_inode(struct super_block *sb) 3809 { 3810 struct shmem_inode_info *info; 3811 info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL); 3812 if (!info) 3813 return NULL; 3814 return &info->vfs_inode; 3815 } 3816 3817 static void shmem_free_in_core_inode(struct inode *inode) 3818 { 3819 if (S_ISLNK(inode->i_mode)) 3820 kfree(inode->i_link); 3821 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode)); 3822 } 3823 3824 static void shmem_destroy_inode(struct inode *inode) 3825 { 3826 if (S_ISREG(inode->i_mode)) 3827 mpol_free_shared_policy(&SHMEM_I(inode)->policy); 3828 } 3829 3830 static void shmem_init_inode(void *foo) 3831 { 3832 struct shmem_inode_info *info = foo; 3833 inode_init_once(&info->vfs_inode); 3834 } 3835 3836 static void shmem_init_inodecache(void) 3837 { 3838 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache", 3839 sizeof(struct shmem_inode_info), 3840 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode); 3841 } 3842 3843 static void shmem_destroy_inodecache(void) 3844 { 3845 kmem_cache_destroy(shmem_inode_cachep); 3846 } 3847 3848 /* Keep the page in page cache instead of truncating it */ 3849 static int shmem_error_remove_page(struct address_space *mapping, 3850 struct page *page) 3851 { 3852 return 0; 3853 } 3854 3855 const struct address_space_operations shmem_aops = { 3856 .writepage = shmem_writepage, 3857 .dirty_folio = noop_dirty_folio, 3858 #ifdef CONFIG_TMPFS 3859 .write_begin = shmem_write_begin, 3860 .write_end = shmem_write_end, 3861 #endif 3862 #ifdef CONFIG_MIGRATION 3863 .migratepage = migrate_page, 3864 #endif 3865 .error_remove_page = shmem_error_remove_page, 3866 }; 3867 EXPORT_SYMBOL(shmem_aops); 3868 3869 static const struct file_operations shmem_file_operations = { 3870 .mmap = shmem_mmap, 3871 .get_unmapped_area = shmem_get_unmapped_area, 3872 #ifdef CONFIG_TMPFS 3873 .llseek = shmem_file_llseek, 3874 .read_iter = shmem_file_read_iter, 3875 .write_iter = generic_file_write_iter, 3876 .fsync = noop_fsync, 3877 .splice_read = generic_file_splice_read, 3878 .splice_write = iter_file_splice_write, 3879 .fallocate = shmem_fallocate, 3880 #endif 3881 }; 3882 3883 static const struct inode_operations shmem_inode_operations = { 3884 .getattr = shmem_getattr, 3885 .setattr = shmem_setattr, 3886 #ifdef CONFIG_TMPFS_XATTR 3887 .listxattr = shmem_listxattr, 3888 .set_acl = simple_set_acl, 3889 .fileattr_get = shmem_fileattr_get, 3890 .fileattr_set = shmem_fileattr_set, 3891 #endif 3892 }; 3893 3894 static const struct inode_operations shmem_dir_inode_operations = { 3895 #ifdef CONFIG_TMPFS 3896 .getattr = shmem_getattr, 3897 .create = shmem_create, 3898 .lookup = simple_lookup, 3899 .link = shmem_link, 3900 .unlink = shmem_unlink, 3901 .symlink = shmem_symlink, 3902 .mkdir = shmem_mkdir, 3903 .rmdir = shmem_rmdir, 3904 .mknod = shmem_mknod, 3905 .rename = shmem_rename2, 3906 .tmpfile = shmem_tmpfile, 3907 #endif 3908 #ifdef CONFIG_TMPFS_XATTR 3909 .listxattr = shmem_listxattr, 3910 .fileattr_get = shmem_fileattr_get, 3911 .fileattr_set = shmem_fileattr_set, 3912 #endif 3913 #ifdef CONFIG_TMPFS_POSIX_ACL 3914 .setattr = shmem_setattr, 3915 .set_acl = simple_set_acl, 3916 #endif 3917 }; 3918 3919 static const struct inode_operations shmem_special_inode_operations = { 3920 .getattr = shmem_getattr, 3921 #ifdef CONFIG_TMPFS_XATTR 3922 .listxattr = shmem_listxattr, 3923 #endif 3924 #ifdef CONFIG_TMPFS_POSIX_ACL 3925 .setattr = shmem_setattr, 3926 .set_acl = simple_set_acl, 3927 #endif 3928 }; 3929 3930 static const struct super_operations shmem_ops = { 3931 .alloc_inode = shmem_alloc_inode, 3932 .free_inode = shmem_free_in_core_inode, 3933 .destroy_inode = shmem_destroy_inode, 3934 #ifdef CONFIG_TMPFS 3935 .statfs = shmem_statfs, 3936 .show_options = shmem_show_options, 3937 #endif 3938 .evict_inode = shmem_evict_inode, 3939 .drop_inode = generic_delete_inode, 3940 .put_super = shmem_put_super, 3941 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 3942 .nr_cached_objects = shmem_unused_huge_count, 3943 .free_cached_objects = shmem_unused_huge_scan, 3944 #endif 3945 }; 3946 3947 static const struct vm_operations_struct shmem_vm_ops = { 3948 .fault = shmem_fault, 3949 .map_pages = filemap_map_pages, 3950 #ifdef CONFIG_NUMA 3951 .set_policy = shmem_set_policy, 3952 .get_policy = shmem_get_policy, 3953 #endif 3954 }; 3955 3956 int shmem_init_fs_context(struct fs_context *fc) 3957 { 3958 struct shmem_options *ctx; 3959 3960 ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL); 3961 if (!ctx) 3962 return -ENOMEM; 3963 3964 ctx->mode = 0777 | S_ISVTX; 3965 ctx->uid = current_fsuid(); 3966 ctx->gid = current_fsgid(); 3967 3968 fc->fs_private = ctx; 3969 fc->ops = &shmem_fs_context_ops; 3970 return 0; 3971 } 3972 3973 static struct file_system_type shmem_fs_type = { 3974 .owner = THIS_MODULE, 3975 .name = "tmpfs", 3976 .init_fs_context = shmem_init_fs_context, 3977 #ifdef CONFIG_TMPFS 3978 .parameters = shmem_fs_parameters, 3979 #endif 3980 .kill_sb = kill_litter_super, 3981 .fs_flags = FS_USERNS_MOUNT, 3982 }; 3983 3984 void __init shmem_init(void) 3985 { 3986 int error; 3987 3988 shmem_init_inodecache(); 3989 3990 error = register_filesystem(&shmem_fs_type); 3991 if (error) { 3992 pr_err("Could not register tmpfs\n"); 3993 goto out2; 3994 } 3995 3996 shm_mnt = kern_mount(&shmem_fs_type); 3997 if (IS_ERR(shm_mnt)) { 3998 error = PTR_ERR(shm_mnt); 3999 pr_err("Could not kern_mount tmpfs\n"); 4000 goto out1; 4001 } 4002 4003 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4004 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY) 4005 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 4006 else 4007 shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */ 4008 #endif 4009 return; 4010 4011 out1: 4012 unregister_filesystem(&shmem_fs_type); 4013 out2: 4014 shmem_destroy_inodecache(); 4015 shm_mnt = ERR_PTR(error); 4016 } 4017 4018 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS) 4019 static ssize_t shmem_enabled_show(struct kobject *kobj, 4020 struct kobj_attribute *attr, char *buf) 4021 { 4022 static const int values[] = { 4023 SHMEM_HUGE_ALWAYS, 4024 SHMEM_HUGE_WITHIN_SIZE, 4025 SHMEM_HUGE_ADVISE, 4026 SHMEM_HUGE_NEVER, 4027 SHMEM_HUGE_DENY, 4028 SHMEM_HUGE_FORCE, 4029 }; 4030 int len = 0; 4031 int i; 4032 4033 for (i = 0; i < ARRAY_SIZE(values); i++) { 4034 len += sysfs_emit_at(buf, len, 4035 shmem_huge == values[i] ? "%s[%s]" : "%s%s", 4036 i ? " " : "", 4037 shmem_format_huge(values[i])); 4038 } 4039 4040 len += sysfs_emit_at(buf, len, "\n"); 4041 4042 return len; 4043 } 4044 4045 static ssize_t shmem_enabled_store(struct kobject *kobj, 4046 struct kobj_attribute *attr, const char *buf, size_t count) 4047 { 4048 char tmp[16]; 4049 int huge; 4050 4051 if (count + 1 > sizeof(tmp)) 4052 return -EINVAL; 4053 memcpy(tmp, buf, count); 4054 tmp[count] = '\0'; 4055 if (count && tmp[count - 1] == '\n') 4056 tmp[count - 1] = '\0'; 4057 4058 huge = shmem_parse_huge(tmp); 4059 if (huge == -EINVAL) 4060 return -EINVAL; 4061 if (!has_transparent_hugepage() && 4062 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY) 4063 return -EINVAL; 4064 4065 shmem_huge = huge; 4066 if (shmem_huge > SHMEM_HUGE_DENY) 4067 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge; 4068 return count; 4069 } 4070 4071 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled); 4072 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */ 4073 4074 #else /* !CONFIG_SHMEM */ 4075 4076 /* 4077 * tiny-shmem: simple shmemfs and tmpfs using ramfs code 4078 * 4079 * This is intended for small system where the benefits of the full 4080 * shmem code (swap-backed and resource-limited) are outweighed by 4081 * their complexity. On systems without swap this code should be 4082 * effectively equivalent, but much lighter weight. 4083 */ 4084 4085 static struct file_system_type shmem_fs_type = { 4086 .name = "tmpfs", 4087 .init_fs_context = ramfs_init_fs_context, 4088 .parameters = ramfs_fs_parameters, 4089 .kill_sb = kill_litter_super, 4090 .fs_flags = FS_USERNS_MOUNT, 4091 }; 4092 4093 void __init shmem_init(void) 4094 { 4095 BUG_ON(register_filesystem(&shmem_fs_type) != 0); 4096 4097 shm_mnt = kern_mount(&shmem_fs_type); 4098 BUG_ON(IS_ERR(shm_mnt)); 4099 } 4100 4101 int shmem_unuse(unsigned int type) 4102 { 4103 return 0; 4104 } 4105 4106 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts) 4107 { 4108 return 0; 4109 } 4110 4111 void shmem_unlock_mapping(struct address_space *mapping) 4112 { 4113 } 4114 4115 #ifdef CONFIG_MMU 4116 unsigned long shmem_get_unmapped_area(struct file *file, 4117 unsigned long addr, unsigned long len, 4118 unsigned long pgoff, unsigned long flags) 4119 { 4120 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags); 4121 } 4122 #endif 4123 4124 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend) 4125 { 4126 truncate_inode_pages_range(inode->i_mapping, lstart, lend); 4127 } 4128 EXPORT_SYMBOL_GPL(shmem_truncate_range); 4129 4130 #define shmem_vm_ops generic_file_vm_ops 4131 #define shmem_file_operations ramfs_file_operations 4132 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev) 4133 #define shmem_acct_size(flags, size) 0 4134 #define shmem_unacct_size(flags, size) do {} while (0) 4135 4136 #endif /* CONFIG_SHMEM */ 4137 4138 /* common code */ 4139 4140 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size, 4141 unsigned long flags, unsigned int i_flags) 4142 { 4143 struct inode *inode; 4144 struct file *res; 4145 4146 if (IS_ERR(mnt)) 4147 return ERR_CAST(mnt); 4148 4149 if (size < 0 || size > MAX_LFS_FILESIZE) 4150 return ERR_PTR(-EINVAL); 4151 4152 if (shmem_acct_size(flags, size)) 4153 return ERR_PTR(-ENOMEM); 4154 4155 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0, 4156 flags); 4157 if (unlikely(!inode)) { 4158 shmem_unacct_size(flags, size); 4159 return ERR_PTR(-ENOSPC); 4160 } 4161 inode->i_flags |= i_flags; 4162 inode->i_size = size; 4163 clear_nlink(inode); /* It is unlinked */ 4164 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size)); 4165 if (!IS_ERR(res)) 4166 res = alloc_file_pseudo(inode, mnt, name, O_RDWR, 4167 &shmem_file_operations); 4168 if (IS_ERR(res)) 4169 iput(inode); 4170 return res; 4171 } 4172 4173 /** 4174 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be 4175 * kernel internal. There will be NO LSM permission checks against the 4176 * underlying inode. So users of this interface must do LSM checks at a 4177 * higher layer. The users are the big_key and shm implementations. LSM 4178 * checks are provided at the key or shm level rather than the inode. 4179 * @name: name for dentry (to be seen in /proc/<pid>/maps 4180 * @size: size to be set for the file 4181 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 4182 */ 4183 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags) 4184 { 4185 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE); 4186 } 4187 4188 /** 4189 * shmem_file_setup - get an unlinked file living in tmpfs 4190 * @name: name for dentry (to be seen in /proc/<pid>/maps 4191 * @size: size to be set for the file 4192 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 4193 */ 4194 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags) 4195 { 4196 return __shmem_file_setup(shm_mnt, name, size, flags, 0); 4197 } 4198 EXPORT_SYMBOL_GPL(shmem_file_setup); 4199 4200 /** 4201 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs 4202 * @mnt: the tmpfs mount where the file will be created 4203 * @name: name for dentry (to be seen in /proc/<pid>/maps 4204 * @size: size to be set for the file 4205 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size 4206 */ 4207 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name, 4208 loff_t size, unsigned long flags) 4209 { 4210 return __shmem_file_setup(mnt, name, size, flags, 0); 4211 } 4212 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt); 4213 4214 /** 4215 * shmem_zero_setup - setup a shared anonymous mapping 4216 * @vma: the vma to be mmapped is prepared by do_mmap 4217 */ 4218 int shmem_zero_setup(struct vm_area_struct *vma) 4219 { 4220 struct file *file; 4221 loff_t size = vma->vm_end - vma->vm_start; 4222 4223 /* 4224 * Cloning a new file under mmap_lock leads to a lock ordering conflict 4225 * between XFS directory reading and selinux: since this file is only 4226 * accessible to the user through its mapping, use S_PRIVATE flag to 4227 * bypass file security, in the same way as shmem_kernel_file_setup(). 4228 */ 4229 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags); 4230 if (IS_ERR(file)) 4231 return PTR_ERR(file); 4232 4233 if (vma->vm_file) 4234 fput(vma->vm_file); 4235 vma->vm_file = file; 4236 vma->vm_ops = &shmem_vm_ops; 4237 4238 return 0; 4239 } 4240 4241 /** 4242 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags. 4243 * @mapping: the page's address_space 4244 * @index: the page index 4245 * @gfp: the page allocator flags to use if allocating 4246 * 4247 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)", 4248 * with any new page allocations done using the specified allocation flags. 4249 * But read_cache_page_gfp() uses the ->read_folio() method: which does not 4250 * suit tmpfs, since it may have pages in swapcache, and needs to find those 4251 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support. 4252 * 4253 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in 4254 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily. 4255 */ 4256 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping, 4257 pgoff_t index, gfp_t gfp) 4258 { 4259 #ifdef CONFIG_SHMEM 4260 struct inode *inode = mapping->host; 4261 struct page *page; 4262 int error; 4263 4264 BUG_ON(!shmem_mapping(mapping)); 4265 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE, 4266 gfp, NULL, NULL, NULL); 4267 if (error) 4268 return ERR_PTR(error); 4269 4270 unlock_page(page); 4271 if (PageHWPoison(page)) { 4272 put_page(page); 4273 return ERR_PTR(-EIO); 4274 } 4275 4276 return page; 4277 #else 4278 /* 4279 * The tiny !SHMEM case uses ramfs without swap 4280 */ 4281 return read_cache_page_gfp(mapping, index, gfp); 4282 #endif 4283 } 4284 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp); 4285