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