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