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