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