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