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