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