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