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