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