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