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