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