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