xref: /openbmc/linux/mm/shmem.c (revision d09e8ca6cb93bb4b97517a18fbbf7eccb0e9ff43)
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/swap.h>
37 #include <linux/uio.h>
38 #include <linux/hugetlb.h>
39 #include <linux/fs_parser.h>
40 #include <linux/swapfile.h>
41 #include <linux/iversion.h>
42 #include "swap.h"
43 
44 static struct vfsmount *shm_mnt;
45 
46 #ifdef CONFIG_SHMEM
47 /*
48  * This virtual memory filesystem is heavily based on the ramfs. It
49  * extends ramfs by the ability to use swap and honor resource limits
50  * which makes it a completely usable filesystem.
51  */
52 
53 #include <linux/xattr.h>
54 #include <linux/exportfs.h>
55 #include <linux/posix_acl.h>
56 #include <linux/posix_acl_xattr.h>
57 #include <linux/mman.h>
58 #include <linux/string.h>
59 #include <linux/slab.h>
60 #include <linux/backing-dev.h>
61 #include <linux/shmem_fs.h>
62 #include <linux/writeback.h>
63 #include <linux/pagevec.h>
64 #include <linux/percpu_counter.h>
65 #include <linux/falloc.h>
66 #include <linux/splice.h>
67 #include <linux/security.h>
68 #include <linux/swapops.h>
69 #include <linux/mempolicy.h>
70 #include <linux/namei.h>
71 #include <linux/ctype.h>
72 #include <linux/migrate.h>
73 #include <linux/highmem.h>
74 #include <linux/seq_file.h>
75 #include <linux/magic.h>
76 #include <linux/syscalls.h>
77 #include <linux/fcntl.h>
78 #include <uapi/linux/memfd.h>
79 #include <linux/userfaultfd_k.h>
80 #include <linux/rmap.h>
81 #include <linux/uuid.h>
82 
83 #include <linux/uaccess.h>
84 
85 #include "internal.h"
86 
87 #define BLOCKS_PER_PAGE  (PAGE_SIZE/512)
88 #define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
89 
90 /* Pretend that each entry is of this size in directory's i_size */
91 #define BOGO_DIRENT_SIZE 20
92 
93 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
94 #define SHORT_SYMLINK_LEN 128
95 
96 /*
97  * shmem_fallocate communicates with shmem_fault or shmem_writepage via
98  * inode->i_private (with i_rwsem making sure that it has only one user at
99  * a time): we would prefer not to enlarge the shmem inode just for that.
100  */
101 struct shmem_falloc {
102 	wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
103 	pgoff_t start;		/* start of range currently being fallocated */
104 	pgoff_t next;		/* the next page offset to be fallocated */
105 	pgoff_t nr_falloced;	/* how many new pages have been fallocated */
106 	pgoff_t nr_unswapped;	/* how often writepage refused to swap out */
107 };
108 
109 struct shmem_options {
110 	unsigned long long blocks;
111 	unsigned long long inodes;
112 	struct mempolicy *mpol;
113 	kuid_t uid;
114 	kgid_t gid;
115 	umode_t mode;
116 	bool full_inums;
117 	int huge;
118 	int seen;
119 #define SHMEM_SEEN_BLOCKS 1
120 #define SHMEM_SEEN_INODES 2
121 #define SHMEM_SEEN_HUGE 4
122 #define SHMEM_SEEN_INUMS 8
123 };
124 
125 #ifdef CONFIG_TMPFS
126 static unsigned long shmem_default_max_blocks(void)
127 {
128 	return totalram_pages() / 2;
129 }
130 
131 static unsigned long shmem_default_max_inodes(void)
132 {
133 	unsigned long nr_pages = totalram_pages();
134 
135 	return min(nr_pages - totalhigh_pages(), nr_pages / 2);
136 }
137 #endif
138 
139 static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
140 			     struct folio **foliop, enum sgp_type sgp,
141 			     gfp_t gfp, struct vm_area_struct *vma,
142 			     vm_fault_t *fault_type);
143 
144 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
145 {
146 	return sb->s_fs_info;
147 }
148 
149 /*
150  * shmem_file_setup pre-accounts the whole fixed size of a VM object,
151  * for shared memory and for shared anonymous (/dev/zero) mappings
152  * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
153  * consistent with the pre-accounting of private mappings ...
154  */
155 static inline int shmem_acct_size(unsigned long flags, loff_t size)
156 {
157 	return (flags & VM_NORESERVE) ?
158 		0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
159 }
160 
161 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
162 {
163 	if (!(flags & VM_NORESERVE))
164 		vm_unacct_memory(VM_ACCT(size));
165 }
166 
167 static inline int shmem_reacct_size(unsigned long flags,
168 		loff_t oldsize, loff_t newsize)
169 {
170 	if (!(flags & VM_NORESERVE)) {
171 		if (VM_ACCT(newsize) > VM_ACCT(oldsize))
172 			return security_vm_enough_memory_mm(current->mm,
173 					VM_ACCT(newsize) - VM_ACCT(oldsize));
174 		else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
175 			vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
176 	}
177 	return 0;
178 }
179 
180 /*
181  * ... whereas tmpfs objects are accounted incrementally as
182  * pages are allocated, in order to allow large sparse files.
183  * shmem_get_folio reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
184  * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
185  */
186 static inline int shmem_acct_block(unsigned long flags, long pages)
187 {
188 	if (!(flags & VM_NORESERVE))
189 		return 0;
190 
191 	return security_vm_enough_memory_mm(current->mm,
192 			pages * VM_ACCT(PAGE_SIZE));
193 }
194 
195 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
196 {
197 	if (flags & VM_NORESERVE)
198 		vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
199 }
200 
201 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
202 {
203 	struct shmem_inode_info *info = SHMEM_I(inode);
204 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
205 
206 	if (shmem_acct_block(info->flags, pages))
207 		return false;
208 
209 	if (sbinfo->max_blocks) {
210 		if (percpu_counter_compare(&sbinfo->used_blocks,
211 					   sbinfo->max_blocks - pages) > 0)
212 			goto unacct;
213 		percpu_counter_add(&sbinfo->used_blocks, pages);
214 	}
215 
216 	return true;
217 
218 unacct:
219 	shmem_unacct_blocks(info->flags, pages);
220 	return false;
221 }
222 
223 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
224 {
225 	struct shmem_inode_info *info = SHMEM_I(inode);
226 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
227 
228 	if (sbinfo->max_blocks)
229 		percpu_counter_sub(&sbinfo->used_blocks, pages);
230 	shmem_unacct_blocks(info->flags, pages);
231 }
232 
233 static const struct super_operations shmem_ops;
234 const struct address_space_operations shmem_aops;
235 static const struct file_operations shmem_file_operations;
236 static const struct inode_operations shmem_inode_operations;
237 static const struct inode_operations shmem_dir_inode_operations;
238 static const struct inode_operations shmem_special_inode_operations;
239 static const struct vm_operations_struct shmem_vm_ops;
240 static const struct vm_operations_struct shmem_anon_vm_ops;
241 static struct file_system_type shmem_fs_type;
242 
243 bool vma_is_anon_shmem(struct vm_area_struct *vma)
244 {
245 	return vma->vm_ops == &shmem_anon_vm_ops;
246 }
247 
248 bool vma_is_shmem(struct vm_area_struct *vma)
249 {
250 	return vma_is_anon_shmem(vma) || vma->vm_ops == &shmem_vm_ops;
251 }
252 
253 static LIST_HEAD(shmem_swaplist);
254 static DEFINE_MUTEX(shmem_swaplist_mutex);
255 
256 /*
257  * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
258  * produces a novel ino for the newly allocated inode.
259  *
260  * It may also be called when making a hard link to permit the space needed by
261  * each dentry. However, in that case, no new inode number is needed since that
262  * internally draws from another pool of inode numbers (currently global
263  * get_next_ino()). This case is indicated by passing NULL as inop.
264  */
265 #define SHMEM_INO_BATCH 1024
266 static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
267 {
268 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
269 	ino_t ino;
270 
271 	if (!(sb->s_flags & SB_KERNMOUNT)) {
272 		raw_spin_lock(&sbinfo->stat_lock);
273 		if (sbinfo->max_inodes) {
274 			if (!sbinfo->free_inodes) {
275 				raw_spin_unlock(&sbinfo->stat_lock);
276 				return -ENOSPC;
277 			}
278 			sbinfo->free_inodes--;
279 		}
280 		if (inop) {
281 			ino = sbinfo->next_ino++;
282 			if (unlikely(is_zero_ino(ino)))
283 				ino = sbinfo->next_ino++;
284 			if (unlikely(!sbinfo->full_inums &&
285 				     ino > UINT_MAX)) {
286 				/*
287 				 * Emulate get_next_ino uint wraparound for
288 				 * compatibility
289 				 */
290 				if (IS_ENABLED(CONFIG_64BIT))
291 					pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
292 						__func__, MINOR(sb->s_dev));
293 				sbinfo->next_ino = 1;
294 				ino = sbinfo->next_ino++;
295 			}
296 			*inop = ino;
297 		}
298 		raw_spin_unlock(&sbinfo->stat_lock);
299 	} else if (inop) {
300 		/*
301 		 * __shmem_file_setup, one of our callers, is lock-free: it
302 		 * doesn't hold stat_lock in shmem_reserve_inode since
303 		 * max_inodes is always 0, and is called from potentially
304 		 * unknown contexts. As such, use a per-cpu batched allocator
305 		 * which doesn't require the per-sb stat_lock unless we are at
306 		 * the batch boundary.
307 		 *
308 		 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
309 		 * shmem mounts are not exposed to userspace, so we don't need
310 		 * to worry about things like glibc compatibility.
311 		 */
312 		ino_t *next_ino;
313 
314 		next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
315 		ino = *next_ino;
316 		if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
317 			raw_spin_lock(&sbinfo->stat_lock);
318 			ino = sbinfo->next_ino;
319 			sbinfo->next_ino += SHMEM_INO_BATCH;
320 			raw_spin_unlock(&sbinfo->stat_lock);
321 			if (unlikely(is_zero_ino(ino)))
322 				ino++;
323 		}
324 		*inop = ino;
325 		*next_ino = ++ino;
326 		put_cpu();
327 	}
328 
329 	return 0;
330 }
331 
332 static void shmem_free_inode(struct super_block *sb)
333 {
334 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
335 	if (sbinfo->max_inodes) {
336 		raw_spin_lock(&sbinfo->stat_lock);
337 		sbinfo->free_inodes++;
338 		raw_spin_unlock(&sbinfo->stat_lock);
339 	}
340 }
341 
342 /**
343  * shmem_recalc_inode - recalculate the block usage of an inode
344  * @inode: inode to recalc
345  *
346  * We have to calculate the free blocks since the mm can drop
347  * undirtied hole pages behind our back.
348  *
349  * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
350  * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
351  *
352  * It has to be called with the spinlock held.
353  */
354 static void shmem_recalc_inode(struct inode *inode)
355 {
356 	struct shmem_inode_info *info = SHMEM_I(inode);
357 	long freed;
358 
359 	freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
360 	if (freed > 0) {
361 		info->alloced -= freed;
362 		inode->i_blocks -= freed * BLOCKS_PER_PAGE;
363 		shmem_inode_unacct_blocks(inode, freed);
364 	}
365 }
366 
367 bool shmem_charge(struct inode *inode, long pages)
368 {
369 	struct shmem_inode_info *info = SHMEM_I(inode);
370 	unsigned long flags;
371 
372 	if (!shmem_inode_acct_block(inode, pages))
373 		return false;
374 
375 	/* nrpages adjustment first, then shmem_recalc_inode() when balanced */
376 	inode->i_mapping->nrpages += pages;
377 
378 	spin_lock_irqsave(&info->lock, flags);
379 	info->alloced += pages;
380 	inode->i_blocks += pages * BLOCKS_PER_PAGE;
381 	shmem_recalc_inode(inode);
382 	spin_unlock_irqrestore(&info->lock, flags);
383 
384 	return true;
385 }
386 
387 void shmem_uncharge(struct inode *inode, long pages)
388 {
389 	struct shmem_inode_info *info = SHMEM_I(inode);
390 	unsigned long flags;
391 
392 	/* nrpages adjustment done by __filemap_remove_folio() or caller */
393 
394 	spin_lock_irqsave(&info->lock, flags);
395 	info->alloced -= pages;
396 	inode->i_blocks -= pages * BLOCKS_PER_PAGE;
397 	shmem_recalc_inode(inode);
398 	spin_unlock_irqrestore(&info->lock, flags);
399 
400 	shmem_inode_unacct_blocks(inode, pages);
401 }
402 
403 /*
404  * Replace item expected in xarray by a new item, while holding xa_lock.
405  */
406 static int shmem_replace_entry(struct address_space *mapping,
407 			pgoff_t index, void *expected, void *replacement)
408 {
409 	XA_STATE(xas, &mapping->i_pages, index);
410 	void *item;
411 
412 	VM_BUG_ON(!expected);
413 	VM_BUG_ON(!replacement);
414 	item = xas_load(&xas);
415 	if (item != expected)
416 		return -ENOENT;
417 	xas_store(&xas, replacement);
418 	return 0;
419 }
420 
421 /*
422  * Sometimes, before we decide whether to proceed or to fail, we must check
423  * that an entry was not already brought back from swap by a racing thread.
424  *
425  * Checking page is not enough: by the time a SwapCache page is locked, it
426  * might be reused, and again be SwapCache, using the same swap as before.
427  */
428 static bool shmem_confirm_swap(struct address_space *mapping,
429 			       pgoff_t index, swp_entry_t swap)
430 {
431 	return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
432 }
433 
434 /*
435  * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
436  *
437  * SHMEM_HUGE_NEVER:
438  *	disables huge pages for the mount;
439  * SHMEM_HUGE_ALWAYS:
440  *	enables huge pages for the mount;
441  * SHMEM_HUGE_WITHIN_SIZE:
442  *	only allocate huge pages if the page will be fully within i_size,
443  *	also respect fadvise()/madvise() hints;
444  * SHMEM_HUGE_ADVISE:
445  *	only allocate huge pages if requested with fadvise()/madvise();
446  */
447 
448 #define SHMEM_HUGE_NEVER	0
449 #define SHMEM_HUGE_ALWAYS	1
450 #define SHMEM_HUGE_WITHIN_SIZE	2
451 #define SHMEM_HUGE_ADVISE	3
452 
453 /*
454  * Special values.
455  * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
456  *
457  * SHMEM_HUGE_DENY:
458  *	disables huge on shm_mnt and all mounts, for emergency use;
459  * SHMEM_HUGE_FORCE:
460  *	enables huge on shm_mnt and all mounts, w/o needing option, for testing;
461  *
462  */
463 #define SHMEM_HUGE_DENY		(-1)
464 #define SHMEM_HUGE_FORCE	(-2)
465 
466 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
467 /* ifdef here to avoid bloating shmem.o when not necessary */
468 
469 static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER;
470 
471 bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode,
472 		   pgoff_t index, bool shmem_huge_force)
473 {
474 	loff_t i_size;
475 
476 	if (!S_ISREG(inode->i_mode))
477 		return false;
478 	if (vma && ((vma->vm_flags & VM_NOHUGEPAGE) ||
479 	    test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags)))
480 		return false;
481 	if (shmem_huge_force)
482 		return true;
483 	if (shmem_huge == SHMEM_HUGE_FORCE)
484 		return true;
485 	if (shmem_huge == SHMEM_HUGE_DENY)
486 		return false;
487 
488 	switch (SHMEM_SB(inode->i_sb)->huge) {
489 	case SHMEM_HUGE_ALWAYS:
490 		return true;
491 	case SHMEM_HUGE_WITHIN_SIZE:
492 		index = round_up(index + 1, HPAGE_PMD_NR);
493 		i_size = round_up(i_size_read(inode), PAGE_SIZE);
494 		if (i_size >> PAGE_SHIFT >= index)
495 			return true;
496 		fallthrough;
497 	case SHMEM_HUGE_ADVISE:
498 		if (vma && (vma->vm_flags & VM_HUGEPAGE))
499 			return true;
500 		fallthrough;
501 	default:
502 		return false;
503 	}
504 }
505 
506 #if defined(CONFIG_SYSFS)
507 static int shmem_parse_huge(const char *str)
508 {
509 	if (!strcmp(str, "never"))
510 		return SHMEM_HUGE_NEVER;
511 	if (!strcmp(str, "always"))
512 		return SHMEM_HUGE_ALWAYS;
513 	if (!strcmp(str, "within_size"))
514 		return SHMEM_HUGE_WITHIN_SIZE;
515 	if (!strcmp(str, "advise"))
516 		return SHMEM_HUGE_ADVISE;
517 	if (!strcmp(str, "deny"))
518 		return SHMEM_HUGE_DENY;
519 	if (!strcmp(str, "force"))
520 		return SHMEM_HUGE_FORCE;
521 	return -EINVAL;
522 }
523 #endif
524 
525 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
526 static const char *shmem_format_huge(int huge)
527 {
528 	switch (huge) {
529 	case SHMEM_HUGE_NEVER:
530 		return "never";
531 	case SHMEM_HUGE_ALWAYS:
532 		return "always";
533 	case SHMEM_HUGE_WITHIN_SIZE:
534 		return "within_size";
535 	case SHMEM_HUGE_ADVISE:
536 		return "advise";
537 	case SHMEM_HUGE_DENY:
538 		return "deny";
539 	case SHMEM_HUGE_FORCE:
540 		return "force";
541 	default:
542 		VM_BUG_ON(1);
543 		return "bad_val";
544 	}
545 }
546 #endif
547 
548 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
549 		struct shrink_control *sc, unsigned long nr_to_split)
550 {
551 	LIST_HEAD(list), *pos, *next;
552 	LIST_HEAD(to_remove);
553 	struct inode *inode;
554 	struct shmem_inode_info *info;
555 	struct folio *folio;
556 	unsigned long batch = sc ? sc->nr_to_scan : 128;
557 	int split = 0;
558 
559 	if (list_empty(&sbinfo->shrinklist))
560 		return SHRINK_STOP;
561 
562 	spin_lock(&sbinfo->shrinklist_lock);
563 	list_for_each_safe(pos, next, &sbinfo->shrinklist) {
564 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
565 
566 		/* pin the inode */
567 		inode = igrab(&info->vfs_inode);
568 
569 		/* inode is about to be evicted */
570 		if (!inode) {
571 			list_del_init(&info->shrinklist);
572 			goto next;
573 		}
574 
575 		/* Check if there's anything to gain */
576 		if (round_up(inode->i_size, PAGE_SIZE) ==
577 				round_up(inode->i_size, HPAGE_PMD_SIZE)) {
578 			list_move(&info->shrinklist, &to_remove);
579 			goto next;
580 		}
581 
582 		list_move(&info->shrinklist, &list);
583 next:
584 		sbinfo->shrinklist_len--;
585 		if (!--batch)
586 			break;
587 	}
588 	spin_unlock(&sbinfo->shrinklist_lock);
589 
590 	list_for_each_safe(pos, next, &to_remove) {
591 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
592 		inode = &info->vfs_inode;
593 		list_del_init(&info->shrinklist);
594 		iput(inode);
595 	}
596 
597 	list_for_each_safe(pos, next, &list) {
598 		int ret;
599 		pgoff_t index;
600 
601 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
602 		inode = &info->vfs_inode;
603 
604 		if (nr_to_split && split >= nr_to_split)
605 			goto move_back;
606 
607 		index = (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT;
608 		folio = filemap_get_folio(inode->i_mapping, index);
609 		if (!folio)
610 			goto drop;
611 
612 		/* No huge page at the end of the file: nothing to split */
613 		if (!folio_test_large(folio)) {
614 			folio_put(folio);
615 			goto drop;
616 		}
617 
618 		/*
619 		 * Move the inode on the list back to shrinklist if we failed
620 		 * to lock the page at this time.
621 		 *
622 		 * Waiting for the lock may lead to deadlock in the
623 		 * reclaim path.
624 		 */
625 		if (!folio_trylock(folio)) {
626 			folio_put(folio);
627 			goto move_back;
628 		}
629 
630 		ret = split_folio(folio);
631 		folio_unlock(folio);
632 		folio_put(folio);
633 
634 		/* If split failed move the inode on the list back to shrinklist */
635 		if (ret)
636 			goto move_back;
637 
638 		split++;
639 drop:
640 		list_del_init(&info->shrinklist);
641 		goto put;
642 move_back:
643 		/*
644 		 * Make sure the inode is either on the global list or deleted
645 		 * from any local list before iput() since it could be deleted
646 		 * in another thread once we put the inode (then the local list
647 		 * is corrupted).
648 		 */
649 		spin_lock(&sbinfo->shrinklist_lock);
650 		list_move(&info->shrinklist, &sbinfo->shrinklist);
651 		sbinfo->shrinklist_len++;
652 		spin_unlock(&sbinfo->shrinklist_lock);
653 put:
654 		iput(inode);
655 	}
656 
657 	return split;
658 }
659 
660 static long shmem_unused_huge_scan(struct super_block *sb,
661 		struct shrink_control *sc)
662 {
663 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
664 
665 	if (!READ_ONCE(sbinfo->shrinklist_len))
666 		return SHRINK_STOP;
667 
668 	return shmem_unused_huge_shrink(sbinfo, sc, 0);
669 }
670 
671 static long shmem_unused_huge_count(struct super_block *sb,
672 		struct shrink_control *sc)
673 {
674 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
675 	return READ_ONCE(sbinfo->shrinklist_len);
676 }
677 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
678 
679 #define shmem_huge SHMEM_HUGE_DENY
680 
681 bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode,
682 		   pgoff_t index, bool shmem_huge_force)
683 {
684 	return false;
685 }
686 
687 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
688 		struct shrink_control *sc, unsigned long nr_to_split)
689 {
690 	return 0;
691 }
692 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
693 
694 /*
695  * Like filemap_add_folio, but error if expected item has gone.
696  */
697 static int shmem_add_to_page_cache(struct folio *folio,
698 				   struct address_space *mapping,
699 				   pgoff_t index, void *expected, gfp_t gfp,
700 				   struct mm_struct *charge_mm)
701 {
702 	XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio));
703 	long nr = folio_nr_pages(folio);
704 	int error;
705 
706 	VM_BUG_ON_FOLIO(index != round_down(index, nr), folio);
707 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
708 	VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio);
709 	VM_BUG_ON(expected && folio_test_large(folio));
710 
711 	folio_ref_add(folio, nr);
712 	folio->mapping = mapping;
713 	folio->index = index;
714 
715 	if (!folio_test_swapcache(folio)) {
716 		error = mem_cgroup_charge(folio, charge_mm, gfp);
717 		if (error) {
718 			if (folio_test_pmd_mappable(folio)) {
719 				count_vm_event(THP_FILE_FALLBACK);
720 				count_vm_event(THP_FILE_FALLBACK_CHARGE);
721 			}
722 			goto error;
723 		}
724 	}
725 	folio_throttle_swaprate(folio, gfp);
726 
727 	do {
728 		xas_lock_irq(&xas);
729 		if (expected != xas_find_conflict(&xas)) {
730 			xas_set_err(&xas, -EEXIST);
731 			goto unlock;
732 		}
733 		if (expected && xas_find_conflict(&xas)) {
734 			xas_set_err(&xas, -EEXIST);
735 			goto unlock;
736 		}
737 		xas_store(&xas, folio);
738 		if (xas_error(&xas))
739 			goto unlock;
740 		if (folio_test_pmd_mappable(folio)) {
741 			count_vm_event(THP_FILE_ALLOC);
742 			__lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr);
743 		}
744 		mapping->nrpages += nr;
745 		__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
746 		__lruvec_stat_mod_folio(folio, NR_SHMEM, nr);
747 unlock:
748 		xas_unlock_irq(&xas);
749 	} while (xas_nomem(&xas, gfp));
750 
751 	if (xas_error(&xas)) {
752 		error = xas_error(&xas);
753 		goto error;
754 	}
755 
756 	return 0;
757 error:
758 	folio->mapping = NULL;
759 	folio_ref_sub(folio, nr);
760 	return error;
761 }
762 
763 /*
764  * Like delete_from_page_cache, but substitutes swap for @folio.
765  */
766 static void shmem_delete_from_page_cache(struct folio *folio, void *radswap)
767 {
768 	struct address_space *mapping = folio->mapping;
769 	long nr = folio_nr_pages(folio);
770 	int error;
771 
772 	xa_lock_irq(&mapping->i_pages);
773 	error = shmem_replace_entry(mapping, folio->index, folio, radswap);
774 	folio->mapping = NULL;
775 	mapping->nrpages -= nr;
776 	__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
777 	__lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
778 	xa_unlock_irq(&mapping->i_pages);
779 	folio_put(folio);
780 	BUG_ON(error);
781 }
782 
783 /*
784  * Remove swap entry from page cache, free the swap and its page cache.
785  */
786 static int shmem_free_swap(struct address_space *mapping,
787 			   pgoff_t index, void *radswap)
788 {
789 	void *old;
790 
791 	old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
792 	if (old != radswap)
793 		return -ENOENT;
794 	free_swap_and_cache(radix_to_swp_entry(radswap));
795 	return 0;
796 }
797 
798 /*
799  * Determine (in bytes) how many of the shmem object's pages mapped by the
800  * given offsets are swapped out.
801  *
802  * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
803  * as long as the inode doesn't go away and racy results are not a problem.
804  */
805 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
806 						pgoff_t start, pgoff_t end)
807 {
808 	XA_STATE(xas, &mapping->i_pages, start);
809 	struct page *page;
810 	unsigned long swapped = 0;
811 
812 	rcu_read_lock();
813 	xas_for_each(&xas, page, end - 1) {
814 		if (xas_retry(&xas, page))
815 			continue;
816 		if (xa_is_value(page))
817 			swapped++;
818 
819 		if (need_resched()) {
820 			xas_pause(&xas);
821 			cond_resched_rcu();
822 		}
823 	}
824 
825 	rcu_read_unlock();
826 
827 	return swapped << PAGE_SHIFT;
828 }
829 
830 /*
831  * Determine (in bytes) how many of the shmem object's pages mapped by the
832  * given vma is swapped out.
833  *
834  * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
835  * as long as the inode doesn't go away and racy results are not a problem.
836  */
837 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
838 {
839 	struct inode *inode = file_inode(vma->vm_file);
840 	struct shmem_inode_info *info = SHMEM_I(inode);
841 	struct address_space *mapping = inode->i_mapping;
842 	unsigned long swapped;
843 
844 	/* Be careful as we don't hold info->lock */
845 	swapped = READ_ONCE(info->swapped);
846 
847 	/*
848 	 * The easier cases are when the shmem object has nothing in swap, or
849 	 * the vma maps it whole. Then we can simply use the stats that we
850 	 * already track.
851 	 */
852 	if (!swapped)
853 		return 0;
854 
855 	if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
856 		return swapped << PAGE_SHIFT;
857 
858 	/* Here comes the more involved part */
859 	return shmem_partial_swap_usage(mapping, vma->vm_pgoff,
860 					vma->vm_pgoff + vma_pages(vma));
861 }
862 
863 /*
864  * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
865  */
866 void shmem_unlock_mapping(struct address_space *mapping)
867 {
868 	struct folio_batch fbatch;
869 	pgoff_t index = 0;
870 
871 	folio_batch_init(&fbatch);
872 	/*
873 	 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
874 	 */
875 	while (!mapping_unevictable(mapping) &&
876 	       filemap_get_folios(mapping, &index, ~0UL, &fbatch)) {
877 		check_move_unevictable_folios(&fbatch);
878 		folio_batch_release(&fbatch);
879 		cond_resched();
880 	}
881 }
882 
883 static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
884 {
885 	struct folio *folio;
886 
887 	/*
888 	 * At first avoid shmem_get_folio(,,,SGP_READ): that fails
889 	 * beyond i_size, and reports fallocated pages as holes.
890 	 */
891 	folio = __filemap_get_folio(inode->i_mapping, index,
892 					FGP_ENTRY | FGP_LOCK, 0);
893 	if (!xa_is_value(folio))
894 		return folio;
895 	/*
896 	 * But read a page back from swap if any of it is within i_size
897 	 * (although in some cases this is just a waste of time).
898 	 */
899 	folio = NULL;
900 	shmem_get_folio(inode, index, &folio, SGP_READ);
901 	return folio;
902 }
903 
904 /*
905  * Remove range of pages and swap entries from page cache, and free them.
906  * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
907  */
908 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
909 								 bool unfalloc)
910 {
911 	struct address_space *mapping = inode->i_mapping;
912 	struct shmem_inode_info *info = SHMEM_I(inode);
913 	pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
914 	pgoff_t end = (lend + 1) >> PAGE_SHIFT;
915 	struct folio_batch fbatch;
916 	pgoff_t indices[PAGEVEC_SIZE];
917 	struct folio *folio;
918 	bool same_folio;
919 	long nr_swaps_freed = 0;
920 	pgoff_t index;
921 	int i;
922 
923 	if (lend == -1)
924 		end = -1;	/* unsigned, so actually very big */
925 
926 	if (info->fallocend > start && info->fallocend <= end && !unfalloc)
927 		info->fallocend = start;
928 
929 	folio_batch_init(&fbatch);
930 	index = start;
931 	while (index < end && find_lock_entries(mapping, &index, end - 1,
932 			&fbatch, indices)) {
933 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
934 			folio = fbatch.folios[i];
935 
936 			if (xa_is_value(folio)) {
937 				if (unfalloc)
938 					continue;
939 				nr_swaps_freed += !shmem_free_swap(mapping,
940 							indices[i], folio);
941 				continue;
942 			}
943 
944 			if (!unfalloc || !folio_test_uptodate(folio))
945 				truncate_inode_folio(mapping, folio);
946 			folio_unlock(folio);
947 		}
948 		folio_batch_remove_exceptionals(&fbatch);
949 		folio_batch_release(&fbatch);
950 		cond_resched();
951 	}
952 
953 	same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
954 	folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT);
955 	if (folio) {
956 		same_folio = lend < folio_pos(folio) + folio_size(folio);
957 		folio_mark_dirty(folio);
958 		if (!truncate_inode_partial_folio(folio, lstart, lend)) {
959 			start = folio->index + folio_nr_pages(folio);
960 			if (same_folio)
961 				end = folio->index;
962 		}
963 		folio_unlock(folio);
964 		folio_put(folio);
965 		folio = NULL;
966 	}
967 
968 	if (!same_folio)
969 		folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT);
970 	if (folio) {
971 		folio_mark_dirty(folio);
972 		if (!truncate_inode_partial_folio(folio, lstart, lend))
973 			end = folio->index;
974 		folio_unlock(folio);
975 		folio_put(folio);
976 	}
977 
978 	index = start;
979 	while (index < end) {
980 		cond_resched();
981 
982 		if (!find_get_entries(mapping, &index, end - 1, &fbatch,
983 				indices)) {
984 			/* If all gone or hole-punch or unfalloc, we're done */
985 			if (index == start || end != -1)
986 				break;
987 			/* But if truncating, restart to make sure all gone */
988 			index = start;
989 			continue;
990 		}
991 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
992 			folio = fbatch.folios[i];
993 
994 			if (xa_is_value(folio)) {
995 				if (unfalloc)
996 					continue;
997 				if (shmem_free_swap(mapping, indices[i], folio)) {
998 					/* Swap was replaced by page: retry */
999 					index = indices[i];
1000 					break;
1001 				}
1002 				nr_swaps_freed++;
1003 				continue;
1004 			}
1005 
1006 			folio_lock(folio);
1007 
1008 			if (!unfalloc || !folio_test_uptodate(folio)) {
1009 				if (folio_mapping(folio) != mapping) {
1010 					/* Page was replaced by swap: retry */
1011 					folio_unlock(folio);
1012 					index = indices[i];
1013 					break;
1014 				}
1015 				VM_BUG_ON_FOLIO(folio_test_writeback(folio),
1016 						folio);
1017 				truncate_inode_folio(mapping, folio);
1018 			}
1019 			folio_unlock(folio);
1020 		}
1021 		folio_batch_remove_exceptionals(&fbatch);
1022 		folio_batch_release(&fbatch);
1023 	}
1024 
1025 	spin_lock_irq(&info->lock);
1026 	info->swapped -= nr_swaps_freed;
1027 	shmem_recalc_inode(inode);
1028 	spin_unlock_irq(&info->lock);
1029 }
1030 
1031 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
1032 {
1033 	shmem_undo_range(inode, lstart, lend, false);
1034 	inode->i_ctime = inode->i_mtime = current_time(inode);
1035 	inode_inc_iversion(inode);
1036 }
1037 EXPORT_SYMBOL_GPL(shmem_truncate_range);
1038 
1039 static int shmem_getattr(struct user_namespace *mnt_userns,
1040 			 const struct path *path, struct kstat *stat,
1041 			 u32 request_mask, unsigned int query_flags)
1042 {
1043 	struct inode *inode = path->dentry->d_inode;
1044 	struct shmem_inode_info *info = SHMEM_I(inode);
1045 
1046 	if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
1047 		spin_lock_irq(&info->lock);
1048 		shmem_recalc_inode(inode);
1049 		spin_unlock_irq(&info->lock);
1050 	}
1051 	if (info->fsflags & FS_APPEND_FL)
1052 		stat->attributes |= STATX_ATTR_APPEND;
1053 	if (info->fsflags & FS_IMMUTABLE_FL)
1054 		stat->attributes |= STATX_ATTR_IMMUTABLE;
1055 	if (info->fsflags & FS_NODUMP_FL)
1056 		stat->attributes |= STATX_ATTR_NODUMP;
1057 	stat->attributes_mask |= (STATX_ATTR_APPEND |
1058 			STATX_ATTR_IMMUTABLE |
1059 			STATX_ATTR_NODUMP);
1060 	generic_fillattr(&init_user_ns, inode, stat);
1061 
1062 	if (shmem_is_huge(NULL, inode, 0, false))
1063 		stat->blksize = HPAGE_PMD_SIZE;
1064 
1065 	if (request_mask & STATX_BTIME) {
1066 		stat->result_mask |= STATX_BTIME;
1067 		stat->btime.tv_sec = info->i_crtime.tv_sec;
1068 		stat->btime.tv_nsec = info->i_crtime.tv_nsec;
1069 	}
1070 
1071 	return 0;
1072 }
1073 
1074 static int shmem_setattr(struct user_namespace *mnt_userns,
1075 			 struct dentry *dentry, struct iattr *attr)
1076 {
1077 	struct inode *inode = d_inode(dentry);
1078 	struct shmem_inode_info *info = SHMEM_I(inode);
1079 	int error;
1080 	bool update_mtime = false;
1081 	bool update_ctime = true;
1082 
1083 	error = setattr_prepare(&init_user_ns, dentry, attr);
1084 	if (error)
1085 		return error;
1086 
1087 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1088 		loff_t oldsize = inode->i_size;
1089 		loff_t newsize = attr->ia_size;
1090 
1091 		/* protected by i_rwsem */
1092 		if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1093 		    (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1094 			return -EPERM;
1095 
1096 		if (newsize != oldsize) {
1097 			error = shmem_reacct_size(SHMEM_I(inode)->flags,
1098 					oldsize, newsize);
1099 			if (error)
1100 				return error;
1101 			i_size_write(inode, newsize);
1102 			update_mtime = true;
1103 		} else {
1104 			update_ctime = false;
1105 		}
1106 		if (newsize <= oldsize) {
1107 			loff_t holebegin = round_up(newsize, PAGE_SIZE);
1108 			if (oldsize > holebegin)
1109 				unmap_mapping_range(inode->i_mapping,
1110 							holebegin, 0, 1);
1111 			if (info->alloced)
1112 				shmem_truncate_range(inode,
1113 							newsize, (loff_t)-1);
1114 			/* unmap again to remove racily COWed private pages */
1115 			if (oldsize > holebegin)
1116 				unmap_mapping_range(inode->i_mapping,
1117 							holebegin, 0, 1);
1118 		}
1119 	}
1120 
1121 	setattr_copy(&init_user_ns, inode, attr);
1122 	if (attr->ia_valid & ATTR_MODE)
1123 		error = posix_acl_chmod(&init_user_ns, inode, inode->i_mode);
1124 	if (!error && update_ctime) {
1125 		inode->i_ctime = current_time(inode);
1126 		if (update_mtime)
1127 			inode->i_mtime = inode->i_ctime;
1128 		inode_inc_iversion(inode);
1129 	}
1130 	return error;
1131 }
1132 
1133 static void shmem_evict_inode(struct inode *inode)
1134 {
1135 	struct shmem_inode_info *info = SHMEM_I(inode);
1136 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1137 
1138 	if (shmem_mapping(inode->i_mapping)) {
1139 		shmem_unacct_size(info->flags, inode->i_size);
1140 		inode->i_size = 0;
1141 		mapping_set_exiting(inode->i_mapping);
1142 		shmem_truncate_range(inode, 0, (loff_t)-1);
1143 		if (!list_empty(&info->shrinklist)) {
1144 			spin_lock(&sbinfo->shrinklist_lock);
1145 			if (!list_empty(&info->shrinklist)) {
1146 				list_del_init(&info->shrinklist);
1147 				sbinfo->shrinklist_len--;
1148 			}
1149 			spin_unlock(&sbinfo->shrinklist_lock);
1150 		}
1151 		while (!list_empty(&info->swaplist)) {
1152 			/* Wait while shmem_unuse() is scanning this inode... */
1153 			wait_var_event(&info->stop_eviction,
1154 				       !atomic_read(&info->stop_eviction));
1155 			mutex_lock(&shmem_swaplist_mutex);
1156 			/* ...but beware of the race if we peeked too early */
1157 			if (!atomic_read(&info->stop_eviction))
1158 				list_del_init(&info->swaplist);
1159 			mutex_unlock(&shmem_swaplist_mutex);
1160 		}
1161 	}
1162 
1163 	simple_xattrs_free(&info->xattrs);
1164 	WARN_ON(inode->i_blocks);
1165 	shmem_free_inode(inode->i_sb);
1166 	clear_inode(inode);
1167 }
1168 
1169 static int shmem_find_swap_entries(struct address_space *mapping,
1170 				   pgoff_t start, struct folio_batch *fbatch,
1171 				   pgoff_t *indices, unsigned int type)
1172 {
1173 	XA_STATE(xas, &mapping->i_pages, start);
1174 	struct folio *folio;
1175 	swp_entry_t entry;
1176 
1177 	rcu_read_lock();
1178 	xas_for_each(&xas, folio, ULONG_MAX) {
1179 		if (xas_retry(&xas, folio))
1180 			continue;
1181 
1182 		if (!xa_is_value(folio))
1183 			continue;
1184 
1185 		entry = radix_to_swp_entry(folio);
1186 		/*
1187 		 * swapin error entries can be found in the mapping. But they're
1188 		 * deliberately ignored here as we've done everything we can do.
1189 		 */
1190 		if (swp_type(entry) != type)
1191 			continue;
1192 
1193 		indices[folio_batch_count(fbatch)] = xas.xa_index;
1194 		if (!folio_batch_add(fbatch, folio))
1195 			break;
1196 
1197 		if (need_resched()) {
1198 			xas_pause(&xas);
1199 			cond_resched_rcu();
1200 		}
1201 	}
1202 	rcu_read_unlock();
1203 
1204 	return xas.xa_index;
1205 }
1206 
1207 /*
1208  * Move the swapped pages for an inode to page cache. Returns the count
1209  * of pages swapped in, or the error in case of failure.
1210  */
1211 static int shmem_unuse_swap_entries(struct inode *inode,
1212 		struct folio_batch *fbatch, pgoff_t *indices)
1213 {
1214 	int i = 0;
1215 	int ret = 0;
1216 	int error = 0;
1217 	struct address_space *mapping = inode->i_mapping;
1218 
1219 	for (i = 0; i < folio_batch_count(fbatch); i++) {
1220 		struct folio *folio = fbatch->folios[i];
1221 
1222 		if (!xa_is_value(folio))
1223 			continue;
1224 		error = shmem_swapin_folio(inode, indices[i],
1225 					  &folio, SGP_CACHE,
1226 					  mapping_gfp_mask(mapping),
1227 					  NULL, NULL);
1228 		if (error == 0) {
1229 			folio_unlock(folio);
1230 			folio_put(folio);
1231 			ret++;
1232 		}
1233 		if (error == -ENOMEM)
1234 			break;
1235 		error = 0;
1236 	}
1237 	return error ? error : ret;
1238 }
1239 
1240 /*
1241  * If swap found in inode, free it and move page from swapcache to filecache.
1242  */
1243 static int shmem_unuse_inode(struct inode *inode, unsigned int type)
1244 {
1245 	struct address_space *mapping = inode->i_mapping;
1246 	pgoff_t start = 0;
1247 	struct folio_batch fbatch;
1248 	pgoff_t indices[PAGEVEC_SIZE];
1249 	int ret = 0;
1250 
1251 	do {
1252 		folio_batch_init(&fbatch);
1253 		shmem_find_swap_entries(mapping, start, &fbatch, indices, type);
1254 		if (folio_batch_count(&fbatch) == 0) {
1255 			ret = 0;
1256 			break;
1257 		}
1258 
1259 		ret = shmem_unuse_swap_entries(inode, &fbatch, indices);
1260 		if (ret < 0)
1261 			break;
1262 
1263 		start = indices[folio_batch_count(&fbatch) - 1];
1264 	} while (true);
1265 
1266 	return ret;
1267 }
1268 
1269 /*
1270  * Read all the shared memory data that resides in the swap
1271  * device 'type' back into memory, so the swap device can be
1272  * unused.
1273  */
1274 int shmem_unuse(unsigned int type)
1275 {
1276 	struct shmem_inode_info *info, *next;
1277 	int error = 0;
1278 
1279 	if (list_empty(&shmem_swaplist))
1280 		return 0;
1281 
1282 	mutex_lock(&shmem_swaplist_mutex);
1283 	list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1284 		if (!info->swapped) {
1285 			list_del_init(&info->swaplist);
1286 			continue;
1287 		}
1288 		/*
1289 		 * Drop the swaplist mutex while searching the inode for swap;
1290 		 * but before doing so, make sure shmem_evict_inode() will not
1291 		 * remove placeholder inode from swaplist, nor let it be freed
1292 		 * (igrab() would protect from unlink, but not from unmount).
1293 		 */
1294 		atomic_inc(&info->stop_eviction);
1295 		mutex_unlock(&shmem_swaplist_mutex);
1296 
1297 		error = shmem_unuse_inode(&info->vfs_inode, type);
1298 		cond_resched();
1299 
1300 		mutex_lock(&shmem_swaplist_mutex);
1301 		next = list_next_entry(info, swaplist);
1302 		if (!info->swapped)
1303 			list_del_init(&info->swaplist);
1304 		if (atomic_dec_and_test(&info->stop_eviction))
1305 			wake_up_var(&info->stop_eviction);
1306 		if (error)
1307 			break;
1308 	}
1309 	mutex_unlock(&shmem_swaplist_mutex);
1310 
1311 	return error;
1312 }
1313 
1314 /*
1315  * Move the page from the page cache to the swap cache.
1316  */
1317 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1318 {
1319 	struct folio *folio = page_folio(page);
1320 	struct shmem_inode_info *info;
1321 	struct address_space *mapping;
1322 	struct inode *inode;
1323 	swp_entry_t swap;
1324 	pgoff_t index;
1325 
1326 	/*
1327 	 * If /sys/kernel/mm/transparent_hugepage/shmem_enabled is "always" or
1328 	 * "force", drivers/gpu/drm/i915/gem/i915_gem_shmem.c gets huge pages,
1329 	 * and its shmem_writeback() needs them to be split when swapping.
1330 	 */
1331 	if (folio_test_large(folio)) {
1332 		/* Ensure the subpages are still dirty */
1333 		folio_test_set_dirty(folio);
1334 		if (split_huge_page(page) < 0)
1335 			goto redirty;
1336 		folio = page_folio(page);
1337 		folio_clear_dirty(folio);
1338 	}
1339 
1340 	BUG_ON(!folio_test_locked(folio));
1341 	mapping = folio->mapping;
1342 	index = folio->index;
1343 	inode = mapping->host;
1344 	info = SHMEM_I(inode);
1345 	if (info->flags & VM_LOCKED)
1346 		goto redirty;
1347 	if (!total_swap_pages)
1348 		goto redirty;
1349 
1350 	/*
1351 	 * Our capabilities prevent regular writeback or sync from ever calling
1352 	 * shmem_writepage; but a stacking filesystem might use ->writepage of
1353 	 * its underlying filesystem, in which case tmpfs should write out to
1354 	 * swap only in response to memory pressure, and not for the writeback
1355 	 * threads or sync.
1356 	 */
1357 	if (!wbc->for_reclaim) {
1358 		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
1359 		goto redirty;
1360 	}
1361 
1362 	/*
1363 	 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1364 	 * value into swapfile.c, the only way we can correctly account for a
1365 	 * fallocated folio arriving here is now to initialize it and write it.
1366 	 *
1367 	 * That's okay for a folio already fallocated earlier, but if we have
1368 	 * not yet completed the fallocation, then (a) we want to keep track
1369 	 * of this folio in case we have to undo it, and (b) it may not be a
1370 	 * good idea to continue anyway, once we're pushing into swap.  So
1371 	 * reactivate the folio, and let shmem_fallocate() quit when too many.
1372 	 */
1373 	if (!folio_test_uptodate(folio)) {
1374 		if (inode->i_private) {
1375 			struct shmem_falloc *shmem_falloc;
1376 			spin_lock(&inode->i_lock);
1377 			shmem_falloc = inode->i_private;
1378 			if (shmem_falloc &&
1379 			    !shmem_falloc->waitq &&
1380 			    index >= shmem_falloc->start &&
1381 			    index < shmem_falloc->next)
1382 				shmem_falloc->nr_unswapped++;
1383 			else
1384 				shmem_falloc = NULL;
1385 			spin_unlock(&inode->i_lock);
1386 			if (shmem_falloc)
1387 				goto redirty;
1388 		}
1389 		folio_zero_range(folio, 0, folio_size(folio));
1390 		flush_dcache_folio(folio);
1391 		folio_mark_uptodate(folio);
1392 	}
1393 
1394 	swap = folio_alloc_swap(folio);
1395 	if (!swap.val)
1396 		goto redirty;
1397 
1398 	/*
1399 	 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1400 	 * if it's not already there.  Do it now before the folio is
1401 	 * moved to swap cache, when its pagelock no longer protects
1402 	 * the inode from eviction.  But don't unlock the mutex until
1403 	 * we've incremented swapped, because shmem_unuse_inode() will
1404 	 * prune a !swapped inode from the swaplist under this mutex.
1405 	 */
1406 	mutex_lock(&shmem_swaplist_mutex);
1407 	if (list_empty(&info->swaplist))
1408 		list_add(&info->swaplist, &shmem_swaplist);
1409 
1410 	if (add_to_swap_cache(folio, swap,
1411 			__GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN,
1412 			NULL) == 0) {
1413 		spin_lock_irq(&info->lock);
1414 		shmem_recalc_inode(inode);
1415 		info->swapped++;
1416 		spin_unlock_irq(&info->lock);
1417 
1418 		swap_shmem_alloc(swap);
1419 		shmem_delete_from_page_cache(folio, swp_to_radix_entry(swap));
1420 
1421 		mutex_unlock(&shmem_swaplist_mutex);
1422 		BUG_ON(folio_mapped(folio));
1423 		swap_writepage(&folio->page, wbc);
1424 		return 0;
1425 	}
1426 
1427 	mutex_unlock(&shmem_swaplist_mutex);
1428 	put_swap_folio(folio, swap);
1429 redirty:
1430 	folio_mark_dirty(folio);
1431 	if (wbc->for_reclaim)
1432 		return AOP_WRITEPAGE_ACTIVATE;	/* Return with folio locked */
1433 	folio_unlock(folio);
1434 	return 0;
1435 }
1436 
1437 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1438 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1439 {
1440 	char buffer[64];
1441 
1442 	if (!mpol || mpol->mode == MPOL_DEFAULT)
1443 		return;		/* show nothing */
1444 
1445 	mpol_to_str(buffer, sizeof(buffer), mpol);
1446 
1447 	seq_printf(seq, ",mpol=%s", buffer);
1448 }
1449 
1450 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1451 {
1452 	struct mempolicy *mpol = NULL;
1453 	if (sbinfo->mpol) {
1454 		raw_spin_lock(&sbinfo->stat_lock);	/* prevent replace/use races */
1455 		mpol = sbinfo->mpol;
1456 		mpol_get(mpol);
1457 		raw_spin_unlock(&sbinfo->stat_lock);
1458 	}
1459 	return mpol;
1460 }
1461 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1462 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1463 {
1464 }
1465 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1466 {
1467 	return NULL;
1468 }
1469 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1470 #ifndef CONFIG_NUMA
1471 #define vm_policy vm_private_data
1472 #endif
1473 
1474 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1475 		struct shmem_inode_info *info, pgoff_t index)
1476 {
1477 	/* Create a pseudo vma that just contains the policy */
1478 	vma_init(vma, NULL);
1479 	/* Bias interleave by inode number to distribute better across nodes */
1480 	vma->vm_pgoff = index + info->vfs_inode.i_ino;
1481 	vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1482 }
1483 
1484 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1485 {
1486 	/* Drop reference taken by mpol_shared_policy_lookup() */
1487 	mpol_cond_put(vma->vm_policy);
1488 }
1489 
1490 static struct folio *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1491 			struct shmem_inode_info *info, pgoff_t index)
1492 {
1493 	struct vm_area_struct pvma;
1494 	struct page *page;
1495 	struct vm_fault vmf = {
1496 		.vma = &pvma,
1497 	};
1498 
1499 	shmem_pseudo_vma_init(&pvma, info, index);
1500 	page = swap_cluster_readahead(swap, gfp, &vmf);
1501 	shmem_pseudo_vma_destroy(&pvma);
1502 
1503 	if (!page)
1504 		return NULL;
1505 	return page_folio(page);
1506 }
1507 
1508 /*
1509  * Make sure huge_gfp is always more limited than limit_gfp.
1510  * Some of the flags set permissions, while others set limitations.
1511  */
1512 static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
1513 {
1514 	gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
1515 	gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
1516 	gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
1517 	gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
1518 
1519 	/* Allow allocations only from the originally specified zones. */
1520 	result |= zoneflags;
1521 
1522 	/*
1523 	 * Minimize the result gfp by taking the union with the deny flags,
1524 	 * and the intersection of the allow flags.
1525 	 */
1526 	result |= (limit_gfp & denyflags);
1527 	result |= (huge_gfp & limit_gfp) & allowflags;
1528 
1529 	return result;
1530 }
1531 
1532 static struct folio *shmem_alloc_hugefolio(gfp_t gfp,
1533 		struct shmem_inode_info *info, pgoff_t index)
1534 {
1535 	struct vm_area_struct pvma;
1536 	struct address_space *mapping = info->vfs_inode.i_mapping;
1537 	pgoff_t hindex;
1538 	struct folio *folio;
1539 
1540 	hindex = round_down(index, HPAGE_PMD_NR);
1541 	if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
1542 								XA_PRESENT))
1543 		return NULL;
1544 
1545 	shmem_pseudo_vma_init(&pvma, info, hindex);
1546 	folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, &pvma, 0, true);
1547 	shmem_pseudo_vma_destroy(&pvma);
1548 	if (!folio)
1549 		count_vm_event(THP_FILE_FALLBACK);
1550 	return folio;
1551 }
1552 
1553 static struct folio *shmem_alloc_folio(gfp_t gfp,
1554 			struct shmem_inode_info *info, pgoff_t index)
1555 {
1556 	struct vm_area_struct pvma;
1557 	struct folio *folio;
1558 
1559 	shmem_pseudo_vma_init(&pvma, info, index);
1560 	folio = vma_alloc_folio(gfp, 0, &pvma, 0, false);
1561 	shmem_pseudo_vma_destroy(&pvma);
1562 
1563 	return folio;
1564 }
1565 
1566 static struct folio *shmem_alloc_and_acct_folio(gfp_t gfp, struct inode *inode,
1567 		pgoff_t index, bool huge)
1568 {
1569 	struct shmem_inode_info *info = SHMEM_I(inode);
1570 	struct folio *folio;
1571 	int nr;
1572 	int err = -ENOSPC;
1573 
1574 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1575 		huge = false;
1576 	nr = huge ? HPAGE_PMD_NR : 1;
1577 
1578 	if (!shmem_inode_acct_block(inode, nr))
1579 		goto failed;
1580 
1581 	if (huge)
1582 		folio = shmem_alloc_hugefolio(gfp, info, index);
1583 	else
1584 		folio = shmem_alloc_folio(gfp, info, index);
1585 	if (folio) {
1586 		__folio_set_locked(folio);
1587 		__folio_set_swapbacked(folio);
1588 		return folio;
1589 	}
1590 
1591 	err = -ENOMEM;
1592 	shmem_inode_unacct_blocks(inode, nr);
1593 failed:
1594 	return ERR_PTR(err);
1595 }
1596 
1597 /*
1598  * When a page is moved from swapcache to shmem filecache (either by the
1599  * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
1600  * shmem_unuse_inode()), it may have been read in earlier from swap, in
1601  * ignorance of the mapping it belongs to.  If that mapping has special
1602  * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1603  * we may need to copy to a suitable page before moving to filecache.
1604  *
1605  * In a future release, this may well be extended to respect cpuset and
1606  * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1607  * but for now it is a simple matter of zone.
1608  */
1609 static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp)
1610 {
1611 	return folio_zonenum(folio) > gfp_zone(gfp);
1612 }
1613 
1614 static int shmem_replace_folio(struct folio **foliop, gfp_t gfp,
1615 				struct shmem_inode_info *info, pgoff_t index)
1616 {
1617 	struct folio *old, *new;
1618 	struct address_space *swap_mapping;
1619 	swp_entry_t entry;
1620 	pgoff_t swap_index;
1621 	int error;
1622 
1623 	old = *foliop;
1624 	entry = folio_swap_entry(old);
1625 	swap_index = swp_offset(entry);
1626 	swap_mapping = swap_address_space(entry);
1627 
1628 	/*
1629 	 * We have arrived here because our zones are constrained, so don't
1630 	 * limit chance of success by further cpuset and node constraints.
1631 	 */
1632 	gfp &= ~GFP_CONSTRAINT_MASK;
1633 	VM_BUG_ON_FOLIO(folio_test_large(old), old);
1634 	new = shmem_alloc_folio(gfp, info, index);
1635 	if (!new)
1636 		return -ENOMEM;
1637 
1638 	folio_get(new);
1639 	folio_copy(new, old);
1640 	flush_dcache_folio(new);
1641 
1642 	__folio_set_locked(new);
1643 	__folio_set_swapbacked(new);
1644 	folio_mark_uptodate(new);
1645 	folio_set_swap_entry(new, entry);
1646 	folio_set_swapcache(new);
1647 
1648 	/*
1649 	 * Our caller will very soon move newpage out of swapcache, but it's
1650 	 * a nice clean interface for us to replace oldpage by newpage there.
1651 	 */
1652 	xa_lock_irq(&swap_mapping->i_pages);
1653 	error = shmem_replace_entry(swap_mapping, swap_index, old, new);
1654 	if (!error) {
1655 		mem_cgroup_migrate(old, new);
1656 		__lruvec_stat_mod_folio(new, NR_FILE_PAGES, 1);
1657 		__lruvec_stat_mod_folio(new, NR_SHMEM, 1);
1658 		__lruvec_stat_mod_folio(old, NR_FILE_PAGES, -1);
1659 		__lruvec_stat_mod_folio(old, NR_SHMEM, -1);
1660 	}
1661 	xa_unlock_irq(&swap_mapping->i_pages);
1662 
1663 	if (unlikely(error)) {
1664 		/*
1665 		 * Is this possible?  I think not, now that our callers check
1666 		 * both PageSwapCache and page_private after getting page lock;
1667 		 * but be defensive.  Reverse old to newpage for clear and free.
1668 		 */
1669 		old = new;
1670 	} else {
1671 		folio_add_lru(new);
1672 		*foliop = new;
1673 	}
1674 
1675 	folio_clear_swapcache(old);
1676 	old->private = NULL;
1677 
1678 	folio_unlock(old);
1679 	folio_put_refs(old, 2);
1680 	return error;
1681 }
1682 
1683 static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,
1684 					 struct folio *folio, swp_entry_t swap)
1685 {
1686 	struct address_space *mapping = inode->i_mapping;
1687 	struct shmem_inode_info *info = SHMEM_I(inode);
1688 	swp_entry_t swapin_error;
1689 	void *old;
1690 
1691 	swapin_error = make_swapin_error_entry();
1692 	old = xa_cmpxchg_irq(&mapping->i_pages, index,
1693 			     swp_to_radix_entry(swap),
1694 			     swp_to_radix_entry(swapin_error), 0);
1695 	if (old != swp_to_radix_entry(swap))
1696 		return;
1697 
1698 	folio_wait_writeback(folio);
1699 	delete_from_swap_cache(folio);
1700 	spin_lock_irq(&info->lock);
1701 	/*
1702 	 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks won't
1703 	 * be 0 when inode is released and thus trigger WARN_ON(inode->i_blocks) in
1704 	 * shmem_evict_inode.
1705 	 */
1706 	info->alloced--;
1707 	info->swapped--;
1708 	shmem_recalc_inode(inode);
1709 	spin_unlock_irq(&info->lock);
1710 	swap_free(swap);
1711 }
1712 
1713 /*
1714  * Swap in the folio pointed to by *foliop.
1715  * Caller has to make sure that *foliop contains a valid swapped folio.
1716  * Returns 0 and the folio in foliop if success. On failure, returns the
1717  * error code and NULL in *foliop.
1718  */
1719 static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
1720 			     struct folio **foliop, enum sgp_type sgp,
1721 			     gfp_t gfp, struct vm_area_struct *vma,
1722 			     vm_fault_t *fault_type)
1723 {
1724 	struct address_space *mapping = inode->i_mapping;
1725 	struct shmem_inode_info *info = SHMEM_I(inode);
1726 	struct mm_struct *charge_mm = vma ? vma->vm_mm : NULL;
1727 	struct folio *folio = NULL;
1728 	swp_entry_t swap;
1729 	int error;
1730 
1731 	VM_BUG_ON(!*foliop || !xa_is_value(*foliop));
1732 	swap = radix_to_swp_entry(*foliop);
1733 	*foliop = NULL;
1734 
1735 	if (is_swapin_error_entry(swap))
1736 		return -EIO;
1737 
1738 	/* Look it up and read it in.. */
1739 	folio = swap_cache_get_folio(swap, NULL, 0);
1740 	if (!folio) {
1741 		/* Or update major stats only when swapin succeeds?? */
1742 		if (fault_type) {
1743 			*fault_type |= VM_FAULT_MAJOR;
1744 			count_vm_event(PGMAJFAULT);
1745 			count_memcg_event_mm(charge_mm, PGMAJFAULT);
1746 		}
1747 		/* Here we actually start the io */
1748 		folio = shmem_swapin(swap, gfp, info, index);
1749 		if (!folio) {
1750 			error = -ENOMEM;
1751 			goto failed;
1752 		}
1753 	}
1754 
1755 	/* We have to do this with folio locked to prevent races */
1756 	folio_lock(folio);
1757 	if (!folio_test_swapcache(folio) ||
1758 	    folio_swap_entry(folio).val != swap.val ||
1759 	    !shmem_confirm_swap(mapping, index, swap)) {
1760 		error = -EEXIST;
1761 		goto unlock;
1762 	}
1763 	if (!folio_test_uptodate(folio)) {
1764 		error = -EIO;
1765 		goto failed;
1766 	}
1767 	folio_wait_writeback(folio);
1768 
1769 	/*
1770 	 * Some architectures may have to restore extra metadata to the
1771 	 * folio after reading from swap.
1772 	 */
1773 	arch_swap_restore(swap, folio);
1774 
1775 	if (shmem_should_replace_folio(folio, gfp)) {
1776 		error = shmem_replace_folio(&folio, gfp, info, index);
1777 		if (error)
1778 			goto failed;
1779 	}
1780 
1781 	error = shmem_add_to_page_cache(folio, mapping, index,
1782 					swp_to_radix_entry(swap), gfp,
1783 					charge_mm);
1784 	if (error)
1785 		goto failed;
1786 
1787 	spin_lock_irq(&info->lock);
1788 	info->swapped--;
1789 	shmem_recalc_inode(inode);
1790 	spin_unlock_irq(&info->lock);
1791 
1792 	if (sgp == SGP_WRITE)
1793 		folio_mark_accessed(folio);
1794 
1795 	delete_from_swap_cache(folio);
1796 	folio_mark_dirty(folio);
1797 	swap_free(swap);
1798 
1799 	*foliop = folio;
1800 	return 0;
1801 failed:
1802 	if (!shmem_confirm_swap(mapping, index, swap))
1803 		error = -EEXIST;
1804 	if (error == -EIO)
1805 		shmem_set_folio_swapin_error(inode, index, folio, swap);
1806 unlock:
1807 	if (folio) {
1808 		folio_unlock(folio);
1809 		folio_put(folio);
1810 	}
1811 
1812 	return error;
1813 }
1814 
1815 /*
1816  * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
1817  *
1818  * If we allocate a new one we do not mark it dirty. That's up to the
1819  * vm. If we swap it in we mark it dirty since we also free the swap
1820  * entry since a page cannot live in both the swap and page cache.
1821  *
1822  * vma, vmf, and fault_type are only supplied by shmem_fault:
1823  * otherwise they are NULL.
1824  */
1825 static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index,
1826 		struct folio **foliop, enum sgp_type sgp, gfp_t gfp,
1827 		struct vm_area_struct *vma, struct vm_fault *vmf,
1828 		vm_fault_t *fault_type)
1829 {
1830 	struct address_space *mapping = inode->i_mapping;
1831 	struct shmem_inode_info *info = SHMEM_I(inode);
1832 	struct shmem_sb_info *sbinfo;
1833 	struct mm_struct *charge_mm;
1834 	struct folio *folio;
1835 	pgoff_t hindex;
1836 	gfp_t huge_gfp;
1837 	int error;
1838 	int once = 0;
1839 	int alloced = 0;
1840 
1841 	if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1842 		return -EFBIG;
1843 repeat:
1844 	if (sgp <= SGP_CACHE &&
1845 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1846 		return -EINVAL;
1847 	}
1848 
1849 	sbinfo = SHMEM_SB(inode->i_sb);
1850 	charge_mm = vma ? vma->vm_mm : NULL;
1851 
1852 	folio = __filemap_get_folio(mapping, index, FGP_ENTRY | FGP_LOCK, 0);
1853 	if (folio && vma && userfaultfd_minor(vma)) {
1854 		if (!xa_is_value(folio)) {
1855 			folio_unlock(folio);
1856 			folio_put(folio);
1857 		}
1858 		*fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
1859 		return 0;
1860 	}
1861 
1862 	if (xa_is_value(folio)) {
1863 		error = shmem_swapin_folio(inode, index, &folio,
1864 					  sgp, gfp, vma, fault_type);
1865 		if (error == -EEXIST)
1866 			goto repeat;
1867 
1868 		*foliop = folio;
1869 		return error;
1870 	}
1871 
1872 	if (folio) {
1873 		if (sgp == SGP_WRITE)
1874 			folio_mark_accessed(folio);
1875 		if (folio_test_uptodate(folio))
1876 			goto out;
1877 		/* fallocated folio */
1878 		if (sgp != SGP_READ)
1879 			goto clear;
1880 		folio_unlock(folio);
1881 		folio_put(folio);
1882 	}
1883 
1884 	/*
1885 	 * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
1886 	 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
1887 	 */
1888 	*foliop = NULL;
1889 	if (sgp == SGP_READ)
1890 		return 0;
1891 	if (sgp == SGP_NOALLOC)
1892 		return -ENOENT;
1893 
1894 	/*
1895 	 * Fast cache lookup and swap lookup did not find it: allocate.
1896 	 */
1897 
1898 	if (vma && userfaultfd_missing(vma)) {
1899 		*fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1900 		return 0;
1901 	}
1902 
1903 	if (!shmem_is_huge(vma, inode, index, false))
1904 		goto alloc_nohuge;
1905 
1906 	huge_gfp = vma_thp_gfp_mask(vma);
1907 	huge_gfp = limit_gfp_mask(huge_gfp, gfp);
1908 	folio = shmem_alloc_and_acct_folio(huge_gfp, inode, index, true);
1909 	if (IS_ERR(folio)) {
1910 alloc_nohuge:
1911 		folio = shmem_alloc_and_acct_folio(gfp, inode, index, false);
1912 	}
1913 	if (IS_ERR(folio)) {
1914 		int retry = 5;
1915 
1916 		error = PTR_ERR(folio);
1917 		folio = NULL;
1918 		if (error != -ENOSPC)
1919 			goto unlock;
1920 		/*
1921 		 * Try to reclaim some space by splitting a large folio
1922 		 * beyond i_size on the filesystem.
1923 		 */
1924 		while (retry--) {
1925 			int ret;
1926 
1927 			ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1928 			if (ret == SHRINK_STOP)
1929 				break;
1930 			if (ret)
1931 				goto alloc_nohuge;
1932 		}
1933 		goto unlock;
1934 	}
1935 
1936 	hindex = round_down(index, folio_nr_pages(folio));
1937 
1938 	if (sgp == SGP_WRITE)
1939 		__folio_set_referenced(folio);
1940 
1941 	error = shmem_add_to_page_cache(folio, mapping, hindex,
1942 					NULL, gfp & GFP_RECLAIM_MASK,
1943 					charge_mm);
1944 	if (error)
1945 		goto unacct;
1946 	folio_add_lru(folio);
1947 
1948 	spin_lock_irq(&info->lock);
1949 	info->alloced += folio_nr_pages(folio);
1950 	inode->i_blocks += (blkcnt_t)BLOCKS_PER_PAGE << folio_order(folio);
1951 	shmem_recalc_inode(inode);
1952 	spin_unlock_irq(&info->lock);
1953 	alloced = true;
1954 
1955 	if (folio_test_pmd_mappable(folio) &&
1956 	    DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1957 					folio_next_index(folio) - 1) {
1958 		/*
1959 		 * Part of the large folio is beyond i_size: subject
1960 		 * to shrink under memory pressure.
1961 		 */
1962 		spin_lock(&sbinfo->shrinklist_lock);
1963 		/*
1964 		 * _careful to defend against unlocked access to
1965 		 * ->shrink_list in shmem_unused_huge_shrink()
1966 		 */
1967 		if (list_empty_careful(&info->shrinklist)) {
1968 			list_add_tail(&info->shrinklist,
1969 				      &sbinfo->shrinklist);
1970 			sbinfo->shrinklist_len++;
1971 		}
1972 		spin_unlock(&sbinfo->shrinklist_lock);
1973 	}
1974 
1975 	/*
1976 	 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
1977 	 */
1978 	if (sgp == SGP_FALLOC)
1979 		sgp = SGP_WRITE;
1980 clear:
1981 	/*
1982 	 * Let SGP_WRITE caller clear ends if write does not fill folio;
1983 	 * but SGP_FALLOC on a folio fallocated earlier must initialize
1984 	 * it now, lest undo on failure cancel our earlier guarantee.
1985 	 */
1986 	if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) {
1987 		long i, n = folio_nr_pages(folio);
1988 
1989 		for (i = 0; i < n; i++)
1990 			clear_highpage(folio_page(folio, i));
1991 		flush_dcache_folio(folio);
1992 		folio_mark_uptodate(folio);
1993 	}
1994 
1995 	/* Perhaps the file has been truncated since we checked */
1996 	if (sgp <= SGP_CACHE &&
1997 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1998 		if (alloced) {
1999 			folio_clear_dirty(folio);
2000 			filemap_remove_folio(folio);
2001 			spin_lock_irq(&info->lock);
2002 			shmem_recalc_inode(inode);
2003 			spin_unlock_irq(&info->lock);
2004 		}
2005 		error = -EINVAL;
2006 		goto unlock;
2007 	}
2008 out:
2009 	*foliop = folio;
2010 	return 0;
2011 
2012 	/*
2013 	 * Error recovery.
2014 	 */
2015 unacct:
2016 	shmem_inode_unacct_blocks(inode, folio_nr_pages(folio));
2017 
2018 	if (folio_test_large(folio)) {
2019 		folio_unlock(folio);
2020 		folio_put(folio);
2021 		goto alloc_nohuge;
2022 	}
2023 unlock:
2024 	if (folio) {
2025 		folio_unlock(folio);
2026 		folio_put(folio);
2027 	}
2028 	if (error == -ENOSPC && !once++) {
2029 		spin_lock_irq(&info->lock);
2030 		shmem_recalc_inode(inode);
2031 		spin_unlock_irq(&info->lock);
2032 		goto repeat;
2033 	}
2034 	if (error == -EEXIST)
2035 		goto repeat;
2036 	return error;
2037 }
2038 
2039 int shmem_get_folio(struct inode *inode, pgoff_t index, struct folio **foliop,
2040 		enum sgp_type sgp)
2041 {
2042 	return shmem_get_folio_gfp(inode, index, foliop, sgp,
2043 			mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
2044 }
2045 
2046 /*
2047  * This is like autoremove_wake_function, but it removes the wait queue
2048  * entry unconditionally - even if something else had already woken the
2049  * target.
2050  */
2051 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
2052 {
2053 	int ret = default_wake_function(wait, mode, sync, key);
2054 	list_del_init(&wait->entry);
2055 	return ret;
2056 }
2057 
2058 static vm_fault_t shmem_fault(struct vm_fault *vmf)
2059 {
2060 	struct vm_area_struct *vma = vmf->vma;
2061 	struct inode *inode = file_inode(vma->vm_file);
2062 	gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
2063 	struct folio *folio = NULL;
2064 	int err;
2065 	vm_fault_t ret = VM_FAULT_LOCKED;
2066 
2067 	/*
2068 	 * Trinity finds that probing a hole which tmpfs is punching can
2069 	 * prevent the hole-punch from ever completing: which in turn
2070 	 * locks writers out with its hold on i_rwsem.  So refrain from
2071 	 * faulting pages into the hole while it's being punched.  Although
2072 	 * shmem_undo_range() does remove the additions, it may be unable to
2073 	 * keep up, as each new page needs its own unmap_mapping_range() call,
2074 	 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2075 	 *
2076 	 * It does not matter if we sometimes reach this check just before the
2077 	 * hole-punch begins, so that one fault then races with the punch:
2078 	 * we just need to make racing faults a rare case.
2079 	 *
2080 	 * The implementation below would be much simpler if we just used a
2081 	 * standard mutex or completion: but we cannot take i_rwsem in fault,
2082 	 * and bloating every shmem inode for this unlikely case would be sad.
2083 	 */
2084 	if (unlikely(inode->i_private)) {
2085 		struct shmem_falloc *shmem_falloc;
2086 
2087 		spin_lock(&inode->i_lock);
2088 		shmem_falloc = inode->i_private;
2089 		if (shmem_falloc &&
2090 		    shmem_falloc->waitq &&
2091 		    vmf->pgoff >= shmem_falloc->start &&
2092 		    vmf->pgoff < shmem_falloc->next) {
2093 			struct file *fpin;
2094 			wait_queue_head_t *shmem_falloc_waitq;
2095 			DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
2096 
2097 			ret = VM_FAULT_NOPAGE;
2098 			fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2099 			if (fpin)
2100 				ret = VM_FAULT_RETRY;
2101 
2102 			shmem_falloc_waitq = shmem_falloc->waitq;
2103 			prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
2104 					TASK_UNINTERRUPTIBLE);
2105 			spin_unlock(&inode->i_lock);
2106 			schedule();
2107 
2108 			/*
2109 			 * shmem_falloc_waitq points into the shmem_fallocate()
2110 			 * stack of the hole-punching task: shmem_falloc_waitq
2111 			 * is usually invalid by the time we reach here, but
2112 			 * finish_wait() does not dereference it in that case;
2113 			 * though i_lock needed lest racing with wake_up_all().
2114 			 */
2115 			spin_lock(&inode->i_lock);
2116 			finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2117 			spin_unlock(&inode->i_lock);
2118 
2119 			if (fpin)
2120 				fput(fpin);
2121 			return ret;
2122 		}
2123 		spin_unlock(&inode->i_lock);
2124 	}
2125 
2126 	err = shmem_get_folio_gfp(inode, vmf->pgoff, &folio, SGP_CACHE,
2127 				  gfp, vma, vmf, &ret);
2128 	if (err)
2129 		return vmf_error(err);
2130 	if (folio)
2131 		vmf->page = folio_file_page(folio, vmf->pgoff);
2132 	return ret;
2133 }
2134 
2135 unsigned long shmem_get_unmapped_area(struct file *file,
2136 				      unsigned long uaddr, unsigned long len,
2137 				      unsigned long pgoff, unsigned long flags)
2138 {
2139 	unsigned long (*get_area)(struct file *,
2140 		unsigned long, unsigned long, unsigned long, unsigned long);
2141 	unsigned long addr;
2142 	unsigned long offset;
2143 	unsigned long inflated_len;
2144 	unsigned long inflated_addr;
2145 	unsigned long inflated_offset;
2146 
2147 	if (len > TASK_SIZE)
2148 		return -ENOMEM;
2149 
2150 	get_area = current->mm->get_unmapped_area;
2151 	addr = get_area(file, uaddr, len, pgoff, flags);
2152 
2153 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
2154 		return addr;
2155 	if (IS_ERR_VALUE(addr))
2156 		return addr;
2157 	if (addr & ~PAGE_MASK)
2158 		return addr;
2159 	if (addr > TASK_SIZE - len)
2160 		return addr;
2161 
2162 	if (shmem_huge == SHMEM_HUGE_DENY)
2163 		return addr;
2164 	if (len < HPAGE_PMD_SIZE)
2165 		return addr;
2166 	if (flags & MAP_FIXED)
2167 		return addr;
2168 	/*
2169 	 * Our priority is to support MAP_SHARED mapped hugely;
2170 	 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2171 	 * But if caller specified an address hint and we allocated area there
2172 	 * successfully, respect that as before.
2173 	 */
2174 	if (uaddr == addr)
2175 		return addr;
2176 
2177 	if (shmem_huge != SHMEM_HUGE_FORCE) {
2178 		struct super_block *sb;
2179 
2180 		if (file) {
2181 			VM_BUG_ON(file->f_op != &shmem_file_operations);
2182 			sb = file_inode(file)->i_sb;
2183 		} else {
2184 			/*
2185 			 * Called directly from mm/mmap.c, or drivers/char/mem.c
2186 			 * for "/dev/zero", to create a shared anonymous object.
2187 			 */
2188 			if (IS_ERR(shm_mnt))
2189 				return addr;
2190 			sb = shm_mnt->mnt_sb;
2191 		}
2192 		if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2193 			return addr;
2194 	}
2195 
2196 	offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2197 	if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2198 		return addr;
2199 	if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2200 		return addr;
2201 
2202 	inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2203 	if (inflated_len > TASK_SIZE)
2204 		return addr;
2205 	if (inflated_len < len)
2206 		return addr;
2207 
2208 	inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
2209 	if (IS_ERR_VALUE(inflated_addr))
2210 		return addr;
2211 	if (inflated_addr & ~PAGE_MASK)
2212 		return addr;
2213 
2214 	inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2215 	inflated_addr += offset - inflated_offset;
2216 	if (inflated_offset > offset)
2217 		inflated_addr += HPAGE_PMD_SIZE;
2218 
2219 	if (inflated_addr > TASK_SIZE - len)
2220 		return addr;
2221 	return inflated_addr;
2222 }
2223 
2224 #ifdef CONFIG_NUMA
2225 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2226 {
2227 	struct inode *inode = file_inode(vma->vm_file);
2228 	return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2229 }
2230 
2231 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2232 					  unsigned long addr)
2233 {
2234 	struct inode *inode = file_inode(vma->vm_file);
2235 	pgoff_t index;
2236 
2237 	index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2238 	return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2239 }
2240 #endif
2241 
2242 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
2243 {
2244 	struct inode *inode = file_inode(file);
2245 	struct shmem_inode_info *info = SHMEM_I(inode);
2246 	int retval = -ENOMEM;
2247 
2248 	/*
2249 	 * What serializes the accesses to info->flags?
2250 	 * ipc_lock_object() when called from shmctl_do_lock(),
2251 	 * no serialization needed when called from shm_destroy().
2252 	 */
2253 	if (lock && !(info->flags & VM_LOCKED)) {
2254 		if (!user_shm_lock(inode->i_size, ucounts))
2255 			goto out_nomem;
2256 		info->flags |= VM_LOCKED;
2257 		mapping_set_unevictable(file->f_mapping);
2258 	}
2259 	if (!lock && (info->flags & VM_LOCKED) && ucounts) {
2260 		user_shm_unlock(inode->i_size, ucounts);
2261 		info->flags &= ~VM_LOCKED;
2262 		mapping_clear_unevictable(file->f_mapping);
2263 	}
2264 	retval = 0;
2265 
2266 out_nomem:
2267 	return retval;
2268 }
2269 
2270 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2271 {
2272 	struct inode *inode = file_inode(file);
2273 	struct shmem_inode_info *info = SHMEM_I(inode);
2274 	int ret;
2275 
2276 	ret = seal_check_future_write(info->seals, vma);
2277 	if (ret)
2278 		return ret;
2279 
2280 	/* arm64 - allow memory tagging on RAM-based files */
2281 	vma->vm_flags |= VM_MTE_ALLOWED;
2282 
2283 	file_accessed(file);
2284 	/* This is anonymous shared memory if it is unlinked at the time of mmap */
2285 	if (inode->i_nlink)
2286 		vma->vm_ops = &shmem_vm_ops;
2287 	else
2288 		vma->vm_ops = &shmem_anon_vm_ops;
2289 	return 0;
2290 }
2291 
2292 #ifdef CONFIG_TMPFS_XATTR
2293 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2294 
2295 /*
2296  * chattr's fsflags are unrelated to extended attributes,
2297  * but tmpfs has chosen to enable them under the same config option.
2298  */
2299 static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags)
2300 {
2301 	unsigned int i_flags = 0;
2302 
2303 	if (fsflags & FS_NOATIME_FL)
2304 		i_flags |= S_NOATIME;
2305 	if (fsflags & FS_APPEND_FL)
2306 		i_flags |= S_APPEND;
2307 	if (fsflags & FS_IMMUTABLE_FL)
2308 		i_flags |= S_IMMUTABLE;
2309 	/*
2310 	 * But FS_NODUMP_FL does not require any action in i_flags.
2311 	 */
2312 	inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE);
2313 }
2314 #else
2315 static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags)
2316 {
2317 }
2318 #define shmem_initxattrs NULL
2319 #endif
2320 
2321 static struct inode *shmem_get_inode(struct super_block *sb, struct inode *dir,
2322 				     umode_t mode, dev_t dev, unsigned long flags)
2323 {
2324 	struct inode *inode;
2325 	struct shmem_inode_info *info;
2326 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2327 	ino_t ino;
2328 
2329 	if (shmem_reserve_inode(sb, &ino))
2330 		return NULL;
2331 
2332 	inode = new_inode(sb);
2333 	if (inode) {
2334 		inode->i_ino = ino;
2335 		inode_init_owner(&init_user_ns, inode, dir, mode);
2336 		inode->i_blocks = 0;
2337 		inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2338 		inode->i_generation = get_random_u32();
2339 		info = SHMEM_I(inode);
2340 		memset(info, 0, (char *)inode - (char *)info);
2341 		spin_lock_init(&info->lock);
2342 		atomic_set(&info->stop_eviction, 0);
2343 		info->seals = F_SEAL_SEAL;
2344 		info->flags = flags & VM_NORESERVE;
2345 		info->i_crtime = inode->i_mtime;
2346 		info->fsflags = (dir == NULL) ? 0 :
2347 			SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED;
2348 		if (info->fsflags)
2349 			shmem_set_inode_flags(inode, info->fsflags);
2350 		INIT_LIST_HEAD(&info->shrinklist);
2351 		INIT_LIST_HEAD(&info->swaplist);
2352 		simple_xattrs_init(&info->xattrs);
2353 		cache_no_acl(inode);
2354 		mapping_set_large_folios(inode->i_mapping);
2355 
2356 		switch (mode & S_IFMT) {
2357 		default:
2358 			inode->i_op = &shmem_special_inode_operations;
2359 			init_special_inode(inode, mode, dev);
2360 			break;
2361 		case S_IFREG:
2362 			inode->i_mapping->a_ops = &shmem_aops;
2363 			inode->i_op = &shmem_inode_operations;
2364 			inode->i_fop = &shmem_file_operations;
2365 			mpol_shared_policy_init(&info->policy,
2366 						 shmem_get_sbmpol(sbinfo));
2367 			break;
2368 		case S_IFDIR:
2369 			inc_nlink(inode);
2370 			/* Some things misbehave if size == 0 on a directory */
2371 			inode->i_size = 2 * BOGO_DIRENT_SIZE;
2372 			inode->i_op = &shmem_dir_inode_operations;
2373 			inode->i_fop = &simple_dir_operations;
2374 			break;
2375 		case S_IFLNK:
2376 			/*
2377 			 * Must not load anything in the rbtree,
2378 			 * mpol_free_shared_policy will not be called.
2379 			 */
2380 			mpol_shared_policy_init(&info->policy, NULL);
2381 			break;
2382 		}
2383 
2384 		lockdep_annotate_inode_mutex_key(inode);
2385 	} else
2386 		shmem_free_inode(sb);
2387 	return inode;
2388 }
2389 
2390 #ifdef CONFIG_USERFAULTFD
2391 int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2392 			   pmd_t *dst_pmd,
2393 			   struct vm_area_struct *dst_vma,
2394 			   unsigned long dst_addr,
2395 			   unsigned long src_addr,
2396 			   bool zeropage, bool wp_copy,
2397 			   struct page **pagep)
2398 {
2399 	struct inode *inode = file_inode(dst_vma->vm_file);
2400 	struct shmem_inode_info *info = SHMEM_I(inode);
2401 	struct address_space *mapping = inode->i_mapping;
2402 	gfp_t gfp = mapping_gfp_mask(mapping);
2403 	pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2404 	void *page_kaddr;
2405 	struct folio *folio;
2406 	int ret;
2407 	pgoff_t max_off;
2408 
2409 	if (!shmem_inode_acct_block(inode, 1)) {
2410 		/*
2411 		 * We may have got a page, returned -ENOENT triggering a retry,
2412 		 * and now we find ourselves with -ENOMEM. Release the page, to
2413 		 * avoid a BUG_ON in our caller.
2414 		 */
2415 		if (unlikely(*pagep)) {
2416 			put_page(*pagep);
2417 			*pagep = NULL;
2418 		}
2419 		return -ENOMEM;
2420 	}
2421 
2422 	if (!*pagep) {
2423 		ret = -ENOMEM;
2424 		folio = shmem_alloc_folio(gfp, info, pgoff);
2425 		if (!folio)
2426 			goto out_unacct_blocks;
2427 
2428 		if (!zeropage) {	/* COPY */
2429 			page_kaddr = kmap_local_folio(folio, 0);
2430 			/*
2431 			 * The read mmap_lock is held here.  Despite the
2432 			 * mmap_lock being read recursive a deadlock is still
2433 			 * possible if a writer has taken a lock.  For example:
2434 			 *
2435 			 * process A thread 1 takes read lock on own mmap_lock
2436 			 * process A thread 2 calls mmap, blocks taking write lock
2437 			 * process B thread 1 takes page fault, read lock on own mmap lock
2438 			 * process B thread 2 calls mmap, blocks taking write lock
2439 			 * process A thread 1 blocks taking read lock on process B
2440 			 * process B thread 1 blocks taking read lock on process A
2441 			 *
2442 			 * Disable page faults to prevent potential deadlock
2443 			 * and retry the copy outside the mmap_lock.
2444 			 */
2445 			pagefault_disable();
2446 			ret = copy_from_user(page_kaddr,
2447 					     (const void __user *)src_addr,
2448 					     PAGE_SIZE);
2449 			pagefault_enable();
2450 			kunmap_local(page_kaddr);
2451 
2452 			/* fallback to copy_from_user outside mmap_lock */
2453 			if (unlikely(ret)) {
2454 				*pagep = &folio->page;
2455 				ret = -ENOENT;
2456 				/* don't free the page */
2457 				goto out_unacct_blocks;
2458 			}
2459 
2460 			flush_dcache_folio(folio);
2461 		} else {		/* ZEROPAGE */
2462 			clear_user_highpage(&folio->page, dst_addr);
2463 		}
2464 	} else {
2465 		folio = page_folio(*pagep);
2466 		VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
2467 		*pagep = NULL;
2468 	}
2469 
2470 	VM_BUG_ON(folio_test_locked(folio));
2471 	VM_BUG_ON(folio_test_swapbacked(folio));
2472 	__folio_set_locked(folio);
2473 	__folio_set_swapbacked(folio);
2474 	__folio_mark_uptodate(folio);
2475 
2476 	ret = -EFAULT;
2477 	max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2478 	if (unlikely(pgoff >= max_off))
2479 		goto out_release;
2480 
2481 	ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL,
2482 				      gfp & GFP_RECLAIM_MASK, dst_mm);
2483 	if (ret)
2484 		goto out_release;
2485 
2486 	ret = mfill_atomic_install_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
2487 				       &folio->page, true, wp_copy);
2488 	if (ret)
2489 		goto out_delete_from_cache;
2490 
2491 	spin_lock_irq(&info->lock);
2492 	info->alloced++;
2493 	inode->i_blocks += BLOCKS_PER_PAGE;
2494 	shmem_recalc_inode(inode);
2495 	spin_unlock_irq(&info->lock);
2496 
2497 	folio_unlock(folio);
2498 	return 0;
2499 out_delete_from_cache:
2500 	filemap_remove_folio(folio);
2501 out_release:
2502 	folio_unlock(folio);
2503 	folio_put(folio);
2504 out_unacct_blocks:
2505 	shmem_inode_unacct_blocks(inode, 1);
2506 	return ret;
2507 }
2508 #endif /* CONFIG_USERFAULTFD */
2509 
2510 #ifdef CONFIG_TMPFS
2511 static const struct inode_operations shmem_symlink_inode_operations;
2512 static const struct inode_operations shmem_short_symlink_operations;
2513 
2514 static int
2515 shmem_write_begin(struct file *file, struct address_space *mapping,
2516 			loff_t pos, unsigned len,
2517 			struct page **pagep, void **fsdata)
2518 {
2519 	struct inode *inode = mapping->host;
2520 	struct shmem_inode_info *info = SHMEM_I(inode);
2521 	pgoff_t index = pos >> PAGE_SHIFT;
2522 	struct folio *folio;
2523 	int ret = 0;
2524 
2525 	/* i_rwsem is held by caller */
2526 	if (unlikely(info->seals & (F_SEAL_GROW |
2527 				   F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
2528 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
2529 			return -EPERM;
2530 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2531 			return -EPERM;
2532 	}
2533 
2534 	ret = shmem_get_folio(inode, index, &folio, SGP_WRITE);
2535 
2536 	if (ret)
2537 		return ret;
2538 
2539 	*pagep = folio_file_page(folio, index);
2540 	if (PageHWPoison(*pagep)) {
2541 		folio_unlock(folio);
2542 		folio_put(folio);
2543 		*pagep = NULL;
2544 		return -EIO;
2545 	}
2546 
2547 	return 0;
2548 }
2549 
2550 static int
2551 shmem_write_end(struct file *file, struct address_space *mapping,
2552 			loff_t pos, unsigned len, unsigned copied,
2553 			struct page *page, void *fsdata)
2554 {
2555 	struct inode *inode = mapping->host;
2556 
2557 	if (pos + copied > inode->i_size)
2558 		i_size_write(inode, pos + copied);
2559 
2560 	if (!PageUptodate(page)) {
2561 		struct page *head = compound_head(page);
2562 		if (PageTransCompound(page)) {
2563 			int i;
2564 
2565 			for (i = 0; i < HPAGE_PMD_NR; i++) {
2566 				if (head + i == page)
2567 					continue;
2568 				clear_highpage(head + i);
2569 				flush_dcache_page(head + i);
2570 			}
2571 		}
2572 		if (copied < PAGE_SIZE) {
2573 			unsigned from = pos & (PAGE_SIZE - 1);
2574 			zero_user_segments(page, 0, from,
2575 					from + copied, PAGE_SIZE);
2576 		}
2577 		SetPageUptodate(head);
2578 	}
2579 	set_page_dirty(page);
2580 	unlock_page(page);
2581 	put_page(page);
2582 
2583 	return copied;
2584 }
2585 
2586 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2587 {
2588 	struct file *file = iocb->ki_filp;
2589 	struct inode *inode = file_inode(file);
2590 	struct address_space *mapping = inode->i_mapping;
2591 	pgoff_t index;
2592 	unsigned long offset;
2593 	int error = 0;
2594 	ssize_t retval = 0;
2595 	loff_t *ppos = &iocb->ki_pos;
2596 
2597 	index = *ppos >> PAGE_SHIFT;
2598 	offset = *ppos & ~PAGE_MASK;
2599 
2600 	for (;;) {
2601 		struct folio *folio = NULL;
2602 		struct page *page = NULL;
2603 		pgoff_t end_index;
2604 		unsigned long nr, ret;
2605 		loff_t i_size = i_size_read(inode);
2606 
2607 		end_index = i_size >> PAGE_SHIFT;
2608 		if (index > end_index)
2609 			break;
2610 		if (index == end_index) {
2611 			nr = i_size & ~PAGE_MASK;
2612 			if (nr <= offset)
2613 				break;
2614 		}
2615 
2616 		error = shmem_get_folio(inode, index, &folio, SGP_READ);
2617 		if (error) {
2618 			if (error == -EINVAL)
2619 				error = 0;
2620 			break;
2621 		}
2622 		if (folio) {
2623 			folio_unlock(folio);
2624 
2625 			page = folio_file_page(folio, index);
2626 			if (PageHWPoison(page)) {
2627 				folio_put(folio);
2628 				error = -EIO;
2629 				break;
2630 			}
2631 		}
2632 
2633 		/*
2634 		 * We must evaluate after, since reads (unlike writes)
2635 		 * are called without i_rwsem protection against truncate
2636 		 */
2637 		nr = PAGE_SIZE;
2638 		i_size = i_size_read(inode);
2639 		end_index = i_size >> PAGE_SHIFT;
2640 		if (index == end_index) {
2641 			nr = i_size & ~PAGE_MASK;
2642 			if (nr <= offset) {
2643 				if (folio)
2644 					folio_put(folio);
2645 				break;
2646 			}
2647 		}
2648 		nr -= offset;
2649 
2650 		if (folio) {
2651 			/*
2652 			 * If users can be writing to this page using arbitrary
2653 			 * virtual addresses, take care about potential aliasing
2654 			 * before reading the page on the kernel side.
2655 			 */
2656 			if (mapping_writably_mapped(mapping))
2657 				flush_dcache_page(page);
2658 			/*
2659 			 * Mark the page accessed if we read the beginning.
2660 			 */
2661 			if (!offset)
2662 				folio_mark_accessed(folio);
2663 			/*
2664 			 * Ok, we have the page, and it's up-to-date, so
2665 			 * now we can copy it to user space...
2666 			 */
2667 			ret = copy_page_to_iter(page, offset, nr, to);
2668 			folio_put(folio);
2669 
2670 		} else if (user_backed_iter(to)) {
2671 			/*
2672 			 * Copy to user tends to be so well optimized, but
2673 			 * clear_user() not so much, that it is noticeably
2674 			 * faster to copy the zero page instead of clearing.
2675 			 */
2676 			ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to);
2677 		} else {
2678 			/*
2679 			 * But submitting the same page twice in a row to
2680 			 * splice() - or others? - can result in confusion:
2681 			 * so don't attempt that optimization on pipes etc.
2682 			 */
2683 			ret = iov_iter_zero(nr, to);
2684 		}
2685 
2686 		retval += ret;
2687 		offset += ret;
2688 		index += offset >> PAGE_SHIFT;
2689 		offset &= ~PAGE_MASK;
2690 
2691 		if (!iov_iter_count(to))
2692 			break;
2693 		if (ret < nr) {
2694 			error = -EFAULT;
2695 			break;
2696 		}
2697 		cond_resched();
2698 	}
2699 
2700 	*ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2701 	file_accessed(file);
2702 	return retval ? retval : error;
2703 }
2704 
2705 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2706 {
2707 	struct address_space *mapping = file->f_mapping;
2708 	struct inode *inode = mapping->host;
2709 
2710 	if (whence != SEEK_DATA && whence != SEEK_HOLE)
2711 		return generic_file_llseek_size(file, offset, whence,
2712 					MAX_LFS_FILESIZE, i_size_read(inode));
2713 	if (offset < 0)
2714 		return -ENXIO;
2715 
2716 	inode_lock(inode);
2717 	/* We're holding i_rwsem so we can access i_size directly */
2718 	offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
2719 	if (offset >= 0)
2720 		offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2721 	inode_unlock(inode);
2722 	return offset;
2723 }
2724 
2725 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2726 							 loff_t len)
2727 {
2728 	struct inode *inode = file_inode(file);
2729 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2730 	struct shmem_inode_info *info = SHMEM_I(inode);
2731 	struct shmem_falloc shmem_falloc;
2732 	pgoff_t start, index, end, undo_fallocend;
2733 	int error;
2734 
2735 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2736 		return -EOPNOTSUPP;
2737 
2738 	inode_lock(inode);
2739 
2740 	if (mode & FALLOC_FL_PUNCH_HOLE) {
2741 		struct address_space *mapping = file->f_mapping;
2742 		loff_t unmap_start = round_up(offset, PAGE_SIZE);
2743 		loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2744 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2745 
2746 		/* protected by i_rwsem */
2747 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
2748 			error = -EPERM;
2749 			goto out;
2750 		}
2751 
2752 		shmem_falloc.waitq = &shmem_falloc_waitq;
2753 		shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
2754 		shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2755 		spin_lock(&inode->i_lock);
2756 		inode->i_private = &shmem_falloc;
2757 		spin_unlock(&inode->i_lock);
2758 
2759 		if ((u64)unmap_end > (u64)unmap_start)
2760 			unmap_mapping_range(mapping, unmap_start,
2761 					    1 + unmap_end - unmap_start, 0);
2762 		shmem_truncate_range(inode, offset, offset + len - 1);
2763 		/* No need to unmap again: hole-punching leaves COWed pages */
2764 
2765 		spin_lock(&inode->i_lock);
2766 		inode->i_private = NULL;
2767 		wake_up_all(&shmem_falloc_waitq);
2768 		WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2769 		spin_unlock(&inode->i_lock);
2770 		error = 0;
2771 		goto out;
2772 	}
2773 
2774 	/* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2775 	error = inode_newsize_ok(inode, offset + len);
2776 	if (error)
2777 		goto out;
2778 
2779 	if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2780 		error = -EPERM;
2781 		goto out;
2782 	}
2783 
2784 	start = offset >> PAGE_SHIFT;
2785 	end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2786 	/* Try to avoid a swapstorm if len is impossible to satisfy */
2787 	if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2788 		error = -ENOSPC;
2789 		goto out;
2790 	}
2791 
2792 	shmem_falloc.waitq = NULL;
2793 	shmem_falloc.start = start;
2794 	shmem_falloc.next  = start;
2795 	shmem_falloc.nr_falloced = 0;
2796 	shmem_falloc.nr_unswapped = 0;
2797 	spin_lock(&inode->i_lock);
2798 	inode->i_private = &shmem_falloc;
2799 	spin_unlock(&inode->i_lock);
2800 
2801 	/*
2802 	 * info->fallocend is only relevant when huge pages might be
2803 	 * involved: to prevent split_huge_page() freeing fallocated
2804 	 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
2805 	 */
2806 	undo_fallocend = info->fallocend;
2807 	if (info->fallocend < end)
2808 		info->fallocend = end;
2809 
2810 	for (index = start; index < end; ) {
2811 		struct folio *folio;
2812 
2813 		/*
2814 		 * Good, the fallocate(2) manpage permits EINTR: we may have
2815 		 * been interrupted because we are using up too much memory.
2816 		 */
2817 		if (signal_pending(current))
2818 			error = -EINTR;
2819 		else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2820 			error = -ENOMEM;
2821 		else
2822 			error = shmem_get_folio(inode, index, &folio,
2823 						SGP_FALLOC);
2824 		if (error) {
2825 			info->fallocend = undo_fallocend;
2826 			/* Remove the !uptodate folios we added */
2827 			if (index > start) {
2828 				shmem_undo_range(inode,
2829 				    (loff_t)start << PAGE_SHIFT,
2830 				    ((loff_t)index << PAGE_SHIFT) - 1, true);
2831 			}
2832 			goto undone;
2833 		}
2834 
2835 		/*
2836 		 * Here is a more important optimization than it appears:
2837 		 * a second SGP_FALLOC on the same large folio will clear it,
2838 		 * making it uptodate and un-undoable if we fail later.
2839 		 */
2840 		index = folio_next_index(folio);
2841 		/* Beware 32-bit wraparound */
2842 		if (!index)
2843 			index--;
2844 
2845 		/*
2846 		 * Inform shmem_writepage() how far we have reached.
2847 		 * No need for lock or barrier: we have the page lock.
2848 		 */
2849 		if (!folio_test_uptodate(folio))
2850 			shmem_falloc.nr_falloced += index - shmem_falloc.next;
2851 		shmem_falloc.next = index;
2852 
2853 		/*
2854 		 * If !uptodate, leave it that way so that freeable folios
2855 		 * can be recognized if we need to rollback on error later.
2856 		 * But mark it dirty so that memory pressure will swap rather
2857 		 * than free the folios we are allocating (and SGP_CACHE folios
2858 		 * might still be clean: we now need to mark those dirty too).
2859 		 */
2860 		folio_mark_dirty(folio);
2861 		folio_unlock(folio);
2862 		folio_put(folio);
2863 		cond_resched();
2864 	}
2865 
2866 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2867 		i_size_write(inode, offset + len);
2868 undone:
2869 	spin_lock(&inode->i_lock);
2870 	inode->i_private = NULL;
2871 	spin_unlock(&inode->i_lock);
2872 out:
2873 	if (!error)
2874 		file_modified(file);
2875 	inode_unlock(inode);
2876 	return error;
2877 }
2878 
2879 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2880 {
2881 	struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2882 
2883 	buf->f_type = TMPFS_MAGIC;
2884 	buf->f_bsize = PAGE_SIZE;
2885 	buf->f_namelen = NAME_MAX;
2886 	if (sbinfo->max_blocks) {
2887 		buf->f_blocks = sbinfo->max_blocks;
2888 		buf->f_bavail =
2889 		buf->f_bfree  = sbinfo->max_blocks -
2890 				percpu_counter_sum(&sbinfo->used_blocks);
2891 	}
2892 	if (sbinfo->max_inodes) {
2893 		buf->f_files = sbinfo->max_inodes;
2894 		buf->f_ffree = sbinfo->free_inodes;
2895 	}
2896 	/* else leave those fields 0 like simple_statfs */
2897 
2898 	buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
2899 
2900 	return 0;
2901 }
2902 
2903 /*
2904  * File creation. Allocate an inode, and we're done..
2905  */
2906 static int
2907 shmem_mknod(struct user_namespace *mnt_userns, struct inode *dir,
2908 	    struct dentry *dentry, umode_t mode, dev_t dev)
2909 {
2910 	struct inode *inode;
2911 	int error = -ENOSPC;
2912 
2913 	inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2914 	if (inode) {
2915 		error = simple_acl_create(dir, inode);
2916 		if (error)
2917 			goto out_iput;
2918 		error = security_inode_init_security(inode, dir,
2919 						     &dentry->d_name,
2920 						     shmem_initxattrs, NULL);
2921 		if (error && error != -EOPNOTSUPP)
2922 			goto out_iput;
2923 
2924 		error = 0;
2925 		dir->i_size += BOGO_DIRENT_SIZE;
2926 		dir->i_ctime = dir->i_mtime = current_time(dir);
2927 		inode_inc_iversion(dir);
2928 		d_instantiate(dentry, inode);
2929 		dget(dentry); /* Extra count - pin the dentry in core */
2930 	}
2931 	return error;
2932 out_iput:
2933 	iput(inode);
2934 	return error;
2935 }
2936 
2937 static int
2938 shmem_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
2939 	      struct file *file, umode_t mode)
2940 {
2941 	struct inode *inode;
2942 	int error = -ENOSPC;
2943 
2944 	inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2945 	if (inode) {
2946 		error = security_inode_init_security(inode, dir,
2947 						     NULL,
2948 						     shmem_initxattrs, NULL);
2949 		if (error && error != -EOPNOTSUPP)
2950 			goto out_iput;
2951 		error = simple_acl_create(dir, inode);
2952 		if (error)
2953 			goto out_iput;
2954 		d_tmpfile(file, inode);
2955 	}
2956 	return finish_open_simple(file, error);
2957 out_iput:
2958 	iput(inode);
2959 	return error;
2960 }
2961 
2962 static int shmem_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
2963 		       struct dentry *dentry, umode_t mode)
2964 {
2965 	int error;
2966 
2967 	if ((error = shmem_mknod(&init_user_ns, dir, dentry,
2968 				 mode | S_IFDIR, 0)))
2969 		return error;
2970 	inc_nlink(dir);
2971 	return 0;
2972 }
2973 
2974 static int shmem_create(struct user_namespace *mnt_userns, struct inode *dir,
2975 			struct dentry *dentry, umode_t mode, bool excl)
2976 {
2977 	return shmem_mknod(&init_user_ns, dir, dentry, mode | S_IFREG, 0);
2978 }
2979 
2980 /*
2981  * Link a file..
2982  */
2983 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2984 {
2985 	struct inode *inode = d_inode(old_dentry);
2986 	int ret = 0;
2987 
2988 	/*
2989 	 * No ordinary (disk based) filesystem counts links as inodes;
2990 	 * but each new link needs a new dentry, pinning lowmem, and
2991 	 * tmpfs dentries cannot be pruned until they are unlinked.
2992 	 * But if an O_TMPFILE file is linked into the tmpfs, the
2993 	 * first link must skip that, to get the accounting right.
2994 	 */
2995 	if (inode->i_nlink) {
2996 		ret = shmem_reserve_inode(inode->i_sb, NULL);
2997 		if (ret)
2998 			goto out;
2999 	}
3000 
3001 	dir->i_size += BOGO_DIRENT_SIZE;
3002 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3003 	inode_inc_iversion(dir);
3004 	inc_nlink(inode);
3005 	ihold(inode);	/* New dentry reference */
3006 	dget(dentry);		/* Extra pinning count for the created dentry */
3007 	d_instantiate(dentry, inode);
3008 out:
3009 	return ret;
3010 }
3011 
3012 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
3013 {
3014 	struct inode *inode = d_inode(dentry);
3015 
3016 	if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
3017 		shmem_free_inode(inode->i_sb);
3018 
3019 	dir->i_size -= BOGO_DIRENT_SIZE;
3020 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3021 	inode_inc_iversion(dir);
3022 	drop_nlink(inode);
3023 	dput(dentry);	/* Undo the count from "create" - this does all the work */
3024 	return 0;
3025 }
3026 
3027 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
3028 {
3029 	if (!simple_empty(dentry))
3030 		return -ENOTEMPTY;
3031 
3032 	drop_nlink(d_inode(dentry));
3033 	drop_nlink(dir);
3034 	return shmem_unlink(dir, dentry);
3035 }
3036 
3037 static int shmem_whiteout(struct user_namespace *mnt_userns,
3038 			  struct inode *old_dir, struct dentry *old_dentry)
3039 {
3040 	struct dentry *whiteout;
3041 	int error;
3042 
3043 	whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
3044 	if (!whiteout)
3045 		return -ENOMEM;
3046 
3047 	error = shmem_mknod(&init_user_ns, old_dir, whiteout,
3048 			    S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
3049 	dput(whiteout);
3050 	if (error)
3051 		return error;
3052 
3053 	/*
3054 	 * Cheat and hash the whiteout while the old dentry is still in
3055 	 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3056 	 *
3057 	 * d_lookup() will consistently find one of them at this point,
3058 	 * not sure which one, but that isn't even important.
3059 	 */
3060 	d_rehash(whiteout);
3061 	return 0;
3062 }
3063 
3064 /*
3065  * The VFS layer already does all the dentry stuff for rename,
3066  * we just have to decrement the usage count for the target if
3067  * it exists so that the VFS layer correctly free's it when it
3068  * gets overwritten.
3069  */
3070 static int shmem_rename2(struct user_namespace *mnt_userns,
3071 			 struct inode *old_dir, struct dentry *old_dentry,
3072 			 struct inode *new_dir, struct dentry *new_dentry,
3073 			 unsigned int flags)
3074 {
3075 	struct inode *inode = d_inode(old_dentry);
3076 	int they_are_dirs = S_ISDIR(inode->i_mode);
3077 
3078 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3079 		return -EINVAL;
3080 
3081 	if (flags & RENAME_EXCHANGE)
3082 		return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
3083 
3084 	if (!simple_empty(new_dentry))
3085 		return -ENOTEMPTY;
3086 
3087 	if (flags & RENAME_WHITEOUT) {
3088 		int error;
3089 
3090 		error = shmem_whiteout(&init_user_ns, old_dir, old_dentry);
3091 		if (error)
3092 			return error;
3093 	}
3094 
3095 	if (d_really_is_positive(new_dentry)) {
3096 		(void) shmem_unlink(new_dir, new_dentry);
3097 		if (they_are_dirs) {
3098 			drop_nlink(d_inode(new_dentry));
3099 			drop_nlink(old_dir);
3100 		}
3101 	} else if (they_are_dirs) {
3102 		drop_nlink(old_dir);
3103 		inc_nlink(new_dir);
3104 	}
3105 
3106 	old_dir->i_size -= BOGO_DIRENT_SIZE;
3107 	new_dir->i_size += BOGO_DIRENT_SIZE;
3108 	old_dir->i_ctime = old_dir->i_mtime =
3109 	new_dir->i_ctime = new_dir->i_mtime =
3110 	inode->i_ctime = current_time(old_dir);
3111 	inode_inc_iversion(old_dir);
3112 	inode_inc_iversion(new_dir);
3113 	return 0;
3114 }
3115 
3116 static int shmem_symlink(struct user_namespace *mnt_userns, struct inode *dir,
3117 			 struct dentry *dentry, const char *symname)
3118 {
3119 	int error;
3120 	int len;
3121 	struct inode *inode;
3122 	struct folio *folio;
3123 
3124 	len = strlen(symname) + 1;
3125 	if (len > PAGE_SIZE)
3126 		return -ENAMETOOLONG;
3127 
3128 	inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
3129 				VM_NORESERVE);
3130 	if (!inode)
3131 		return -ENOSPC;
3132 
3133 	error = security_inode_init_security(inode, dir, &dentry->d_name,
3134 					     shmem_initxattrs, NULL);
3135 	if (error && error != -EOPNOTSUPP) {
3136 		iput(inode);
3137 		return error;
3138 	}
3139 
3140 	inode->i_size = len-1;
3141 	if (len <= SHORT_SYMLINK_LEN) {
3142 		inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3143 		if (!inode->i_link) {
3144 			iput(inode);
3145 			return -ENOMEM;
3146 		}
3147 		inode->i_op = &shmem_short_symlink_operations;
3148 	} else {
3149 		inode_nohighmem(inode);
3150 		error = shmem_get_folio(inode, 0, &folio, SGP_WRITE);
3151 		if (error) {
3152 			iput(inode);
3153 			return error;
3154 		}
3155 		inode->i_mapping->a_ops = &shmem_aops;
3156 		inode->i_op = &shmem_symlink_inode_operations;
3157 		memcpy(folio_address(folio), symname, len);
3158 		folio_mark_uptodate(folio);
3159 		folio_mark_dirty(folio);
3160 		folio_unlock(folio);
3161 		folio_put(folio);
3162 	}
3163 	dir->i_size += BOGO_DIRENT_SIZE;
3164 	dir->i_ctime = dir->i_mtime = current_time(dir);
3165 	inode_inc_iversion(dir);
3166 	d_instantiate(dentry, inode);
3167 	dget(dentry);
3168 	return 0;
3169 }
3170 
3171 static void shmem_put_link(void *arg)
3172 {
3173 	folio_mark_accessed(arg);
3174 	folio_put(arg);
3175 }
3176 
3177 static const char *shmem_get_link(struct dentry *dentry,
3178 				  struct inode *inode,
3179 				  struct delayed_call *done)
3180 {
3181 	struct folio *folio = NULL;
3182 	int error;
3183 
3184 	if (!dentry) {
3185 		folio = filemap_get_folio(inode->i_mapping, 0);
3186 		if (!folio)
3187 			return ERR_PTR(-ECHILD);
3188 		if (PageHWPoison(folio_page(folio, 0)) ||
3189 		    !folio_test_uptodate(folio)) {
3190 			folio_put(folio);
3191 			return ERR_PTR(-ECHILD);
3192 		}
3193 	} else {
3194 		error = shmem_get_folio(inode, 0, &folio, SGP_READ);
3195 		if (error)
3196 			return ERR_PTR(error);
3197 		if (!folio)
3198 			return ERR_PTR(-ECHILD);
3199 		if (PageHWPoison(folio_page(folio, 0))) {
3200 			folio_unlock(folio);
3201 			folio_put(folio);
3202 			return ERR_PTR(-ECHILD);
3203 		}
3204 		folio_unlock(folio);
3205 	}
3206 	set_delayed_call(done, shmem_put_link, folio);
3207 	return folio_address(folio);
3208 }
3209 
3210 #ifdef CONFIG_TMPFS_XATTR
3211 
3212 static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa)
3213 {
3214 	struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3215 
3216 	fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE);
3217 
3218 	return 0;
3219 }
3220 
3221 static int shmem_fileattr_set(struct user_namespace *mnt_userns,
3222 			      struct dentry *dentry, struct fileattr *fa)
3223 {
3224 	struct inode *inode = d_inode(dentry);
3225 	struct shmem_inode_info *info = SHMEM_I(inode);
3226 
3227 	if (fileattr_has_fsx(fa))
3228 		return -EOPNOTSUPP;
3229 	if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE)
3230 		return -EOPNOTSUPP;
3231 
3232 	info->fsflags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) |
3233 		(fa->flags & SHMEM_FL_USER_MODIFIABLE);
3234 
3235 	shmem_set_inode_flags(inode, info->fsflags);
3236 	inode->i_ctime = current_time(inode);
3237 	inode_inc_iversion(inode);
3238 	return 0;
3239 }
3240 
3241 /*
3242  * Superblocks without xattr inode operations may get some security.* xattr
3243  * support from the LSM "for free". As soon as we have any other xattrs
3244  * like ACLs, we also need to implement the security.* handlers at
3245  * filesystem level, though.
3246  */
3247 
3248 /*
3249  * Callback for security_inode_init_security() for acquiring xattrs.
3250  */
3251 static int shmem_initxattrs(struct inode *inode,
3252 			    const struct xattr *xattr_array,
3253 			    void *fs_info)
3254 {
3255 	struct shmem_inode_info *info = SHMEM_I(inode);
3256 	const struct xattr *xattr;
3257 	struct simple_xattr *new_xattr;
3258 	size_t len;
3259 
3260 	for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3261 		new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3262 		if (!new_xattr)
3263 			return -ENOMEM;
3264 
3265 		len = strlen(xattr->name) + 1;
3266 		new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3267 					  GFP_KERNEL);
3268 		if (!new_xattr->name) {
3269 			kvfree(new_xattr);
3270 			return -ENOMEM;
3271 		}
3272 
3273 		memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3274 		       XATTR_SECURITY_PREFIX_LEN);
3275 		memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3276 		       xattr->name, len);
3277 
3278 		simple_xattr_list_add(&info->xattrs, new_xattr);
3279 	}
3280 
3281 	return 0;
3282 }
3283 
3284 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3285 				   struct dentry *unused, struct inode *inode,
3286 				   const char *name, void *buffer, size_t size)
3287 {
3288 	struct shmem_inode_info *info = SHMEM_I(inode);
3289 
3290 	name = xattr_full_name(handler, name);
3291 	return simple_xattr_get(&info->xattrs, name, buffer, size);
3292 }
3293 
3294 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3295 				   struct user_namespace *mnt_userns,
3296 				   struct dentry *unused, struct inode *inode,
3297 				   const char *name, const void *value,
3298 				   size_t size, int flags)
3299 {
3300 	struct shmem_inode_info *info = SHMEM_I(inode);
3301 	int err;
3302 
3303 	name = xattr_full_name(handler, name);
3304 	err = simple_xattr_set(&info->xattrs, name, value, size, flags, NULL);
3305 	if (!err) {
3306 		inode->i_ctime = current_time(inode);
3307 		inode_inc_iversion(inode);
3308 	}
3309 	return err;
3310 }
3311 
3312 static const struct xattr_handler shmem_security_xattr_handler = {
3313 	.prefix = XATTR_SECURITY_PREFIX,
3314 	.get = shmem_xattr_handler_get,
3315 	.set = shmem_xattr_handler_set,
3316 };
3317 
3318 static const struct xattr_handler shmem_trusted_xattr_handler = {
3319 	.prefix = XATTR_TRUSTED_PREFIX,
3320 	.get = shmem_xattr_handler_get,
3321 	.set = shmem_xattr_handler_set,
3322 };
3323 
3324 static const struct xattr_handler *shmem_xattr_handlers[] = {
3325 #ifdef CONFIG_TMPFS_POSIX_ACL
3326 	&posix_acl_access_xattr_handler,
3327 	&posix_acl_default_xattr_handler,
3328 #endif
3329 	&shmem_security_xattr_handler,
3330 	&shmem_trusted_xattr_handler,
3331 	NULL
3332 };
3333 
3334 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3335 {
3336 	struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3337 	return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3338 }
3339 #endif /* CONFIG_TMPFS_XATTR */
3340 
3341 static const struct inode_operations shmem_short_symlink_operations = {
3342 	.getattr	= shmem_getattr,
3343 	.get_link	= simple_get_link,
3344 #ifdef CONFIG_TMPFS_XATTR
3345 	.listxattr	= shmem_listxattr,
3346 #endif
3347 };
3348 
3349 static const struct inode_operations shmem_symlink_inode_operations = {
3350 	.getattr	= shmem_getattr,
3351 	.get_link	= shmem_get_link,
3352 #ifdef CONFIG_TMPFS_XATTR
3353 	.listxattr	= shmem_listxattr,
3354 #endif
3355 };
3356 
3357 static struct dentry *shmem_get_parent(struct dentry *child)
3358 {
3359 	return ERR_PTR(-ESTALE);
3360 }
3361 
3362 static int shmem_match(struct inode *ino, void *vfh)
3363 {
3364 	__u32 *fh = vfh;
3365 	__u64 inum = fh[2];
3366 	inum = (inum << 32) | fh[1];
3367 	return ino->i_ino == inum && fh[0] == ino->i_generation;
3368 }
3369 
3370 /* Find any alias of inode, but prefer a hashed alias */
3371 static struct dentry *shmem_find_alias(struct inode *inode)
3372 {
3373 	struct dentry *alias = d_find_alias(inode);
3374 
3375 	return alias ?: d_find_any_alias(inode);
3376 }
3377 
3378 
3379 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3380 		struct fid *fid, int fh_len, int fh_type)
3381 {
3382 	struct inode *inode;
3383 	struct dentry *dentry = NULL;
3384 	u64 inum;
3385 
3386 	if (fh_len < 3)
3387 		return NULL;
3388 
3389 	inum = fid->raw[2];
3390 	inum = (inum << 32) | fid->raw[1];
3391 
3392 	inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3393 			shmem_match, fid->raw);
3394 	if (inode) {
3395 		dentry = shmem_find_alias(inode);
3396 		iput(inode);
3397 	}
3398 
3399 	return dentry;
3400 }
3401 
3402 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3403 				struct inode *parent)
3404 {
3405 	if (*len < 3) {
3406 		*len = 3;
3407 		return FILEID_INVALID;
3408 	}
3409 
3410 	if (inode_unhashed(inode)) {
3411 		/* Unfortunately insert_inode_hash is not idempotent,
3412 		 * so as we hash inodes here rather than at creation
3413 		 * time, we need a lock to ensure we only try
3414 		 * to do it once
3415 		 */
3416 		static DEFINE_SPINLOCK(lock);
3417 		spin_lock(&lock);
3418 		if (inode_unhashed(inode))
3419 			__insert_inode_hash(inode,
3420 					    inode->i_ino + inode->i_generation);
3421 		spin_unlock(&lock);
3422 	}
3423 
3424 	fh[0] = inode->i_generation;
3425 	fh[1] = inode->i_ino;
3426 	fh[2] = ((__u64)inode->i_ino) >> 32;
3427 
3428 	*len = 3;
3429 	return 1;
3430 }
3431 
3432 static const struct export_operations shmem_export_ops = {
3433 	.get_parent     = shmem_get_parent,
3434 	.encode_fh      = shmem_encode_fh,
3435 	.fh_to_dentry	= shmem_fh_to_dentry,
3436 };
3437 
3438 enum shmem_param {
3439 	Opt_gid,
3440 	Opt_huge,
3441 	Opt_mode,
3442 	Opt_mpol,
3443 	Opt_nr_blocks,
3444 	Opt_nr_inodes,
3445 	Opt_size,
3446 	Opt_uid,
3447 	Opt_inode32,
3448 	Opt_inode64,
3449 };
3450 
3451 static const struct constant_table shmem_param_enums_huge[] = {
3452 	{"never",	SHMEM_HUGE_NEVER },
3453 	{"always",	SHMEM_HUGE_ALWAYS },
3454 	{"within_size",	SHMEM_HUGE_WITHIN_SIZE },
3455 	{"advise",	SHMEM_HUGE_ADVISE },
3456 	{}
3457 };
3458 
3459 const struct fs_parameter_spec shmem_fs_parameters[] = {
3460 	fsparam_u32   ("gid",		Opt_gid),
3461 	fsparam_enum  ("huge",		Opt_huge,  shmem_param_enums_huge),
3462 	fsparam_u32oct("mode",		Opt_mode),
3463 	fsparam_string("mpol",		Opt_mpol),
3464 	fsparam_string("nr_blocks",	Opt_nr_blocks),
3465 	fsparam_string("nr_inodes",	Opt_nr_inodes),
3466 	fsparam_string("size",		Opt_size),
3467 	fsparam_u32   ("uid",		Opt_uid),
3468 	fsparam_flag  ("inode32",	Opt_inode32),
3469 	fsparam_flag  ("inode64",	Opt_inode64),
3470 	{}
3471 };
3472 
3473 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
3474 {
3475 	struct shmem_options *ctx = fc->fs_private;
3476 	struct fs_parse_result result;
3477 	unsigned long long size;
3478 	char *rest;
3479 	int opt;
3480 
3481 	opt = fs_parse(fc, shmem_fs_parameters, param, &result);
3482 	if (opt < 0)
3483 		return opt;
3484 
3485 	switch (opt) {
3486 	case Opt_size:
3487 		size = memparse(param->string, &rest);
3488 		if (*rest == '%') {
3489 			size <<= PAGE_SHIFT;
3490 			size *= totalram_pages();
3491 			do_div(size, 100);
3492 			rest++;
3493 		}
3494 		if (*rest)
3495 			goto bad_value;
3496 		ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
3497 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3498 		break;
3499 	case Opt_nr_blocks:
3500 		ctx->blocks = memparse(param->string, &rest);
3501 		if (*rest || ctx->blocks > S64_MAX)
3502 			goto bad_value;
3503 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3504 		break;
3505 	case Opt_nr_inodes:
3506 		ctx->inodes = memparse(param->string, &rest);
3507 		if (*rest)
3508 			goto bad_value;
3509 		ctx->seen |= SHMEM_SEEN_INODES;
3510 		break;
3511 	case Opt_mode:
3512 		ctx->mode = result.uint_32 & 07777;
3513 		break;
3514 	case Opt_uid:
3515 		ctx->uid = make_kuid(current_user_ns(), result.uint_32);
3516 		if (!uid_valid(ctx->uid))
3517 			goto bad_value;
3518 		break;
3519 	case Opt_gid:
3520 		ctx->gid = make_kgid(current_user_ns(), result.uint_32);
3521 		if (!gid_valid(ctx->gid))
3522 			goto bad_value;
3523 		break;
3524 	case Opt_huge:
3525 		ctx->huge = result.uint_32;
3526 		if (ctx->huge != SHMEM_HUGE_NEVER &&
3527 		    !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
3528 		      has_transparent_hugepage()))
3529 			goto unsupported_parameter;
3530 		ctx->seen |= SHMEM_SEEN_HUGE;
3531 		break;
3532 	case Opt_mpol:
3533 		if (IS_ENABLED(CONFIG_NUMA)) {
3534 			mpol_put(ctx->mpol);
3535 			ctx->mpol = NULL;
3536 			if (mpol_parse_str(param->string, &ctx->mpol))
3537 				goto bad_value;
3538 			break;
3539 		}
3540 		goto unsupported_parameter;
3541 	case Opt_inode32:
3542 		ctx->full_inums = false;
3543 		ctx->seen |= SHMEM_SEEN_INUMS;
3544 		break;
3545 	case Opt_inode64:
3546 		if (sizeof(ino_t) < 8) {
3547 			return invalfc(fc,
3548 				       "Cannot use inode64 with <64bit inums in kernel\n");
3549 		}
3550 		ctx->full_inums = true;
3551 		ctx->seen |= SHMEM_SEEN_INUMS;
3552 		break;
3553 	}
3554 	return 0;
3555 
3556 unsupported_parameter:
3557 	return invalfc(fc, "Unsupported parameter '%s'", param->key);
3558 bad_value:
3559 	return invalfc(fc, "Bad value for '%s'", param->key);
3560 }
3561 
3562 static int shmem_parse_options(struct fs_context *fc, void *data)
3563 {
3564 	char *options = data;
3565 
3566 	if (options) {
3567 		int err = security_sb_eat_lsm_opts(options, &fc->security);
3568 		if (err)
3569 			return err;
3570 	}
3571 
3572 	while (options != NULL) {
3573 		char *this_char = options;
3574 		for (;;) {
3575 			/*
3576 			 * NUL-terminate this option: unfortunately,
3577 			 * mount options form a comma-separated list,
3578 			 * but mpol's nodelist may also contain commas.
3579 			 */
3580 			options = strchr(options, ',');
3581 			if (options == NULL)
3582 				break;
3583 			options++;
3584 			if (!isdigit(*options)) {
3585 				options[-1] = '\0';
3586 				break;
3587 			}
3588 		}
3589 		if (*this_char) {
3590 			char *value = strchr(this_char, '=');
3591 			size_t len = 0;
3592 			int err;
3593 
3594 			if (value) {
3595 				*value++ = '\0';
3596 				len = strlen(value);
3597 			}
3598 			err = vfs_parse_fs_string(fc, this_char, value, len);
3599 			if (err < 0)
3600 				return err;
3601 		}
3602 	}
3603 	return 0;
3604 }
3605 
3606 /*
3607  * Reconfigure a shmem filesystem.
3608  *
3609  * Note that we disallow change from limited->unlimited blocks/inodes while any
3610  * are in use; but we must separately disallow unlimited->limited, because in
3611  * that case we have no record of how much is already in use.
3612  */
3613 static int shmem_reconfigure(struct fs_context *fc)
3614 {
3615 	struct shmem_options *ctx = fc->fs_private;
3616 	struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
3617 	unsigned long inodes;
3618 	struct mempolicy *mpol = NULL;
3619 	const char *err;
3620 
3621 	raw_spin_lock(&sbinfo->stat_lock);
3622 	inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3623 
3624 	if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
3625 		if (!sbinfo->max_blocks) {
3626 			err = "Cannot retroactively limit size";
3627 			goto out;
3628 		}
3629 		if (percpu_counter_compare(&sbinfo->used_blocks,
3630 					   ctx->blocks) > 0) {
3631 			err = "Too small a size for current use";
3632 			goto out;
3633 		}
3634 	}
3635 	if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
3636 		if (!sbinfo->max_inodes) {
3637 			err = "Cannot retroactively limit inodes";
3638 			goto out;
3639 		}
3640 		if (ctx->inodes < inodes) {
3641 			err = "Too few inodes for current use";
3642 			goto out;
3643 		}
3644 	}
3645 
3646 	if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
3647 	    sbinfo->next_ino > UINT_MAX) {
3648 		err = "Current inum too high to switch to 32-bit inums";
3649 		goto out;
3650 	}
3651 
3652 	if (ctx->seen & SHMEM_SEEN_HUGE)
3653 		sbinfo->huge = ctx->huge;
3654 	if (ctx->seen & SHMEM_SEEN_INUMS)
3655 		sbinfo->full_inums = ctx->full_inums;
3656 	if (ctx->seen & SHMEM_SEEN_BLOCKS)
3657 		sbinfo->max_blocks  = ctx->blocks;
3658 	if (ctx->seen & SHMEM_SEEN_INODES) {
3659 		sbinfo->max_inodes  = ctx->inodes;
3660 		sbinfo->free_inodes = ctx->inodes - inodes;
3661 	}
3662 
3663 	/*
3664 	 * Preserve previous mempolicy unless mpol remount option was specified.
3665 	 */
3666 	if (ctx->mpol) {
3667 		mpol = sbinfo->mpol;
3668 		sbinfo->mpol = ctx->mpol;	/* transfers initial ref */
3669 		ctx->mpol = NULL;
3670 	}
3671 	raw_spin_unlock(&sbinfo->stat_lock);
3672 	mpol_put(mpol);
3673 	return 0;
3674 out:
3675 	raw_spin_unlock(&sbinfo->stat_lock);
3676 	return invalfc(fc, "%s", err);
3677 }
3678 
3679 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3680 {
3681 	struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3682 
3683 	if (sbinfo->max_blocks != shmem_default_max_blocks())
3684 		seq_printf(seq, ",size=%luk",
3685 			sbinfo->max_blocks << (PAGE_SHIFT - 10));
3686 	if (sbinfo->max_inodes != shmem_default_max_inodes())
3687 		seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3688 	if (sbinfo->mode != (0777 | S_ISVTX))
3689 		seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3690 	if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3691 		seq_printf(seq, ",uid=%u",
3692 				from_kuid_munged(&init_user_ns, sbinfo->uid));
3693 	if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3694 		seq_printf(seq, ",gid=%u",
3695 				from_kgid_munged(&init_user_ns, sbinfo->gid));
3696 
3697 	/*
3698 	 * Showing inode{64,32} might be useful even if it's the system default,
3699 	 * since then people don't have to resort to checking both here and
3700 	 * /proc/config.gz to confirm 64-bit inums were successfully applied
3701 	 * (which may not even exist if IKCONFIG_PROC isn't enabled).
3702 	 *
3703 	 * We hide it when inode64 isn't the default and we are using 32-bit
3704 	 * inodes, since that probably just means the feature isn't even under
3705 	 * consideration.
3706 	 *
3707 	 * As such:
3708 	 *
3709 	 *                     +-----------------+-----------------+
3710 	 *                     | TMPFS_INODE64=y | TMPFS_INODE64=n |
3711 	 *  +------------------+-----------------+-----------------+
3712 	 *  | full_inums=true  | show            | show            |
3713 	 *  | full_inums=false | show            | hide            |
3714 	 *  +------------------+-----------------+-----------------+
3715 	 *
3716 	 */
3717 	if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
3718 		seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
3719 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3720 	/* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3721 	if (sbinfo->huge)
3722 		seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3723 #endif
3724 	shmem_show_mpol(seq, sbinfo->mpol);
3725 	return 0;
3726 }
3727 
3728 #endif /* CONFIG_TMPFS */
3729 
3730 static void shmem_put_super(struct super_block *sb)
3731 {
3732 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3733 
3734 	free_percpu(sbinfo->ino_batch);
3735 	percpu_counter_destroy(&sbinfo->used_blocks);
3736 	mpol_put(sbinfo->mpol);
3737 	kfree(sbinfo);
3738 	sb->s_fs_info = NULL;
3739 }
3740 
3741 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
3742 {
3743 	struct shmem_options *ctx = fc->fs_private;
3744 	struct inode *inode;
3745 	struct shmem_sb_info *sbinfo;
3746 
3747 	/* Round up to L1_CACHE_BYTES to resist false sharing */
3748 	sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3749 				L1_CACHE_BYTES), GFP_KERNEL);
3750 	if (!sbinfo)
3751 		return -ENOMEM;
3752 
3753 	sb->s_fs_info = sbinfo;
3754 
3755 #ifdef CONFIG_TMPFS
3756 	/*
3757 	 * Per default we only allow half of the physical ram per
3758 	 * tmpfs instance, limiting inodes to one per page of lowmem;
3759 	 * but the internal instance is left unlimited.
3760 	 */
3761 	if (!(sb->s_flags & SB_KERNMOUNT)) {
3762 		if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
3763 			ctx->blocks = shmem_default_max_blocks();
3764 		if (!(ctx->seen & SHMEM_SEEN_INODES))
3765 			ctx->inodes = shmem_default_max_inodes();
3766 		if (!(ctx->seen & SHMEM_SEEN_INUMS))
3767 			ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
3768 	} else {
3769 		sb->s_flags |= SB_NOUSER;
3770 	}
3771 	sb->s_export_op = &shmem_export_ops;
3772 	sb->s_flags |= SB_NOSEC | SB_I_VERSION;
3773 #else
3774 	sb->s_flags |= SB_NOUSER;
3775 #endif
3776 	sbinfo->max_blocks = ctx->blocks;
3777 	sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes;
3778 	if (sb->s_flags & SB_KERNMOUNT) {
3779 		sbinfo->ino_batch = alloc_percpu(ino_t);
3780 		if (!sbinfo->ino_batch)
3781 			goto failed;
3782 	}
3783 	sbinfo->uid = ctx->uid;
3784 	sbinfo->gid = ctx->gid;
3785 	sbinfo->full_inums = ctx->full_inums;
3786 	sbinfo->mode = ctx->mode;
3787 	sbinfo->huge = ctx->huge;
3788 	sbinfo->mpol = ctx->mpol;
3789 	ctx->mpol = NULL;
3790 
3791 	raw_spin_lock_init(&sbinfo->stat_lock);
3792 	if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3793 		goto failed;
3794 	spin_lock_init(&sbinfo->shrinklist_lock);
3795 	INIT_LIST_HEAD(&sbinfo->shrinklist);
3796 
3797 	sb->s_maxbytes = MAX_LFS_FILESIZE;
3798 	sb->s_blocksize = PAGE_SIZE;
3799 	sb->s_blocksize_bits = PAGE_SHIFT;
3800 	sb->s_magic = TMPFS_MAGIC;
3801 	sb->s_op = &shmem_ops;
3802 	sb->s_time_gran = 1;
3803 #ifdef CONFIG_TMPFS_XATTR
3804 	sb->s_xattr = shmem_xattr_handlers;
3805 #endif
3806 #ifdef CONFIG_TMPFS_POSIX_ACL
3807 	sb->s_flags |= SB_POSIXACL;
3808 #endif
3809 	uuid_gen(&sb->s_uuid);
3810 
3811 	inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3812 	if (!inode)
3813 		goto failed;
3814 	inode->i_uid = sbinfo->uid;
3815 	inode->i_gid = sbinfo->gid;
3816 	sb->s_root = d_make_root(inode);
3817 	if (!sb->s_root)
3818 		goto failed;
3819 	return 0;
3820 
3821 failed:
3822 	shmem_put_super(sb);
3823 	return -ENOMEM;
3824 }
3825 
3826 static int shmem_get_tree(struct fs_context *fc)
3827 {
3828 	return get_tree_nodev(fc, shmem_fill_super);
3829 }
3830 
3831 static void shmem_free_fc(struct fs_context *fc)
3832 {
3833 	struct shmem_options *ctx = fc->fs_private;
3834 
3835 	if (ctx) {
3836 		mpol_put(ctx->mpol);
3837 		kfree(ctx);
3838 	}
3839 }
3840 
3841 static const struct fs_context_operations shmem_fs_context_ops = {
3842 	.free			= shmem_free_fc,
3843 	.get_tree		= shmem_get_tree,
3844 #ifdef CONFIG_TMPFS
3845 	.parse_monolithic	= shmem_parse_options,
3846 	.parse_param		= shmem_parse_one,
3847 	.reconfigure		= shmem_reconfigure,
3848 #endif
3849 };
3850 
3851 static struct kmem_cache *shmem_inode_cachep;
3852 
3853 static struct inode *shmem_alloc_inode(struct super_block *sb)
3854 {
3855 	struct shmem_inode_info *info;
3856 	info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL);
3857 	if (!info)
3858 		return NULL;
3859 	return &info->vfs_inode;
3860 }
3861 
3862 static void shmem_free_in_core_inode(struct inode *inode)
3863 {
3864 	if (S_ISLNK(inode->i_mode))
3865 		kfree(inode->i_link);
3866 	kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3867 }
3868 
3869 static void shmem_destroy_inode(struct inode *inode)
3870 {
3871 	if (S_ISREG(inode->i_mode))
3872 		mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3873 }
3874 
3875 static void shmem_init_inode(void *foo)
3876 {
3877 	struct shmem_inode_info *info = foo;
3878 	inode_init_once(&info->vfs_inode);
3879 }
3880 
3881 static void shmem_init_inodecache(void)
3882 {
3883 	shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3884 				sizeof(struct shmem_inode_info),
3885 				0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3886 }
3887 
3888 static void shmem_destroy_inodecache(void)
3889 {
3890 	kmem_cache_destroy(shmem_inode_cachep);
3891 }
3892 
3893 /* Keep the page in page cache instead of truncating it */
3894 static int shmem_error_remove_page(struct address_space *mapping,
3895 				   struct page *page)
3896 {
3897 	return 0;
3898 }
3899 
3900 const struct address_space_operations shmem_aops = {
3901 	.writepage	= shmem_writepage,
3902 	.dirty_folio	= noop_dirty_folio,
3903 #ifdef CONFIG_TMPFS
3904 	.write_begin	= shmem_write_begin,
3905 	.write_end	= shmem_write_end,
3906 #endif
3907 #ifdef CONFIG_MIGRATION
3908 	.migrate_folio	= migrate_folio,
3909 #endif
3910 	.error_remove_page = shmem_error_remove_page,
3911 };
3912 EXPORT_SYMBOL(shmem_aops);
3913 
3914 static const struct file_operations shmem_file_operations = {
3915 	.mmap		= shmem_mmap,
3916 	.open		= generic_file_open,
3917 	.get_unmapped_area = shmem_get_unmapped_area,
3918 #ifdef CONFIG_TMPFS
3919 	.llseek		= shmem_file_llseek,
3920 	.read_iter	= shmem_file_read_iter,
3921 	.write_iter	= generic_file_write_iter,
3922 	.fsync		= noop_fsync,
3923 	.splice_read	= generic_file_splice_read,
3924 	.splice_write	= iter_file_splice_write,
3925 	.fallocate	= shmem_fallocate,
3926 #endif
3927 };
3928 
3929 static const struct inode_operations shmem_inode_operations = {
3930 	.getattr	= shmem_getattr,
3931 	.setattr	= shmem_setattr,
3932 #ifdef CONFIG_TMPFS_XATTR
3933 	.listxattr	= shmem_listxattr,
3934 	.set_acl	= simple_set_acl,
3935 	.fileattr_get	= shmem_fileattr_get,
3936 	.fileattr_set	= shmem_fileattr_set,
3937 #endif
3938 };
3939 
3940 static const struct inode_operations shmem_dir_inode_operations = {
3941 #ifdef CONFIG_TMPFS
3942 	.getattr	= shmem_getattr,
3943 	.create		= shmem_create,
3944 	.lookup		= simple_lookup,
3945 	.link		= shmem_link,
3946 	.unlink		= shmem_unlink,
3947 	.symlink	= shmem_symlink,
3948 	.mkdir		= shmem_mkdir,
3949 	.rmdir		= shmem_rmdir,
3950 	.mknod		= shmem_mknod,
3951 	.rename		= shmem_rename2,
3952 	.tmpfile	= shmem_tmpfile,
3953 #endif
3954 #ifdef CONFIG_TMPFS_XATTR
3955 	.listxattr	= shmem_listxattr,
3956 	.fileattr_get	= shmem_fileattr_get,
3957 	.fileattr_set	= shmem_fileattr_set,
3958 #endif
3959 #ifdef CONFIG_TMPFS_POSIX_ACL
3960 	.setattr	= shmem_setattr,
3961 	.set_acl	= simple_set_acl,
3962 #endif
3963 };
3964 
3965 static const struct inode_operations shmem_special_inode_operations = {
3966 	.getattr	= shmem_getattr,
3967 #ifdef CONFIG_TMPFS_XATTR
3968 	.listxattr	= shmem_listxattr,
3969 #endif
3970 #ifdef CONFIG_TMPFS_POSIX_ACL
3971 	.setattr	= shmem_setattr,
3972 	.set_acl	= simple_set_acl,
3973 #endif
3974 };
3975 
3976 static const struct super_operations shmem_ops = {
3977 	.alloc_inode	= shmem_alloc_inode,
3978 	.free_inode	= shmem_free_in_core_inode,
3979 	.destroy_inode	= shmem_destroy_inode,
3980 #ifdef CONFIG_TMPFS
3981 	.statfs		= shmem_statfs,
3982 	.show_options	= shmem_show_options,
3983 #endif
3984 	.evict_inode	= shmem_evict_inode,
3985 	.drop_inode	= generic_delete_inode,
3986 	.put_super	= shmem_put_super,
3987 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3988 	.nr_cached_objects	= shmem_unused_huge_count,
3989 	.free_cached_objects	= shmem_unused_huge_scan,
3990 #endif
3991 };
3992 
3993 static const struct vm_operations_struct shmem_vm_ops = {
3994 	.fault		= shmem_fault,
3995 	.map_pages	= filemap_map_pages,
3996 #ifdef CONFIG_NUMA
3997 	.set_policy     = shmem_set_policy,
3998 	.get_policy     = shmem_get_policy,
3999 #endif
4000 };
4001 
4002 static const struct vm_operations_struct shmem_anon_vm_ops = {
4003 	.fault		= shmem_fault,
4004 	.map_pages	= filemap_map_pages,
4005 #ifdef CONFIG_NUMA
4006 	.set_policy     = shmem_set_policy,
4007 	.get_policy     = shmem_get_policy,
4008 #endif
4009 };
4010 
4011 int shmem_init_fs_context(struct fs_context *fc)
4012 {
4013 	struct shmem_options *ctx;
4014 
4015 	ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL);
4016 	if (!ctx)
4017 		return -ENOMEM;
4018 
4019 	ctx->mode = 0777 | S_ISVTX;
4020 	ctx->uid = current_fsuid();
4021 	ctx->gid = current_fsgid();
4022 
4023 	fc->fs_private = ctx;
4024 	fc->ops = &shmem_fs_context_ops;
4025 	return 0;
4026 }
4027 
4028 static struct file_system_type shmem_fs_type = {
4029 	.owner		= THIS_MODULE,
4030 	.name		= "tmpfs",
4031 	.init_fs_context = shmem_init_fs_context,
4032 #ifdef CONFIG_TMPFS
4033 	.parameters	= shmem_fs_parameters,
4034 #endif
4035 	.kill_sb	= kill_litter_super,
4036 	.fs_flags	= FS_USERNS_MOUNT,
4037 };
4038 
4039 void __init shmem_init(void)
4040 {
4041 	int error;
4042 
4043 	shmem_init_inodecache();
4044 
4045 	error = register_filesystem(&shmem_fs_type);
4046 	if (error) {
4047 		pr_err("Could not register tmpfs\n");
4048 		goto out2;
4049 	}
4050 
4051 	shm_mnt = kern_mount(&shmem_fs_type);
4052 	if (IS_ERR(shm_mnt)) {
4053 		error = PTR_ERR(shm_mnt);
4054 		pr_err("Could not kern_mount tmpfs\n");
4055 		goto out1;
4056 	}
4057 
4058 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4059 	if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
4060 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4061 	else
4062 		shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
4063 #endif
4064 	return;
4065 
4066 out1:
4067 	unregister_filesystem(&shmem_fs_type);
4068 out2:
4069 	shmem_destroy_inodecache();
4070 	shm_mnt = ERR_PTR(error);
4071 }
4072 
4073 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
4074 static ssize_t shmem_enabled_show(struct kobject *kobj,
4075 				  struct kobj_attribute *attr, char *buf)
4076 {
4077 	static const int values[] = {
4078 		SHMEM_HUGE_ALWAYS,
4079 		SHMEM_HUGE_WITHIN_SIZE,
4080 		SHMEM_HUGE_ADVISE,
4081 		SHMEM_HUGE_NEVER,
4082 		SHMEM_HUGE_DENY,
4083 		SHMEM_HUGE_FORCE,
4084 	};
4085 	int len = 0;
4086 	int i;
4087 
4088 	for (i = 0; i < ARRAY_SIZE(values); i++) {
4089 		len += sysfs_emit_at(buf, len,
4090 				     shmem_huge == values[i] ? "%s[%s]" : "%s%s",
4091 				     i ? " " : "",
4092 				     shmem_format_huge(values[i]));
4093 	}
4094 
4095 	len += sysfs_emit_at(buf, len, "\n");
4096 
4097 	return len;
4098 }
4099 
4100 static ssize_t shmem_enabled_store(struct kobject *kobj,
4101 		struct kobj_attribute *attr, const char *buf, size_t count)
4102 {
4103 	char tmp[16];
4104 	int huge;
4105 
4106 	if (count + 1 > sizeof(tmp))
4107 		return -EINVAL;
4108 	memcpy(tmp, buf, count);
4109 	tmp[count] = '\0';
4110 	if (count && tmp[count - 1] == '\n')
4111 		tmp[count - 1] = '\0';
4112 
4113 	huge = shmem_parse_huge(tmp);
4114 	if (huge == -EINVAL)
4115 		return -EINVAL;
4116 	if (!has_transparent_hugepage() &&
4117 			huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
4118 		return -EINVAL;
4119 
4120 	shmem_huge = huge;
4121 	if (shmem_huge > SHMEM_HUGE_DENY)
4122 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4123 	return count;
4124 }
4125 
4126 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);
4127 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
4128 
4129 #else /* !CONFIG_SHMEM */
4130 
4131 /*
4132  * tiny-shmem: simple shmemfs and tmpfs using ramfs code
4133  *
4134  * This is intended for small system where the benefits of the full
4135  * shmem code (swap-backed and resource-limited) are outweighed by
4136  * their complexity. On systems without swap this code should be
4137  * effectively equivalent, but much lighter weight.
4138  */
4139 
4140 static struct file_system_type shmem_fs_type = {
4141 	.name		= "tmpfs",
4142 	.init_fs_context = ramfs_init_fs_context,
4143 	.parameters	= ramfs_fs_parameters,
4144 	.kill_sb	= kill_litter_super,
4145 	.fs_flags	= FS_USERNS_MOUNT,
4146 };
4147 
4148 void __init shmem_init(void)
4149 {
4150 	BUG_ON(register_filesystem(&shmem_fs_type) != 0);
4151 
4152 	shm_mnt = kern_mount(&shmem_fs_type);
4153 	BUG_ON(IS_ERR(shm_mnt));
4154 }
4155 
4156 int shmem_unuse(unsigned int type)
4157 {
4158 	return 0;
4159 }
4160 
4161 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
4162 {
4163 	return 0;
4164 }
4165 
4166 void shmem_unlock_mapping(struct address_space *mapping)
4167 {
4168 }
4169 
4170 #ifdef CONFIG_MMU
4171 unsigned long shmem_get_unmapped_area(struct file *file,
4172 				      unsigned long addr, unsigned long len,
4173 				      unsigned long pgoff, unsigned long flags)
4174 {
4175 	return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
4176 }
4177 #endif
4178 
4179 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
4180 {
4181 	truncate_inode_pages_range(inode->i_mapping, lstart, lend);
4182 }
4183 EXPORT_SYMBOL_GPL(shmem_truncate_range);
4184 
4185 #define shmem_vm_ops				generic_file_vm_ops
4186 #define shmem_anon_vm_ops			generic_file_vm_ops
4187 #define shmem_file_operations			ramfs_file_operations
4188 #define shmem_get_inode(sb, dir, mode, dev, flags)	ramfs_get_inode(sb, dir, mode, dev)
4189 #define shmem_acct_size(flags, size)		0
4190 #define shmem_unacct_size(flags, size)		do {} while (0)
4191 
4192 #endif /* CONFIG_SHMEM */
4193 
4194 /* common code */
4195 
4196 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
4197 				       unsigned long flags, unsigned int i_flags)
4198 {
4199 	struct inode *inode;
4200 	struct file *res;
4201 
4202 	if (IS_ERR(mnt))
4203 		return ERR_CAST(mnt);
4204 
4205 	if (size < 0 || size > MAX_LFS_FILESIZE)
4206 		return ERR_PTR(-EINVAL);
4207 
4208 	if (shmem_acct_size(flags, size))
4209 		return ERR_PTR(-ENOMEM);
4210 
4211 	inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
4212 				flags);
4213 	if (unlikely(!inode)) {
4214 		shmem_unacct_size(flags, size);
4215 		return ERR_PTR(-ENOSPC);
4216 	}
4217 	inode->i_flags |= i_flags;
4218 	inode->i_size = size;
4219 	clear_nlink(inode);	/* It is unlinked */
4220 	res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
4221 	if (!IS_ERR(res))
4222 		res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
4223 				&shmem_file_operations);
4224 	if (IS_ERR(res))
4225 		iput(inode);
4226 	return res;
4227 }
4228 
4229 /**
4230  * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4231  * 	kernel internal.  There will be NO LSM permission checks against the
4232  * 	underlying inode.  So users of this interface must do LSM checks at a
4233  *	higher layer.  The users are the big_key and shm implementations.  LSM
4234  *	checks are provided at the key or shm level rather than the inode.
4235  * @name: name for dentry (to be seen in /proc/<pid>/maps
4236  * @size: size to be set for the file
4237  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4238  */
4239 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4240 {
4241 	return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
4242 }
4243 
4244 /**
4245  * shmem_file_setup - get an unlinked file living in tmpfs
4246  * @name: name for dentry (to be seen in /proc/<pid>/maps
4247  * @size: size to be set for the file
4248  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4249  */
4250 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4251 {
4252 	return __shmem_file_setup(shm_mnt, name, size, flags, 0);
4253 }
4254 EXPORT_SYMBOL_GPL(shmem_file_setup);
4255 
4256 /**
4257  * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4258  * @mnt: the tmpfs mount where the file will be created
4259  * @name: name for dentry (to be seen in /proc/<pid>/maps
4260  * @size: size to be set for the file
4261  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4262  */
4263 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4264 				       loff_t size, unsigned long flags)
4265 {
4266 	return __shmem_file_setup(mnt, name, size, flags, 0);
4267 }
4268 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4269 
4270 /**
4271  * shmem_zero_setup - setup a shared anonymous mapping
4272  * @vma: the vma to be mmapped is prepared by do_mmap
4273  */
4274 int shmem_zero_setup(struct vm_area_struct *vma)
4275 {
4276 	struct file *file;
4277 	loff_t size = vma->vm_end - vma->vm_start;
4278 
4279 	/*
4280 	 * Cloning a new file under mmap_lock leads to a lock ordering conflict
4281 	 * between XFS directory reading and selinux: since this file is only
4282 	 * accessible to the user through its mapping, use S_PRIVATE flag to
4283 	 * bypass file security, in the same way as shmem_kernel_file_setup().
4284 	 */
4285 	file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
4286 	if (IS_ERR(file))
4287 		return PTR_ERR(file);
4288 
4289 	if (vma->vm_file)
4290 		fput(vma->vm_file);
4291 	vma->vm_file = file;
4292 	vma->vm_ops = &shmem_anon_vm_ops;
4293 
4294 	return 0;
4295 }
4296 
4297 /**
4298  * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4299  * @mapping:	the page's address_space
4300  * @index:	the page index
4301  * @gfp:	the page allocator flags to use if allocating
4302  *
4303  * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4304  * with any new page allocations done using the specified allocation flags.
4305  * But read_cache_page_gfp() uses the ->read_folio() method: which does not
4306  * suit tmpfs, since it may have pages in swapcache, and needs to find those
4307  * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4308  *
4309  * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4310  * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4311  */
4312 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4313 					 pgoff_t index, gfp_t gfp)
4314 {
4315 #ifdef CONFIG_SHMEM
4316 	struct inode *inode = mapping->host;
4317 	struct folio *folio;
4318 	struct page *page;
4319 	int error;
4320 
4321 	BUG_ON(!shmem_mapping(mapping));
4322 	error = shmem_get_folio_gfp(inode, index, &folio, SGP_CACHE,
4323 				  gfp, NULL, NULL, NULL);
4324 	if (error)
4325 		return ERR_PTR(error);
4326 
4327 	folio_unlock(folio);
4328 	page = folio_file_page(folio, index);
4329 	if (PageHWPoison(page)) {
4330 		folio_put(folio);
4331 		return ERR_PTR(-EIO);
4332 	}
4333 
4334 	return page;
4335 #else
4336 	/*
4337 	 * The tiny !SHMEM case uses ramfs without swap
4338 	 */
4339 	return read_cache_page_gfp(mapping, index, gfp);
4340 #endif
4341 }
4342 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
4343