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