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