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