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