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