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