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