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