xref: /openbmc/linux/mm/shmem.c (revision 014bb1de4fc17d54907d54418126a9a9736f4aff)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * Resizable virtual memory filesystem for Linux.
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  * Copyright (C) 2000 Linus Torvalds.
51da177e4SLinus Torvalds  *		 2000 Transmeta Corp.
61da177e4SLinus Torvalds  *		 2000-2001 Christoph Rohland
71da177e4SLinus Torvalds  *		 2000-2001 SAP AG
81da177e4SLinus Torvalds  *		 2002 Red Hat Inc.
96922c0c7SHugh Dickins  * Copyright (C) 2002-2011 Hugh Dickins.
106922c0c7SHugh Dickins  * Copyright (C) 2011 Google Inc.
110edd73b3SHugh Dickins  * Copyright (C) 2002-2005 VERITAS Software Corporation.
121da177e4SLinus Torvalds  * Copyright (C) 2004 Andi Kleen, SuSE Labs
131da177e4SLinus Torvalds  *
141da177e4SLinus Torvalds  * Extended attribute support for tmpfs:
151da177e4SLinus Torvalds  * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
161da177e4SLinus Torvalds  * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
171da177e4SLinus Torvalds  *
18853ac43aSMatt Mackall  * tiny-shmem:
19853ac43aSMatt Mackall  * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
20853ac43aSMatt Mackall  *
211da177e4SLinus Torvalds  * This file is released under the GPL.
221da177e4SLinus Torvalds  */
231da177e4SLinus Torvalds 
24853ac43aSMatt Mackall #include <linux/fs.h>
25853ac43aSMatt Mackall #include <linux/init.h>
26853ac43aSMatt Mackall #include <linux/vfs.h>
27853ac43aSMatt Mackall #include <linux/mount.h>
28250297edSAndrew Morton #include <linux/ramfs.h>
29caefba17SHugh Dickins #include <linux/pagemap.h>
30853ac43aSMatt Mackall #include <linux/file.h>
31853ac43aSMatt Mackall #include <linux/mm.h>
3246c9a946SArnd Bergmann #include <linux/random.h>
33174cd4b1SIngo Molnar #include <linux/sched/signal.h>
34b95f1b31SPaul Gortmaker #include <linux/export.h>
35853ac43aSMatt Mackall #include <linux/swap.h>
36e2e40f2cSChristoph Hellwig #include <linux/uio.h>
37f3f0e1d2SKirill A. Shutemov #include <linux/khugepaged.h>
38749df87bSMike Kravetz #include <linux/hugetlb.h>
39626c3920SAl Viro #include <linux/fs_parser.h>
4086a2f3f2SMiaohe Lin #include <linux/swapfile.h>
41*014bb1deSNeilBrown #include "swap.h"
4295cc09d6SAndrea Arcangeli 
43853ac43aSMatt Mackall static struct vfsmount *shm_mnt;
44853ac43aSMatt Mackall 
45853ac43aSMatt Mackall #ifdef CONFIG_SHMEM
461da177e4SLinus Torvalds /*
471da177e4SLinus Torvalds  * This virtual memory filesystem is heavily based on the ramfs. It
481da177e4SLinus Torvalds  * extends ramfs by the ability to use swap and honor resource limits
491da177e4SLinus Torvalds  * which makes it a completely usable filesystem.
501da177e4SLinus Torvalds  */
511da177e4SLinus Torvalds 
5239f0247dSAndreas Gruenbacher #include <linux/xattr.h>
53a5694255SChristoph Hellwig #include <linux/exportfs.h>
541c7c474cSChristoph Hellwig #include <linux/posix_acl.h>
55feda821eSChristoph Hellwig #include <linux/posix_acl_xattr.h>
561da177e4SLinus Torvalds #include <linux/mman.h>
571da177e4SLinus Torvalds #include <linux/string.h>
581da177e4SLinus Torvalds #include <linux/slab.h>
591da177e4SLinus Torvalds #include <linux/backing-dev.h>
601da177e4SLinus Torvalds #include <linux/shmem_fs.h>
611da177e4SLinus Torvalds #include <linux/writeback.h>
62bda97eabSHugh Dickins #include <linux/pagevec.h>
6341ffe5d5SHugh Dickins #include <linux/percpu_counter.h>
6483e4fa9cSHugh Dickins #include <linux/falloc.h>
65708e3508SHugh Dickins #include <linux/splice.h>
661da177e4SLinus Torvalds #include <linux/security.h>
671da177e4SLinus Torvalds #include <linux/swapops.h>
681da177e4SLinus Torvalds #include <linux/mempolicy.h>
691da177e4SLinus Torvalds #include <linux/namei.h>
70b00dc3adSHugh Dickins #include <linux/ctype.h>
71304dbdb7SLee Schermerhorn #include <linux/migrate.h>
72c1f60a5aSChristoph Lameter #include <linux/highmem.h>
73680d794bSakpm@linux-foundation.org #include <linux/seq_file.h>
7492562927SMimi Zohar #include <linux/magic.h>
759183df25SDavid Herrmann #include <linux/syscalls.h>
7640e041a2SDavid Herrmann #include <linux/fcntl.h>
779183df25SDavid Herrmann #include <uapi/linux/memfd.h>
78cfda0526SMike Rapoport #include <linux/userfaultfd_k.h>
794c27fe4cSMike Rapoport #include <linux/rmap.h>
802b4db796SAmir Goldstein #include <linux/uuid.h>
81304dbdb7SLee Schermerhorn 
827c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
831da177e4SLinus Torvalds 
84dd56b046SMel Gorman #include "internal.h"
85dd56b046SMel Gorman 
8609cbfeafSKirill A. Shutemov #define BLOCKS_PER_PAGE  (PAGE_SIZE/512)
8709cbfeafSKirill A. Shutemov #define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
881da177e4SLinus Torvalds 
891da177e4SLinus Torvalds /* Pretend that each entry is of this size in directory's i_size */
901da177e4SLinus Torvalds #define BOGO_DIRENT_SIZE 20
911da177e4SLinus Torvalds 
9269f07ec9SHugh Dickins /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
9369f07ec9SHugh Dickins #define SHORT_SYMLINK_LEN 128
9469f07ec9SHugh Dickins 
951aac1400SHugh Dickins /*
96f00cdc6dSHugh Dickins  * shmem_fallocate communicates with shmem_fault or shmem_writepage via
979608703eSJan Kara  * inode->i_private (with i_rwsem making sure that it has only one user at
98f00cdc6dSHugh Dickins  * a time): we would prefer not to enlarge the shmem inode just for that.
991aac1400SHugh Dickins  */
1001aac1400SHugh Dickins struct shmem_falloc {
1018e205f77SHugh Dickins 	wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
1021aac1400SHugh Dickins 	pgoff_t start;		/* start of range currently being fallocated */
1031aac1400SHugh Dickins 	pgoff_t next;		/* the next page offset to be fallocated */
1041aac1400SHugh Dickins 	pgoff_t nr_falloced;	/* how many new pages have been fallocated */
1051aac1400SHugh Dickins 	pgoff_t nr_unswapped;	/* how often writepage refused to swap out */
1061aac1400SHugh Dickins };
1071aac1400SHugh Dickins 
1080b5071ddSAl Viro struct shmem_options {
1090b5071ddSAl Viro 	unsigned long long blocks;
1100b5071ddSAl Viro 	unsigned long long inodes;
1110b5071ddSAl Viro 	struct mempolicy *mpol;
1120b5071ddSAl Viro 	kuid_t uid;
1130b5071ddSAl Viro 	kgid_t gid;
1140b5071ddSAl Viro 	umode_t mode;
115ea3271f7SChris Down 	bool full_inums;
1160b5071ddSAl Viro 	int huge;
1170b5071ddSAl Viro 	int seen;
1180b5071ddSAl Viro #define SHMEM_SEEN_BLOCKS 1
1190b5071ddSAl Viro #define SHMEM_SEEN_INODES 2
1200b5071ddSAl Viro #define SHMEM_SEEN_HUGE 4
121ea3271f7SChris Down #define SHMEM_SEEN_INUMS 8
1220b5071ddSAl Viro };
1230b5071ddSAl Viro 
124b76db735SAndrew Morton #ifdef CONFIG_TMPFS
125680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_blocks(void)
126680d794bSakpm@linux-foundation.org {
127ca79b0c2SArun KS 	return totalram_pages() / 2;
128680d794bSakpm@linux-foundation.org }
129680d794bSakpm@linux-foundation.org 
130680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_inodes(void)
131680d794bSakpm@linux-foundation.org {
132ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
133ca79b0c2SArun KS 
134ca79b0c2SArun KS 	return min(nr_pages - totalhigh_pages(), nr_pages / 2);
135680d794bSakpm@linux-foundation.org }
136b76db735SAndrew Morton #endif
137680d794bSakpm@linux-foundation.org 
138c5bf121eSVineeth Remanan Pillai static int shmem_swapin_page(struct inode *inode, pgoff_t index,
139c5bf121eSVineeth Remanan Pillai 			     struct page **pagep, enum sgp_type sgp,
140c5bf121eSVineeth Remanan Pillai 			     gfp_t gfp, struct vm_area_struct *vma,
141c5bf121eSVineeth Remanan Pillai 			     vm_fault_t *fault_type);
14268da9f05SHugh Dickins static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1439e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp,
144cfda0526SMike Rapoport 		gfp_t gfp, struct vm_area_struct *vma,
1452b740303SSouptick Joarder 		struct vm_fault *vmf, vm_fault_t *fault_type);
14668da9f05SHugh Dickins 
147f3f0e1d2SKirill A. Shutemov int shmem_getpage(struct inode *inode, pgoff_t index,
1489e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp)
14968da9f05SHugh Dickins {
15068da9f05SHugh Dickins 	return shmem_getpage_gfp(inode, index, pagep, sgp,
151cfda0526SMike Rapoport 		mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
15268da9f05SHugh Dickins }
1531da177e4SLinus Torvalds 
1541da177e4SLinus Torvalds static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
1551da177e4SLinus Torvalds {
1561da177e4SLinus Torvalds 	return sb->s_fs_info;
1571da177e4SLinus Torvalds }
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds /*
1601da177e4SLinus Torvalds  * shmem_file_setup pre-accounts the whole fixed size of a VM object,
1611da177e4SLinus Torvalds  * for shared memory and for shared anonymous (/dev/zero) mappings
1621da177e4SLinus Torvalds  * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
1631da177e4SLinus Torvalds  * consistent with the pre-accounting of private mappings ...
1641da177e4SLinus Torvalds  */
1651da177e4SLinus Torvalds static inline int shmem_acct_size(unsigned long flags, loff_t size)
1661da177e4SLinus Torvalds {
1670b0a0806SHugh Dickins 	return (flags & VM_NORESERVE) ?
168191c5424SAl Viro 		0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
1691da177e4SLinus Torvalds }
1701da177e4SLinus Torvalds 
1711da177e4SLinus Torvalds static inline void shmem_unacct_size(unsigned long flags, loff_t size)
1721da177e4SLinus Torvalds {
1730b0a0806SHugh Dickins 	if (!(flags & VM_NORESERVE))
1741da177e4SLinus Torvalds 		vm_unacct_memory(VM_ACCT(size));
1751da177e4SLinus Torvalds }
1761da177e4SLinus Torvalds 
17777142517SKonstantin Khlebnikov static inline int shmem_reacct_size(unsigned long flags,
17877142517SKonstantin Khlebnikov 		loff_t oldsize, loff_t newsize)
17977142517SKonstantin Khlebnikov {
18077142517SKonstantin Khlebnikov 	if (!(flags & VM_NORESERVE)) {
18177142517SKonstantin Khlebnikov 		if (VM_ACCT(newsize) > VM_ACCT(oldsize))
18277142517SKonstantin Khlebnikov 			return security_vm_enough_memory_mm(current->mm,
18377142517SKonstantin Khlebnikov 					VM_ACCT(newsize) - VM_ACCT(oldsize));
18477142517SKonstantin Khlebnikov 		else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
18577142517SKonstantin Khlebnikov 			vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
18677142517SKonstantin Khlebnikov 	}
18777142517SKonstantin Khlebnikov 	return 0;
18877142517SKonstantin Khlebnikov }
18977142517SKonstantin Khlebnikov 
1901da177e4SLinus Torvalds /*
1911da177e4SLinus Torvalds  * ... whereas tmpfs objects are accounted incrementally as
19275edd345SHugh Dickins  * pages are allocated, in order to allow large sparse files.
1931da177e4SLinus Torvalds  * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
1941da177e4SLinus Torvalds  * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
1951da177e4SLinus Torvalds  */
196800d8c63SKirill A. Shutemov static inline int shmem_acct_block(unsigned long flags, long pages)
1971da177e4SLinus Torvalds {
198800d8c63SKirill A. Shutemov 	if (!(flags & VM_NORESERVE))
199800d8c63SKirill A. Shutemov 		return 0;
200800d8c63SKirill A. Shutemov 
201800d8c63SKirill A. Shutemov 	return security_vm_enough_memory_mm(current->mm,
202800d8c63SKirill A. Shutemov 			pages * VM_ACCT(PAGE_SIZE));
2031da177e4SLinus Torvalds }
2041da177e4SLinus Torvalds 
2051da177e4SLinus Torvalds static inline void shmem_unacct_blocks(unsigned long flags, long pages)
2061da177e4SLinus Torvalds {
2070b0a0806SHugh Dickins 	if (flags & VM_NORESERVE)
20809cbfeafSKirill A. Shutemov 		vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
2091da177e4SLinus Torvalds }
2101da177e4SLinus Torvalds 
2110f079694SMike Rapoport static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
2120f079694SMike Rapoport {
2130f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
2140f079694SMike Rapoport 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2150f079694SMike Rapoport 
2160f079694SMike Rapoport 	if (shmem_acct_block(info->flags, pages))
2170f079694SMike Rapoport 		return false;
2180f079694SMike Rapoport 
2190f079694SMike Rapoport 	if (sbinfo->max_blocks) {
2200f079694SMike Rapoport 		if (percpu_counter_compare(&sbinfo->used_blocks,
2210f079694SMike Rapoport 					   sbinfo->max_blocks - pages) > 0)
2220f079694SMike Rapoport 			goto unacct;
2230f079694SMike Rapoport 		percpu_counter_add(&sbinfo->used_blocks, pages);
2240f079694SMike Rapoport 	}
2250f079694SMike Rapoport 
2260f079694SMike Rapoport 	return true;
2270f079694SMike Rapoport 
2280f079694SMike Rapoport unacct:
2290f079694SMike Rapoport 	shmem_unacct_blocks(info->flags, pages);
2300f079694SMike Rapoport 	return false;
2310f079694SMike Rapoport }
2320f079694SMike Rapoport 
2330f079694SMike Rapoport static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
2340f079694SMike Rapoport {
2350f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
2360f079694SMike Rapoport 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2370f079694SMike Rapoport 
2380f079694SMike Rapoport 	if (sbinfo->max_blocks)
2390f079694SMike Rapoport 		percpu_counter_sub(&sbinfo->used_blocks, pages);
2400f079694SMike Rapoport 	shmem_unacct_blocks(info->flags, pages);
2410f079694SMike Rapoport }
2420f079694SMike Rapoport 
243759b9775SHugh Dickins static const struct super_operations shmem_ops;
24430e6a51dSHui Su const struct address_space_operations shmem_aops;
24515ad7cdcSHelge Deller static const struct file_operations shmem_file_operations;
24692e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations;
24792e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations;
24892e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations;
249f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops;
250779750d2SKirill A. Shutemov static struct file_system_type shmem_fs_type;
2511da177e4SLinus Torvalds 
252b0506e48SMike Rapoport bool vma_is_shmem(struct vm_area_struct *vma)
253b0506e48SMike Rapoport {
254b0506e48SMike Rapoport 	return vma->vm_ops == &shmem_vm_ops;
255b0506e48SMike Rapoport }
256b0506e48SMike Rapoport 
2571da177e4SLinus Torvalds static LIST_HEAD(shmem_swaplist);
258cb5f7b9aSHugh Dickins static DEFINE_MUTEX(shmem_swaplist_mutex);
2591da177e4SLinus Torvalds 
260e809d5f0SChris Down /*
261e809d5f0SChris Down  * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
262e809d5f0SChris Down  * produces a novel ino for the newly allocated inode.
263e809d5f0SChris Down  *
264e809d5f0SChris Down  * It may also be called when making a hard link to permit the space needed by
265e809d5f0SChris Down  * each dentry. However, in that case, no new inode number is needed since that
266e809d5f0SChris Down  * internally draws from another pool of inode numbers (currently global
267e809d5f0SChris Down  * get_next_ino()). This case is indicated by passing NULL as inop.
268e809d5f0SChris Down  */
269e809d5f0SChris Down #define SHMEM_INO_BATCH 1024
270e809d5f0SChris Down static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
2715b04c689SPavel Emelyanov {
2725b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
273e809d5f0SChris Down 	ino_t ino;
274e809d5f0SChris Down 
275e809d5f0SChris Down 	if (!(sb->s_flags & SB_KERNMOUNT)) {
276bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);
277bb3e96d6SByron Stanoszek 		if (sbinfo->max_inodes) {
2785b04c689SPavel Emelyanov 			if (!sbinfo->free_inodes) {
279bf11b9a8SSebastian Andrzej Siewior 				raw_spin_unlock(&sbinfo->stat_lock);
2805b04c689SPavel Emelyanov 				return -ENOSPC;
2815b04c689SPavel Emelyanov 			}
2825b04c689SPavel Emelyanov 			sbinfo->free_inodes--;
283bb3e96d6SByron Stanoszek 		}
284e809d5f0SChris Down 		if (inop) {
285e809d5f0SChris Down 			ino = sbinfo->next_ino++;
286e809d5f0SChris Down 			if (unlikely(is_zero_ino(ino)))
287e809d5f0SChris Down 				ino = sbinfo->next_ino++;
288ea3271f7SChris Down 			if (unlikely(!sbinfo->full_inums &&
289ea3271f7SChris Down 				     ino > UINT_MAX)) {
290e809d5f0SChris Down 				/*
291e809d5f0SChris Down 				 * Emulate get_next_ino uint wraparound for
292e809d5f0SChris Down 				 * compatibility
293e809d5f0SChris Down 				 */
294ea3271f7SChris Down 				if (IS_ENABLED(CONFIG_64BIT))
295ea3271f7SChris Down 					pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
296ea3271f7SChris Down 						__func__, MINOR(sb->s_dev));
297ea3271f7SChris Down 				sbinfo->next_ino = 1;
298ea3271f7SChris Down 				ino = sbinfo->next_ino++;
2995b04c689SPavel Emelyanov 			}
300e809d5f0SChris Down 			*inop = ino;
301e809d5f0SChris Down 		}
302bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
303e809d5f0SChris Down 	} else if (inop) {
304e809d5f0SChris Down 		/*
305e809d5f0SChris Down 		 * __shmem_file_setup, one of our callers, is lock-free: it
306e809d5f0SChris Down 		 * doesn't hold stat_lock in shmem_reserve_inode since
307e809d5f0SChris Down 		 * max_inodes is always 0, and is called from potentially
308e809d5f0SChris Down 		 * unknown contexts. As such, use a per-cpu batched allocator
309e809d5f0SChris Down 		 * which doesn't require the per-sb stat_lock unless we are at
310e809d5f0SChris Down 		 * the batch boundary.
311ea3271f7SChris Down 		 *
312ea3271f7SChris Down 		 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
313ea3271f7SChris Down 		 * shmem mounts are not exposed to userspace, so we don't need
314ea3271f7SChris Down 		 * to worry about things like glibc compatibility.
315e809d5f0SChris Down 		 */
316e809d5f0SChris Down 		ino_t *next_ino;
317bf11b9a8SSebastian Andrzej Siewior 
318e809d5f0SChris Down 		next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
319e809d5f0SChris Down 		ino = *next_ino;
320e809d5f0SChris Down 		if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
321bf11b9a8SSebastian Andrzej Siewior 			raw_spin_lock(&sbinfo->stat_lock);
322e809d5f0SChris Down 			ino = sbinfo->next_ino;
323e809d5f0SChris Down 			sbinfo->next_ino += SHMEM_INO_BATCH;
324bf11b9a8SSebastian Andrzej Siewior 			raw_spin_unlock(&sbinfo->stat_lock);
325e809d5f0SChris Down 			if (unlikely(is_zero_ino(ino)))
326e809d5f0SChris Down 				ino++;
327e809d5f0SChris Down 		}
328e809d5f0SChris Down 		*inop = ino;
329e809d5f0SChris Down 		*next_ino = ++ino;
330e809d5f0SChris Down 		put_cpu();
331e809d5f0SChris Down 	}
332e809d5f0SChris Down 
3335b04c689SPavel Emelyanov 	return 0;
3345b04c689SPavel Emelyanov }
3355b04c689SPavel Emelyanov 
3365b04c689SPavel Emelyanov static void shmem_free_inode(struct super_block *sb)
3375b04c689SPavel Emelyanov {
3385b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3395b04c689SPavel Emelyanov 	if (sbinfo->max_inodes) {
340bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);
3415b04c689SPavel Emelyanov 		sbinfo->free_inodes++;
342bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
3435b04c689SPavel Emelyanov 	}
3445b04c689SPavel Emelyanov }
3455b04c689SPavel Emelyanov 
34646711810SRandy Dunlap /**
34741ffe5d5SHugh Dickins  * shmem_recalc_inode - recalculate the block usage of an inode
3481da177e4SLinus Torvalds  * @inode: inode to recalc
3491da177e4SLinus Torvalds  *
3501da177e4SLinus Torvalds  * We have to calculate the free blocks since the mm can drop
3511da177e4SLinus Torvalds  * undirtied hole pages behind our back.
3521da177e4SLinus Torvalds  *
3531da177e4SLinus Torvalds  * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
3541da177e4SLinus Torvalds  * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
3551da177e4SLinus Torvalds  *
3561da177e4SLinus Torvalds  * It has to be called with the spinlock held.
3571da177e4SLinus Torvalds  */
3581da177e4SLinus Torvalds static void shmem_recalc_inode(struct inode *inode)
3591da177e4SLinus Torvalds {
3601da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
3611da177e4SLinus Torvalds 	long freed;
3621da177e4SLinus Torvalds 
3631da177e4SLinus Torvalds 	freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
3641da177e4SLinus Torvalds 	if (freed > 0) {
3651da177e4SLinus Torvalds 		info->alloced -= freed;
36654af6042SHugh Dickins 		inode->i_blocks -= freed * BLOCKS_PER_PAGE;
3670f079694SMike Rapoport 		shmem_inode_unacct_blocks(inode, freed);
3681da177e4SLinus Torvalds 	}
3691da177e4SLinus Torvalds }
3701da177e4SLinus Torvalds 
371800d8c63SKirill A. Shutemov bool shmem_charge(struct inode *inode, long pages)
372800d8c63SKirill A. Shutemov {
373800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
3744595ef88SKirill A. Shutemov 	unsigned long flags;
375800d8c63SKirill A. Shutemov 
3760f079694SMike Rapoport 	if (!shmem_inode_acct_block(inode, pages))
377800d8c63SKirill A. Shutemov 		return false;
378b1cc94abSMike Rapoport 
379aaa52e34SHugh Dickins 	/* nrpages adjustment first, then shmem_recalc_inode() when balanced */
380aaa52e34SHugh Dickins 	inode->i_mapping->nrpages += pages;
381aaa52e34SHugh Dickins 
3824595ef88SKirill A. Shutemov 	spin_lock_irqsave(&info->lock, flags);
383800d8c63SKirill A. Shutemov 	info->alloced += pages;
384800d8c63SKirill A. Shutemov 	inode->i_blocks += pages * BLOCKS_PER_PAGE;
385800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
3864595ef88SKirill A. Shutemov 	spin_unlock_irqrestore(&info->lock, flags);
387800d8c63SKirill A. Shutemov 
388800d8c63SKirill A. Shutemov 	return true;
389800d8c63SKirill A. Shutemov }
390800d8c63SKirill A. Shutemov 
391800d8c63SKirill A. Shutemov void shmem_uncharge(struct inode *inode, long pages)
392800d8c63SKirill A. Shutemov {
393800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
3944595ef88SKirill A. Shutemov 	unsigned long flags;
395800d8c63SKirill A. Shutemov 
396aaa52e34SHugh Dickins 	/* nrpages adjustment done by __delete_from_page_cache() or caller */
397aaa52e34SHugh Dickins 
3984595ef88SKirill A. Shutemov 	spin_lock_irqsave(&info->lock, flags);
399800d8c63SKirill A. Shutemov 	info->alloced -= pages;
400800d8c63SKirill A. Shutemov 	inode->i_blocks -= pages * BLOCKS_PER_PAGE;
401800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
4024595ef88SKirill A. Shutemov 	spin_unlock_irqrestore(&info->lock, flags);
403800d8c63SKirill A. Shutemov 
4040f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, pages);
405800d8c63SKirill A. Shutemov }
406800d8c63SKirill A. Shutemov 
4077a5d0fbbSHugh Dickins /*
40862f945b6SMatthew Wilcox  * Replace item expected in xarray by a new item, while holding xa_lock.
4097a5d0fbbSHugh Dickins  */
41062f945b6SMatthew Wilcox static int shmem_replace_entry(struct address_space *mapping,
4117a5d0fbbSHugh Dickins 			pgoff_t index, void *expected, void *replacement)
4127a5d0fbbSHugh Dickins {
41362f945b6SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, index);
4146dbaf22cSJohannes Weiner 	void *item;
4157a5d0fbbSHugh Dickins 
4167a5d0fbbSHugh Dickins 	VM_BUG_ON(!expected);
4176dbaf22cSJohannes Weiner 	VM_BUG_ON(!replacement);
41862f945b6SMatthew Wilcox 	item = xas_load(&xas);
4197a5d0fbbSHugh Dickins 	if (item != expected)
4207a5d0fbbSHugh Dickins 		return -ENOENT;
42162f945b6SMatthew Wilcox 	xas_store(&xas, replacement);
4227a5d0fbbSHugh Dickins 	return 0;
4237a5d0fbbSHugh Dickins }
4247a5d0fbbSHugh Dickins 
4257a5d0fbbSHugh Dickins /*
426d1899228SHugh Dickins  * Sometimes, before we decide whether to proceed or to fail, we must check
427d1899228SHugh Dickins  * that an entry was not already brought back from swap by a racing thread.
428d1899228SHugh Dickins  *
429d1899228SHugh Dickins  * Checking page is not enough: by the time a SwapCache page is locked, it
430d1899228SHugh Dickins  * might be reused, and again be SwapCache, using the same swap as before.
431d1899228SHugh Dickins  */
432d1899228SHugh Dickins static bool shmem_confirm_swap(struct address_space *mapping,
433d1899228SHugh Dickins 			       pgoff_t index, swp_entry_t swap)
434d1899228SHugh Dickins {
435a12831bfSMatthew Wilcox 	return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
436d1899228SHugh Dickins }
437d1899228SHugh Dickins 
438d1899228SHugh Dickins /*
4395a6e75f8SKirill A. Shutemov  * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
4405a6e75f8SKirill A. Shutemov  *
4415a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_NEVER:
4425a6e75f8SKirill A. Shutemov  *	disables huge pages for the mount;
4435a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ALWAYS:
4445a6e75f8SKirill A. Shutemov  *	enables huge pages for the mount;
4455a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_WITHIN_SIZE:
4465a6e75f8SKirill A. Shutemov  *	only allocate huge pages if the page will be fully within i_size,
4475a6e75f8SKirill A. Shutemov  *	also respect fadvise()/madvise() hints;
4485a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ADVISE:
4495a6e75f8SKirill A. Shutemov  *	only allocate huge pages if requested with fadvise()/madvise();
4505a6e75f8SKirill A. Shutemov  */
4515a6e75f8SKirill A. Shutemov 
4525a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_NEVER	0
4535a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ALWAYS	1
4545a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_WITHIN_SIZE	2
4555a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ADVISE	3
4565a6e75f8SKirill A. Shutemov 
4575a6e75f8SKirill A. Shutemov /*
4585a6e75f8SKirill A. Shutemov  * Special values.
4595a6e75f8SKirill A. Shutemov  * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
4605a6e75f8SKirill A. Shutemov  *
4615a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_DENY:
4625a6e75f8SKirill A. Shutemov  *	disables huge on shm_mnt and all mounts, for emergency use;
4635a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_FORCE:
4645a6e75f8SKirill A. Shutemov  *	enables huge on shm_mnt and all mounts, w/o needing option, for testing;
4655a6e75f8SKirill A. Shutemov  *
4665a6e75f8SKirill A. Shutemov  */
4675a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_DENY		(-1)
4685a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_FORCE	(-2)
4695a6e75f8SKirill A. Shutemov 
470396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4715a6e75f8SKirill A. Shutemov /* ifdef here to avoid bloating shmem.o when not necessary */
4725a6e75f8SKirill A. Shutemov 
4735e6e5a12SHugh Dickins static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER;
4745a6e75f8SKirill A. Shutemov 
4755e6e5a12SHugh Dickins bool shmem_is_huge(struct vm_area_struct *vma,
4765e6e5a12SHugh Dickins 		   struct inode *inode, pgoff_t index)
477c852023eSHugh Dickins {
478c852023eSHugh Dickins 	loff_t i_size;
479c852023eSHugh Dickins 
480f7cd16a5SXavier Roche 	if (!S_ISREG(inode->i_mode))
481f7cd16a5SXavier Roche 		return false;
4825e6e5a12SHugh Dickins 	if (shmem_huge == SHMEM_HUGE_DENY)
4835e6e5a12SHugh Dickins 		return false;
4845e6e5a12SHugh Dickins 	if (vma && ((vma->vm_flags & VM_NOHUGEPAGE) ||
4855e6e5a12SHugh Dickins 	    test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags)))
486c852023eSHugh Dickins 		return false;
487c852023eSHugh Dickins 	if (shmem_huge == SHMEM_HUGE_FORCE)
488c852023eSHugh Dickins 		return true;
4895e6e5a12SHugh Dickins 
4905e6e5a12SHugh Dickins 	switch (SHMEM_SB(inode->i_sb)->huge) {
491c852023eSHugh Dickins 	case SHMEM_HUGE_ALWAYS:
492c852023eSHugh Dickins 		return true;
493c852023eSHugh Dickins 	case SHMEM_HUGE_WITHIN_SIZE:
494de6ee659SLiu Yuntao 		index = round_up(index + 1, HPAGE_PMD_NR);
495c852023eSHugh Dickins 		i_size = round_up(i_size_read(inode), PAGE_SIZE);
496de6ee659SLiu Yuntao 		if (i_size >> PAGE_SHIFT >= index)
497c852023eSHugh Dickins 			return true;
498c852023eSHugh Dickins 		fallthrough;
499c852023eSHugh Dickins 	case SHMEM_HUGE_ADVISE:
5005e6e5a12SHugh Dickins 		if (vma && (vma->vm_flags & VM_HUGEPAGE))
5015e6e5a12SHugh Dickins 			return true;
5025e6e5a12SHugh Dickins 		fallthrough;
503c852023eSHugh Dickins 	default:
504c852023eSHugh Dickins 		return false;
505c852023eSHugh Dickins 	}
506c852023eSHugh Dickins }
5075a6e75f8SKirill A. Shutemov 
508e5f2249aSArnd Bergmann #if defined(CONFIG_SYSFS)
5095a6e75f8SKirill A. Shutemov static int shmem_parse_huge(const char *str)
5105a6e75f8SKirill A. Shutemov {
5115a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "never"))
5125a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_NEVER;
5135a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "always"))
5145a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ALWAYS;
5155a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "within_size"))
5165a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_WITHIN_SIZE;
5175a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "advise"))
5185a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ADVISE;
5195a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "deny"))
5205a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_DENY;
5215a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "force"))
5225a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_FORCE;
5235a6e75f8SKirill A. Shutemov 	return -EINVAL;
5245a6e75f8SKirill A. Shutemov }
525e5f2249aSArnd Bergmann #endif
5265a6e75f8SKirill A. Shutemov 
527e5f2249aSArnd Bergmann #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
5285a6e75f8SKirill A. Shutemov static const char *shmem_format_huge(int huge)
5295a6e75f8SKirill A. Shutemov {
5305a6e75f8SKirill A. Shutemov 	switch (huge) {
5315a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_NEVER:
5325a6e75f8SKirill A. Shutemov 		return "never";
5335a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ALWAYS:
5345a6e75f8SKirill A. Shutemov 		return "always";
5355a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_WITHIN_SIZE:
5365a6e75f8SKirill A. Shutemov 		return "within_size";
5375a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ADVISE:
5385a6e75f8SKirill A. Shutemov 		return "advise";
5395a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_DENY:
5405a6e75f8SKirill A. Shutemov 		return "deny";
5415a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_FORCE:
5425a6e75f8SKirill A. Shutemov 		return "force";
5435a6e75f8SKirill A. Shutemov 	default:
5445a6e75f8SKirill A. Shutemov 		VM_BUG_ON(1);
5455a6e75f8SKirill A. Shutemov 		return "bad_val";
5465a6e75f8SKirill A. Shutemov 	}
5475a6e75f8SKirill A. Shutemov }
548f1f5929cSJérémy Lefaure #endif
5495a6e75f8SKirill A. Shutemov 
550779750d2SKirill A. Shutemov static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
551779750d2SKirill A. Shutemov 		struct shrink_control *sc, unsigned long nr_to_split)
552779750d2SKirill A. Shutemov {
553779750d2SKirill A. Shutemov 	LIST_HEAD(list), *pos, *next;
554253fd0f0SKirill A. Shutemov 	LIST_HEAD(to_remove);
555779750d2SKirill A. Shutemov 	struct inode *inode;
556779750d2SKirill A. Shutemov 	struct shmem_inode_info *info;
557779750d2SKirill A. Shutemov 	struct page *page;
558779750d2SKirill A. Shutemov 	unsigned long batch = sc ? sc->nr_to_scan : 128;
55962c9827cSGang Li 	int split = 0;
560779750d2SKirill A. Shutemov 
561779750d2SKirill A. Shutemov 	if (list_empty(&sbinfo->shrinklist))
562779750d2SKirill A. Shutemov 		return SHRINK_STOP;
563779750d2SKirill A. Shutemov 
564779750d2SKirill A. Shutemov 	spin_lock(&sbinfo->shrinklist_lock);
565779750d2SKirill A. Shutemov 	list_for_each_safe(pos, next, &sbinfo->shrinklist) {
566779750d2SKirill A. Shutemov 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
567779750d2SKirill A. Shutemov 
568779750d2SKirill A. Shutemov 		/* pin the inode */
569779750d2SKirill A. Shutemov 		inode = igrab(&info->vfs_inode);
570779750d2SKirill A. Shutemov 
571779750d2SKirill A. Shutemov 		/* inode is about to be evicted */
572779750d2SKirill A. Shutemov 		if (!inode) {
573779750d2SKirill A. Shutemov 			list_del_init(&info->shrinklist);
574779750d2SKirill A. Shutemov 			goto next;
575779750d2SKirill A. Shutemov 		}
576779750d2SKirill A. Shutemov 
577779750d2SKirill A. Shutemov 		/* Check if there's anything to gain */
578779750d2SKirill A. Shutemov 		if (round_up(inode->i_size, PAGE_SIZE) ==
579779750d2SKirill A. Shutemov 				round_up(inode->i_size, HPAGE_PMD_SIZE)) {
580253fd0f0SKirill A. Shutemov 			list_move(&info->shrinklist, &to_remove);
581779750d2SKirill A. Shutemov 			goto next;
582779750d2SKirill A. Shutemov 		}
583779750d2SKirill A. Shutemov 
584779750d2SKirill A. Shutemov 		list_move(&info->shrinklist, &list);
585779750d2SKirill A. Shutemov next:
58662c9827cSGang Li 		sbinfo->shrinklist_len--;
587779750d2SKirill A. Shutemov 		if (!--batch)
588779750d2SKirill A. Shutemov 			break;
589779750d2SKirill A. Shutemov 	}
590779750d2SKirill A. Shutemov 	spin_unlock(&sbinfo->shrinklist_lock);
591779750d2SKirill A. Shutemov 
592253fd0f0SKirill A. Shutemov 	list_for_each_safe(pos, next, &to_remove) {
593253fd0f0SKirill A. Shutemov 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
594253fd0f0SKirill A. Shutemov 		inode = &info->vfs_inode;
595253fd0f0SKirill A. Shutemov 		list_del_init(&info->shrinklist);
596253fd0f0SKirill A. Shutemov 		iput(inode);
597253fd0f0SKirill A. Shutemov 	}
598253fd0f0SKirill A. Shutemov 
599779750d2SKirill A. Shutemov 	list_for_each_safe(pos, next, &list) {
600779750d2SKirill A. Shutemov 		int ret;
601779750d2SKirill A. Shutemov 
602779750d2SKirill A. Shutemov 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
603779750d2SKirill A. Shutemov 		inode = &info->vfs_inode;
604779750d2SKirill A. Shutemov 
605b3cd54b2SKirill A. Shutemov 		if (nr_to_split && split >= nr_to_split)
60662c9827cSGang Li 			goto move_back;
607779750d2SKirill A. Shutemov 
608b3cd54b2SKirill A. Shutemov 		page = find_get_page(inode->i_mapping,
609779750d2SKirill A. Shutemov 				(inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
610779750d2SKirill A. Shutemov 		if (!page)
611779750d2SKirill A. Shutemov 			goto drop;
612779750d2SKirill A. Shutemov 
613b3cd54b2SKirill A. Shutemov 		/* No huge page at the end of the file: nothing to split */
614779750d2SKirill A. Shutemov 		if (!PageTransHuge(page)) {
615779750d2SKirill A. Shutemov 			put_page(page);
616779750d2SKirill A. Shutemov 			goto drop;
617779750d2SKirill A. Shutemov 		}
618779750d2SKirill A. Shutemov 
619b3cd54b2SKirill A. Shutemov 		/*
62062c9827cSGang Li 		 * Move the inode on the list back to shrinklist if we failed
62162c9827cSGang Li 		 * to lock the page at this time.
622b3cd54b2SKirill A. Shutemov 		 *
623b3cd54b2SKirill A. Shutemov 		 * Waiting for the lock may lead to deadlock in the
624b3cd54b2SKirill A. Shutemov 		 * reclaim path.
625b3cd54b2SKirill A. Shutemov 		 */
626b3cd54b2SKirill A. Shutemov 		if (!trylock_page(page)) {
627b3cd54b2SKirill A. Shutemov 			put_page(page);
62862c9827cSGang Li 			goto move_back;
629b3cd54b2SKirill A. Shutemov 		}
630b3cd54b2SKirill A. Shutemov 
631779750d2SKirill A. Shutemov 		ret = split_huge_page(page);
632779750d2SKirill A. Shutemov 		unlock_page(page);
633779750d2SKirill A. Shutemov 		put_page(page);
634779750d2SKirill A. Shutemov 
63562c9827cSGang Li 		/* If split failed move the inode on the list back to shrinklist */
636b3cd54b2SKirill A. Shutemov 		if (ret)
63762c9827cSGang Li 			goto move_back;
638779750d2SKirill A. Shutemov 
639779750d2SKirill A. Shutemov 		split++;
640779750d2SKirill A. Shutemov drop:
641779750d2SKirill A. Shutemov 		list_del_init(&info->shrinklist);
64262c9827cSGang Li 		goto put;
64362c9827cSGang Li move_back:
64462c9827cSGang Li 		/*
64562c9827cSGang Li 		 * Make sure the inode is either on the global list or deleted
64662c9827cSGang Li 		 * from any local list before iput() since it could be deleted
64762c9827cSGang Li 		 * in another thread once we put the inode (then the local list
64862c9827cSGang Li 		 * is corrupted).
64962c9827cSGang Li 		 */
65062c9827cSGang Li 		spin_lock(&sbinfo->shrinklist_lock);
65162c9827cSGang Li 		list_move(&info->shrinklist, &sbinfo->shrinklist);
65262c9827cSGang Li 		sbinfo->shrinklist_len++;
65362c9827cSGang Li 		spin_unlock(&sbinfo->shrinklist_lock);
65462c9827cSGang Li put:
655779750d2SKirill A. Shutemov 		iput(inode);
656779750d2SKirill A. Shutemov 	}
657779750d2SKirill A. Shutemov 
658779750d2SKirill A. Shutemov 	return split;
659779750d2SKirill A. Shutemov }
660779750d2SKirill A. Shutemov 
661779750d2SKirill A. Shutemov static long shmem_unused_huge_scan(struct super_block *sb,
662779750d2SKirill A. Shutemov 		struct shrink_control *sc)
663779750d2SKirill A. Shutemov {
664779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
665779750d2SKirill A. Shutemov 
666779750d2SKirill A. Shutemov 	if (!READ_ONCE(sbinfo->shrinklist_len))
667779750d2SKirill A. Shutemov 		return SHRINK_STOP;
668779750d2SKirill A. Shutemov 
669779750d2SKirill A. Shutemov 	return shmem_unused_huge_shrink(sbinfo, sc, 0);
670779750d2SKirill A. Shutemov }
671779750d2SKirill A. Shutemov 
672779750d2SKirill A. Shutemov static long shmem_unused_huge_count(struct super_block *sb,
673779750d2SKirill A. Shutemov 		struct shrink_control *sc)
674779750d2SKirill A. Shutemov {
675779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
676779750d2SKirill A. Shutemov 	return READ_ONCE(sbinfo->shrinklist_len);
677779750d2SKirill A. Shutemov }
678396bcc52SMatthew Wilcox (Oracle) #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
6795a6e75f8SKirill A. Shutemov 
6805a6e75f8SKirill A. Shutemov #define shmem_huge SHMEM_HUGE_DENY
6815a6e75f8SKirill A. Shutemov 
6825e6e5a12SHugh Dickins bool shmem_is_huge(struct vm_area_struct *vma,
6835e6e5a12SHugh Dickins 		   struct inode *inode, pgoff_t index)
6845e6e5a12SHugh Dickins {
6855e6e5a12SHugh Dickins 	return false;
6865e6e5a12SHugh Dickins }
6875e6e5a12SHugh Dickins 
688779750d2SKirill A. Shutemov static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
689779750d2SKirill A. Shutemov 		struct shrink_control *sc, unsigned long nr_to_split)
690779750d2SKirill A. Shutemov {
691779750d2SKirill A. Shutemov 	return 0;
692779750d2SKirill A. Shutemov }
693396bcc52SMatthew Wilcox (Oracle) #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
6945a6e75f8SKirill A. Shutemov 
6955a6e75f8SKirill A. Shutemov /*
69646f65ec1SHugh Dickins  * Like add_to_page_cache_locked, but error if expected item has gone.
69746f65ec1SHugh Dickins  */
69846f65ec1SHugh Dickins static int shmem_add_to_page_cache(struct page *page,
69946f65ec1SHugh Dickins 				   struct address_space *mapping,
7003fea5a49SJohannes Weiner 				   pgoff_t index, void *expected, gfp_t gfp,
7013fea5a49SJohannes Weiner 				   struct mm_struct *charge_mm)
70246f65ec1SHugh Dickins {
703552446a4SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
704d8c6546bSMatthew Wilcox (Oracle) 	unsigned long nr = compound_nr(page);
7053fea5a49SJohannes Weiner 	int error;
70646f65ec1SHugh Dickins 
707800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageTail(page), page);
708800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(index != round_down(index, nr), page);
709309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
710309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
711800d8c63SKirill A. Shutemov 	VM_BUG_ON(expected && PageTransHuge(page));
71246f65ec1SHugh Dickins 
713800d8c63SKirill A. Shutemov 	page_ref_add(page, nr);
71446f65ec1SHugh Dickins 	page->mapping = mapping;
71546f65ec1SHugh Dickins 	page->index = index;
71646f65ec1SHugh Dickins 
7174c6355b2SJohannes Weiner 	if (!PageSwapCache(page)) {
7188f425e4eSMatthew Wilcox (Oracle) 		error = mem_cgroup_charge(page_folio(page), charge_mm, gfp);
7193fea5a49SJohannes Weiner 		if (error) {
7204c6355b2SJohannes Weiner 			if (PageTransHuge(page)) {
7213fea5a49SJohannes Weiner 				count_vm_event(THP_FILE_FALLBACK);
7223fea5a49SJohannes Weiner 				count_vm_event(THP_FILE_FALLBACK_CHARGE);
7233fea5a49SJohannes Weiner 			}
7243fea5a49SJohannes Weiner 			goto error;
7253fea5a49SJohannes Weiner 		}
7264c6355b2SJohannes Weiner 	}
7273fea5a49SJohannes Weiner 	cgroup_throttle_swaprate(page, gfp);
7283fea5a49SJohannes Weiner 
729552446a4SMatthew Wilcox 	do {
730552446a4SMatthew Wilcox 		xas_lock_irq(&xas);
7316b24ca4aSMatthew Wilcox (Oracle) 		if (expected != xas_find_conflict(&xas)) {
732552446a4SMatthew Wilcox 			xas_set_err(&xas, -EEXIST);
7336b24ca4aSMatthew Wilcox (Oracle) 			goto unlock;
7346b24ca4aSMatthew Wilcox (Oracle) 		}
7356b24ca4aSMatthew Wilcox (Oracle) 		if (expected && xas_find_conflict(&xas)) {
7366b24ca4aSMatthew Wilcox (Oracle) 			xas_set_err(&xas, -EEXIST);
7376b24ca4aSMatthew Wilcox (Oracle) 			goto unlock;
7386b24ca4aSMatthew Wilcox (Oracle) 		}
7396b24ca4aSMatthew Wilcox (Oracle) 		xas_store(&xas, page);
740552446a4SMatthew Wilcox 		if (xas_error(&xas))
741552446a4SMatthew Wilcox 			goto unlock;
742800d8c63SKirill A. Shutemov 		if (PageTransHuge(page)) {
743800d8c63SKirill A. Shutemov 			count_vm_event(THP_FILE_ALLOC);
74457b2847dSMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_THPS, nr);
745552446a4SMatthew Wilcox 		}
746552446a4SMatthew Wilcox 		mapping->nrpages += nr;
7470d1c2072SJohannes Weiner 		__mod_lruvec_page_state(page, NR_FILE_PAGES, nr);
7480d1c2072SJohannes Weiner 		__mod_lruvec_page_state(page, NR_SHMEM, nr);
749552446a4SMatthew Wilcox unlock:
750552446a4SMatthew Wilcox 		xas_unlock_irq(&xas);
751552446a4SMatthew Wilcox 	} while (xas_nomem(&xas, gfp));
752552446a4SMatthew Wilcox 
753552446a4SMatthew Wilcox 	if (xas_error(&xas)) {
7543fea5a49SJohannes Weiner 		error = xas_error(&xas);
7553fea5a49SJohannes Weiner 		goto error;
75646f65ec1SHugh Dickins 	}
757552446a4SMatthew Wilcox 
758552446a4SMatthew Wilcox 	return 0;
7593fea5a49SJohannes Weiner error:
7603fea5a49SJohannes Weiner 	page->mapping = NULL;
7613fea5a49SJohannes Weiner 	page_ref_sub(page, nr);
7623fea5a49SJohannes Weiner 	return error;
76346f65ec1SHugh Dickins }
76446f65ec1SHugh Dickins 
76546f65ec1SHugh Dickins /*
7666922c0c7SHugh Dickins  * Like delete_from_page_cache, but substitutes swap for page.
7676922c0c7SHugh Dickins  */
7686922c0c7SHugh Dickins static void shmem_delete_from_page_cache(struct page *page, void *radswap)
7696922c0c7SHugh Dickins {
7706922c0c7SHugh Dickins 	struct address_space *mapping = page->mapping;
7716922c0c7SHugh Dickins 	int error;
7726922c0c7SHugh Dickins 
773800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageCompound(page), page);
774800d8c63SKirill A. Shutemov 
775b93b0163SMatthew Wilcox 	xa_lock_irq(&mapping->i_pages);
77662f945b6SMatthew Wilcox 	error = shmem_replace_entry(mapping, page->index, page, radswap);
7776922c0c7SHugh Dickins 	page->mapping = NULL;
7786922c0c7SHugh Dickins 	mapping->nrpages--;
7790d1c2072SJohannes Weiner 	__dec_lruvec_page_state(page, NR_FILE_PAGES);
7800d1c2072SJohannes Weiner 	__dec_lruvec_page_state(page, NR_SHMEM);
781b93b0163SMatthew Wilcox 	xa_unlock_irq(&mapping->i_pages);
78209cbfeafSKirill A. Shutemov 	put_page(page);
7836922c0c7SHugh Dickins 	BUG_ON(error);
7846922c0c7SHugh Dickins }
7856922c0c7SHugh Dickins 
7866922c0c7SHugh Dickins /*
787c121d3bbSMatthew Wilcox  * Remove swap entry from page cache, free the swap and its page cache.
7887a5d0fbbSHugh Dickins  */
7897a5d0fbbSHugh Dickins static int shmem_free_swap(struct address_space *mapping,
7907a5d0fbbSHugh Dickins 			   pgoff_t index, void *radswap)
7917a5d0fbbSHugh Dickins {
7926dbaf22cSJohannes Weiner 	void *old;
7937a5d0fbbSHugh Dickins 
79455f3f7eaSMatthew Wilcox 	old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
7956dbaf22cSJohannes Weiner 	if (old != radswap)
7966dbaf22cSJohannes Weiner 		return -ENOENT;
7977a5d0fbbSHugh Dickins 	free_swap_and_cache(radix_to_swp_entry(radswap));
7986dbaf22cSJohannes Weiner 	return 0;
7997a5d0fbbSHugh Dickins }
8007a5d0fbbSHugh Dickins 
8017a5d0fbbSHugh Dickins /*
8026a15a370SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
80348131e03SVlastimil Babka  * given offsets are swapped out.
8046a15a370SVlastimil Babka  *
8059608703eSJan Kara  * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
8066a15a370SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
8076a15a370SVlastimil Babka  */
80848131e03SVlastimil Babka unsigned long shmem_partial_swap_usage(struct address_space *mapping,
80948131e03SVlastimil Babka 						pgoff_t start, pgoff_t end)
8106a15a370SVlastimil Babka {
8117ae3424fSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
8126a15a370SVlastimil Babka 	struct page *page;
81348131e03SVlastimil Babka 	unsigned long swapped = 0;
8146a15a370SVlastimil Babka 
8156a15a370SVlastimil Babka 	rcu_read_lock();
8167ae3424fSMatthew Wilcox 	xas_for_each(&xas, page, end - 1) {
8177ae3424fSMatthew Wilcox 		if (xas_retry(&xas, page))
8182cf938aaSMatthew Wilcox 			continue;
8193159f943SMatthew Wilcox 		if (xa_is_value(page))
8206a15a370SVlastimil Babka 			swapped++;
8216a15a370SVlastimil Babka 
8226a15a370SVlastimil Babka 		if (need_resched()) {
8237ae3424fSMatthew Wilcox 			xas_pause(&xas);
8246a15a370SVlastimil Babka 			cond_resched_rcu();
8256a15a370SVlastimil Babka 		}
8266a15a370SVlastimil Babka 	}
8276a15a370SVlastimil Babka 
8286a15a370SVlastimil Babka 	rcu_read_unlock();
8296a15a370SVlastimil Babka 
8306a15a370SVlastimil Babka 	return swapped << PAGE_SHIFT;
8316a15a370SVlastimil Babka }
8326a15a370SVlastimil Babka 
8336a15a370SVlastimil Babka /*
83448131e03SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
83548131e03SVlastimil Babka  * given vma is swapped out.
83648131e03SVlastimil Babka  *
8379608703eSJan Kara  * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
83848131e03SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
83948131e03SVlastimil Babka  */
84048131e03SVlastimil Babka unsigned long shmem_swap_usage(struct vm_area_struct *vma)
84148131e03SVlastimil Babka {
84248131e03SVlastimil Babka 	struct inode *inode = file_inode(vma->vm_file);
84348131e03SVlastimil Babka 	struct shmem_inode_info *info = SHMEM_I(inode);
84448131e03SVlastimil Babka 	struct address_space *mapping = inode->i_mapping;
84548131e03SVlastimil Babka 	unsigned long swapped;
84648131e03SVlastimil Babka 
84748131e03SVlastimil Babka 	/* Be careful as we don't hold info->lock */
84848131e03SVlastimil Babka 	swapped = READ_ONCE(info->swapped);
84948131e03SVlastimil Babka 
85048131e03SVlastimil Babka 	/*
85148131e03SVlastimil Babka 	 * The easier cases are when the shmem object has nothing in swap, or
85248131e03SVlastimil Babka 	 * the vma maps it whole. Then we can simply use the stats that we
85348131e03SVlastimil Babka 	 * already track.
85448131e03SVlastimil Babka 	 */
85548131e03SVlastimil Babka 	if (!swapped)
85648131e03SVlastimil Babka 		return 0;
85748131e03SVlastimil Babka 
85848131e03SVlastimil Babka 	if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
85948131e03SVlastimil Babka 		return swapped << PAGE_SHIFT;
86048131e03SVlastimil Babka 
86148131e03SVlastimil Babka 	/* Here comes the more involved part */
86202399c88SPeter Xu 	return shmem_partial_swap_usage(mapping, vma->vm_pgoff,
86302399c88SPeter Xu 					vma->vm_pgoff + vma_pages(vma));
86448131e03SVlastimil Babka }
86548131e03SVlastimil Babka 
86648131e03SVlastimil Babka /*
86724513264SHugh Dickins  * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
86824513264SHugh Dickins  */
86924513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
87024513264SHugh Dickins {
87124513264SHugh Dickins 	struct pagevec pvec;
87224513264SHugh Dickins 	pgoff_t index = 0;
87324513264SHugh Dickins 
87486679820SMel Gorman 	pagevec_init(&pvec);
87524513264SHugh Dickins 	/*
87624513264SHugh Dickins 	 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
87724513264SHugh Dickins 	 */
87824513264SHugh Dickins 	while (!mapping_unevictable(mapping)) {
87996888e0aSMatthew Wilcox (Oracle) 		if (!pagevec_lookup(&pvec, mapping, &index))
88024513264SHugh Dickins 			break;
88164e3d12fSKuo-Hsin Yang 		check_move_unevictable_pages(&pvec);
88224513264SHugh Dickins 		pagevec_release(&pvec);
88324513264SHugh Dickins 		cond_resched();
88424513264SHugh Dickins 	}
8857a5d0fbbSHugh Dickins }
8867a5d0fbbSHugh Dickins 
887b9a8a419SMatthew Wilcox (Oracle) static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
88871725ed1SHugh Dickins {
889b9a8a419SMatthew Wilcox (Oracle) 	struct folio *folio;
890b9a8a419SMatthew Wilcox (Oracle) 	struct page *page;
89171725ed1SHugh Dickins 
892b9a8a419SMatthew Wilcox (Oracle) 	/*
893b9a8a419SMatthew Wilcox (Oracle) 	 * At first avoid shmem_getpage(,,,SGP_READ): that fails
894b9a8a419SMatthew Wilcox (Oracle) 	 * beyond i_size, and reports fallocated pages as holes.
895b9a8a419SMatthew Wilcox (Oracle) 	 */
896b9a8a419SMatthew Wilcox (Oracle) 	folio = __filemap_get_folio(inode->i_mapping, index,
897b9a8a419SMatthew Wilcox (Oracle) 					FGP_ENTRY | FGP_LOCK, 0);
898b9a8a419SMatthew Wilcox (Oracle) 	if (!xa_is_value(folio))
899b9a8a419SMatthew Wilcox (Oracle) 		return folio;
900b9a8a419SMatthew Wilcox (Oracle) 	/*
901b9a8a419SMatthew Wilcox (Oracle) 	 * But read a page back from swap if any of it is within i_size
902b9a8a419SMatthew Wilcox (Oracle) 	 * (although in some cases this is just a waste of time).
903b9a8a419SMatthew Wilcox (Oracle) 	 */
904b9a8a419SMatthew Wilcox (Oracle) 	page = NULL;
905b9a8a419SMatthew Wilcox (Oracle) 	shmem_getpage(inode, index, &page, SGP_READ);
906b9a8a419SMatthew Wilcox (Oracle) 	return page ? page_folio(page) : NULL;
90771725ed1SHugh Dickins }
90871725ed1SHugh Dickins 
90971725ed1SHugh Dickins /*
9107f4446eeSMatthew Wilcox  * Remove range of pages and swap entries from page cache, and free them.
9111635f6a7SHugh Dickins  * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
9127a5d0fbbSHugh Dickins  */
9131635f6a7SHugh Dickins static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
9141635f6a7SHugh Dickins 								 bool unfalloc)
9151da177e4SLinus Torvalds {
916285b2c4fSHugh Dickins 	struct address_space *mapping = inode->i_mapping;
9171da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
91809cbfeafSKirill A. Shutemov 	pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
91909cbfeafSKirill A. Shutemov 	pgoff_t end = (lend + 1) >> PAGE_SHIFT;
9200e499ed3SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
9217a5d0fbbSHugh Dickins 	pgoff_t indices[PAGEVEC_SIZE];
922b9a8a419SMatthew Wilcox (Oracle) 	struct folio *folio;
923b9a8a419SMatthew Wilcox (Oracle) 	bool same_folio;
9247a5d0fbbSHugh Dickins 	long nr_swaps_freed = 0;
925285b2c4fSHugh Dickins 	pgoff_t index;
926bda97eabSHugh Dickins 	int i;
9271da177e4SLinus Torvalds 
92883e4fa9cSHugh Dickins 	if (lend == -1)
92983e4fa9cSHugh Dickins 		end = -1;	/* unsigned, so actually very big */
930bda97eabSHugh Dickins 
931d144bf62SHugh Dickins 	if (info->fallocend > start && info->fallocend <= end && !unfalloc)
932d144bf62SHugh Dickins 		info->fallocend = start;
933d144bf62SHugh Dickins 
93451dcbdacSMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
935bda97eabSHugh Dickins 	index = start;
9365c211ba2SMatthew Wilcox (Oracle) 	while (index < end && find_lock_entries(mapping, index, end - 1,
93751dcbdacSMatthew Wilcox (Oracle) 			&fbatch, indices)) {
93851dcbdacSMatthew Wilcox (Oracle) 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
939b9a8a419SMatthew Wilcox (Oracle) 			folio = fbatch.folios[i];
940bda97eabSHugh Dickins 
9417a5d0fbbSHugh Dickins 			index = indices[i];
942bda97eabSHugh Dickins 
9437b774aabSMatthew Wilcox (Oracle) 			if (xa_is_value(folio)) {
9441635f6a7SHugh Dickins 				if (unfalloc)
9451635f6a7SHugh Dickins 					continue;
9467a5d0fbbSHugh Dickins 				nr_swaps_freed += !shmem_free_swap(mapping,
9477b774aabSMatthew Wilcox (Oracle) 								index, folio);
9487a5d0fbbSHugh Dickins 				continue;
9497a5d0fbbSHugh Dickins 			}
9507b774aabSMatthew Wilcox (Oracle) 			index += folio_nr_pages(folio) - 1;
9517a5d0fbbSHugh Dickins 
9527b774aabSMatthew Wilcox (Oracle) 			if (!unfalloc || !folio_test_uptodate(folio))
9531e84a3d9SMatthew Wilcox (Oracle) 				truncate_inode_folio(mapping, folio);
9547b774aabSMatthew Wilcox (Oracle) 			folio_unlock(folio);
955bda97eabSHugh Dickins 		}
95651dcbdacSMatthew Wilcox (Oracle) 		folio_batch_remove_exceptionals(&fbatch);
95751dcbdacSMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
958bda97eabSHugh Dickins 		cond_resched();
959bda97eabSHugh Dickins 		index++;
960bda97eabSHugh Dickins 	}
961bda97eabSHugh Dickins 
962b9a8a419SMatthew Wilcox (Oracle) 	same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
963b9a8a419SMatthew Wilcox (Oracle) 	folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT);
964b9a8a419SMatthew Wilcox (Oracle) 	if (folio) {
965b9a8a419SMatthew Wilcox (Oracle) 		same_folio = lend < folio_pos(folio) + folio_size(folio);
966b9a8a419SMatthew Wilcox (Oracle) 		folio_mark_dirty(folio);
967b9a8a419SMatthew Wilcox (Oracle) 		if (!truncate_inode_partial_folio(folio, lstart, lend)) {
968b9a8a419SMatthew Wilcox (Oracle) 			start = folio->index + folio_nr_pages(folio);
969b9a8a419SMatthew Wilcox (Oracle) 			if (same_folio)
970b9a8a419SMatthew Wilcox (Oracle) 				end = folio->index;
97183e4fa9cSHugh Dickins 		}
972b9a8a419SMatthew Wilcox (Oracle) 		folio_unlock(folio);
973b9a8a419SMatthew Wilcox (Oracle) 		folio_put(folio);
974b9a8a419SMatthew Wilcox (Oracle) 		folio = NULL;
975bda97eabSHugh Dickins 	}
976b9a8a419SMatthew Wilcox (Oracle) 
977b9a8a419SMatthew Wilcox (Oracle) 	if (!same_folio)
978b9a8a419SMatthew Wilcox (Oracle) 		folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT);
979b9a8a419SMatthew Wilcox (Oracle) 	if (folio) {
980b9a8a419SMatthew Wilcox (Oracle) 		folio_mark_dirty(folio);
981b9a8a419SMatthew Wilcox (Oracle) 		if (!truncate_inode_partial_folio(folio, lstart, lend))
982b9a8a419SMatthew Wilcox (Oracle) 			end = folio->index;
983b9a8a419SMatthew Wilcox (Oracle) 		folio_unlock(folio);
984b9a8a419SMatthew Wilcox (Oracle) 		folio_put(folio);
985bda97eabSHugh Dickins 	}
986bda97eabSHugh Dickins 
987bda97eabSHugh Dickins 	index = start;
988b1a36650SHugh Dickins 	while (index < end) {
989bda97eabSHugh Dickins 		cond_resched();
9900cd6144aSJohannes Weiner 
9910e499ed3SMatthew Wilcox (Oracle) 		if (!find_get_entries(mapping, index, end - 1, &fbatch,
992cf2039afSMatthew Wilcox (Oracle) 				indices)) {
993b1a36650SHugh Dickins 			/* If all gone or hole-punch or unfalloc, we're done */
994b1a36650SHugh Dickins 			if (index == start || end != -1)
995bda97eabSHugh Dickins 				break;
996b1a36650SHugh Dickins 			/* But if truncating, restart to make sure all gone */
997bda97eabSHugh Dickins 			index = start;
998bda97eabSHugh Dickins 			continue;
999bda97eabSHugh Dickins 		}
10000e499ed3SMatthew Wilcox (Oracle) 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
1001b9a8a419SMatthew Wilcox (Oracle) 			folio = fbatch.folios[i];
1002bda97eabSHugh Dickins 
10037a5d0fbbSHugh Dickins 			index = indices[i];
10040e499ed3SMatthew Wilcox (Oracle) 			if (xa_is_value(folio)) {
10051635f6a7SHugh Dickins 				if (unfalloc)
10061635f6a7SHugh Dickins 					continue;
10070e499ed3SMatthew Wilcox (Oracle) 				if (shmem_free_swap(mapping, index, folio)) {
1008b1a36650SHugh Dickins 					/* Swap was replaced by page: retry */
1009b1a36650SHugh Dickins 					index--;
1010b1a36650SHugh Dickins 					break;
1011b1a36650SHugh Dickins 				}
1012b1a36650SHugh Dickins 				nr_swaps_freed++;
10137a5d0fbbSHugh Dickins 				continue;
10147a5d0fbbSHugh Dickins 			}
10157a5d0fbbSHugh Dickins 
10160e499ed3SMatthew Wilcox (Oracle) 			folio_lock(folio);
1017800d8c63SKirill A. Shutemov 
10180e499ed3SMatthew Wilcox (Oracle) 			if (!unfalloc || !folio_test_uptodate(folio)) {
10190e499ed3SMatthew Wilcox (Oracle) 				if (folio_mapping(folio) != mapping) {
1020b1a36650SHugh Dickins 					/* Page was replaced by swap: retry */
10210e499ed3SMatthew Wilcox (Oracle) 					folio_unlock(folio);
1022b1a36650SHugh Dickins 					index--;
1023b1a36650SHugh Dickins 					break;
10247a5d0fbbSHugh Dickins 				}
10250e499ed3SMatthew Wilcox (Oracle) 				VM_BUG_ON_FOLIO(folio_test_writeback(folio),
10260e499ed3SMatthew Wilcox (Oracle) 						folio);
10270e499ed3SMatthew Wilcox (Oracle) 				truncate_inode_folio(mapping, folio);
102871725ed1SHugh Dickins 			}
1029b9a8a419SMatthew Wilcox (Oracle) 			index = folio->index + folio_nr_pages(folio) - 1;
10300e499ed3SMatthew Wilcox (Oracle) 			folio_unlock(folio);
1031bda97eabSHugh Dickins 		}
10320e499ed3SMatthew Wilcox (Oracle) 		folio_batch_remove_exceptionals(&fbatch);
10330e499ed3SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1034bda97eabSHugh Dickins 		index++;
1035bda97eabSHugh Dickins 	}
103694c1e62dSHugh Dickins 
10374595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
10387a5d0fbbSHugh Dickins 	info->swapped -= nr_swaps_freed;
10391da177e4SLinus Torvalds 	shmem_recalc_inode(inode);
10404595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
10411635f6a7SHugh Dickins }
10421da177e4SLinus Torvalds 
10431635f6a7SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
10441635f6a7SHugh Dickins {
10451635f6a7SHugh Dickins 	shmem_undo_range(inode, lstart, lend, false);
1046078cd827SDeepa Dinamani 	inode->i_ctime = inode->i_mtime = current_time(inode);
10471da177e4SLinus Torvalds }
104894c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
10491da177e4SLinus Torvalds 
1050549c7297SChristian Brauner static int shmem_getattr(struct user_namespace *mnt_userns,
1051549c7297SChristian Brauner 			 const struct path *path, struct kstat *stat,
1052a528d35eSDavid Howells 			 u32 request_mask, unsigned int query_flags)
105344a30220SYu Zhao {
1054a528d35eSDavid Howells 	struct inode *inode = path->dentry->d_inode;
105544a30220SYu Zhao 	struct shmem_inode_info *info = SHMEM_I(inode);
105644a30220SYu Zhao 
1057d0424c42SHugh Dickins 	if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
10584595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
105944a30220SYu Zhao 		shmem_recalc_inode(inode);
10604595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
1061d0424c42SHugh Dickins 	}
10620d56a451SChristian Brauner 	generic_fillattr(&init_user_ns, inode, stat);
106389fdcd26SYang Shi 
1064a7fddc36SHugh Dickins 	if (shmem_is_huge(NULL, inode, 0))
106589fdcd26SYang Shi 		stat->blksize = HPAGE_PMD_SIZE;
106689fdcd26SYang Shi 
1067f7cd16a5SXavier Roche 	if (request_mask & STATX_BTIME) {
1068f7cd16a5SXavier Roche 		stat->result_mask |= STATX_BTIME;
1069f7cd16a5SXavier Roche 		stat->btime.tv_sec = info->i_crtime.tv_sec;
1070f7cd16a5SXavier Roche 		stat->btime.tv_nsec = info->i_crtime.tv_nsec;
1071f7cd16a5SXavier Roche 	}
1072f7cd16a5SXavier Roche 
107344a30220SYu Zhao 	return 0;
107444a30220SYu Zhao }
107544a30220SYu Zhao 
1076549c7297SChristian Brauner static int shmem_setattr(struct user_namespace *mnt_userns,
1077549c7297SChristian Brauner 			 struct dentry *dentry, struct iattr *attr)
10781da177e4SLinus Torvalds {
107975c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
108040e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
10811da177e4SLinus Torvalds 	int error;
10821da177e4SLinus Torvalds 
10832f221d6fSChristian Brauner 	error = setattr_prepare(&init_user_ns, dentry, attr);
1084db78b877SChristoph Hellwig 	if (error)
1085db78b877SChristoph Hellwig 		return error;
1086db78b877SChristoph Hellwig 
108794c1e62dSHugh Dickins 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
108894c1e62dSHugh Dickins 		loff_t oldsize = inode->i_size;
108994c1e62dSHugh Dickins 		loff_t newsize = attr->ia_size;
10903889e6e7Snpiggin@suse.de 
10919608703eSJan Kara 		/* protected by i_rwsem */
109240e041a2SDavid Herrmann 		if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
109340e041a2SDavid Herrmann 		    (newsize > oldsize && (info->seals & F_SEAL_GROW)))
109440e041a2SDavid Herrmann 			return -EPERM;
109540e041a2SDavid Herrmann 
109694c1e62dSHugh Dickins 		if (newsize != oldsize) {
109777142517SKonstantin Khlebnikov 			error = shmem_reacct_size(SHMEM_I(inode)->flags,
109877142517SKonstantin Khlebnikov 					oldsize, newsize);
109977142517SKonstantin Khlebnikov 			if (error)
110077142517SKonstantin Khlebnikov 				return error;
110194c1e62dSHugh Dickins 			i_size_write(inode, newsize);
1102078cd827SDeepa Dinamani 			inode->i_ctime = inode->i_mtime = current_time(inode);
110394c1e62dSHugh Dickins 		}
1104afa2db2fSJosef Bacik 		if (newsize <= oldsize) {
110594c1e62dSHugh Dickins 			loff_t holebegin = round_up(newsize, PAGE_SIZE);
1106d0424c42SHugh Dickins 			if (oldsize > holebegin)
1107d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
1108d0424c42SHugh Dickins 							holebegin, 0, 1);
1109d0424c42SHugh Dickins 			if (info->alloced)
1110d0424c42SHugh Dickins 				shmem_truncate_range(inode,
1111d0424c42SHugh Dickins 							newsize, (loff_t)-1);
111294c1e62dSHugh Dickins 			/* unmap again to remove racily COWed private pages */
1113d0424c42SHugh Dickins 			if (oldsize > holebegin)
1114d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
1115d0424c42SHugh Dickins 							holebegin, 0, 1);
111694c1e62dSHugh Dickins 		}
11171da177e4SLinus Torvalds 	}
11181da177e4SLinus Torvalds 
11192f221d6fSChristian Brauner 	setattr_copy(&init_user_ns, inode, attr);
1120db78b877SChristoph Hellwig 	if (attr->ia_valid & ATTR_MODE)
1121e65ce2a5SChristian Brauner 		error = posix_acl_chmod(&init_user_ns, inode, inode->i_mode);
11221da177e4SLinus Torvalds 	return error;
11231da177e4SLinus Torvalds }
11241da177e4SLinus Torvalds 
11251f895f75SAl Viro static void shmem_evict_inode(struct inode *inode)
11261da177e4SLinus Torvalds {
11271da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
1128779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
11291da177e4SLinus Torvalds 
113030e6a51dSHui Su 	if (shmem_mapping(inode->i_mapping)) {
11311da177e4SLinus Torvalds 		shmem_unacct_size(info->flags, inode->i_size);
11321da177e4SLinus Torvalds 		inode->i_size = 0;
1133bc786390SHugh Dickins 		mapping_set_exiting(inode->i_mapping);
11343889e6e7Snpiggin@suse.de 		shmem_truncate_range(inode, 0, (loff_t)-1);
1135779750d2SKirill A. Shutemov 		if (!list_empty(&info->shrinklist)) {
1136779750d2SKirill A. Shutemov 			spin_lock(&sbinfo->shrinklist_lock);
1137779750d2SKirill A. Shutemov 			if (!list_empty(&info->shrinklist)) {
1138779750d2SKirill A. Shutemov 				list_del_init(&info->shrinklist);
1139779750d2SKirill A. Shutemov 				sbinfo->shrinklist_len--;
1140779750d2SKirill A. Shutemov 			}
1141779750d2SKirill A. Shutemov 			spin_unlock(&sbinfo->shrinklist_lock);
1142779750d2SKirill A. Shutemov 		}
1143af53d3e9SHugh Dickins 		while (!list_empty(&info->swaplist)) {
1144af53d3e9SHugh Dickins 			/* Wait while shmem_unuse() is scanning this inode... */
1145af53d3e9SHugh Dickins 			wait_var_event(&info->stop_eviction,
1146af53d3e9SHugh Dickins 				       !atomic_read(&info->stop_eviction));
1147cb5f7b9aSHugh Dickins 			mutex_lock(&shmem_swaplist_mutex);
1148af53d3e9SHugh Dickins 			/* ...but beware of the race if we peeked too early */
1149af53d3e9SHugh Dickins 			if (!atomic_read(&info->stop_eviction))
11501da177e4SLinus Torvalds 				list_del_init(&info->swaplist);
1151cb5f7b9aSHugh Dickins 			mutex_unlock(&shmem_swaplist_mutex);
11521da177e4SLinus Torvalds 		}
11533ed47db3SAl Viro 	}
1154b09e0fa4SEric Paris 
115538f38657SAristeu Rozanski 	simple_xattrs_free(&info->xattrs);
11560f3c42f5SHugh Dickins 	WARN_ON(inode->i_blocks);
11575b04c689SPavel Emelyanov 	shmem_free_inode(inode->i_sb);
1158dbd5768fSJan Kara 	clear_inode(inode);
11591da177e4SLinus Torvalds }
11601da177e4SLinus Torvalds 
1161b56a2d8aSVineeth Remanan Pillai static int shmem_find_swap_entries(struct address_space *mapping,
1162b56a2d8aSVineeth Remanan Pillai 				   pgoff_t start, unsigned int nr_entries,
1163b56a2d8aSVineeth Remanan Pillai 				   struct page **entries, pgoff_t *indices,
116410a9c496SChristoph Hellwig 				   unsigned int type)
1165478922e2SMatthew Wilcox {
1166b56a2d8aSVineeth Remanan Pillai 	XA_STATE(xas, &mapping->i_pages, start);
1167b56a2d8aSVineeth Remanan Pillai 	struct page *page;
116887039546SHugh Dickins 	swp_entry_t entry;
1169b56a2d8aSVineeth Remanan Pillai 	unsigned int ret = 0;
1170b56a2d8aSVineeth Remanan Pillai 
1171b56a2d8aSVineeth Remanan Pillai 	if (!nr_entries)
1172b56a2d8aSVineeth Remanan Pillai 		return 0;
1173478922e2SMatthew Wilcox 
1174478922e2SMatthew Wilcox 	rcu_read_lock();
1175b56a2d8aSVineeth Remanan Pillai 	xas_for_each(&xas, page, ULONG_MAX) {
1176b56a2d8aSVineeth Remanan Pillai 		if (xas_retry(&xas, page))
11775b9c98f3SMike Kravetz 			continue;
1178b56a2d8aSVineeth Remanan Pillai 
1179b56a2d8aSVineeth Remanan Pillai 		if (!xa_is_value(page))
1180478922e2SMatthew Wilcox 			continue;
1181b56a2d8aSVineeth Remanan Pillai 
118287039546SHugh Dickins 		entry = radix_to_swp_entry(page);
118387039546SHugh Dickins 		if (swp_type(entry) != type)
1184b56a2d8aSVineeth Remanan Pillai 			continue;
1185b56a2d8aSVineeth Remanan Pillai 
1186b56a2d8aSVineeth Remanan Pillai 		indices[ret] = xas.xa_index;
1187b56a2d8aSVineeth Remanan Pillai 		entries[ret] = page;
1188b56a2d8aSVineeth Remanan Pillai 
1189b56a2d8aSVineeth Remanan Pillai 		if (need_resched()) {
1190e21a2955SMatthew Wilcox 			xas_pause(&xas);
1191478922e2SMatthew Wilcox 			cond_resched_rcu();
1192478922e2SMatthew Wilcox 		}
1193b56a2d8aSVineeth Remanan Pillai 		if (++ret == nr_entries)
1194b56a2d8aSVineeth Remanan Pillai 			break;
1195b56a2d8aSVineeth Remanan Pillai 	}
1196478922e2SMatthew Wilcox 	rcu_read_unlock();
1197e21a2955SMatthew Wilcox 
1198b56a2d8aSVineeth Remanan Pillai 	return ret;
1199b56a2d8aSVineeth Remanan Pillai }
1200b56a2d8aSVineeth Remanan Pillai 
1201b56a2d8aSVineeth Remanan Pillai /*
1202b56a2d8aSVineeth Remanan Pillai  * Move the swapped pages for an inode to page cache. Returns the count
1203b56a2d8aSVineeth Remanan Pillai  * of pages swapped in, or the error in case of failure.
1204b56a2d8aSVineeth Remanan Pillai  */
1205b56a2d8aSVineeth Remanan Pillai static int shmem_unuse_swap_entries(struct inode *inode, struct pagevec pvec,
1206b56a2d8aSVineeth Remanan Pillai 				    pgoff_t *indices)
1207b56a2d8aSVineeth Remanan Pillai {
1208b56a2d8aSVineeth Remanan Pillai 	int i = 0;
1209b56a2d8aSVineeth Remanan Pillai 	int ret = 0;
1210b56a2d8aSVineeth Remanan Pillai 	int error = 0;
1211b56a2d8aSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1212b56a2d8aSVineeth Remanan Pillai 
1213b56a2d8aSVineeth Remanan Pillai 	for (i = 0; i < pvec.nr; i++) {
1214b56a2d8aSVineeth Remanan Pillai 		struct page *page = pvec.pages[i];
1215b56a2d8aSVineeth Remanan Pillai 
1216b56a2d8aSVineeth Remanan Pillai 		if (!xa_is_value(page))
1217b56a2d8aSVineeth Remanan Pillai 			continue;
1218b56a2d8aSVineeth Remanan Pillai 		error = shmem_swapin_page(inode, indices[i],
1219b56a2d8aSVineeth Remanan Pillai 					  &page, SGP_CACHE,
1220b56a2d8aSVineeth Remanan Pillai 					  mapping_gfp_mask(mapping),
1221b56a2d8aSVineeth Remanan Pillai 					  NULL, NULL);
1222b56a2d8aSVineeth Remanan Pillai 		if (error == 0) {
1223b56a2d8aSVineeth Remanan Pillai 			unlock_page(page);
1224b56a2d8aSVineeth Remanan Pillai 			put_page(page);
1225b56a2d8aSVineeth Remanan Pillai 			ret++;
1226b56a2d8aSVineeth Remanan Pillai 		}
1227b56a2d8aSVineeth Remanan Pillai 		if (error == -ENOMEM)
1228b56a2d8aSVineeth Remanan Pillai 			break;
1229b56a2d8aSVineeth Remanan Pillai 		error = 0;
1230b56a2d8aSVineeth Remanan Pillai 	}
1231b56a2d8aSVineeth Remanan Pillai 	return error ? error : ret;
1232478922e2SMatthew Wilcox }
1233478922e2SMatthew Wilcox 
123446f65ec1SHugh Dickins /*
123546f65ec1SHugh Dickins  * If swap found in inode, free it and move page from swapcache to filecache.
123646f65ec1SHugh Dickins  */
123710a9c496SChristoph Hellwig static int shmem_unuse_inode(struct inode *inode, unsigned int type)
12381da177e4SLinus Torvalds {
1239b56a2d8aSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1240b56a2d8aSVineeth Remanan Pillai 	pgoff_t start = 0;
1241b56a2d8aSVineeth Remanan Pillai 	struct pagevec pvec;
1242b56a2d8aSVineeth Remanan Pillai 	pgoff_t indices[PAGEVEC_SIZE];
1243b56a2d8aSVineeth Remanan Pillai 	int ret = 0;
12441da177e4SLinus Torvalds 
1245b56a2d8aSVineeth Remanan Pillai 	pagevec_init(&pvec);
1246b56a2d8aSVineeth Remanan Pillai 	do {
1247b56a2d8aSVineeth Remanan Pillai 		unsigned int nr_entries = PAGEVEC_SIZE;
12482e0e26c7SHugh Dickins 
1249b56a2d8aSVineeth Remanan Pillai 		pvec.nr = shmem_find_swap_entries(mapping, start, nr_entries,
125010a9c496SChristoph Hellwig 						  pvec.pages, indices, type);
1251b56a2d8aSVineeth Remanan Pillai 		if (pvec.nr == 0) {
1252b56a2d8aSVineeth Remanan Pillai 			ret = 0;
1253778dd893SHugh Dickins 			break;
1254b56a2d8aSVineeth Remanan Pillai 		}
1255b56a2d8aSVineeth Remanan Pillai 
1256b56a2d8aSVineeth Remanan Pillai 		ret = shmem_unuse_swap_entries(inode, pvec, indices);
1257b56a2d8aSVineeth Remanan Pillai 		if (ret < 0)
1258b56a2d8aSVineeth Remanan Pillai 			break;
1259b56a2d8aSVineeth Remanan Pillai 
1260b56a2d8aSVineeth Remanan Pillai 		start = indices[pvec.nr - 1];
1261b56a2d8aSVineeth Remanan Pillai 	} while (true);
1262b56a2d8aSVineeth Remanan Pillai 
1263b56a2d8aSVineeth Remanan Pillai 	return ret;
1264b56a2d8aSVineeth Remanan Pillai }
1265b56a2d8aSVineeth Remanan Pillai 
1266b56a2d8aSVineeth Remanan Pillai /*
1267b56a2d8aSVineeth Remanan Pillai  * Read all the shared memory data that resides in the swap
1268b56a2d8aSVineeth Remanan Pillai  * device 'type' back into memory, so the swap device can be
1269b56a2d8aSVineeth Remanan Pillai  * unused.
1270b56a2d8aSVineeth Remanan Pillai  */
127110a9c496SChristoph Hellwig int shmem_unuse(unsigned int type)
1272b56a2d8aSVineeth Remanan Pillai {
1273b56a2d8aSVineeth Remanan Pillai 	struct shmem_inode_info *info, *next;
1274b56a2d8aSVineeth Remanan Pillai 	int error = 0;
1275b56a2d8aSVineeth Remanan Pillai 
1276b56a2d8aSVineeth Remanan Pillai 	if (list_empty(&shmem_swaplist))
1277b56a2d8aSVineeth Remanan Pillai 		return 0;
1278b56a2d8aSVineeth Remanan Pillai 
1279b56a2d8aSVineeth Remanan Pillai 	mutex_lock(&shmem_swaplist_mutex);
1280b56a2d8aSVineeth Remanan Pillai 	list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1281b56a2d8aSVineeth Remanan Pillai 		if (!info->swapped) {
1282b56a2d8aSVineeth Remanan Pillai 			list_del_init(&info->swaplist);
1283b56a2d8aSVineeth Remanan Pillai 			continue;
1284b56a2d8aSVineeth Remanan Pillai 		}
1285af53d3e9SHugh Dickins 		/*
1286af53d3e9SHugh Dickins 		 * Drop the swaplist mutex while searching the inode for swap;
1287af53d3e9SHugh Dickins 		 * but before doing so, make sure shmem_evict_inode() will not
1288af53d3e9SHugh Dickins 		 * remove placeholder inode from swaplist, nor let it be freed
1289af53d3e9SHugh Dickins 		 * (igrab() would protect from unlink, but not from unmount).
1290af53d3e9SHugh Dickins 		 */
1291af53d3e9SHugh Dickins 		atomic_inc(&info->stop_eviction);
1292b56a2d8aSVineeth Remanan Pillai 		mutex_unlock(&shmem_swaplist_mutex);
1293b56a2d8aSVineeth Remanan Pillai 
129410a9c496SChristoph Hellwig 		error = shmem_unuse_inode(&info->vfs_inode, type);
1295b56a2d8aSVineeth Remanan Pillai 		cond_resched();
1296b56a2d8aSVineeth Remanan Pillai 
1297b56a2d8aSVineeth Remanan Pillai 		mutex_lock(&shmem_swaplist_mutex);
1298b56a2d8aSVineeth Remanan Pillai 		next = list_next_entry(info, swaplist);
1299b56a2d8aSVineeth Remanan Pillai 		if (!info->swapped)
1300b56a2d8aSVineeth Remanan Pillai 			list_del_init(&info->swaplist);
1301af53d3e9SHugh Dickins 		if (atomic_dec_and_test(&info->stop_eviction))
1302af53d3e9SHugh Dickins 			wake_up_var(&info->stop_eviction);
1303b56a2d8aSVineeth Remanan Pillai 		if (error)
1304b56a2d8aSVineeth Remanan Pillai 			break;
13051da177e4SLinus Torvalds 	}
1306cb5f7b9aSHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
1307778dd893SHugh Dickins 
1308778dd893SHugh Dickins 	return error;
13091da177e4SLinus Torvalds }
13101da177e4SLinus Torvalds 
13111da177e4SLinus Torvalds /*
13121da177e4SLinus Torvalds  * Move the page from the page cache to the swap cache.
13131da177e4SLinus Torvalds  */
13141da177e4SLinus Torvalds static int shmem_writepage(struct page *page, struct writeback_control *wbc)
13151da177e4SLinus Torvalds {
13161da177e4SLinus Torvalds 	struct shmem_inode_info *info;
13171da177e4SLinus Torvalds 	struct address_space *mapping;
13181da177e4SLinus Torvalds 	struct inode *inode;
13196922c0c7SHugh Dickins 	swp_entry_t swap;
13206922c0c7SHugh Dickins 	pgoff_t index;
13211da177e4SLinus Torvalds 
13221e6decf3SHugh Dickins 	/*
13231e6decf3SHugh Dickins 	 * If /sys/kernel/mm/transparent_hugepage/shmem_enabled is "always" or
13241e6decf3SHugh Dickins 	 * "force", drivers/gpu/drm/i915/gem/i915_gem_shmem.c gets huge pages,
13251e6decf3SHugh Dickins 	 * and its shmem_writeback() needs them to be split when swapping.
13261e6decf3SHugh Dickins 	 */
13271e6decf3SHugh Dickins 	if (PageTransCompound(page)) {
13281e6decf3SHugh Dickins 		/* Ensure the subpages are still dirty */
13291e6decf3SHugh Dickins 		SetPageDirty(page);
13301e6decf3SHugh Dickins 		if (split_huge_page(page) < 0)
13311e6decf3SHugh Dickins 			goto redirty;
13321e6decf3SHugh Dickins 		ClearPageDirty(page);
13331e6decf3SHugh Dickins 	}
13341e6decf3SHugh Dickins 
13351da177e4SLinus Torvalds 	BUG_ON(!PageLocked(page));
13361da177e4SLinus Torvalds 	mapping = page->mapping;
13371da177e4SLinus Torvalds 	index = page->index;
13381da177e4SLinus Torvalds 	inode = mapping->host;
13391da177e4SLinus Torvalds 	info = SHMEM_I(inode);
13401da177e4SLinus Torvalds 	if (info->flags & VM_LOCKED)
13411da177e4SLinus Torvalds 		goto redirty;
1342d9fe526aSHugh Dickins 	if (!total_swap_pages)
13431da177e4SLinus Torvalds 		goto redirty;
13441da177e4SLinus Torvalds 
1345d9fe526aSHugh Dickins 	/*
134697b713baSChristoph Hellwig 	 * Our capabilities prevent regular writeback or sync from ever calling
134797b713baSChristoph Hellwig 	 * shmem_writepage; but a stacking filesystem might use ->writepage of
134897b713baSChristoph Hellwig 	 * its underlying filesystem, in which case tmpfs should write out to
134997b713baSChristoph Hellwig 	 * swap only in response to memory pressure, and not for the writeback
135097b713baSChristoph Hellwig 	 * threads or sync.
1351d9fe526aSHugh Dickins 	 */
135248f170fbSHugh Dickins 	if (!wbc->for_reclaim) {
135348f170fbSHugh Dickins 		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
135448f170fbSHugh Dickins 		goto redirty;
135548f170fbSHugh Dickins 	}
13561635f6a7SHugh Dickins 
13571635f6a7SHugh Dickins 	/*
13581635f6a7SHugh Dickins 	 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
13591635f6a7SHugh Dickins 	 * value into swapfile.c, the only way we can correctly account for a
13601635f6a7SHugh Dickins 	 * fallocated page arriving here is now to initialize it and write it.
13611aac1400SHugh Dickins 	 *
13621aac1400SHugh Dickins 	 * That's okay for a page already fallocated earlier, but if we have
13631aac1400SHugh Dickins 	 * not yet completed the fallocation, then (a) we want to keep track
13641aac1400SHugh Dickins 	 * of this page in case we have to undo it, and (b) it may not be a
13651aac1400SHugh Dickins 	 * good idea to continue anyway, once we're pushing into swap.  So
13661aac1400SHugh Dickins 	 * reactivate the page, and let shmem_fallocate() quit when too many.
13671635f6a7SHugh Dickins 	 */
13681635f6a7SHugh Dickins 	if (!PageUptodate(page)) {
13691aac1400SHugh Dickins 		if (inode->i_private) {
13701aac1400SHugh Dickins 			struct shmem_falloc *shmem_falloc;
13711aac1400SHugh Dickins 			spin_lock(&inode->i_lock);
13721aac1400SHugh Dickins 			shmem_falloc = inode->i_private;
13731aac1400SHugh Dickins 			if (shmem_falloc &&
13748e205f77SHugh Dickins 			    !shmem_falloc->waitq &&
13751aac1400SHugh Dickins 			    index >= shmem_falloc->start &&
13761aac1400SHugh Dickins 			    index < shmem_falloc->next)
13771aac1400SHugh Dickins 				shmem_falloc->nr_unswapped++;
13781aac1400SHugh Dickins 			else
13791aac1400SHugh Dickins 				shmem_falloc = NULL;
13801aac1400SHugh Dickins 			spin_unlock(&inode->i_lock);
13811aac1400SHugh Dickins 			if (shmem_falloc)
13821aac1400SHugh Dickins 				goto redirty;
13831aac1400SHugh Dickins 		}
13841635f6a7SHugh Dickins 		clear_highpage(page);
13851635f6a7SHugh Dickins 		flush_dcache_page(page);
13861635f6a7SHugh Dickins 		SetPageUptodate(page);
13871635f6a7SHugh Dickins 	}
13881635f6a7SHugh Dickins 
138938d8b4e6SHuang Ying 	swap = get_swap_page(page);
139048f170fbSHugh Dickins 	if (!swap.val)
139148f170fbSHugh Dickins 		goto redirty;
1392d9fe526aSHugh Dickins 
1393b1dea800SHugh Dickins 	/*
1394b1dea800SHugh Dickins 	 * Add inode to shmem_unuse()'s list of swapped-out inodes,
13956922c0c7SHugh Dickins 	 * if it's not already there.  Do it now before the page is
13966922c0c7SHugh Dickins 	 * moved to swap cache, when its pagelock no longer protects
1397b1dea800SHugh Dickins 	 * the inode from eviction.  But don't unlock the mutex until
13986922c0c7SHugh Dickins 	 * we've incremented swapped, because shmem_unuse_inode() will
13996922c0c7SHugh Dickins 	 * prune a !swapped inode from the swaplist under this mutex.
1400b1dea800SHugh Dickins 	 */
1401b1dea800SHugh Dickins 	mutex_lock(&shmem_swaplist_mutex);
140205bf86b4SHugh Dickins 	if (list_empty(&info->swaplist))
1403b56a2d8aSVineeth Remanan Pillai 		list_add(&info->swaplist, &shmem_swaplist);
1404b1dea800SHugh Dickins 
14054afab1cdSYang Shi 	if (add_to_swap_cache(page, swap,
14063852f676SJoonsoo Kim 			__GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN,
14073852f676SJoonsoo Kim 			NULL) == 0) {
14084595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
1409267a4c76SHugh Dickins 		shmem_recalc_inode(inode);
1410267a4c76SHugh Dickins 		info->swapped++;
14114595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
1412267a4c76SHugh Dickins 
1413aaa46865SHugh Dickins 		swap_shmem_alloc(swap);
14146922c0c7SHugh Dickins 		shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
14156922c0c7SHugh Dickins 
14166922c0c7SHugh Dickins 		mutex_unlock(&shmem_swaplist_mutex);
1417d9fe526aSHugh Dickins 		BUG_ON(page_mapped(page));
14189fab5619SHugh Dickins 		swap_writepage(page, wbc);
14191da177e4SLinus Torvalds 		return 0;
14201da177e4SLinus Torvalds 	}
14211da177e4SLinus Torvalds 
14226922c0c7SHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
142375f6d6d2SMinchan Kim 	put_swap_page(page, swap);
14241da177e4SLinus Torvalds redirty:
14251da177e4SLinus Torvalds 	set_page_dirty(page);
1426d9fe526aSHugh Dickins 	if (wbc->for_reclaim)
1427d9fe526aSHugh Dickins 		return AOP_WRITEPAGE_ACTIVATE;	/* Return with page locked */
1428d9fe526aSHugh Dickins 	unlock_page(page);
1429d9fe526aSHugh Dickins 	return 0;
14301da177e4SLinus Torvalds }
14311da177e4SLinus Torvalds 
143275edd345SHugh Dickins #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
143371fe804bSLee Schermerhorn static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1434680d794bSakpm@linux-foundation.org {
1435680d794bSakpm@linux-foundation.org 	char buffer[64];
1436680d794bSakpm@linux-foundation.org 
143771fe804bSLee Schermerhorn 	if (!mpol || mpol->mode == MPOL_DEFAULT)
1438095f1fc4SLee Schermerhorn 		return;		/* show nothing */
1439095f1fc4SLee Schermerhorn 
1440a7a88b23SHugh Dickins 	mpol_to_str(buffer, sizeof(buffer), mpol);
1441095f1fc4SLee Schermerhorn 
1442095f1fc4SLee Schermerhorn 	seq_printf(seq, ",mpol=%s", buffer);
1443680d794bSakpm@linux-foundation.org }
144471fe804bSLee Schermerhorn 
144571fe804bSLee Schermerhorn static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
144671fe804bSLee Schermerhorn {
144771fe804bSLee Schermerhorn 	struct mempolicy *mpol = NULL;
144871fe804bSLee Schermerhorn 	if (sbinfo->mpol) {
1449bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);	/* prevent replace/use races */
145071fe804bSLee Schermerhorn 		mpol = sbinfo->mpol;
145171fe804bSLee Schermerhorn 		mpol_get(mpol);
1452bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
145371fe804bSLee Schermerhorn 	}
145471fe804bSLee Schermerhorn 	return mpol;
145571fe804bSLee Schermerhorn }
145675edd345SHugh Dickins #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
145775edd345SHugh Dickins static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
145875edd345SHugh Dickins {
145975edd345SHugh Dickins }
146075edd345SHugh Dickins static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
146175edd345SHugh Dickins {
146275edd345SHugh Dickins 	return NULL;
146375edd345SHugh Dickins }
146475edd345SHugh Dickins #endif /* CONFIG_NUMA && CONFIG_TMPFS */
146575edd345SHugh Dickins #ifndef CONFIG_NUMA
146675edd345SHugh Dickins #define vm_policy vm_private_data
146775edd345SHugh Dickins #endif
1468680d794bSakpm@linux-foundation.org 
1469800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1470800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1471800d8c63SKirill A. Shutemov {
1472800d8c63SKirill A. Shutemov 	/* Create a pseudo vma that just contains the policy */
14732c4541e2SKirill A. Shutemov 	vma_init(vma, NULL);
1474800d8c63SKirill A. Shutemov 	/* Bias interleave by inode number to distribute better across nodes */
1475800d8c63SKirill A. Shutemov 	vma->vm_pgoff = index + info->vfs_inode.i_ino;
1476800d8c63SKirill A. Shutemov 	vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1477800d8c63SKirill A. Shutemov }
1478800d8c63SKirill A. Shutemov 
1479800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1480800d8c63SKirill A. Shutemov {
1481800d8c63SKirill A. Shutemov 	/* Drop reference taken by mpol_shared_policy_lookup() */
1482800d8c63SKirill A. Shutemov 	mpol_cond_put(vma->vm_policy);
1483800d8c63SKirill A. Shutemov }
1484800d8c63SKirill A. Shutemov 
148541ffe5d5SHugh Dickins static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
148641ffe5d5SHugh Dickins 			struct shmem_inode_info *info, pgoff_t index)
14871da177e4SLinus Torvalds {
14881da177e4SLinus Torvalds 	struct vm_area_struct pvma;
148918a2f371SMel Gorman 	struct page *page;
14908c63ca5bSWill Deacon 	struct vm_fault vmf = {
14918c63ca5bSWill Deacon 		.vma = &pvma,
14928c63ca5bSWill Deacon 	};
14931da177e4SLinus Torvalds 
1494800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
1495e9e9b7ecSMinchan Kim 	page = swap_cluster_readahead(swap, gfp, &vmf);
1496800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
149718a2f371SMel Gorman 
1498800d8c63SKirill A. Shutemov 	return page;
1499800d8c63SKirill A. Shutemov }
150018a2f371SMel Gorman 
150178cc8cdcSRik van Riel /*
150278cc8cdcSRik van Riel  * Make sure huge_gfp is always more limited than limit_gfp.
150378cc8cdcSRik van Riel  * Some of the flags set permissions, while others set limitations.
150478cc8cdcSRik van Riel  */
150578cc8cdcSRik van Riel static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
150678cc8cdcSRik van Riel {
150778cc8cdcSRik van Riel 	gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
150878cc8cdcSRik van Riel 	gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
1509187df5ddSRik van Riel 	gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
1510187df5ddSRik van Riel 	gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
1511187df5ddSRik van Riel 
1512187df5ddSRik van Riel 	/* Allow allocations only from the originally specified zones. */
1513187df5ddSRik van Riel 	result |= zoneflags;
151478cc8cdcSRik van Riel 
151578cc8cdcSRik van Riel 	/*
151678cc8cdcSRik van Riel 	 * Minimize the result gfp by taking the union with the deny flags,
151778cc8cdcSRik van Riel 	 * and the intersection of the allow flags.
151878cc8cdcSRik van Riel 	 */
151978cc8cdcSRik van Riel 	result |= (limit_gfp & denyflags);
152078cc8cdcSRik van Riel 	result |= (huge_gfp & limit_gfp) & allowflags;
152178cc8cdcSRik van Riel 
152278cc8cdcSRik van Riel 	return result;
152378cc8cdcSRik van Riel }
152478cc8cdcSRik van Riel 
1525800d8c63SKirill A. Shutemov static struct page *shmem_alloc_hugepage(gfp_t gfp,
1526800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1527800d8c63SKirill A. Shutemov {
1528800d8c63SKirill A. Shutemov 	struct vm_area_struct pvma;
15297b8d046fSMatthew Wilcox 	struct address_space *mapping = info->vfs_inode.i_mapping;
15307b8d046fSMatthew Wilcox 	pgoff_t hindex;
1531800d8c63SKirill A. Shutemov 	struct page *page;
1532800d8c63SKirill A. Shutemov 
15334620a06eSGeert Uytterhoeven 	hindex = round_down(index, HPAGE_PMD_NR);
15347b8d046fSMatthew Wilcox 	if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
15357b8d046fSMatthew Wilcox 								XA_PRESENT))
1536800d8c63SKirill A. Shutemov 		return NULL;
1537800d8c63SKirill A. Shutemov 
1538800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, hindex);
1539be1a13ebSMichal Hocko 	page = alloc_pages_vma(gfp, HPAGE_PMD_ORDER, &pvma, 0, true);
1540800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
1541800d8c63SKirill A. Shutemov 	if (page)
1542800d8c63SKirill A. Shutemov 		prep_transhuge_page(page);
1543dcdf11eeSDavid Rientjes 	else
1544dcdf11eeSDavid Rientjes 		count_vm_event(THP_FILE_FALLBACK);
154518a2f371SMel Gorman 	return page;
154618a2f371SMel Gorman }
154718a2f371SMel Gorman 
154818a2f371SMel Gorman static struct page *shmem_alloc_page(gfp_t gfp,
154918a2f371SMel Gorman 			struct shmem_inode_info *info, pgoff_t index)
155018a2f371SMel Gorman {
155118a2f371SMel Gorman 	struct vm_area_struct pvma;
155218a2f371SMel Gorman 	struct page *page;
155318a2f371SMel Gorman 
1554800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
1555800d8c63SKirill A. Shutemov 	page = alloc_page_vma(gfp, &pvma, 0);
1556800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
155718a2f371SMel Gorman 
1558800d8c63SKirill A. Shutemov 	return page;
1559800d8c63SKirill A. Shutemov }
1560800d8c63SKirill A. Shutemov 
1561800d8c63SKirill A. Shutemov static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
15620f079694SMike Rapoport 		struct inode *inode,
1563800d8c63SKirill A. Shutemov 		pgoff_t index, bool huge)
1564800d8c63SKirill A. Shutemov {
15650f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
1566800d8c63SKirill A. Shutemov 	struct page *page;
1567800d8c63SKirill A. Shutemov 	int nr;
1568800d8c63SKirill A. Shutemov 	int err = -ENOSPC;
1569800d8c63SKirill A. Shutemov 
1570396bcc52SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1571800d8c63SKirill A. Shutemov 		huge = false;
1572800d8c63SKirill A. Shutemov 	nr = huge ? HPAGE_PMD_NR : 1;
1573800d8c63SKirill A. Shutemov 
15740f079694SMike Rapoport 	if (!shmem_inode_acct_block(inode, nr))
1575800d8c63SKirill A. Shutemov 		goto failed;
1576800d8c63SKirill A. Shutemov 
1577800d8c63SKirill A. Shutemov 	if (huge)
1578800d8c63SKirill A. Shutemov 		page = shmem_alloc_hugepage(gfp, info, index);
1579800d8c63SKirill A. Shutemov 	else
1580800d8c63SKirill A. Shutemov 		page = shmem_alloc_page(gfp, info, index);
158175edd345SHugh Dickins 	if (page) {
158275edd345SHugh Dickins 		__SetPageLocked(page);
158375edd345SHugh Dickins 		__SetPageSwapBacked(page);
1584800d8c63SKirill A. Shutemov 		return page;
158575edd345SHugh Dickins 	}
158618a2f371SMel Gorman 
1587800d8c63SKirill A. Shutemov 	err = -ENOMEM;
15880f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, nr);
1589800d8c63SKirill A. Shutemov failed:
1590800d8c63SKirill A. Shutemov 	return ERR_PTR(err);
15911da177e4SLinus Torvalds }
159271fe804bSLee Schermerhorn 
15931da177e4SLinus Torvalds /*
1594bde05d1cSHugh Dickins  * When a page is moved from swapcache to shmem filecache (either by the
1595bde05d1cSHugh Dickins  * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1596bde05d1cSHugh Dickins  * shmem_unuse_inode()), it may have been read in earlier from swap, in
1597bde05d1cSHugh Dickins  * ignorance of the mapping it belongs to.  If that mapping has special
1598bde05d1cSHugh Dickins  * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1599bde05d1cSHugh Dickins  * we may need to copy to a suitable page before moving to filecache.
1600bde05d1cSHugh Dickins  *
1601bde05d1cSHugh Dickins  * In a future release, this may well be extended to respect cpuset and
1602bde05d1cSHugh Dickins  * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1603bde05d1cSHugh Dickins  * but for now it is a simple matter of zone.
1604bde05d1cSHugh Dickins  */
1605bde05d1cSHugh Dickins static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1606bde05d1cSHugh Dickins {
1607bde05d1cSHugh Dickins 	return page_zonenum(page) > gfp_zone(gfp);
1608bde05d1cSHugh Dickins }
1609bde05d1cSHugh Dickins 
1610bde05d1cSHugh Dickins static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1611bde05d1cSHugh Dickins 				struct shmem_inode_info *info, pgoff_t index)
1612bde05d1cSHugh Dickins {
1613bde05d1cSHugh Dickins 	struct page *oldpage, *newpage;
1614d21bba2bSMatthew Wilcox (Oracle) 	struct folio *old, *new;
1615bde05d1cSHugh Dickins 	struct address_space *swap_mapping;
1616c1cb20d4SYu Zhao 	swp_entry_t entry;
1617bde05d1cSHugh Dickins 	pgoff_t swap_index;
1618bde05d1cSHugh Dickins 	int error;
1619bde05d1cSHugh Dickins 
1620bde05d1cSHugh Dickins 	oldpage = *pagep;
1621c1cb20d4SYu Zhao 	entry.val = page_private(oldpage);
1622c1cb20d4SYu Zhao 	swap_index = swp_offset(entry);
1623bde05d1cSHugh Dickins 	swap_mapping = page_mapping(oldpage);
1624bde05d1cSHugh Dickins 
1625bde05d1cSHugh Dickins 	/*
1626bde05d1cSHugh Dickins 	 * We have arrived here because our zones are constrained, so don't
1627bde05d1cSHugh Dickins 	 * limit chance of success by further cpuset and node constraints.
1628bde05d1cSHugh Dickins 	 */
1629bde05d1cSHugh Dickins 	gfp &= ~GFP_CONSTRAINT_MASK;
1630bde05d1cSHugh Dickins 	newpage = shmem_alloc_page(gfp, info, index);
1631bde05d1cSHugh Dickins 	if (!newpage)
1632bde05d1cSHugh Dickins 		return -ENOMEM;
1633bde05d1cSHugh Dickins 
163409cbfeafSKirill A. Shutemov 	get_page(newpage);
1635bde05d1cSHugh Dickins 	copy_highpage(newpage, oldpage);
16360142ef6cSHugh Dickins 	flush_dcache_page(newpage);
1637bde05d1cSHugh Dickins 
16389956edf3SHugh Dickins 	__SetPageLocked(newpage);
16399956edf3SHugh Dickins 	__SetPageSwapBacked(newpage);
1640bde05d1cSHugh Dickins 	SetPageUptodate(newpage);
1641c1cb20d4SYu Zhao 	set_page_private(newpage, entry.val);
1642bde05d1cSHugh Dickins 	SetPageSwapCache(newpage);
1643bde05d1cSHugh Dickins 
1644bde05d1cSHugh Dickins 	/*
1645bde05d1cSHugh Dickins 	 * Our caller will very soon move newpage out of swapcache, but it's
1646bde05d1cSHugh Dickins 	 * a nice clean interface for us to replace oldpage by newpage there.
1647bde05d1cSHugh Dickins 	 */
1648b93b0163SMatthew Wilcox 	xa_lock_irq(&swap_mapping->i_pages);
164962f945b6SMatthew Wilcox 	error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
16500142ef6cSHugh Dickins 	if (!error) {
1651d21bba2bSMatthew Wilcox (Oracle) 		old = page_folio(oldpage);
1652d21bba2bSMatthew Wilcox (Oracle) 		new = page_folio(newpage);
1653d21bba2bSMatthew Wilcox (Oracle) 		mem_cgroup_migrate(old, new);
16540d1c2072SJohannes Weiner 		__inc_lruvec_page_state(newpage, NR_FILE_PAGES);
16550d1c2072SJohannes Weiner 		__dec_lruvec_page_state(oldpage, NR_FILE_PAGES);
16560142ef6cSHugh Dickins 	}
1657b93b0163SMatthew Wilcox 	xa_unlock_irq(&swap_mapping->i_pages);
1658bde05d1cSHugh Dickins 
16590142ef6cSHugh Dickins 	if (unlikely(error)) {
16600142ef6cSHugh Dickins 		/*
16610142ef6cSHugh Dickins 		 * Is this possible?  I think not, now that our callers check
16620142ef6cSHugh Dickins 		 * both PageSwapCache and page_private after getting page lock;
16630142ef6cSHugh Dickins 		 * but be defensive.  Reverse old to newpage for clear and free.
16640142ef6cSHugh Dickins 		 */
16650142ef6cSHugh Dickins 		oldpage = newpage;
16660142ef6cSHugh Dickins 	} else {
16676058eaecSJohannes Weiner 		lru_cache_add(newpage);
16680142ef6cSHugh Dickins 		*pagep = newpage;
16690142ef6cSHugh Dickins 	}
1670bde05d1cSHugh Dickins 
1671bde05d1cSHugh Dickins 	ClearPageSwapCache(oldpage);
1672bde05d1cSHugh Dickins 	set_page_private(oldpage, 0);
1673bde05d1cSHugh Dickins 
1674bde05d1cSHugh Dickins 	unlock_page(oldpage);
167509cbfeafSKirill A. Shutemov 	put_page(oldpage);
167609cbfeafSKirill A. Shutemov 	put_page(oldpage);
16770142ef6cSHugh Dickins 	return error;
1678bde05d1cSHugh Dickins }
1679bde05d1cSHugh Dickins 
1680bde05d1cSHugh Dickins /*
1681c5bf121eSVineeth Remanan Pillai  * Swap in the page pointed to by *pagep.
1682c5bf121eSVineeth Remanan Pillai  * Caller has to make sure that *pagep contains a valid swapped page.
1683c5bf121eSVineeth Remanan Pillai  * Returns 0 and the page in pagep if success. On failure, returns the
1684af44c12fSRandy Dunlap  * error code and NULL in *pagep.
16851da177e4SLinus Torvalds  */
1686c5bf121eSVineeth Remanan Pillai static int shmem_swapin_page(struct inode *inode, pgoff_t index,
1687c5bf121eSVineeth Remanan Pillai 			     struct page **pagep, enum sgp_type sgp,
1688c5bf121eSVineeth Remanan Pillai 			     gfp_t gfp, struct vm_area_struct *vma,
16892b740303SSouptick Joarder 			     vm_fault_t *fault_type)
16901da177e4SLinus Torvalds {
16911da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
169223f919d4SArnd Bergmann 	struct shmem_inode_info *info = SHMEM_I(inode);
169304f94e3fSDan Schatzberg 	struct mm_struct *charge_mm = vma ? vma->vm_mm : NULL;
1694b1e1ef34SYang Shi 	struct page *page;
16951da177e4SLinus Torvalds 	swp_entry_t swap;
16961da177e4SLinus Torvalds 	int error;
16971da177e4SLinus Torvalds 
1698c5bf121eSVineeth Remanan Pillai 	VM_BUG_ON(!*pagep || !xa_is_value(*pagep));
1699c5bf121eSVineeth Remanan Pillai 	swap = radix_to_swp_entry(*pagep);
1700c5bf121eSVineeth Remanan Pillai 	*pagep = NULL;
170154af6042SHugh Dickins 
17021da177e4SLinus Torvalds 	/* Look it up and read it in.. */
1703ec560175SHuang Ying 	page = lookup_swap_cache(swap, NULL, 0);
170427ab7006SHugh Dickins 	if (!page) {
17059e18eb29SAndres Lagar-Cavilla 		/* Or update major stats only when swapin succeeds?? */
17069e18eb29SAndres Lagar-Cavilla 		if (fault_type) {
170768da9f05SHugh Dickins 			*fault_type |= VM_FAULT_MAJOR;
17089e18eb29SAndres Lagar-Cavilla 			count_vm_event(PGMAJFAULT);
17092262185cSRoman Gushchin 			count_memcg_event_mm(charge_mm, PGMAJFAULT);
17109e18eb29SAndres Lagar-Cavilla 		}
17119e18eb29SAndres Lagar-Cavilla 		/* Here we actually start the io */
171241ffe5d5SHugh Dickins 		page = shmem_swapin(swap, gfp, info, index);
171327ab7006SHugh Dickins 		if (!page) {
17141da177e4SLinus Torvalds 			error = -ENOMEM;
171554af6042SHugh Dickins 			goto failed;
1716285b2c4fSHugh Dickins 		}
17171da177e4SLinus Torvalds 	}
17181da177e4SLinus Torvalds 
17191da177e4SLinus Torvalds 	/* We have to do this with page locked to prevent races */
172054af6042SHugh Dickins 	lock_page(page);
17210142ef6cSHugh Dickins 	if (!PageSwapCache(page) || page_private(page) != swap.val ||
1722d1899228SHugh Dickins 	    !shmem_confirm_swap(mapping, index, swap)) {
1723c5bf121eSVineeth Remanan Pillai 		error = -EEXIST;
1724d1899228SHugh Dickins 		goto unlock;
1725bde05d1cSHugh Dickins 	}
172627ab7006SHugh Dickins 	if (!PageUptodate(page)) {
17271da177e4SLinus Torvalds 		error = -EIO;
172854af6042SHugh Dickins 		goto failed;
172954af6042SHugh Dickins 	}
173054af6042SHugh Dickins 	wait_on_page_writeback(page);
173154af6042SHugh Dickins 
17328a84802eSSteven Price 	/*
17338a84802eSSteven Price 	 * Some architectures may have to restore extra metadata to the
17348a84802eSSteven Price 	 * physical page after reading from swap.
17358a84802eSSteven Price 	 */
17368a84802eSSteven Price 	arch_swap_restore(swap, page);
17378a84802eSSteven Price 
1738bde05d1cSHugh Dickins 	if (shmem_should_replace_page(page, gfp)) {
1739bde05d1cSHugh Dickins 		error = shmem_replace_page(&page, gfp, info, index);
1740bde05d1cSHugh Dickins 		if (error)
174154af6042SHugh Dickins 			goto failed;
17421da177e4SLinus Torvalds 	}
17431da177e4SLinus Torvalds 
17443fea5a49SJohannes Weiner 	error = shmem_add_to_page_cache(page, mapping, index,
17453fea5a49SJohannes Weiner 					swp_to_radix_entry(swap), gfp,
17463fea5a49SJohannes Weiner 					charge_mm);
174754af6042SHugh Dickins 	if (error)
174854af6042SHugh Dickins 		goto failed;
174954af6042SHugh Dickins 
17504595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
175154af6042SHugh Dickins 	info->swapped--;
175254af6042SHugh Dickins 	shmem_recalc_inode(inode);
17534595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
175427ab7006SHugh Dickins 
175566d2f4d2SHugh Dickins 	if (sgp == SGP_WRITE)
175666d2f4d2SHugh Dickins 		mark_page_accessed(page);
175766d2f4d2SHugh Dickins 
175827ab7006SHugh Dickins 	delete_from_swap_cache(page);
175927ab7006SHugh Dickins 	set_page_dirty(page);
176027ab7006SHugh Dickins 	swap_free(swap);
176127ab7006SHugh Dickins 
1762c5bf121eSVineeth Remanan Pillai 	*pagep = page;
1763c5bf121eSVineeth Remanan Pillai 	return 0;
1764c5bf121eSVineeth Remanan Pillai failed:
1765c5bf121eSVineeth Remanan Pillai 	if (!shmem_confirm_swap(mapping, index, swap))
1766c5bf121eSVineeth Remanan Pillai 		error = -EEXIST;
1767c5bf121eSVineeth Remanan Pillai unlock:
1768c5bf121eSVineeth Remanan Pillai 	if (page) {
1769c5bf121eSVineeth Remanan Pillai 		unlock_page(page);
1770c5bf121eSVineeth Remanan Pillai 		put_page(page);
1771c5bf121eSVineeth Remanan Pillai 	}
1772c5bf121eSVineeth Remanan Pillai 
1773c5bf121eSVineeth Remanan Pillai 	return error;
1774c5bf121eSVineeth Remanan Pillai }
1775c5bf121eSVineeth Remanan Pillai 
1776c5bf121eSVineeth Remanan Pillai /*
1777c5bf121eSVineeth Remanan Pillai  * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1778c5bf121eSVineeth Remanan Pillai  *
1779c5bf121eSVineeth Remanan Pillai  * If we allocate a new one we do not mark it dirty. That's up to the
1780c5bf121eSVineeth Remanan Pillai  * vm. If we swap it in we mark it dirty since we also free the swap
1781c5bf121eSVineeth Remanan Pillai  * entry since a page cannot live in both the swap and page cache.
1782c5bf121eSVineeth Remanan Pillai  *
1783c949b097SAxel Rasmussen  * vma, vmf, and fault_type are only supplied by shmem_fault:
1784c5bf121eSVineeth Remanan Pillai  * otherwise they are NULL.
1785c5bf121eSVineeth Remanan Pillai  */
1786c5bf121eSVineeth Remanan Pillai static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1787c5bf121eSVineeth Remanan Pillai 	struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1788c5bf121eSVineeth Remanan Pillai 	struct vm_area_struct *vma, struct vm_fault *vmf,
1789c5bf121eSVineeth Remanan Pillai 			vm_fault_t *fault_type)
1790c5bf121eSVineeth Remanan Pillai {
1791c5bf121eSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1792c5bf121eSVineeth Remanan Pillai 	struct shmem_inode_info *info = SHMEM_I(inode);
1793c5bf121eSVineeth Remanan Pillai 	struct shmem_sb_info *sbinfo;
1794c5bf121eSVineeth Remanan Pillai 	struct mm_struct *charge_mm;
1795c5bf121eSVineeth Remanan Pillai 	struct page *page;
1796c5bf121eSVineeth Remanan Pillai 	pgoff_t hindex = index;
1797164cc4feSRik van Riel 	gfp_t huge_gfp;
1798c5bf121eSVineeth Remanan Pillai 	int error;
1799c5bf121eSVineeth Remanan Pillai 	int once = 0;
1800c5bf121eSVineeth Remanan Pillai 	int alloced = 0;
1801c5bf121eSVineeth Remanan Pillai 
1802c5bf121eSVineeth Remanan Pillai 	if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1803c5bf121eSVineeth Remanan Pillai 		return -EFBIG;
1804c5bf121eSVineeth Remanan Pillai repeat:
1805c5bf121eSVineeth Remanan Pillai 	if (sgp <= SGP_CACHE &&
1806c5bf121eSVineeth Remanan Pillai 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1807c5bf121eSVineeth Remanan Pillai 		return -EINVAL;
1808c5bf121eSVineeth Remanan Pillai 	}
1809c5bf121eSVineeth Remanan Pillai 
1810c5bf121eSVineeth Remanan Pillai 	sbinfo = SHMEM_SB(inode->i_sb);
181104f94e3fSDan Schatzberg 	charge_mm = vma ? vma->vm_mm : NULL;
1812c5bf121eSVineeth Remanan Pillai 
181344835d20SMatthew Wilcox (Oracle) 	page = pagecache_get_page(mapping, index,
181444835d20SMatthew Wilcox (Oracle) 					FGP_ENTRY | FGP_HEAD | FGP_LOCK, 0);
1815c949b097SAxel Rasmussen 
1816c949b097SAxel Rasmussen 	if (page && vma && userfaultfd_minor(vma)) {
1817c949b097SAxel Rasmussen 		if (!xa_is_value(page)) {
1818c949b097SAxel Rasmussen 			unlock_page(page);
1819c949b097SAxel Rasmussen 			put_page(page);
1820c949b097SAxel Rasmussen 		}
1821c949b097SAxel Rasmussen 		*fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
1822c949b097SAxel Rasmussen 		return 0;
1823c949b097SAxel Rasmussen 	}
1824c949b097SAxel Rasmussen 
1825c5bf121eSVineeth Remanan Pillai 	if (xa_is_value(page)) {
1826c5bf121eSVineeth Remanan Pillai 		error = shmem_swapin_page(inode, index, &page,
1827c5bf121eSVineeth Remanan Pillai 					  sgp, gfp, vma, fault_type);
1828c5bf121eSVineeth Remanan Pillai 		if (error == -EEXIST)
1829c5bf121eSVineeth Remanan Pillai 			goto repeat;
1830c5bf121eSVineeth Remanan Pillai 
1831c5bf121eSVineeth Remanan Pillai 		*pagep = page;
1832c5bf121eSVineeth Remanan Pillai 		return error;
1833c5bf121eSVineeth Remanan Pillai 	}
1834c5bf121eSVineeth Remanan Pillai 
1835acdd9f8eSHugh Dickins 	if (page) {
183663ec1973SMatthew Wilcox (Oracle) 		hindex = page->index;
1837acdd9f8eSHugh Dickins 		if (sgp == SGP_WRITE)
1838c5bf121eSVineeth Remanan Pillai 			mark_page_accessed(page);
1839acdd9f8eSHugh Dickins 		if (PageUptodate(page))
1840acdd9f8eSHugh Dickins 			goto out;
1841acdd9f8eSHugh Dickins 		/* fallocated page */
1842c5bf121eSVineeth Remanan Pillai 		if (sgp != SGP_READ)
1843c5bf121eSVineeth Remanan Pillai 			goto clear;
1844c5bf121eSVineeth Remanan Pillai 		unlock_page(page);
1845c5bf121eSVineeth Remanan Pillai 		put_page(page);
1846c5bf121eSVineeth Remanan Pillai 	}
1847c5bf121eSVineeth Remanan Pillai 
1848c5bf121eSVineeth Remanan Pillai 	/*
1849acdd9f8eSHugh Dickins 	 * SGP_READ: succeed on hole, with NULL page, letting caller zero.
1850acdd9f8eSHugh Dickins 	 * SGP_NOALLOC: fail on hole, with NULL page, letting caller fail.
1851acdd9f8eSHugh Dickins 	 */
1852acdd9f8eSHugh Dickins 	*pagep = NULL;
1853acdd9f8eSHugh Dickins 	if (sgp == SGP_READ)
1854acdd9f8eSHugh Dickins 		return 0;
1855acdd9f8eSHugh Dickins 	if (sgp == SGP_NOALLOC)
1856acdd9f8eSHugh Dickins 		return -ENOENT;
1857acdd9f8eSHugh Dickins 
1858acdd9f8eSHugh Dickins 	/*
1859acdd9f8eSHugh Dickins 	 * Fast cache lookup and swap lookup did not find it: allocate.
1860c5bf121eSVineeth Remanan Pillai 	 */
1861c5bf121eSVineeth Remanan Pillai 
1862cfda0526SMike Rapoport 	if (vma && userfaultfd_missing(vma)) {
1863cfda0526SMike Rapoport 		*fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1864cfda0526SMike Rapoport 		return 0;
1865cfda0526SMike Rapoport 	}
1866cfda0526SMike Rapoport 
18675e6e5a12SHugh Dickins 	if (!shmem_is_huge(vma, inode, index))
1868800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
186927d80fa2SKees Cook 
1870164cc4feSRik van Riel 	huge_gfp = vma_thp_gfp_mask(vma);
187178cc8cdcSRik van Riel 	huge_gfp = limit_gfp_mask(huge_gfp, gfp);
1872164cc4feSRik van Riel 	page = shmem_alloc_and_acct_page(huge_gfp, inode, index, true);
1873800d8c63SKirill A. Shutemov 	if (IS_ERR(page)) {
1874c5bf121eSVineeth Remanan Pillai alloc_nohuge:
1875c5bf121eSVineeth Remanan Pillai 		page = shmem_alloc_and_acct_page(gfp, inode,
1876800d8c63SKirill A. Shutemov 						 index, false);
187754af6042SHugh Dickins 	}
1878800d8c63SKirill A. Shutemov 	if (IS_ERR(page)) {
1879779750d2SKirill A. Shutemov 		int retry = 5;
1880c5bf121eSVineeth Remanan Pillai 
1881800d8c63SKirill A. Shutemov 		error = PTR_ERR(page);
1882800d8c63SKirill A. Shutemov 		page = NULL;
1883779750d2SKirill A. Shutemov 		if (error != -ENOSPC)
1884c5bf121eSVineeth Remanan Pillai 			goto unlock;
1885779750d2SKirill A. Shutemov 		/*
1886c5bf121eSVineeth Remanan Pillai 		 * Try to reclaim some space by splitting a huge page
1887779750d2SKirill A. Shutemov 		 * beyond i_size on the filesystem.
1888779750d2SKirill A. Shutemov 		 */
1889779750d2SKirill A. Shutemov 		while (retry--) {
1890779750d2SKirill A. Shutemov 			int ret;
1891c5bf121eSVineeth Remanan Pillai 
1892779750d2SKirill A. Shutemov 			ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1893779750d2SKirill A. Shutemov 			if (ret == SHRINK_STOP)
1894779750d2SKirill A. Shutemov 				break;
1895779750d2SKirill A. Shutemov 			if (ret)
1896779750d2SKirill A. Shutemov 				goto alloc_nohuge;
1897779750d2SKirill A. Shutemov 		}
1898c5bf121eSVineeth Remanan Pillai 		goto unlock;
1899800d8c63SKirill A. Shutemov 	}
1900800d8c63SKirill A. Shutemov 
1901800d8c63SKirill A. Shutemov 	if (PageTransHuge(page))
1902800d8c63SKirill A. Shutemov 		hindex = round_down(index, HPAGE_PMD_NR);
1903800d8c63SKirill A. Shutemov 	else
1904800d8c63SKirill A. Shutemov 		hindex = index;
1905800d8c63SKirill A. Shutemov 
190666d2f4d2SHugh Dickins 	if (sgp == SGP_WRITE)
1907eb39d618SHugh Dickins 		__SetPageReferenced(page);
190866d2f4d2SHugh Dickins 
1909800d8c63SKirill A. Shutemov 	error = shmem_add_to_page_cache(page, mapping, hindex,
19103fea5a49SJohannes Weiner 					NULL, gfp & GFP_RECLAIM_MASK,
19113fea5a49SJohannes Weiner 					charge_mm);
19123fea5a49SJohannes Weiner 	if (error)
1913800d8c63SKirill A. Shutemov 		goto unacct;
19146058eaecSJohannes Weiner 	lru_cache_add(page);
191554af6042SHugh Dickins 
19164595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
1917d8c6546bSMatthew Wilcox (Oracle) 	info->alloced += compound_nr(page);
1918800d8c63SKirill A. Shutemov 	inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
191954af6042SHugh Dickins 	shmem_recalc_inode(inode);
19204595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
19211635f6a7SHugh Dickins 	alloced = true;
192254af6042SHugh Dickins 
1923779750d2SKirill A. Shutemov 	if (PageTransHuge(page) &&
1924779750d2SKirill A. Shutemov 	    DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1925779750d2SKirill A. Shutemov 			hindex + HPAGE_PMD_NR - 1) {
1926779750d2SKirill A. Shutemov 		/*
1927779750d2SKirill A. Shutemov 		 * Part of the huge page is beyond i_size: subject
1928779750d2SKirill A. Shutemov 		 * to shrink under memory pressure.
1929779750d2SKirill A. Shutemov 		 */
1930779750d2SKirill A. Shutemov 		spin_lock(&sbinfo->shrinklist_lock);
1931d041353dSCong Wang 		/*
1932d041353dSCong Wang 		 * _careful to defend against unlocked access to
1933d041353dSCong Wang 		 * ->shrink_list in shmem_unused_huge_shrink()
1934d041353dSCong Wang 		 */
1935d041353dSCong Wang 		if (list_empty_careful(&info->shrinklist)) {
1936779750d2SKirill A. Shutemov 			list_add_tail(&info->shrinklist,
1937779750d2SKirill A. Shutemov 				      &sbinfo->shrinklist);
1938779750d2SKirill A. Shutemov 			sbinfo->shrinklist_len++;
1939779750d2SKirill A. Shutemov 		}
1940779750d2SKirill A. Shutemov 		spin_unlock(&sbinfo->shrinklist_lock);
1941779750d2SKirill A. Shutemov 	}
1942779750d2SKirill A. Shutemov 
1943ec9516fbSHugh Dickins 	/*
19441635f6a7SHugh Dickins 	 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
19451635f6a7SHugh Dickins 	 */
19461635f6a7SHugh Dickins 	if (sgp == SGP_FALLOC)
19471635f6a7SHugh Dickins 		sgp = SGP_WRITE;
19481635f6a7SHugh Dickins clear:
19491635f6a7SHugh Dickins 	/*
19501635f6a7SHugh Dickins 	 * Let SGP_WRITE caller clear ends if write does not fill page;
19511635f6a7SHugh Dickins 	 * but SGP_FALLOC on a page fallocated earlier must initialize
19521635f6a7SHugh Dickins 	 * it now, lest undo on failure cancel our earlier guarantee.
1953ec9516fbSHugh Dickins 	 */
1954800d8c63SKirill A. Shutemov 	if (sgp != SGP_WRITE && !PageUptodate(page)) {
1955800d8c63SKirill A. Shutemov 		int i;
1956800d8c63SKirill A. Shutemov 
195763ec1973SMatthew Wilcox (Oracle) 		for (i = 0; i < compound_nr(page); i++) {
195863ec1973SMatthew Wilcox (Oracle) 			clear_highpage(page + i);
195963ec1973SMatthew Wilcox (Oracle) 			flush_dcache_page(page + i);
1960800d8c63SKirill A. Shutemov 		}
196163ec1973SMatthew Wilcox (Oracle) 		SetPageUptodate(page);
1962ec9516fbSHugh Dickins 	}
1963bde05d1cSHugh Dickins 
196454af6042SHugh Dickins 	/* Perhaps the file has been truncated since we checked */
196575edd345SHugh Dickins 	if (sgp <= SGP_CACHE &&
196609cbfeafSKirill A. Shutemov 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1967267a4c76SHugh Dickins 		if (alloced) {
1968267a4c76SHugh Dickins 			ClearPageDirty(page);
1969267a4c76SHugh Dickins 			delete_from_page_cache(page);
19704595ef88SKirill A. Shutemov 			spin_lock_irq(&info->lock);
1971267a4c76SHugh Dickins 			shmem_recalc_inode(inode);
19724595ef88SKirill A. Shutemov 			spin_unlock_irq(&info->lock);
1973267a4c76SHugh Dickins 		}
197454af6042SHugh Dickins 		error = -EINVAL;
1975267a4c76SHugh Dickins 		goto unlock;
1976ff36b801SShaohua Li 	}
197763ec1973SMatthew Wilcox (Oracle) out:
1978800d8c63SKirill A. Shutemov 	*pagep = page + index - hindex;
197954af6042SHugh Dickins 	return 0;
1980d00806b1SNick Piggin 
1981d0217ac0SNick Piggin 	/*
198254af6042SHugh Dickins 	 * Error recovery.
19831da177e4SLinus Torvalds 	 */
198454af6042SHugh Dickins unacct:
1985d8c6546bSMatthew Wilcox (Oracle) 	shmem_inode_unacct_blocks(inode, compound_nr(page));
1986800d8c63SKirill A. Shutemov 
1987800d8c63SKirill A. Shutemov 	if (PageTransHuge(page)) {
1988800d8c63SKirill A. Shutemov 		unlock_page(page);
1989800d8c63SKirill A. Shutemov 		put_page(page);
1990800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
1991800d8c63SKirill A. Shutemov 	}
1992d1899228SHugh Dickins unlock:
199327ab7006SHugh Dickins 	if (page) {
199454af6042SHugh Dickins 		unlock_page(page);
199509cbfeafSKirill A. Shutemov 		put_page(page);
199654af6042SHugh Dickins 	}
199754af6042SHugh Dickins 	if (error == -ENOSPC && !once++) {
19984595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
199954af6042SHugh Dickins 		shmem_recalc_inode(inode);
20004595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
20011da177e4SLinus Torvalds 		goto repeat;
2002d8dc74f2SAdrian Bunk 	}
20037f4446eeSMatthew Wilcox 	if (error == -EEXIST)
200454af6042SHugh Dickins 		goto repeat;
200554af6042SHugh Dickins 	return error;
20061da177e4SLinus Torvalds }
20071da177e4SLinus Torvalds 
200810d20bd2SLinus Torvalds /*
200910d20bd2SLinus Torvalds  * This is like autoremove_wake_function, but it removes the wait queue
201010d20bd2SLinus Torvalds  * entry unconditionally - even if something else had already woken the
201110d20bd2SLinus Torvalds  * target.
201210d20bd2SLinus Torvalds  */
2013ac6424b9SIngo Molnar static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
201410d20bd2SLinus Torvalds {
201510d20bd2SLinus Torvalds 	int ret = default_wake_function(wait, mode, sync, key);
20162055da97SIngo Molnar 	list_del_init(&wait->entry);
201710d20bd2SLinus Torvalds 	return ret;
201810d20bd2SLinus Torvalds }
201910d20bd2SLinus Torvalds 
202020acce67SSouptick Joarder static vm_fault_t shmem_fault(struct vm_fault *vmf)
20211da177e4SLinus Torvalds {
202211bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
2023496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
20249e18eb29SAndres Lagar-Cavilla 	gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
202520acce67SSouptick Joarder 	int err;
202620acce67SSouptick Joarder 	vm_fault_t ret = VM_FAULT_LOCKED;
20271da177e4SLinus Torvalds 
2028f00cdc6dSHugh Dickins 	/*
2029f00cdc6dSHugh Dickins 	 * Trinity finds that probing a hole which tmpfs is punching can
2030f00cdc6dSHugh Dickins 	 * prevent the hole-punch from ever completing: which in turn
20319608703eSJan Kara 	 * locks writers out with its hold on i_rwsem.  So refrain from
20328e205f77SHugh Dickins 	 * faulting pages into the hole while it's being punched.  Although
20338e205f77SHugh Dickins 	 * shmem_undo_range() does remove the additions, it may be unable to
20348e205f77SHugh Dickins 	 * keep up, as each new page needs its own unmap_mapping_range() call,
20358e205f77SHugh Dickins 	 * and the i_mmap tree grows ever slower to scan if new vmas are added.
20368e205f77SHugh Dickins 	 *
20378e205f77SHugh Dickins 	 * It does not matter if we sometimes reach this check just before the
20388e205f77SHugh Dickins 	 * hole-punch begins, so that one fault then races with the punch:
20398e205f77SHugh Dickins 	 * we just need to make racing faults a rare case.
20408e205f77SHugh Dickins 	 *
20418e205f77SHugh Dickins 	 * The implementation below would be much simpler if we just used a
20429608703eSJan Kara 	 * standard mutex or completion: but we cannot take i_rwsem in fault,
20438e205f77SHugh Dickins 	 * and bloating every shmem inode for this unlikely case would be sad.
2044f00cdc6dSHugh Dickins 	 */
2045f00cdc6dSHugh Dickins 	if (unlikely(inode->i_private)) {
2046f00cdc6dSHugh Dickins 		struct shmem_falloc *shmem_falloc;
2047f00cdc6dSHugh Dickins 
2048f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
2049f00cdc6dSHugh Dickins 		shmem_falloc = inode->i_private;
20508e205f77SHugh Dickins 		if (shmem_falloc &&
20518e205f77SHugh Dickins 		    shmem_falloc->waitq &&
20528e205f77SHugh Dickins 		    vmf->pgoff >= shmem_falloc->start &&
20538e205f77SHugh Dickins 		    vmf->pgoff < shmem_falloc->next) {
20548897c1b1SKirill A. Shutemov 			struct file *fpin;
20558e205f77SHugh Dickins 			wait_queue_head_t *shmem_falloc_waitq;
205610d20bd2SLinus Torvalds 			DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
20578e205f77SHugh Dickins 
20588e205f77SHugh Dickins 			ret = VM_FAULT_NOPAGE;
20598897c1b1SKirill A. Shutemov 			fpin = maybe_unlock_mmap_for_io(vmf, NULL);
20608897c1b1SKirill A. Shutemov 			if (fpin)
20618e205f77SHugh Dickins 				ret = VM_FAULT_RETRY;
20628e205f77SHugh Dickins 
20638e205f77SHugh Dickins 			shmem_falloc_waitq = shmem_falloc->waitq;
20648e205f77SHugh Dickins 			prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
20658e205f77SHugh Dickins 					TASK_UNINTERRUPTIBLE);
20668e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
20678e205f77SHugh Dickins 			schedule();
20688e205f77SHugh Dickins 
20698e205f77SHugh Dickins 			/*
20708e205f77SHugh Dickins 			 * shmem_falloc_waitq points into the shmem_fallocate()
20718e205f77SHugh Dickins 			 * stack of the hole-punching task: shmem_falloc_waitq
20728e205f77SHugh Dickins 			 * is usually invalid by the time we reach here, but
20738e205f77SHugh Dickins 			 * finish_wait() does not dereference it in that case;
20748e205f77SHugh Dickins 			 * though i_lock needed lest racing with wake_up_all().
20758e205f77SHugh Dickins 			 */
20768e205f77SHugh Dickins 			spin_lock(&inode->i_lock);
20778e205f77SHugh Dickins 			finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
20788e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
20798897c1b1SKirill A. Shutemov 
20808897c1b1SKirill A. Shutemov 			if (fpin)
20818897c1b1SKirill A. Shutemov 				fput(fpin);
20828e205f77SHugh Dickins 			return ret;
2083f00cdc6dSHugh Dickins 		}
20848e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
2085f00cdc6dSHugh Dickins 	}
2086f00cdc6dSHugh Dickins 
20875e6e5a12SHugh Dickins 	err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, SGP_CACHE,
2088cfda0526SMike Rapoport 				  gfp, vma, vmf, &ret);
208920acce67SSouptick Joarder 	if (err)
209020acce67SSouptick Joarder 		return vmf_error(err);
209168da9f05SHugh Dickins 	return ret;
20921da177e4SLinus Torvalds }
20931da177e4SLinus Torvalds 
2094c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
2095c01d5b30SHugh Dickins 				      unsigned long uaddr, unsigned long len,
2096c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
2097c01d5b30SHugh Dickins {
2098c01d5b30SHugh Dickins 	unsigned long (*get_area)(struct file *,
2099c01d5b30SHugh Dickins 		unsigned long, unsigned long, unsigned long, unsigned long);
2100c01d5b30SHugh Dickins 	unsigned long addr;
2101c01d5b30SHugh Dickins 	unsigned long offset;
2102c01d5b30SHugh Dickins 	unsigned long inflated_len;
2103c01d5b30SHugh Dickins 	unsigned long inflated_addr;
2104c01d5b30SHugh Dickins 	unsigned long inflated_offset;
2105c01d5b30SHugh Dickins 
2106c01d5b30SHugh Dickins 	if (len > TASK_SIZE)
2107c01d5b30SHugh Dickins 		return -ENOMEM;
2108c01d5b30SHugh Dickins 
2109c01d5b30SHugh Dickins 	get_area = current->mm->get_unmapped_area;
2110c01d5b30SHugh Dickins 	addr = get_area(file, uaddr, len, pgoff, flags);
2111c01d5b30SHugh Dickins 
2112396bcc52SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
2113c01d5b30SHugh Dickins 		return addr;
2114c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(addr))
2115c01d5b30SHugh Dickins 		return addr;
2116c01d5b30SHugh Dickins 	if (addr & ~PAGE_MASK)
2117c01d5b30SHugh Dickins 		return addr;
2118c01d5b30SHugh Dickins 	if (addr > TASK_SIZE - len)
2119c01d5b30SHugh Dickins 		return addr;
2120c01d5b30SHugh Dickins 
2121c01d5b30SHugh Dickins 	if (shmem_huge == SHMEM_HUGE_DENY)
2122c01d5b30SHugh Dickins 		return addr;
2123c01d5b30SHugh Dickins 	if (len < HPAGE_PMD_SIZE)
2124c01d5b30SHugh Dickins 		return addr;
2125c01d5b30SHugh Dickins 	if (flags & MAP_FIXED)
2126c01d5b30SHugh Dickins 		return addr;
2127c01d5b30SHugh Dickins 	/*
2128c01d5b30SHugh Dickins 	 * Our priority is to support MAP_SHARED mapped hugely;
2129c01d5b30SHugh Dickins 	 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
213099158997SKirill A. Shutemov 	 * But if caller specified an address hint and we allocated area there
213199158997SKirill A. Shutemov 	 * successfully, respect that as before.
2132c01d5b30SHugh Dickins 	 */
213399158997SKirill A. Shutemov 	if (uaddr == addr)
2134c01d5b30SHugh Dickins 		return addr;
2135c01d5b30SHugh Dickins 
2136c01d5b30SHugh Dickins 	if (shmem_huge != SHMEM_HUGE_FORCE) {
2137c01d5b30SHugh Dickins 		struct super_block *sb;
2138c01d5b30SHugh Dickins 
2139c01d5b30SHugh Dickins 		if (file) {
2140c01d5b30SHugh Dickins 			VM_BUG_ON(file->f_op != &shmem_file_operations);
2141c01d5b30SHugh Dickins 			sb = file_inode(file)->i_sb;
2142c01d5b30SHugh Dickins 		} else {
2143c01d5b30SHugh Dickins 			/*
2144c01d5b30SHugh Dickins 			 * Called directly from mm/mmap.c, or drivers/char/mem.c
2145c01d5b30SHugh Dickins 			 * for "/dev/zero", to create a shared anonymous object.
2146c01d5b30SHugh Dickins 			 */
2147c01d5b30SHugh Dickins 			if (IS_ERR(shm_mnt))
2148c01d5b30SHugh Dickins 				return addr;
2149c01d5b30SHugh Dickins 			sb = shm_mnt->mnt_sb;
2150c01d5b30SHugh Dickins 		}
21513089bf61SToshi Kani 		if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2152c01d5b30SHugh Dickins 			return addr;
2153c01d5b30SHugh Dickins 	}
2154c01d5b30SHugh Dickins 
2155c01d5b30SHugh Dickins 	offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2156c01d5b30SHugh Dickins 	if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2157c01d5b30SHugh Dickins 		return addr;
2158c01d5b30SHugh Dickins 	if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2159c01d5b30SHugh Dickins 		return addr;
2160c01d5b30SHugh Dickins 
2161c01d5b30SHugh Dickins 	inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2162c01d5b30SHugh Dickins 	if (inflated_len > TASK_SIZE)
2163c01d5b30SHugh Dickins 		return addr;
2164c01d5b30SHugh Dickins 	if (inflated_len < len)
2165c01d5b30SHugh Dickins 		return addr;
2166c01d5b30SHugh Dickins 
216799158997SKirill A. Shutemov 	inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
2168c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(inflated_addr))
2169c01d5b30SHugh Dickins 		return addr;
2170c01d5b30SHugh Dickins 	if (inflated_addr & ~PAGE_MASK)
2171c01d5b30SHugh Dickins 		return addr;
2172c01d5b30SHugh Dickins 
2173c01d5b30SHugh Dickins 	inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2174c01d5b30SHugh Dickins 	inflated_addr += offset - inflated_offset;
2175c01d5b30SHugh Dickins 	if (inflated_offset > offset)
2176c01d5b30SHugh Dickins 		inflated_addr += HPAGE_PMD_SIZE;
2177c01d5b30SHugh Dickins 
2178c01d5b30SHugh Dickins 	if (inflated_addr > TASK_SIZE - len)
2179c01d5b30SHugh Dickins 		return addr;
2180c01d5b30SHugh Dickins 	return inflated_addr;
2181c01d5b30SHugh Dickins }
2182c01d5b30SHugh Dickins 
21831da177e4SLinus Torvalds #ifdef CONFIG_NUMA
218441ffe5d5SHugh Dickins static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
21851da177e4SLinus Torvalds {
2186496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
218741ffe5d5SHugh Dickins 	return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
21881da177e4SLinus Torvalds }
21891da177e4SLinus Torvalds 
2190d8dc74f2SAdrian Bunk static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2191d8dc74f2SAdrian Bunk 					  unsigned long addr)
21921da177e4SLinus Torvalds {
2193496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
219441ffe5d5SHugh Dickins 	pgoff_t index;
21951da177e4SLinus Torvalds 
219641ffe5d5SHugh Dickins 	index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
219741ffe5d5SHugh Dickins 	return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
21981da177e4SLinus Torvalds }
21991da177e4SLinus Torvalds #endif
22001da177e4SLinus Torvalds 
2201d7c9e99aSAlexey Gladkov int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
22021da177e4SLinus Torvalds {
2203496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
22041da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
22051da177e4SLinus Torvalds 	int retval = -ENOMEM;
22061da177e4SLinus Torvalds 
2207ea0dfeb4SHugh Dickins 	/*
2208ea0dfeb4SHugh Dickins 	 * What serializes the accesses to info->flags?
2209ea0dfeb4SHugh Dickins 	 * ipc_lock_object() when called from shmctl_do_lock(),
2210ea0dfeb4SHugh Dickins 	 * no serialization needed when called from shm_destroy().
2211ea0dfeb4SHugh Dickins 	 */
22121da177e4SLinus Torvalds 	if (lock && !(info->flags & VM_LOCKED)) {
2213d7c9e99aSAlexey Gladkov 		if (!user_shm_lock(inode->i_size, ucounts))
22141da177e4SLinus Torvalds 			goto out_nomem;
22151da177e4SLinus Torvalds 		info->flags |= VM_LOCKED;
221689e004eaSLee Schermerhorn 		mapping_set_unevictable(file->f_mapping);
22171da177e4SLinus Torvalds 	}
2218d7c9e99aSAlexey Gladkov 	if (!lock && (info->flags & VM_LOCKED) && ucounts) {
2219d7c9e99aSAlexey Gladkov 		user_shm_unlock(inode->i_size, ucounts);
22201da177e4SLinus Torvalds 		info->flags &= ~VM_LOCKED;
222189e004eaSLee Schermerhorn 		mapping_clear_unevictable(file->f_mapping);
22221da177e4SLinus Torvalds 	}
22231da177e4SLinus Torvalds 	retval = 0;
222489e004eaSLee Schermerhorn 
22251da177e4SLinus Torvalds out_nomem:
22261da177e4SLinus Torvalds 	return retval;
22271da177e4SLinus Torvalds }
22281da177e4SLinus Torvalds 
22299b83a6a8SAdrian Bunk static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
22301da177e4SLinus Torvalds {
2231ab3948f5SJoel Fernandes (Google) 	struct shmem_inode_info *info = SHMEM_I(file_inode(file));
223222247efdSPeter Xu 	int ret;
2233ab3948f5SJoel Fernandes (Google) 
223422247efdSPeter Xu 	ret = seal_check_future_write(info->seals, vma);
223522247efdSPeter Xu 	if (ret)
223622247efdSPeter Xu 		return ret;
2237ab3948f5SJoel Fernandes (Google) 
223851b0bff2SCatalin Marinas 	/* arm64 - allow memory tagging on RAM-based files */
223951b0bff2SCatalin Marinas 	vma->vm_flags |= VM_MTE_ALLOWED;
224051b0bff2SCatalin Marinas 
22411da177e4SLinus Torvalds 	file_accessed(file);
22421da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
2243396bcc52SMatthew Wilcox (Oracle) 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
2244f3f0e1d2SKirill A. Shutemov 			((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2245f3f0e1d2SKirill A. Shutemov 			(vma->vm_end & HPAGE_PMD_MASK)) {
2246f3f0e1d2SKirill A. Shutemov 		khugepaged_enter(vma, vma->vm_flags);
2247f3f0e1d2SKirill A. Shutemov 	}
22481da177e4SLinus Torvalds 	return 0;
22491da177e4SLinus Torvalds }
22501da177e4SLinus Torvalds 
2251454abafeSDmitry Monakhov static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
225209208d15SAl Viro 				     umode_t mode, dev_t dev, unsigned long flags)
22531da177e4SLinus Torvalds {
22541da177e4SLinus Torvalds 	struct inode *inode;
22551da177e4SLinus Torvalds 	struct shmem_inode_info *info;
22561da177e4SLinus Torvalds 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2257e809d5f0SChris Down 	ino_t ino;
22581da177e4SLinus Torvalds 
2259e809d5f0SChris Down 	if (shmem_reserve_inode(sb, &ino))
22601da177e4SLinus Torvalds 		return NULL;
22611da177e4SLinus Torvalds 
22621da177e4SLinus Torvalds 	inode = new_inode(sb);
22631da177e4SLinus Torvalds 	if (inode) {
2264e809d5f0SChris Down 		inode->i_ino = ino;
226521cb47beSChristian Brauner 		inode_init_owner(&init_user_ns, inode, dir, mode);
22661da177e4SLinus Torvalds 		inode->i_blocks = 0;
2267078cd827SDeepa Dinamani 		inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
226846c9a946SArnd Bergmann 		inode->i_generation = prandom_u32();
22691da177e4SLinus Torvalds 		info = SHMEM_I(inode);
22701da177e4SLinus Torvalds 		memset(info, 0, (char *)inode - (char *)info);
22711da177e4SLinus Torvalds 		spin_lock_init(&info->lock);
2272af53d3e9SHugh Dickins 		atomic_set(&info->stop_eviction, 0);
227340e041a2SDavid Herrmann 		info->seals = F_SEAL_SEAL;
22740b0a0806SHugh Dickins 		info->flags = flags & VM_NORESERVE;
2275f7cd16a5SXavier Roche 		info->i_crtime = inode->i_mtime;
2276779750d2SKirill A. Shutemov 		INIT_LIST_HEAD(&info->shrinklist);
22771da177e4SLinus Torvalds 		INIT_LIST_HEAD(&info->swaplist);
227838f38657SAristeu Rozanski 		simple_xattrs_init(&info->xattrs);
227972c04902SAl Viro 		cache_no_acl(inode);
2280ff36da69SMatthew Wilcox (Oracle) 		mapping_set_large_folios(inode->i_mapping);
22811da177e4SLinus Torvalds 
22821da177e4SLinus Torvalds 		switch (mode & S_IFMT) {
22831da177e4SLinus Torvalds 		default:
228439f0247dSAndreas Gruenbacher 			inode->i_op = &shmem_special_inode_operations;
22851da177e4SLinus Torvalds 			init_special_inode(inode, mode, dev);
22861da177e4SLinus Torvalds 			break;
22871da177e4SLinus Torvalds 		case S_IFREG:
228814fcc23fSHugh Dickins 			inode->i_mapping->a_ops = &shmem_aops;
22891da177e4SLinus Torvalds 			inode->i_op = &shmem_inode_operations;
22901da177e4SLinus Torvalds 			inode->i_fop = &shmem_file_operations;
229171fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy,
229271fe804bSLee Schermerhorn 						 shmem_get_sbmpol(sbinfo));
22931da177e4SLinus Torvalds 			break;
22941da177e4SLinus Torvalds 		case S_IFDIR:
2295d8c76e6fSDave Hansen 			inc_nlink(inode);
22961da177e4SLinus Torvalds 			/* Some things misbehave if size == 0 on a directory */
22971da177e4SLinus Torvalds 			inode->i_size = 2 * BOGO_DIRENT_SIZE;
22981da177e4SLinus Torvalds 			inode->i_op = &shmem_dir_inode_operations;
22991da177e4SLinus Torvalds 			inode->i_fop = &simple_dir_operations;
23001da177e4SLinus Torvalds 			break;
23011da177e4SLinus Torvalds 		case S_IFLNK:
23021da177e4SLinus Torvalds 			/*
23031da177e4SLinus Torvalds 			 * Must not load anything in the rbtree,
23041da177e4SLinus Torvalds 			 * mpol_free_shared_policy will not be called.
23051da177e4SLinus Torvalds 			 */
230671fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy, NULL);
23071da177e4SLinus Torvalds 			break;
23081da177e4SLinus Torvalds 		}
2309b45d71fbSJoel Fernandes (Google) 
2310b45d71fbSJoel Fernandes (Google) 		lockdep_annotate_inode_mutex_key(inode);
23115b04c689SPavel Emelyanov 	} else
23125b04c689SPavel Emelyanov 		shmem_free_inode(sb);
23131da177e4SLinus Torvalds 	return inode;
23141da177e4SLinus Torvalds }
23151da177e4SLinus Torvalds 
23163460f6e5SAxel Rasmussen #ifdef CONFIG_USERFAULTFD
23173460f6e5SAxel Rasmussen int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
23184c27fe4cSMike Rapoport 			   pmd_t *dst_pmd,
23194c27fe4cSMike Rapoport 			   struct vm_area_struct *dst_vma,
23204c27fe4cSMike Rapoport 			   unsigned long dst_addr,
23214c27fe4cSMike Rapoport 			   unsigned long src_addr,
23228d103963SMike Rapoport 			   bool zeropage,
23234c27fe4cSMike Rapoport 			   struct page **pagep)
23244c27fe4cSMike Rapoport {
23254c27fe4cSMike Rapoport 	struct inode *inode = file_inode(dst_vma->vm_file);
23264c27fe4cSMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
23274c27fe4cSMike Rapoport 	struct address_space *mapping = inode->i_mapping;
23284c27fe4cSMike Rapoport 	gfp_t gfp = mapping_gfp_mask(mapping);
23294c27fe4cSMike Rapoport 	pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
23304c27fe4cSMike Rapoport 	void *page_kaddr;
23314c27fe4cSMike Rapoport 	struct page *page;
23324c27fe4cSMike Rapoport 	int ret;
23333460f6e5SAxel Rasmussen 	pgoff_t max_off;
23344c27fe4cSMike Rapoport 
23357ed9d238SAxel Rasmussen 	if (!shmem_inode_acct_block(inode, 1)) {
23367ed9d238SAxel Rasmussen 		/*
23377ed9d238SAxel Rasmussen 		 * We may have got a page, returned -ENOENT triggering a retry,
23387ed9d238SAxel Rasmussen 		 * and now we find ourselves with -ENOMEM. Release the page, to
23397ed9d238SAxel Rasmussen 		 * avoid a BUG_ON in our caller.
23407ed9d238SAxel Rasmussen 		 */
23417ed9d238SAxel Rasmussen 		if (unlikely(*pagep)) {
23427ed9d238SAxel Rasmussen 			put_page(*pagep);
23437ed9d238SAxel Rasmussen 			*pagep = NULL;
23447ed9d238SAxel Rasmussen 		}
23457d64ae3aSAxel Rasmussen 		return -ENOMEM;
23467ed9d238SAxel Rasmussen 	}
23474c27fe4cSMike Rapoport 
2348cb658a45SAndrea Arcangeli 	if (!*pagep) {
23497d64ae3aSAxel Rasmussen 		ret = -ENOMEM;
23504c27fe4cSMike Rapoport 		page = shmem_alloc_page(gfp, info, pgoff);
23514c27fe4cSMike Rapoport 		if (!page)
23520f079694SMike Rapoport 			goto out_unacct_blocks;
23534c27fe4cSMike Rapoport 
23543460f6e5SAxel Rasmussen 		if (!zeropage) {	/* COPY */
23554c27fe4cSMike Rapoport 			page_kaddr = kmap_atomic(page);
23568d103963SMike Rapoport 			ret = copy_from_user(page_kaddr,
23578d103963SMike Rapoport 					     (const void __user *)src_addr,
23584c27fe4cSMike Rapoport 					     PAGE_SIZE);
23594c27fe4cSMike Rapoport 			kunmap_atomic(page_kaddr);
23604c27fe4cSMike Rapoport 
2361c1e8d7c6SMichel Lespinasse 			/* fallback to copy_from_user outside mmap_lock */
23624c27fe4cSMike Rapoport 			if (unlikely(ret)) {
23634c27fe4cSMike Rapoport 				*pagep = page;
23647d64ae3aSAxel Rasmussen 				ret = -ENOENT;
23654c27fe4cSMike Rapoport 				/* don't free the page */
23667d64ae3aSAxel Rasmussen 				goto out_unacct_blocks;
23674c27fe4cSMike Rapoport 			}
236819b482c2SMuchun Song 
236919b482c2SMuchun Song 			flush_dcache_page(page);
23703460f6e5SAxel Rasmussen 		} else {		/* ZEROPAGE */
237119b482c2SMuchun Song 			clear_user_highpage(page, dst_addr);
23728d103963SMike Rapoport 		}
23734c27fe4cSMike Rapoport 	} else {
23744c27fe4cSMike Rapoport 		page = *pagep;
23754c27fe4cSMike Rapoport 		*pagep = NULL;
23764c27fe4cSMike Rapoport 	}
23774c27fe4cSMike Rapoport 
23783460f6e5SAxel Rasmussen 	VM_BUG_ON(PageLocked(page));
23793460f6e5SAxel Rasmussen 	VM_BUG_ON(PageSwapBacked(page));
23809cc90c66SAndrea Arcangeli 	__SetPageLocked(page);
23819cc90c66SAndrea Arcangeli 	__SetPageSwapBacked(page);
2382a425d358SAndrea Arcangeli 	__SetPageUptodate(page);
23839cc90c66SAndrea Arcangeli 
2384e2a50c1fSAndrea Arcangeli 	ret = -EFAULT;
2385e2a50c1fSAndrea Arcangeli 	max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
23863460f6e5SAxel Rasmussen 	if (unlikely(pgoff >= max_off))
2387e2a50c1fSAndrea Arcangeli 		goto out_release;
2388e2a50c1fSAndrea Arcangeli 
23893fea5a49SJohannes Weiner 	ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
23903fea5a49SJohannes Weiner 				      gfp & GFP_RECLAIM_MASK, dst_mm);
23914c27fe4cSMike Rapoport 	if (ret)
23924c27fe4cSMike Rapoport 		goto out_release;
23934c27fe4cSMike Rapoport 
23947d64ae3aSAxel Rasmussen 	ret = mfill_atomic_install_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
23957d64ae3aSAxel Rasmussen 				       page, true, false);
23967d64ae3aSAxel Rasmussen 	if (ret)
23977d64ae3aSAxel Rasmussen 		goto out_delete_from_cache;
23984c27fe4cSMike Rapoport 
239994b7cc01SYang Shi 	spin_lock_irq(&info->lock);
24004c27fe4cSMike Rapoport 	info->alloced++;
24014c27fe4cSMike Rapoport 	inode->i_blocks += BLOCKS_PER_PAGE;
24024c27fe4cSMike Rapoport 	shmem_recalc_inode(inode);
240394b7cc01SYang Shi 	spin_unlock_irq(&info->lock);
24044c27fe4cSMike Rapoport 
2405e2a50c1fSAndrea Arcangeli 	unlock_page(page);
24067d64ae3aSAxel Rasmussen 	return 0;
24077d64ae3aSAxel Rasmussen out_delete_from_cache:
2408e2a50c1fSAndrea Arcangeli 	delete_from_page_cache(page);
24094c27fe4cSMike Rapoport out_release:
24109cc90c66SAndrea Arcangeli 	unlock_page(page);
24114c27fe4cSMike Rapoport 	put_page(page);
24124c27fe4cSMike Rapoport out_unacct_blocks:
24130f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, 1);
24147d64ae3aSAxel Rasmussen 	return ret;
24154c27fe4cSMike Rapoport }
24163460f6e5SAxel Rasmussen #endif /* CONFIG_USERFAULTFD */
24178d103963SMike Rapoport 
24181da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
241992e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations;
242069f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations;
24211da177e4SLinus Torvalds 
24226d9d88d0SJarkko Sakkinen #ifdef CONFIG_TMPFS_XATTR
24236d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
24246d9d88d0SJarkko Sakkinen #else
24256d9d88d0SJarkko Sakkinen #define shmem_initxattrs NULL
24266d9d88d0SJarkko Sakkinen #endif
24276d9d88d0SJarkko Sakkinen 
24281da177e4SLinus Torvalds static int
2429800d15a5SNick Piggin shmem_write_begin(struct file *file, struct address_space *mapping,
2430800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned flags,
2431800d15a5SNick Piggin 			struct page **pagep, void **fsdata)
24321da177e4SLinus Torvalds {
2433800d15a5SNick Piggin 	struct inode *inode = mapping->host;
243440e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
243509cbfeafSKirill A. Shutemov 	pgoff_t index = pos >> PAGE_SHIFT;
2436a7605426SYang Shi 	int ret = 0;
243740e041a2SDavid Herrmann 
24389608703eSJan Kara 	/* i_rwsem is held by caller */
2439ab3948f5SJoel Fernandes (Google) 	if (unlikely(info->seals & (F_SEAL_GROW |
2440ab3948f5SJoel Fernandes (Google) 				   F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
2441ab3948f5SJoel Fernandes (Google) 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
244240e041a2SDavid Herrmann 			return -EPERM;
244340e041a2SDavid Herrmann 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
244440e041a2SDavid Herrmann 			return -EPERM;
244540e041a2SDavid Herrmann 	}
244640e041a2SDavid Herrmann 
2447a7605426SYang Shi 	ret = shmem_getpage(inode, index, pagep, SGP_WRITE);
2448a7605426SYang Shi 
2449a7605426SYang Shi 	if (ret)
2450a7605426SYang Shi 		return ret;
2451a7605426SYang Shi 
2452a7605426SYang Shi 	if (PageHWPoison(*pagep)) {
2453a7605426SYang Shi 		unlock_page(*pagep);
2454a7605426SYang Shi 		put_page(*pagep);
2455a7605426SYang Shi 		*pagep = NULL;
2456a7605426SYang Shi 		return -EIO;
2457a7605426SYang Shi 	}
2458a7605426SYang Shi 
2459a7605426SYang Shi 	return 0;
2460800d15a5SNick Piggin }
2461800d15a5SNick Piggin 
2462800d15a5SNick Piggin static int
2463800d15a5SNick Piggin shmem_write_end(struct file *file, struct address_space *mapping,
2464800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned copied,
2465800d15a5SNick Piggin 			struct page *page, void *fsdata)
2466800d15a5SNick Piggin {
2467800d15a5SNick Piggin 	struct inode *inode = mapping->host;
2468800d15a5SNick Piggin 
2469800d15a5SNick Piggin 	if (pos + copied > inode->i_size)
2470800d15a5SNick Piggin 		i_size_write(inode, pos + copied);
2471800d15a5SNick Piggin 
2472ec9516fbSHugh Dickins 	if (!PageUptodate(page)) {
2473800d8c63SKirill A. Shutemov 		struct page *head = compound_head(page);
2474800d8c63SKirill A. Shutemov 		if (PageTransCompound(page)) {
2475800d8c63SKirill A. Shutemov 			int i;
2476800d8c63SKirill A. Shutemov 
2477800d8c63SKirill A. Shutemov 			for (i = 0; i < HPAGE_PMD_NR; i++) {
2478800d8c63SKirill A. Shutemov 				if (head + i == page)
2479800d8c63SKirill A. Shutemov 					continue;
2480800d8c63SKirill A. Shutemov 				clear_highpage(head + i);
2481800d8c63SKirill A. Shutemov 				flush_dcache_page(head + i);
2482800d8c63SKirill A. Shutemov 			}
2483800d8c63SKirill A. Shutemov 		}
248409cbfeafSKirill A. Shutemov 		if (copied < PAGE_SIZE) {
248509cbfeafSKirill A. Shutemov 			unsigned from = pos & (PAGE_SIZE - 1);
2486ec9516fbSHugh Dickins 			zero_user_segments(page, 0, from,
248709cbfeafSKirill A. Shutemov 					from + copied, PAGE_SIZE);
2488ec9516fbSHugh Dickins 		}
2489800d8c63SKirill A. Shutemov 		SetPageUptodate(head);
2490ec9516fbSHugh Dickins 	}
2491d3602444SHugh Dickins 	set_page_dirty(page);
24926746aff7SWu Fengguang 	unlock_page(page);
249309cbfeafSKirill A. Shutemov 	put_page(page);
2494d3602444SHugh Dickins 
2495800d15a5SNick Piggin 	return copied;
24961da177e4SLinus Torvalds }
24971da177e4SLinus Torvalds 
24982ba5bbedSAl Viro static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
24991da177e4SLinus Torvalds {
25006e58e79dSAl Viro 	struct file *file = iocb->ki_filp;
25016e58e79dSAl Viro 	struct inode *inode = file_inode(file);
25021da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
250341ffe5d5SHugh Dickins 	pgoff_t index;
250441ffe5d5SHugh Dickins 	unsigned long offset;
2505f7c1d074SGeert Uytterhoeven 	int error = 0;
2506cb66a7a1SAl Viro 	ssize_t retval = 0;
25076e58e79dSAl Viro 	loff_t *ppos = &iocb->ki_pos;
2508a0ee5ec5SHugh Dickins 
250909cbfeafSKirill A. Shutemov 	index = *ppos >> PAGE_SHIFT;
251009cbfeafSKirill A. Shutemov 	offset = *ppos & ~PAGE_MASK;
25111da177e4SLinus Torvalds 
25121da177e4SLinus Torvalds 	for (;;) {
25131da177e4SLinus Torvalds 		struct page *page = NULL;
251441ffe5d5SHugh Dickins 		pgoff_t end_index;
251541ffe5d5SHugh Dickins 		unsigned long nr, ret;
25161da177e4SLinus Torvalds 		loff_t i_size = i_size_read(inode);
25171da177e4SLinus Torvalds 
251809cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
25191da177e4SLinus Torvalds 		if (index > end_index)
25201da177e4SLinus Torvalds 			break;
25211da177e4SLinus Torvalds 		if (index == end_index) {
252209cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
25231da177e4SLinus Torvalds 			if (nr <= offset)
25241da177e4SLinus Torvalds 				break;
25251da177e4SLinus Torvalds 		}
25261da177e4SLinus Torvalds 
252756a8c8ebSHugh Dickins 		error = shmem_getpage(inode, index, &page, SGP_READ);
25286e58e79dSAl Viro 		if (error) {
25296e58e79dSAl Viro 			if (error == -EINVAL)
25306e58e79dSAl Viro 				error = 0;
25311da177e4SLinus Torvalds 			break;
25321da177e4SLinus Torvalds 		}
253375edd345SHugh Dickins 		if (page) {
2534d3602444SHugh Dickins 			unlock_page(page);
2535a7605426SYang Shi 
2536a7605426SYang Shi 			if (PageHWPoison(page)) {
2537a7605426SYang Shi 				put_page(page);
2538a7605426SYang Shi 				error = -EIO;
2539a7605426SYang Shi 				break;
2540a7605426SYang Shi 			}
254175edd345SHugh Dickins 		}
25421da177e4SLinus Torvalds 
25431da177e4SLinus Torvalds 		/*
25441da177e4SLinus Torvalds 		 * We must evaluate after, since reads (unlike writes)
25459608703eSJan Kara 		 * are called without i_rwsem protection against truncate
25461da177e4SLinus Torvalds 		 */
254709cbfeafSKirill A. Shutemov 		nr = PAGE_SIZE;
25481da177e4SLinus Torvalds 		i_size = i_size_read(inode);
254909cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
25501da177e4SLinus Torvalds 		if (index == end_index) {
255109cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
25521da177e4SLinus Torvalds 			if (nr <= offset) {
25531da177e4SLinus Torvalds 				if (page)
255409cbfeafSKirill A. Shutemov 					put_page(page);
25551da177e4SLinus Torvalds 				break;
25561da177e4SLinus Torvalds 			}
25571da177e4SLinus Torvalds 		}
25581da177e4SLinus Torvalds 		nr -= offset;
25591da177e4SLinus Torvalds 
25601da177e4SLinus Torvalds 		if (page) {
25611da177e4SLinus Torvalds 			/*
25621da177e4SLinus Torvalds 			 * If users can be writing to this page using arbitrary
25631da177e4SLinus Torvalds 			 * virtual addresses, take care about potential aliasing
25641da177e4SLinus Torvalds 			 * before reading the page on the kernel side.
25651da177e4SLinus Torvalds 			 */
25661da177e4SLinus Torvalds 			if (mapping_writably_mapped(mapping))
25671da177e4SLinus Torvalds 				flush_dcache_page(page);
25681da177e4SLinus Torvalds 			/*
25691da177e4SLinus Torvalds 			 * Mark the page accessed if we read the beginning.
25701da177e4SLinus Torvalds 			 */
25711da177e4SLinus Torvalds 			if (!offset)
25721da177e4SLinus Torvalds 				mark_page_accessed(page);
25731da177e4SLinus Torvalds 			/*
25741da177e4SLinus Torvalds 			 * Ok, we have the page, and it's up-to-date, so
25751da177e4SLinus Torvalds 			 * now we can copy it to user space...
25761da177e4SLinus Torvalds 			 */
25772ba5bbedSAl Viro 			ret = copy_page_to_iter(page, offset, nr, to);
25781bdec44bSHugh Dickins 			put_page(page);
25791bdec44bSHugh Dickins 
25801bdec44bSHugh Dickins 		} else if (iter_is_iovec(to)) {
25811bdec44bSHugh Dickins 			/*
25821bdec44bSHugh Dickins 			 * Copy to user tends to be so well optimized, but
25831bdec44bSHugh Dickins 			 * clear_user() not so much, that it is noticeably
25841bdec44bSHugh Dickins 			 * faster to copy the zero page instead of clearing.
25851bdec44bSHugh Dickins 			 */
25861bdec44bSHugh Dickins 			ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to);
25871bdec44bSHugh Dickins 		} else {
25881bdec44bSHugh Dickins 			/*
25891bdec44bSHugh Dickins 			 * But submitting the same page twice in a row to
25901bdec44bSHugh Dickins 			 * splice() - or others? - can result in confusion:
25911bdec44bSHugh Dickins 			 * so don't attempt that optimization on pipes etc.
25921bdec44bSHugh Dickins 			 */
25931bdec44bSHugh Dickins 			ret = iov_iter_zero(nr, to);
25941bdec44bSHugh Dickins 		}
25951bdec44bSHugh Dickins 
25966e58e79dSAl Viro 		retval += ret;
25971da177e4SLinus Torvalds 		offset += ret;
259809cbfeafSKirill A. Shutemov 		index += offset >> PAGE_SHIFT;
259909cbfeafSKirill A. Shutemov 		offset &= ~PAGE_MASK;
26001da177e4SLinus Torvalds 
26012ba5bbedSAl Viro 		if (!iov_iter_count(to))
26021da177e4SLinus Torvalds 			break;
26036e58e79dSAl Viro 		if (ret < nr) {
26046e58e79dSAl Viro 			error = -EFAULT;
26056e58e79dSAl Viro 			break;
26066e58e79dSAl Viro 		}
26071da177e4SLinus Torvalds 		cond_resched();
26081da177e4SLinus Torvalds 	}
26091da177e4SLinus Torvalds 
261009cbfeafSKirill A. Shutemov 	*ppos = ((loff_t) index << PAGE_SHIFT) + offset;
26116e58e79dSAl Viro 	file_accessed(file);
26126e58e79dSAl Viro 	return retval ? retval : error;
26131da177e4SLinus Torvalds }
26141da177e4SLinus Torvalds 
2615965c8e59SAndrew Morton static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2616220f2ac9SHugh Dickins {
2617220f2ac9SHugh Dickins 	struct address_space *mapping = file->f_mapping;
2618220f2ac9SHugh Dickins 	struct inode *inode = mapping->host;
2619220f2ac9SHugh Dickins 
2620965c8e59SAndrew Morton 	if (whence != SEEK_DATA && whence != SEEK_HOLE)
2621965c8e59SAndrew Morton 		return generic_file_llseek_size(file, offset, whence,
2622220f2ac9SHugh Dickins 					MAX_LFS_FILESIZE, i_size_read(inode));
262341139aa4SMatthew Wilcox (Oracle) 	if (offset < 0)
262441139aa4SMatthew Wilcox (Oracle) 		return -ENXIO;
262541139aa4SMatthew Wilcox (Oracle) 
26265955102cSAl Viro 	inode_lock(inode);
26279608703eSJan Kara 	/* We're holding i_rwsem so we can access i_size directly */
262841139aa4SMatthew Wilcox (Oracle) 	offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
2629387aae6fSHugh Dickins 	if (offset >= 0)
263046a1c2c7SJie Liu 		offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
26315955102cSAl Viro 	inode_unlock(inode);
2632220f2ac9SHugh Dickins 	return offset;
2633220f2ac9SHugh Dickins }
2634220f2ac9SHugh Dickins 
263583e4fa9cSHugh Dickins static long shmem_fallocate(struct file *file, int mode, loff_t offset,
263683e4fa9cSHugh Dickins 							 loff_t len)
263783e4fa9cSHugh Dickins {
2638496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2639e2d12e22SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
264040e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
26411aac1400SHugh Dickins 	struct shmem_falloc shmem_falloc;
2642d144bf62SHugh Dickins 	pgoff_t start, index, end, undo_fallocend;
2643e2d12e22SHugh Dickins 	int error;
264483e4fa9cSHugh Dickins 
264513ace4d0SHugh Dickins 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
264613ace4d0SHugh Dickins 		return -EOPNOTSUPP;
264713ace4d0SHugh Dickins 
26485955102cSAl Viro 	inode_lock(inode);
264983e4fa9cSHugh Dickins 
265083e4fa9cSHugh Dickins 	if (mode & FALLOC_FL_PUNCH_HOLE) {
265183e4fa9cSHugh Dickins 		struct address_space *mapping = file->f_mapping;
265283e4fa9cSHugh Dickins 		loff_t unmap_start = round_up(offset, PAGE_SIZE);
265383e4fa9cSHugh Dickins 		loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
26548e205f77SHugh Dickins 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
265583e4fa9cSHugh Dickins 
26569608703eSJan Kara 		/* protected by i_rwsem */
2657ab3948f5SJoel Fernandes (Google) 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
265840e041a2SDavid Herrmann 			error = -EPERM;
265940e041a2SDavid Herrmann 			goto out;
266040e041a2SDavid Herrmann 		}
266140e041a2SDavid Herrmann 
26628e205f77SHugh Dickins 		shmem_falloc.waitq = &shmem_falloc_waitq;
2663aa71ecd8SChen Jun 		shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
2664f00cdc6dSHugh Dickins 		shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2665f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
2666f00cdc6dSHugh Dickins 		inode->i_private = &shmem_falloc;
2667f00cdc6dSHugh Dickins 		spin_unlock(&inode->i_lock);
2668f00cdc6dSHugh Dickins 
266983e4fa9cSHugh Dickins 		if ((u64)unmap_end > (u64)unmap_start)
267083e4fa9cSHugh Dickins 			unmap_mapping_range(mapping, unmap_start,
267183e4fa9cSHugh Dickins 					    1 + unmap_end - unmap_start, 0);
267283e4fa9cSHugh Dickins 		shmem_truncate_range(inode, offset, offset + len - 1);
267383e4fa9cSHugh Dickins 		/* No need to unmap again: hole-punching leaves COWed pages */
26748e205f77SHugh Dickins 
26758e205f77SHugh Dickins 		spin_lock(&inode->i_lock);
26768e205f77SHugh Dickins 		inode->i_private = NULL;
26778e205f77SHugh Dickins 		wake_up_all(&shmem_falloc_waitq);
26782055da97SIngo Molnar 		WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
26798e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
268083e4fa9cSHugh Dickins 		error = 0;
26818e205f77SHugh Dickins 		goto out;
268283e4fa9cSHugh Dickins 	}
268383e4fa9cSHugh Dickins 
2684e2d12e22SHugh Dickins 	/* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2685e2d12e22SHugh Dickins 	error = inode_newsize_ok(inode, offset + len);
2686e2d12e22SHugh Dickins 	if (error)
2687e2d12e22SHugh Dickins 		goto out;
2688e2d12e22SHugh Dickins 
268940e041a2SDavid Herrmann 	if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
269040e041a2SDavid Herrmann 		error = -EPERM;
269140e041a2SDavid Herrmann 		goto out;
269240e041a2SDavid Herrmann 	}
269340e041a2SDavid Herrmann 
269409cbfeafSKirill A. Shutemov 	start = offset >> PAGE_SHIFT;
269509cbfeafSKirill A. Shutemov 	end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2696e2d12e22SHugh Dickins 	/* Try to avoid a swapstorm if len is impossible to satisfy */
2697e2d12e22SHugh Dickins 	if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2698e2d12e22SHugh Dickins 		error = -ENOSPC;
2699e2d12e22SHugh Dickins 		goto out;
2700e2d12e22SHugh Dickins 	}
2701e2d12e22SHugh Dickins 
27028e205f77SHugh Dickins 	shmem_falloc.waitq = NULL;
27031aac1400SHugh Dickins 	shmem_falloc.start = start;
27041aac1400SHugh Dickins 	shmem_falloc.next  = start;
27051aac1400SHugh Dickins 	shmem_falloc.nr_falloced = 0;
27061aac1400SHugh Dickins 	shmem_falloc.nr_unswapped = 0;
27071aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
27081aac1400SHugh Dickins 	inode->i_private = &shmem_falloc;
27091aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
27101aac1400SHugh Dickins 
2711d144bf62SHugh Dickins 	/*
2712d144bf62SHugh Dickins 	 * info->fallocend is only relevant when huge pages might be
2713d144bf62SHugh Dickins 	 * involved: to prevent split_huge_page() freeing fallocated
2714d144bf62SHugh Dickins 	 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
2715d144bf62SHugh Dickins 	 */
2716d144bf62SHugh Dickins 	undo_fallocend = info->fallocend;
2717d144bf62SHugh Dickins 	if (info->fallocend < end)
2718d144bf62SHugh Dickins 		info->fallocend = end;
2719d144bf62SHugh Dickins 
2720050dcb5cSHugh Dickins 	for (index = start; index < end; ) {
2721e2d12e22SHugh Dickins 		struct page *page;
2722e2d12e22SHugh Dickins 
2723e2d12e22SHugh Dickins 		/*
2724e2d12e22SHugh Dickins 		 * Good, the fallocate(2) manpage permits EINTR: we may have
2725e2d12e22SHugh Dickins 		 * been interrupted because we are using up too much memory.
2726e2d12e22SHugh Dickins 		 */
2727e2d12e22SHugh Dickins 		if (signal_pending(current))
2728e2d12e22SHugh Dickins 			error = -EINTR;
27291aac1400SHugh Dickins 		else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
27301aac1400SHugh Dickins 			error = -ENOMEM;
2731e2d12e22SHugh Dickins 		else
27329e18eb29SAndres Lagar-Cavilla 			error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2733e2d12e22SHugh Dickins 		if (error) {
2734d144bf62SHugh Dickins 			info->fallocend = undo_fallocend;
27351635f6a7SHugh Dickins 			/* Remove the !PageUptodate pages we added */
27367f556567SHugh Dickins 			if (index > start) {
27371635f6a7SHugh Dickins 				shmem_undo_range(inode,
273809cbfeafSKirill A. Shutemov 				    (loff_t)start << PAGE_SHIFT,
2739b9b4bb26SAnthony Romano 				    ((loff_t)index << PAGE_SHIFT) - 1, true);
27407f556567SHugh Dickins 			}
27411aac1400SHugh Dickins 			goto undone;
2742e2d12e22SHugh Dickins 		}
2743e2d12e22SHugh Dickins 
2744050dcb5cSHugh Dickins 		index++;
2745050dcb5cSHugh Dickins 		/*
2746050dcb5cSHugh Dickins 		 * Here is a more important optimization than it appears:
2747050dcb5cSHugh Dickins 		 * a second SGP_FALLOC on the same huge page will clear it,
2748050dcb5cSHugh Dickins 		 * making it PageUptodate and un-undoable if we fail later.
2749050dcb5cSHugh Dickins 		 */
2750050dcb5cSHugh Dickins 		if (PageTransCompound(page)) {
2751050dcb5cSHugh Dickins 			index = round_up(index, HPAGE_PMD_NR);
2752050dcb5cSHugh Dickins 			/* Beware 32-bit wraparound */
2753050dcb5cSHugh Dickins 			if (!index)
2754050dcb5cSHugh Dickins 				index--;
2755050dcb5cSHugh Dickins 		}
2756050dcb5cSHugh Dickins 
2757e2d12e22SHugh Dickins 		/*
27581aac1400SHugh Dickins 		 * Inform shmem_writepage() how far we have reached.
27591aac1400SHugh Dickins 		 * No need for lock or barrier: we have the page lock.
27601aac1400SHugh Dickins 		 */
27611aac1400SHugh Dickins 		if (!PageUptodate(page))
2762050dcb5cSHugh Dickins 			shmem_falloc.nr_falloced += index - shmem_falloc.next;
2763050dcb5cSHugh Dickins 		shmem_falloc.next = index;
27641aac1400SHugh Dickins 
27651aac1400SHugh Dickins 		/*
27661635f6a7SHugh Dickins 		 * If !PageUptodate, leave it that way so that freeable pages
27671635f6a7SHugh Dickins 		 * can be recognized if we need to rollback on error later.
27681635f6a7SHugh Dickins 		 * But set_page_dirty so that memory pressure will swap rather
2769e2d12e22SHugh Dickins 		 * than free the pages we are allocating (and SGP_CACHE pages
2770e2d12e22SHugh Dickins 		 * might still be clean: we now need to mark those dirty too).
2771e2d12e22SHugh Dickins 		 */
2772e2d12e22SHugh Dickins 		set_page_dirty(page);
2773e2d12e22SHugh Dickins 		unlock_page(page);
277409cbfeafSKirill A. Shutemov 		put_page(page);
2775e2d12e22SHugh Dickins 		cond_resched();
2776e2d12e22SHugh Dickins 	}
2777e2d12e22SHugh Dickins 
2778e2d12e22SHugh Dickins 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2779e2d12e22SHugh Dickins 		i_size_write(inode, offset + len);
2780078cd827SDeepa Dinamani 	inode->i_ctime = current_time(inode);
27811aac1400SHugh Dickins undone:
27821aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
27831aac1400SHugh Dickins 	inode->i_private = NULL;
27841aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
2785e2d12e22SHugh Dickins out:
27865955102cSAl Viro 	inode_unlock(inode);
278783e4fa9cSHugh Dickins 	return error;
278883e4fa9cSHugh Dickins }
278983e4fa9cSHugh Dickins 
2790726c3342SDavid Howells static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
27911da177e4SLinus Torvalds {
2792726c3342SDavid Howells 	struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
27931da177e4SLinus Torvalds 
27941da177e4SLinus Torvalds 	buf->f_type = TMPFS_MAGIC;
279509cbfeafSKirill A. Shutemov 	buf->f_bsize = PAGE_SIZE;
27961da177e4SLinus Torvalds 	buf->f_namelen = NAME_MAX;
27970edd73b3SHugh Dickins 	if (sbinfo->max_blocks) {
27981da177e4SLinus Torvalds 		buf->f_blocks = sbinfo->max_blocks;
279941ffe5d5SHugh Dickins 		buf->f_bavail =
280041ffe5d5SHugh Dickins 		buf->f_bfree  = sbinfo->max_blocks -
280141ffe5d5SHugh Dickins 				percpu_counter_sum(&sbinfo->used_blocks);
28020edd73b3SHugh Dickins 	}
28030edd73b3SHugh Dickins 	if (sbinfo->max_inodes) {
28041da177e4SLinus Torvalds 		buf->f_files = sbinfo->max_inodes;
28051da177e4SLinus Torvalds 		buf->f_ffree = sbinfo->free_inodes;
28061da177e4SLinus Torvalds 	}
28071da177e4SLinus Torvalds 	/* else leave those fields 0 like simple_statfs */
280859cda49eSAmir Goldstein 
280959cda49eSAmir Goldstein 	buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
281059cda49eSAmir Goldstein 
28111da177e4SLinus Torvalds 	return 0;
28121da177e4SLinus Torvalds }
28131da177e4SLinus Torvalds 
28141da177e4SLinus Torvalds /*
28151da177e4SLinus Torvalds  * File creation. Allocate an inode, and we're done..
28161da177e4SLinus Torvalds  */
28171da177e4SLinus Torvalds static int
2818549c7297SChristian Brauner shmem_mknod(struct user_namespace *mnt_userns, struct inode *dir,
2819549c7297SChristian Brauner 	    struct dentry *dentry, umode_t mode, dev_t dev)
28201da177e4SLinus Torvalds {
28210b0a0806SHugh Dickins 	struct inode *inode;
28221da177e4SLinus Torvalds 	int error = -ENOSPC;
28231da177e4SLinus Torvalds 
2824454abafeSDmitry Monakhov 	inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
28251da177e4SLinus Torvalds 	if (inode) {
2826feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2827feda821eSChristoph Hellwig 		if (error)
2828feda821eSChristoph Hellwig 			goto out_iput;
28292a7dba39SEric Paris 		error = security_inode_init_security(inode, dir,
28309d8f13baSMimi Zohar 						     &dentry->d_name,
28316d9d88d0SJarkko Sakkinen 						     shmem_initxattrs, NULL);
2832feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2833feda821eSChristoph Hellwig 			goto out_iput;
283437ec43cdSMimi Zohar 
2835718deb6bSAl Viro 		error = 0;
28361da177e4SLinus Torvalds 		dir->i_size += BOGO_DIRENT_SIZE;
2837078cd827SDeepa Dinamani 		dir->i_ctime = dir->i_mtime = current_time(dir);
28381da177e4SLinus Torvalds 		d_instantiate(dentry, inode);
28391da177e4SLinus Torvalds 		dget(dentry); /* Extra count - pin the dentry in core */
28401da177e4SLinus Torvalds 	}
28411da177e4SLinus Torvalds 	return error;
2842feda821eSChristoph Hellwig out_iput:
2843feda821eSChristoph Hellwig 	iput(inode);
2844feda821eSChristoph Hellwig 	return error;
28451da177e4SLinus Torvalds }
28461da177e4SLinus Torvalds 
284760545d0dSAl Viro static int
2848549c7297SChristian Brauner shmem_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
2849549c7297SChristian Brauner 	      struct dentry *dentry, umode_t mode)
285060545d0dSAl Viro {
285160545d0dSAl Viro 	struct inode *inode;
285260545d0dSAl Viro 	int error = -ENOSPC;
285360545d0dSAl Viro 
285460545d0dSAl Viro 	inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
285560545d0dSAl Viro 	if (inode) {
285660545d0dSAl Viro 		error = security_inode_init_security(inode, dir,
285760545d0dSAl Viro 						     NULL,
285860545d0dSAl Viro 						     shmem_initxattrs, NULL);
2859feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2860feda821eSChristoph Hellwig 			goto out_iput;
2861feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2862feda821eSChristoph Hellwig 		if (error)
2863feda821eSChristoph Hellwig 			goto out_iput;
286460545d0dSAl Viro 		d_tmpfile(dentry, inode);
286560545d0dSAl Viro 	}
286660545d0dSAl Viro 	return error;
2867feda821eSChristoph Hellwig out_iput:
2868feda821eSChristoph Hellwig 	iput(inode);
2869feda821eSChristoph Hellwig 	return error;
287060545d0dSAl Viro }
287160545d0dSAl Viro 
2872549c7297SChristian Brauner static int shmem_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
2873549c7297SChristian Brauner 		       struct dentry *dentry, umode_t mode)
28741da177e4SLinus Torvalds {
28751da177e4SLinus Torvalds 	int error;
28761da177e4SLinus Torvalds 
2877549c7297SChristian Brauner 	if ((error = shmem_mknod(&init_user_ns, dir, dentry,
2878549c7297SChristian Brauner 				 mode | S_IFDIR, 0)))
28791da177e4SLinus Torvalds 		return error;
2880d8c76e6fSDave Hansen 	inc_nlink(dir);
28811da177e4SLinus Torvalds 	return 0;
28821da177e4SLinus Torvalds }
28831da177e4SLinus Torvalds 
2884549c7297SChristian Brauner static int shmem_create(struct user_namespace *mnt_userns, struct inode *dir,
2885549c7297SChristian Brauner 			struct dentry *dentry, umode_t mode, bool excl)
28861da177e4SLinus Torvalds {
2887549c7297SChristian Brauner 	return shmem_mknod(&init_user_ns, dir, dentry, mode | S_IFREG, 0);
28881da177e4SLinus Torvalds }
28891da177e4SLinus Torvalds 
28901da177e4SLinus Torvalds /*
28911da177e4SLinus Torvalds  * Link a file..
28921da177e4SLinus Torvalds  */
28931da177e4SLinus Torvalds static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
28941da177e4SLinus Torvalds {
289575c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
289629b00e60SDarrick J. Wong 	int ret = 0;
28971da177e4SLinus Torvalds 
28981da177e4SLinus Torvalds 	/*
28991da177e4SLinus Torvalds 	 * No ordinary (disk based) filesystem counts links as inodes;
29001da177e4SLinus Torvalds 	 * but each new link needs a new dentry, pinning lowmem, and
29011da177e4SLinus Torvalds 	 * tmpfs dentries cannot be pruned until they are unlinked.
29021062af92SDarrick J. Wong 	 * But if an O_TMPFILE file is linked into the tmpfs, the
29031062af92SDarrick J. Wong 	 * first link must skip that, to get the accounting right.
29041da177e4SLinus Torvalds 	 */
29051062af92SDarrick J. Wong 	if (inode->i_nlink) {
2906e809d5f0SChris Down 		ret = shmem_reserve_inode(inode->i_sb, NULL);
29075b04c689SPavel Emelyanov 		if (ret)
29085b04c689SPavel Emelyanov 			goto out;
29091062af92SDarrick J. Wong 	}
29101da177e4SLinus Torvalds 
29111da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
2912078cd827SDeepa Dinamani 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2913d8c76e6fSDave Hansen 	inc_nlink(inode);
29147de9c6eeSAl Viro 	ihold(inode);	/* New dentry reference */
29151da177e4SLinus Torvalds 	dget(dentry);		/* Extra pinning count for the created dentry */
29161da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
29175b04c689SPavel Emelyanov out:
29185b04c689SPavel Emelyanov 	return ret;
29191da177e4SLinus Torvalds }
29201da177e4SLinus Torvalds 
29211da177e4SLinus Torvalds static int shmem_unlink(struct inode *dir, struct dentry *dentry)
29221da177e4SLinus Torvalds {
292375c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
29241da177e4SLinus Torvalds 
29255b04c689SPavel Emelyanov 	if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
29265b04c689SPavel Emelyanov 		shmem_free_inode(inode->i_sb);
29271da177e4SLinus Torvalds 
29281da177e4SLinus Torvalds 	dir->i_size -= BOGO_DIRENT_SIZE;
2929078cd827SDeepa Dinamani 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
29309a53c3a7SDave Hansen 	drop_nlink(inode);
29311da177e4SLinus Torvalds 	dput(dentry);	/* Undo the count from "create" - this does all the work */
29321da177e4SLinus Torvalds 	return 0;
29331da177e4SLinus Torvalds }
29341da177e4SLinus Torvalds 
29351da177e4SLinus Torvalds static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
29361da177e4SLinus Torvalds {
29371da177e4SLinus Torvalds 	if (!simple_empty(dentry))
29381da177e4SLinus Torvalds 		return -ENOTEMPTY;
29391da177e4SLinus Torvalds 
294075c3cfa8SDavid Howells 	drop_nlink(d_inode(dentry));
29419a53c3a7SDave Hansen 	drop_nlink(dir);
29421da177e4SLinus Torvalds 	return shmem_unlink(dir, dentry);
29431da177e4SLinus Torvalds }
29441da177e4SLinus Torvalds 
2945549c7297SChristian Brauner static int shmem_whiteout(struct user_namespace *mnt_userns,
2946549c7297SChristian Brauner 			  struct inode *old_dir, struct dentry *old_dentry)
294746fdb794SMiklos Szeredi {
294846fdb794SMiklos Szeredi 	struct dentry *whiteout;
294946fdb794SMiklos Szeredi 	int error;
295046fdb794SMiklos Szeredi 
295146fdb794SMiklos Szeredi 	whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
295246fdb794SMiklos Szeredi 	if (!whiteout)
295346fdb794SMiklos Szeredi 		return -ENOMEM;
295446fdb794SMiklos Szeredi 
2955549c7297SChristian Brauner 	error = shmem_mknod(&init_user_ns, old_dir, whiteout,
295646fdb794SMiklos Szeredi 			    S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
295746fdb794SMiklos Szeredi 	dput(whiteout);
295846fdb794SMiklos Szeredi 	if (error)
295946fdb794SMiklos Szeredi 		return error;
296046fdb794SMiklos Szeredi 
296146fdb794SMiklos Szeredi 	/*
296246fdb794SMiklos Szeredi 	 * Cheat and hash the whiteout while the old dentry is still in
296346fdb794SMiklos Szeredi 	 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
296446fdb794SMiklos Szeredi 	 *
296546fdb794SMiklos Szeredi 	 * d_lookup() will consistently find one of them at this point,
296646fdb794SMiklos Szeredi 	 * not sure which one, but that isn't even important.
296746fdb794SMiklos Szeredi 	 */
296846fdb794SMiklos Szeredi 	d_rehash(whiteout);
296946fdb794SMiklos Szeredi 	return 0;
297046fdb794SMiklos Szeredi }
297146fdb794SMiklos Szeredi 
29721da177e4SLinus Torvalds /*
29731da177e4SLinus Torvalds  * The VFS layer already does all the dentry stuff for rename,
29741da177e4SLinus Torvalds  * we just have to decrement the usage count for the target if
29751da177e4SLinus Torvalds  * it exists so that the VFS layer correctly free's it when it
29761da177e4SLinus Torvalds  * gets overwritten.
29771da177e4SLinus Torvalds  */
2978549c7297SChristian Brauner static int shmem_rename2(struct user_namespace *mnt_userns,
2979549c7297SChristian Brauner 			 struct inode *old_dir, struct dentry *old_dentry,
2980549c7297SChristian Brauner 			 struct inode *new_dir, struct dentry *new_dentry,
2981549c7297SChristian Brauner 			 unsigned int flags)
29821da177e4SLinus Torvalds {
298375c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
29841da177e4SLinus Torvalds 	int they_are_dirs = S_ISDIR(inode->i_mode);
29851da177e4SLinus Torvalds 
298646fdb794SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
29873b69ff51SMiklos Szeredi 		return -EINVAL;
29883b69ff51SMiklos Szeredi 
298937456771SMiklos Szeredi 	if (flags & RENAME_EXCHANGE)
29906429e463SLorenz Bauer 		return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
299137456771SMiklos Szeredi 
29921da177e4SLinus Torvalds 	if (!simple_empty(new_dentry))
29931da177e4SLinus Torvalds 		return -ENOTEMPTY;
29941da177e4SLinus Torvalds 
299546fdb794SMiklos Szeredi 	if (flags & RENAME_WHITEOUT) {
299646fdb794SMiklos Szeredi 		int error;
299746fdb794SMiklos Szeredi 
2998549c7297SChristian Brauner 		error = shmem_whiteout(&init_user_ns, old_dir, old_dentry);
299946fdb794SMiklos Szeredi 		if (error)
300046fdb794SMiklos Szeredi 			return error;
300146fdb794SMiklos Szeredi 	}
300246fdb794SMiklos Szeredi 
300375c3cfa8SDavid Howells 	if (d_really_is_positive(new_dentry)) {
30041da177e4SLinus Torvalds 		(void) shmem_unlink(new_dir, new_dentry);
3005b928095bSMiklos Szeredi 		if (they_are_dirs) {
300675c3cfa8SDavid Howells 			drop_nlink(d_inode(new_dentry));
30079a53c3a7SDave Hansen 			drop_nlink(old_dir);
3008b928095bSMiklos Szeredi 		}
30091da177e4SLinus Torvalds 	} else if (they_are_dirs) {
30109a53c3a7SDave Hansen 		drop_nlink(old_dir);
3011d8c76e6fSDave Hansen 		inc_nlink(new_dir);
30121da177e4SLinus Torvalds 	}
30131da177e4SLinus Torvalds 
30141da177e4SLinus Torvalds 	old_dir->i_size -= BOGO_DIRENT_SIZE;
30151da177e4SLinus Torvalds 	new_dir->i_size += BOGO_DIRENT_SIZE;
30161da177e4SLinus Torvalds 	old_dir->i_ctime = old_dir->i_mtime =
30171da177e4SLinus Torvalds 	new_dir->i_ctime = new_dir->i_mtime =
3018078cd827SDeepa Dinamani 	inode->i_ctime = current_time(old_dir);
30191da177e4SLinus Torvalds 	return 0;
30201da177e4SLinus Torvalds }
30211da177e4SLinus Torvalds 
3022549c7297SChristian Brauner static int shmem_symlink(struct user_namespace *mnt_userns, struct inode *dir,
3023549c7297SChristian Brauner 			 struct dentry *dentry, const char *symname)
30241da177e4SLinus Torvalds {
30251da177e4SLinus Torvalds 	int error;
30261da177e4SLinus Torvalds 	int len;
30271da177e4SLinus Torvalds 	struct inode *inode;
30289276aad6SHugh Dickins 	struct page *page;
30291da177e4SLinus Torvalds 
30301da177e4SLinus Torvalds 	len = strlen(symname) + 1;
303109cbfeafSKirill A. Shutemov 	if (len > PAGE_SIZE)
30321da177e4SLinus Torvalds 		return -ENAMETOOLONG;
30331da177e4SLinus Torvalds 
30340825a6f9SJoe Perches 	inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
30350825a6f9SJoe Perches 				VM_NORESERVE);
30361da177e4SLinus Torvalds 	if (!inode)
30371da177e4SLinus Torvalds 		return -ENOSPC;
30381da177e4SLinus Torvalds 
30399d8f13baSMimi Zohar 	error = security_inode_init_security(inode, dir, &dentry->d_name,
30406d9d88d0SJarkko Sakkinen 					     shmem_initxattrs, NULL);
3041343c3d7fSMateusz Nosek 	if (error && error != -EOPNOTSUPP) {
3042570bc1c2SStephen Smalley 		iput(inode);
3043570bc1c2SStephen Smalley 		return error;
3044570bc1c2SStephen Smalley 	}
3045570bc1c2SStephen Smalley 
30461da177e4SLinus Torvalds 	inode->i_size = len-1;
304769f07ec9SHugh Dickins 	if (len <= SHORT_SYMLINK_LEN) {
30483ed47db3SAl Viro 		inode->i_link = kmemdup(symname, len, GFP_KERNEL);
30493ed47db3SAl Viro 		if (!inode->i_link) {
305069f07ec9SHugh Dickins 			iput(inode);
305169f07ec9SHugh Dickins 			return -ENOMEM;
305269f07ec9SHugh Dickins 		}
305369f07ec9SHugh Dickins 		inode->i_op = &shmem_short_symlink_operations;
30541da177e4SLinus Torvalds 	} else {
3055e8ecde25SAl Viro 		inode_nohighmem(inode);
30569e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_WRITE);
30571da177e4SLinus Torvalds 		if (error) {
30581da177e4SLinus Torvalds 			iput(inode);
30591da177e4SLinus Torvalds 			return error;
30601da177e4SLinus Torvalds 		}
306114fcc23fSHugh Dickins 		inode->i_mapping->a_ops = &shmem_aops;
30621da177e4SLinus Torvalds 		inode->i_op = &shmem_symlink_inode_operations;
306321fc61c7SAl Viro 		memcpy(page_address(page), symname, len);
3064ec9516fbSHugh Dickins 		SetPageUptodate(page);
30651da177e4SLinus Torvalds 		set_page_dirty(page);
30666746aff7SWu Fengguang 		unlock_page(page);
306709cbfeafSKirill A. Shutemov 		put_page(page);
30681da177e4SLinus Torvalds 	}
30691da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
3070078cd827SDeepa Dinamani 	dir->i_ctime = dir->i_mtime = current_time(dir);
30711da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
30721da177e4SLinus Torvalds 	dget(dentry);
30731da177e4SLinus Torvalds 	return 0;
30741da177e4SLinus Torvalds }
30751da177e4SLinus Torvalds 
3076fceef393SAl Viro static void shmem_put_link(void *arg)
3077fceef393SAl Viro {
3078fceef393SAl Viro 	mark_page_accessed(arg);
3079fceef393SAl Viro 	put_page(arg);
3080fceef393SAl Viro }
3081fceef393SAl Viro 
30826b255391SAl Viro static const char *shmem_get_link(struct dentry *dentry,
3083fceef393SAl Viro 				  struct inode *inode,
3084fceef393SAl Viro 				  struct delayed_call *done)
30851da177e4SLinus Torvalds {
30861da177e4SLinus Torvalds 	struct page *page = NULL;
30876b255391SAl Viro 	int error;
30886a6c9904SAl Viro 	if (!dentry) {
30896a6c9904SAl Viro 		page = find_get_page(inode->i_mapping, 0);
30906a6c9904SAl Viro 		if (!page)
30916b255391SAl Viro 			return ERR_PTR(-ECHILD);
3092a7605426SYang Shi 		if (PageHWPoison(page) ||
3093a7605426SYang Shi 		    !PageUptodate(page)) {
30946a6c9904SAl Viro 			put_page(page);
30956a6c9904SAl Viro 			return ERR_PTR(-ECHILD);
30966a6c9904SAl Viro 		}
30976a6c9904SAl Viro 	} else {
30989e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_READ);
3099680baacbSAl Viro 		if (error)
3100680baacbSAl Viro 			return ERR_PTR(error);
3101a7605426SYang Shi 		if (!page)
3102a7605426SYang Shi 			return ERR_PTR(-ECHILD);
3103a7605426SYang Shi 		if (PageHWPoison(page)) {
3104a7605426SYang Shi 			unlock_page(page);
3105a7605426SYang Shi 			put_page(page);
3106a7605426SYang Shi 			return ERR_PTR(-ECHILD);
3107a7605426SYang Shi 		}
3108d3602444SHugh Dickins 		unlock_page(page);
31091da177e4SLinus Torvalds 	}
3110fceef393SAl Viro 	set_delayed_call(done, shmem_put_link, page);
311121fc61c7SAl Viro 	return page_address(page);
31121da177e4SLinus Torvalds }
31131da177e4SLinus Torvalds 
3114b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3115b09e0fa4SEric Paris /*
3116b09e0fa4SEric Paris  * Superblocks without xattr inode operations may get some security.* xattr
3117b09e0fa4SEric Paris  * support from the LSM "for free". As soon as we have any other xattrs
3118b09e0fa4SEric Paris  * like ACLs, we also need to implement the security.* handlers at
3119b09e0fa4SEric Paris  * filesystem level, though.
3120b09e0fa4SEric Paris  */
3121b09e0fa4SEric Paris 
31226d9d88d0SJarkko Sakkinen /*
31236d9d88d0SJarkko Sakkinen  * Callback for security_inode_init_security() for acquiring xattrs.
31246d9d88d0SJarkko Sakkinen  */
31256d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *inode,
31266d9d88d0SJarkko Sakkinen 			    const struct xattr *xattr_array,
31276d9d88d0SJarkko Sakkinen 			    void *fs_info)
31286d9d88d0SJarkko Sakkinen {
31296d9d88d0SJarkko Sakkinen 	struct shmem_inode_info *info = SHMEM_I(inode);
31306d9d88d0SJarkko Sakkinen 	const struct xattr *xattr;
313138f38657SAristeu Rozanski 	struct simple_xattr *new_xattr;
31326d9d88d0SJarkko Sakkinen 	size_t len;
31336d9d88d0SJarkko Sakkinen 
31346d9d88d0SJarkko Sakkinen 	for (xattr = xattr_array; xattr->name != NULL; xattr++) {
313538f38657SAristeu Rozanski 		new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
31366d9d88d0SJarkko Sakkinen 		if (!new_xattr)
31376d9d88d0SJarkko Sakkinen 			return -ENOMEM;
31386d9d88d0SJarkko Sakkinen 
31396d9d88d0SJarkko Sakkinen 		len = strlen(xattr->name) + 1;
31406d9d88d0SJarkko Sakkinen 		new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
31416d9d88d0SJarkko Sakkinen 					  GFP_KERNEL);
31426d9d88d0SJarkko Sakkinen 		if (!new_xattr->name) {
31433bef735aSChengguang Xu 			kvfree(new_xattr);
31446d9d88d0SJarkko Sakkinen 			return -ENOMEM;
31456d9d88d0SJarkko Sakkinen 		}
31466d9d88d0SJarkko Sakkinen 
31476d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
31486d9d88d0SJarkko Sakkinen 		       XATTR_SECURITY_PREFIX_LEN);
31496d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
31506d9d88d0SJarkko Sakkinen 		       xattr->name, len);
31516d9d88d0SJarkko Sakkinen 
315238f38657SAristeu Rozanski 		simple_xattr_list_add(&info->xattrs, new_xattr);
31536d9d88d0SJarkko Sakkinen 	}
31546d9d88d0SJarkko Sakkinen 
31556d9d88d0SJarkko Sakkinen 	return 0;
31566d9d88d0SJarkko Sakkinen }
31576d9d88d0SJarkko Sakkinen 
3158aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3159b296821aSAl Viro 				   struct dentry *unused, struct inode *inode,
3160b296821aSAl Viro 				   const char *name, void *buffer, size_t size)
3161aa7c5241SAndreas Gruenbacher {
3162b296821aSAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3163aa7c5241SAndreas Gruenbacher 
3164aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3165aa7c5241SAndreas Gruenbacher 	return simple_xattr_get(&info->xattrs, name, buffer, size);
3166aa7c5241SAndreas Gruenbacher }
3167aa7c5241SAndreas Gruenbacher 
3168aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3169e65ce2a5SChristian Brauner 				   struct user_namespace *mnt_userns,
317059301226SAl Viro 				   struct dentry *unused, struct inode *inode,
317159301226SAl Viro 				   const char *name, const void *value,
317259301226SAl Viro 				   size_t size, int flags)
3173aa7c5241SAndreas Gruenbacher {
317459301226SAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3175aa7c5241SAndreas Gruenbacher 
3176aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3177a46a2295SDaniel Xu 	return simple_xattr_set(&info->xattrs, name, value, size, flags, NULL);
3178aa7c5241SAndreas Gruenbacher }
3179aa7c5241SAndreas Gruenbacher 
3180aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_security_xattr_handler = {
3181aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_SECURITY_PREFIX,
3182aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3183aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3184aa7c5241SAndreas Gruenbacher };
3185aa7c5241SAndreas Gruenbacher 
3186aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_trusted_xattr_handler = {
3187aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_TRUSTED_PREFIX,
3188aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3189aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3190aa7c5241SAndreas Gruenbacher };
3191aa7c5241SAndreas Gruenbacher 
3192b09e0fa4SEric Paris static const struct xattr_handler *shmem_xattr_handlers[] = {
3193b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
3194feda821eSChristoph Hellwig 	&posix_acl_access_xattr_handler,
3195feda821eSChristoph Hellwig 	&posix_acl_default_xattr_handler,
3196b09e0fa4SEric Paris #endif
3197aa7c5241SAndreas Gruenbacher 	&shmem_security_xattr_handler,
3198aa7c5241SAndreas Gruenbacher 	&shmem_trusted_xattr_handler,
3199b09e0fa4SEric Paris 	NULL
3200b09e0fa4SEric Paris };
3201b09e0fa4SEric Paris 
3202b09e0fa4SEric Paris static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3203b09e0fa4SEric Paris {
320475c3cfa8SDavid Howells 	struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3205786534b9SAndreas Gruenbacher 	return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3206b09e0fa4SEric Paris }
3207b09e0fa4SEric Paris #endif /* CONFIG_TMPFS_XATTR */
3208b09e0fa4SEric Paris 
320969f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations = {
3210f7cd16a5SXavier Roche 	.getattr	= shmem_getattr,
32116b255391SAl Viro 	.get_link	= simple_get_link,
3212b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3213b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3214b09e0fa4SEric Paris #endif
32151da177e4SLinus Torvalds };
32161da177e4SLinus Torvalds 
321792e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations = {
3218f7cd16a5SXavier Roche 	.getattr	= shmem_getattr,
32196b255391SAl Viro 	.get_link	= shmem_get_link,
3220b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3221b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
322239f0247dSAndreas Gruenbacher #endif
3223b09e0fa4SEric Paris };
322439f0247dSAndreas Gruenbacher 
322591828a40SDavid M. Grimes static struct dentry *shmem_get_parent(struct dentry *child)
322691828a40SDavid M. Grimes {
322791828a40SDavid M. Grimes 	return ERR_PTR(-ESTALE);
322891828a40SDavid M. Grimes }
322991828a40SDavid M. Grimes 
323091828a40SDavid M. Grimes static int shmem_match(struct inode *ino, void *vfh)
323191828a40SDavid M. Grimes {
323291828a40SDavid M. Grimes 	__u32 *fh = vfh;
323391828a40SDavid M. Grimes 	__u64 inum = fh[2];
323491828a40SDavid M. Grimes 	inum = (inum << 32) | fh[1];
323591828a40SDavid M. Grimes 	return ino->i_ino == inum && fh[0] == ino->i_generation;
323691828a40SDavid M. Grimes }
323791828a40SDavid M. Grimes 
323812ba780dSAmir Goldstein /* Find any alias of inode, but prefer a hashed alias */
323912ba780dSAmir Goldstein static struct dentry *shmem_find_alias(struct inode *inode)
324012ba780dSAmir Goldstein {
324112ba780dSAmir Goldstein 	struct dentry *alias = d_find_alias(inode);
324212ba780dSAmir Goldstein 
324312ba780dSAmir Goldstein 	return alias ?: d_find_any_alias(inode);
324412ba780dSAmir Goldstein }
324512ba780dSAmir Goldstein 
324612ba780dSAmir Goldstein 
3247480b116cSChristoph Hellwig static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3248480b116cSChristoph Hellwig 		struct fid *fid, int fh_len, int fh_type)
324991828a40SDavid M. Grimes {
325091828a40SDavid M. Grimes 	struct inode *inode;
3251480b116cSChristoph Hellwig 	struct dentry *dentry = NULL;
325235c2a7f4SHugh Dickins 	u64 inum;
325391828a40SDavid M. Grimes 
3254480b116cSChristoph Hellwig 	if (fh_len < 3)
3255480b116cSChristoph Hellwig 		return NULL;
3256480b116cSChristoph Hellwig 
325735c2a7f4SHugh Dickins 	inum = fid->raw[2];
325835c2a7f4SHugh Dickins 	inum = (inum << 32) | fid->raw[1];
325935c2a7f4SHugh Dickins 
3260480b116cSChristoph Hellwig 	inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3261480b116cSChristoph Hellwig 			shmem_match, fid->raw);
326291828a40SDavid M. Grimes 	if (inode) {
326312ba780dSAmir Goldstein 		dentry = shmem_find_alias(inode);
326491828a40SDavid M. Grimes 		iput(inode);
326591828a40SDavid M. Grimes 	}
326691828a40SDavid M. Grimes 
3267480b116cSChristoph Hellwig 	return dentry;
326891828a40SDavid M. Grimes }
326991828a40SDavid M. Grimes 
3270b0b0382bSAl Viro static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3271b0b0382bSAl Viro 				struct inode *parent)
327291828a40SDavid M. Grimes {
32735fe0c237SAneesh Kumar K.V 	if (*len < 3) {
32745fe0c237SAneesh Kumar K.V 		*len = 3;
327594e07a75SNamjae Jeon 		return FILEID_INVALID;
32765fe0c237SAneesh Kumar K.V 	}
327791828a40SDavid M. Grimes 
32781d3382cbSAl Viro 	if (inode_unhashed(inode)) {
327991828a40SDavid M. Grimes 		/* Unfortunately insert_inode_hash is not idempotent,
328091828a40SDavid M. Grimes 		 * so as we hash inodes here rather than at creation
328191828a40SDavid M. Grimes 		 * time, we need a lock to ensure we only try
328291828a40SDavid M. Grimes 		 * to do it once
328391828a40SDavid M. Grimes 		 */
328491828a40SDavid M. Grimes 		static DEFINE_SPINLOCK(lock);
328591828a40SDavid M. Grimes 		spin_lock(&lock);
32861d3382cbSAl Viro 		if (inode_unhashed(inode))
328791828a40SDavid M. Grimes 			__insert_inode_hash(inode,
328891828a40SDavid M. Grimes 					    inode->i_ino + inode->i_generation);
328991828a40SDavid M. Grimes 		spin_unlock(&lock);
329091828a40SDavid M. Grimes 	}
329191828a40SDavid M. Grimes 
329291828a40SDavid M. Grimes 	fh[0] = inode->i_generation;
329391828a40SDavid M. Grimes 	fh[1] = inode->i_ino;
329491828a40SDavid M. Grimes 	fh[2] = ((__u64)inode->i_ino) >> 32;
329591828a40SDavid M. Grimes 
329691828a40SDavid M. Grimes 	*len = 3;
329791828a40SDavid M. Grimes 	return 1;
329891828a40SDavid M. Grimes }
329991828a40SDavid M. Grimes 
330039655164SChristoph Hellwig static const struct export_operations shmem_export_ops = {
330191828a40SDavid M. Grimes 	.get_parent     = shmem_get_parent,
330291828a40SDavid M. Grimes 	.encode_fh      = shmem_encode_fh,
3303480b116cSChristoph Hellwig 	.fh_to_dentry	= shmem_fh_to_dentry,
330491828a40SDavid M. Grimes };
330591828a40SDavid M. Grimes 
3306626c3920SAl Viro enum shmem_param {
3307626c3920SAl Viro 	Opt_gid,
3308626c3920SAl Viro 	Opt_huge,
3309626c3920SAl Viro 	Opt_mode,
3310626c3920SAl Viro 	Opt_mpol,
3311626c3920SAl Viro 	Opt_nr_blocks,
3312626c3920SAl Viro 	Opt_nr_inodes,
3313626c3920SAl Viro 	Opt_size,
3314626c3920SAl Viro 	Opt_uid,
3315ea3271f7SChris Down 	Opt_inode32,
3316ea3271f7SChris Down 	Opt_inode64,
3317626c3920SAl Viro };
33181da177e4SLinus Torvalds 
33195eede625SAl Viro static const struct constant_table shmem_param_enums_huge[] = {
33202710c957SAl Viro 	{"never",	SHMEM_HUGE_NEVER },
33212710c957SAl Viro 	{"always",	SHMEM_HUGE_ALWAYS },
33222710c957SAl Viro 	{"within_size",	SHMEM_HUGE_WITHIN_SIZE },
33232710c957SAl Viro 	{"advise",	SHMEM_HUGE_ADVISE },
33242710c957SAl Viro 	{}
33252710c957SAl Viro };
33262710c957SAl Viro 
3327d7167b14SAl Viro const struct fs_parameter_spec shmem_fs_parameters[] = {
3328626c3920SAl Viro 	fsparam_u32   ("gid",		Opt_gid),
33292710c957SAl Viro 	fsparam_enum  ("huge",		Opt_huge,  shmem_param_enums_huge),
3330626c3920SAl Viro 	fsparam_u32oct("mode",		Opt_mode),
3331626c3920SAl Viro 	fsparam_string("mpol",		Opt_mpol),
3332626c3920SAl Viro 	fsparam_string("nr_blocks",	Opt_nr_blocks),
3333626c3920SAl Viro 	fsparam_string("nr_inodes",	Opt_nr_inodes),
3334626c3920SAl Viro 	fsparam_string("size",		Opt_size),
3335626c3920SAl Viro 	fsparam_u32   ("uid",		Opt_uid),
3336ea3271f7SChris Down 	fsparam_flag  ("inode32",	Opt_inode32),
3337ea3271f7SChris Down 	fsparam_flag  ("inode64",	Opt_inode64),
3338626c3920SAl Viro 	{}
3339626c3920SAl Viro };
3340626c3920SAl Viro 
3341f3235626SDavid Howells static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
3342626c3920SAl Viro {
3343f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3344626c3920SAl Viro 	struct fs_parse_result result;
3345e04dc423SAl Viro 	unsigned long long size;
3346626c3920SAl Viro 	char *rest;
3347626c3920SAl Viro 	int opt;
3348626c3920SAl Viro 
3349d7167b14SAl Viro 	opt = fs_parse(fc, shmem_fs_parameters, param, &result);
3350f3235626SDavid Howells 	if (opt < 0)
3351626c3920SAl Viro 		return opt;
3352626c3920SAl Viro 
3353626c3920SAl Viro 	switch (opt) {
3354626c3920SAl Viro 	case Opt_size:
3355626c3920SAl Viro 		size = memparse(param->string, &rest);
3356e04dc423SAl Viro 		if (*rest == '%') {
3357e04dc423SAl Viro 			size <<= PAGE_SHIFT;
3358e04dc423SAl Viro 			size *= totalram_pages();
3359e04dc423SAl Viro 			do_div(size, 100);
3360e04dc423SAl Viro 			rest++;
3361e04dc423SAl Viro 		}
3362e04dc423SAl Viro 		if (*rest)
3363626c3920SAl Viro 			goto bad_value;
3364e04dc423SAl Viro 		ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
3365e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3366626c3920SAl Viro 		break;
3367626c3920SAl Viro 	case Opt_nr_blocks:
3368626c3920SAl Viro 		ctx->blocks = memparse(param->string, &rest);
3369e04dc423SAl Viro 		if (*rest)
3370626c3920SAl Viro 			goto bad_value;
3371e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3372626c3920SAl Viro 		break;
3373626c3920SAl Viro 	case Opt_nr_inodes:
3374626c3920SAl Viro 		ctx->inodes = memparse(param->string, &rest);
3375e04dc423SAl Viro 		if (*rest)
3376626c3920SAl Viro 			goto bad_value;
3377e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_INODES;
3378626c3920SAl Viro 		break;
3379626c3920SAl Viro 	case Opt_mode:
3380626c3920SAl Viro 		ctx->mode = result.uint_32 & 07777;
3381626c3920SAl Viro 		break;
3382626c3920SAl Viro 	case Opt_uid:
3383626c3920SAl Viro 		ctx->uid = make_kuid(current_user_ns(), result.uint_32);
3384e04dc423SAl Viro 		if (!uid_valid(ctx->uid))
3385626c3920SAl Viro 			goto bad_value;
3386626c3920SAl Viro 		break;
3387626c3920SAl Viro 	case Opt_gid:
3388626c3920SAl Viro 		ctx->gid = make_kgid(current_user_ns(), result.uint_32);
3389e04dc423SAl Viro 		if (!gid_valid(ctx->gid))
3390626c3920SAl Viro 			goto bad_value;
3391626c3920SAl Viro 		break;
3392626c3920SAl Viro 	case Opt_huge:
3393626c3920SAl Viro 		ctx->huge = result.uint_32;
3394626c3920SAl Viro 		if (ctx->huge != SHMEM_HUGE_NEVER &&
3395396bcc52SMatthew Wilcox (Oracle) 		    !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
3396626c3920SAl Viro 		      has_transparent_hugepage()))
3397626c3920SAl Viro 			goto unsupported_parameter;
3398e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_HUGE;
3399626c3920SAl Viro 		break;
3400626c3920SAl Viro 	case Opt_mpol:
3401626c3920SAl Viro 		if (IS_ENABLED(CONFIG_NUMA)) {
3402e04dc423SAl Viro 			mpol_put(ctx->mpol);
3403e04dc423SAl Viro 			ctx->mpol = NULL;
3404626c3920SAl Viro 			if (mpol_parse_str(param->string, &ctx->mpol))
3405626c3920SAl Viro 				goto bad_value;
3406626c3920SAl Viro 			break;
3407626c3920SAl Viro 		}
3408626c3920SAl Viro 		goto unsupported_parameter;
3409ea3271f7SChris Down 	case Opt_inode32:
3410ea3271f7SChris Down 		ctx->full_inums = false;
3411ea3271f7SChris Down 		ctx->seen |= SHMEM_SEEN_INUMS;
3412ea3271f7SChris Down 		break;
3413ea3271f7SChris Down 	case Opt_inode64:
3414ea3271f7SChris Down 		if (sizeof(ino_t) < 8) {
3415ea3271f7SChris Down 			return invalfc(fc,
3416ea3271f7SChris Down 				       "Cannot use inode64 with <64bit inums in kernel\n");
3417ea3271f7SChris Down 		}
3418ea3271f7SChris Down 		ctx->full_inums = true;
3419ea3271f7SChris Down 		ctx->seen |= SHMEM_SEEN_INUMS;
3420ea3271f7SChris Down 		break;
3421e04dc423SAl Viro 	}
3422e04dc423SAl Viro 	return 0;
3423e04dc423SAl Viro 
3424626c3920SAl Viro unsupported_parameter:
3425f35aa2bcSAl Viro 	return invalfc(fc, "Unsupported parameter '%s'", param->key);
3426626c3920SAl Viro bad_value:
3427f35aa2bcSAl Viro 	return invalfc(fc, "Bad value for '%s'", param->key);
3428e04dc423SAl Viro }
3429e04dc423SAl Viro 
3430f3235626SDavid Howells static int shmem_parse_options(struct fs_context *fc, void *data)
3431e04dc423SAl Viro {
3432f3235626SDavid Howells 	char *options = data;
3433f3235626SDavid Howells 
343433f37c64SAl Viro 	if (options) {
343533f37c64SAl Viro 		int err = security_sb_eat_lsm_opts(options, &fc->security);
343633f37c64SAl Viro 		if (err)
343733f37c64SAl Viro 			return err;
343833f37c64SAl Viro 	}
343933f37c64SAl Viro 
3440b00dc3adSHugh Dickins 	while (options != NULL) {
3441626c3920SAl Viro 		char *this_char = options;
3442b00dc3adSHugh Dickins 		for (;;) {
3443b00dc3adSHugh Dickins 			/*
3444b00dc3adSHugh Dickins 			 * NUL-terminate this option: unfortunately,
3445b00dc3adSHugh Dickins 			 * mount options form a comma-separated list,
3446b00dc3adSHugh Dickins 			 * but mpol's nodelist may also contain commas.
3447b00dc3adSHugh Dickins 			 */
3448b00dc3adSHugh Dickins 			options = strchr(options, ',');
3449b00dc3adSHugh Dickins 			if (options == NULL)
3450b00dc3adSHugh Dickins 				break;
3451b00dc3adSHugh Dickins 			options++;
3452b00dc3adSHugh Dickins 			if (!isdigit(*options)) {
3453b00dc3adSHugh Dickins 				options[-1] = '\0';
3454b00dc3adSHugh Dickins 				break;
3455b00dc3adSHugh Dickins 			}
3456b00dc3adSHugh Dickins 		}
3457626c3920SAl Viro 		if (*this_char) {
3458626c3920SAl Viro 			char *value = strchr(this_char, '=');
3459f3235626SDavid Howells 			size_t len = 0;
3460626c3920SAl Viro 			int err;
3461626c3920SAl Viro 
3462626c3920SAl Viro 			if (value) {
3463626c3920SAl Viro 				*value++ = '\0';
3464f3235626SDavid Howells 				len = strlen(value);
34651da177e4SLinus Torvalds 			}
3466f3235626SDavid Howells 			err = vfs_parse_fs_string(fc, this_char, value, len);
3467f3235626SDavid Howells 			if (err < 0)
3468f3235626SDavid Howells 				return err;
34691da177e4SLinus Torvalds 		}
3470626c3920SAl Viro 	}
34711da177e4SLinus Torvalds 	return 0;
34721da177e4SLinus Torvalds }
34731da177e4SLinus Torvalds 
3474f3235626SDavid Howells /*
3475f3235626SDavid Howells  * Reconfigure a shmem filesystem.
3476f3235626SDavid Howells  *
3477f3235626SDavid Howells  * Note that we disallow change from limited->unlimited blocks/inodes while any
3478f3235626SDavid Howells  * are in use; but we must separately disallow unlimited->limited, because in
3479f3235626SDavid Howells  * that case we have no record of how much is already in use.
3480f3235626SDavid Howells  */
3481f3235626SDavid Howells static int shmem_reconfigure(struct fs_context *fc)
34821da177e4SLinus Torvalds {
3483f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3484f3235626SDavid Howells 	struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
34850edd73b3SHugh Dickins 	unsigned long inodes;
3486bf11b9a8SSebastian Andrzej Siewior 	struct mempolicy *mpol = NULL;
3487f3235626SDavid Howells 	const char *err;
34880edd73b3SHugh Dickins 
3489bf11b9a8SSebastian Andrzej Siewior 	raw_spin_lock(&sbinfo->stat_lock);
34900edd73b3SHugh Dickins 	inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3491f3235626SDavid Howells 	if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
3492f3235626SDavid Howells 		if (!sbinfo->max_blocks) {
3493f3235626SDavid Howells 			err = "Cannot retroactively limit size";
34940edd73b3SHugh Dickins 			goto out;
34950b5071ddSAl Viro 		}
3496f3235626SDavid Howells 		if (percpu_counter_compare(&sbinfo->used_blocks,
3497f3235626SDavid Howells 					   ctx->blocks) > 0) {
3498f3235626SDavid Howells 			err = "Too small a size for current use";
34990b5071ddSAl Viro 			goto out;
3500f3235626SDavid Howells 		}
3501f3235626SDavid Howells 	}
3502f3235626SDavid Howells 	if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
3503f3235626SDavid Howells 		if (!sbinfo->max_inodes) {
3504f3235626SDavid Howells 			err = "Cannot retroactively limit inodes";
35050b5071ddSAl Viro 			goto out;
35060b5071ddSAl Viro 		}
3507f3235626SDavid Howells 		if (ctx->inodes < inodes) {
3508f3235626SDavid Howells 			err = "Too few inodes for current use";
3509f3235626SDavid Howells 			goto out;
3510f3235626SDavid Howells 		}
3511f3235626SDavid Howells 	}
35120edd73b3SHugh Dickins 
3513ea3271f7SChris Down 	if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
3514ea3271f7SChris Down 	    sbinfo->next_ino > UINT_MAX) {
3515ea3271f7SChris Down 		err = "Current inum too high to switch to 32-bit inums";
3516ea3271f7SChris Down 		goto out;
3517ea3271f7SChris Down 	}
3518ea3271f7SChris Down 
3519f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_HUGE)
3520f3235626SDavid Howells 		sbinfo->huge = ctx->huge;
3521ea3271f7SChris Down 	if (ctx->seen & SHMEM_SEEN_INUMS)
3522ea3271f7SChris Down 		sbinfo->full_inums = ctx->full_inums;
3523f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_BLOCKS)
3524f3235626SDavid Howells 		sbinfo->max_blocks  = ctx->blocks;
3525f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_INODES) {
3526f3235626SDavid Howells 		sbinfo->max_inodes  = ctx->inodes;
3527f3235626SDavid Howells 		sbinfo->free_inodes = ctx->inodes - inodes;
35280b5071ddSAl Viro 	}
352971fe804bSLee Schermerhorn 
35305f00110fSGreg Thelen 	/*
35315f00110fSGreg Thelen 	 * Preserve previous mempolicy unless mpol remount option was specified.
35325f00110fSGreg Thelen 	 */
3533f3235626SDavid Howells 	if (ctx->mpol) {
3534bf11b9a8SSebastian Andrzej Siewior 		mpol = sbinfo->mpol;
3535f3235626SDavid Howells 		sbinfo->mpol = ctx->mpol;	/* transfers initial ref */
3536f3235626SDavid Howells 		ctx->mpol = NULL;
35375f00110fSGreg Thelen 	}
3538bf11b9a8SSebastian Andrzej Siewior 	raw_spin_unlock(&sbinfo->stat_lock);
3539bf11b9a8SSebastian Andrzej Siewior 	mpol_put(mpol);
3540f3235626SDavid Howells 	return 0;
35410edd73b3SHugh Dickins out:
3542bf11b9a8SSebastian Andrzej Siewior 	raw_spin_unlock(&sbinfo->stat_lock);
3543f35aa2bcSAl Viro 	return invalfc(fc, "%s", err);
35441da177e4SLinus Torvalds }
3545680d794bSakpm@linux-foundation.org 
354634c80b1dSAl Viro static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3547680d794bSakpm@linux-foundation.org {
354834c80b1dSAl Viro 	struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3549680d794bSakpm@linux-foundation.org 
3550680d794bSakpm@linux-foundation.org 	if (sbinfo->max_blocks != shmem_default_max_blocks())
3551680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",size=%luk",
355209cbfeafSKirill A. Shutemov 			sbinfo->max_blocks << (PAGE_SHIFT - 10));
3553680d794bSakpm@linux-foundation.org 	if (sbinfo->max_inodes != shmem_default_max_inodes())
3554680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
35550825a6f9SJoe Perches 	if (sbinfo->mode != (0777 | S_ISVTX))
355609208d15SAl Viro 		seq_printf(seq, ",mode=%03ho", sbinfo->mode);
35578751e039SEric W. Biederman 	if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
35588751e039SEric W. Biederman 		seq_printf(seq, ",uid=%u",
35598751e039SEric W. Biederman 				from_kuid_munged(&init_user_ns, sbinfo->uid));
35608751e039SEric W. Biederman 	if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
35618751e039SEric W. Biederman 		seq_printf(seq, ",gid=%u",
35628751e039SEric W. Biederman 				from_kgid_munged(&init_user_ns, sbinfo->gid));
3563ea3271f7SChris Down 
3564ea3271f7SChris Down 	/*
3565ea3271f7SChris Down 	 * Showing inode{64,32} might be useful even if it's the system default,
3566ea3271f7SChris Down 	 * since then people don't have to resort to checking both here and
3567ea3271f7SChris Down 	 * /proc/config.gz to confirm 64-bit inums were successfully applied
3568ea3271f7SChris Down 	 * (which may not even exist if IKCONFIG_PROC isn't enabled).
3569ea3271f7SChris Down 	 *
3570ea3271f7SChris Down 	 * We hide it when inode64 isn't the default and we are using 32-bit
3571ea3271f7SChris Down 	 * inodes, since that probably just means the feature isn't even under
3572ea3271f7SChris Down 	 * consideration.
3573ea3271f7SChris Down 	 *
3574ea3271f7SChris Down 	 * As such:
3575ea3271f7SChris Down 	 *
3576ea3271f7SChris Down 	 *                     +-----------------+-----------------+
3577ea3271f7SChris Down 	 *                     | TMPFS_INODE64=y | TMPFS_INODE64=n |
3578ea3271f7SChris Down 	 *  +------------------+-----------------+-----------------+
3579ea3271f7SChris Down 	 *  | full_inums=true  | show            | show            |
3580ea3271f7SChris Down 	 *  | full_inums=false | show            | hide            |
3581ea3271f7SChris Down 	 *  +------------------+-----------------+-----------------+
3582ea3271f7SChris Down 	 *
3583ea3271f7SChris Down 	 */
3584ea3271f7SChris Down 	if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
3585ea3271f7SChris Down 		seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
3586396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
35875a6e75f8SKirill A. Shutemov 	/* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
35885a6e75f8SKirill A. Shutemov 	if (sbinfo->huge)
35895a6e75f8SKirill A. Shutemov 		seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
35905a6e75f8SKirill A. Shutemov #endif
359171fe804bSLee Schermerhorn 	shmem_show_mpol(seq, sbinfo->mpol);
3592680d794bSakpm@linux-foundation.org 	return 0;
3593680d794bSakpm@linux-foundation.org }
35949183df25SDavid Herrmann 
3595680d794bSakpm@linux-foundation.org #endif /* CONFIG_TMPFS */
35961da177e4SLinus Torvalds 
35971da177e4SLinus Torvalds static void shmem_put_super(struct super_block *sb)
35981da177e4SLinus Torvalds {
3599602586a8SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3600602586a8SHugh Dickins 
3601e809d5f0SChris Down 	free_percpu(sbinfo->ino_batch);
3602602586a8SHugh Dickins 	percpu_counter_destroy(&sbinfo->used_blocks);
360349cd0a5cSGreg Thelen 	mpol_put(sbinfo->mpol);
3604602586a8SHugh Dickins 	kfree(sbinfo);
36051da177e4SLinus Torvalds 	sb->s_fs_info = NULL;
36061da177e4SLinus Torvalds }
36071da177e4SLinus Torvalds 
3608f3235626SDavid Howells static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
36091da177e4SLinus Torvalds {
3610f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
36111da177e4SLinus Torvalds 	struct inode *inode;
36120edd73b3SHugh Dickins 	struct shmem_sb_info *sbinfo;
3613680d794bSakpm@linux-foundation.org 
3614680d794bSakpm@linux-foundation.org 	/* Round up to L1_CACHE_BYTES to resist false sharing */
3615425fbf04SPekka Enberg 	sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3616680d794bSakpm@linux-foundation.org 				L1_CACHE_BYTES), GFP_KERNEL);
3617680d794bSakpm@linux-foundation.org 	if (!sbinfo)
3618680d794bSakpm@linux-foundation.org 		return -ENOMEM;
3619680d794bSakpm@linux-foundation.org 
3620680d794bSakpm@linux-foundation.org 	sb->s_fs_info = sbinfo;
36211da177e4SLinus Torvalds 
36220edd73b3SHugh Dickins #ifdef CONFIG_TMPFS
36231da177e4SLinus Torvalds 	/*
36241da177e4SLinus Torvalds 	 * Per default we only allow half of the physical ram per
36251da177e4SLinus Torvalds 	 * tmpfs instance, limiting inodes to one per page of lowmem;
36261da177e4SLinus Torvalds 	 * but the internal instance is left unlimited.
36271da177e4SLinus Torvalds 	 */
36281751e8a6SLinus Torvalds 	if (!(sb->s_flags & SB_KERNMOUNT)) {
3629f3235626SDavid Howells 		if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
3630f3235626SDavid Howells 			ctx->blocks = shmem_default_max_blocks();
3631f3235626SDavid Howells 		if (!(ctx->seen & SHMEM_SEEN_INODES))
3632f3235626SDavid Howells 			ctx->inodes = shmem_default_max_inodes();
3633ea3271f7SChris Down 		if (!(ctx->seen & SHMEM_SEEN_INUMS))
3634ea3271f7SChris Down 			ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
3635ca4e0519SAl Viro 	} else {
36361751e8a6SLinus Torvalds 		sb->s_flags |= SB_NOUSER;
36371da177e4SLinus Torvalds 	}
363891828a40SDavid M. Grimes 	sb->s_export_op = &shmem_export_ops;
36391751e8a6SLinus Torvalds 	sb->s_flags |= SB_NOSEC;
36400edd73b3SHugh Dickins #else
36411751e8a6SLinus Torvalds 	sb->s_flags |= SB_NOUSER;
36420edd73b3SHugh Dickins #endif
3643f3235626SDavid Howells 	sbinfo->max_blocks = ctx->blocks;
3644f3235626SDavid Howells 	sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes;
3645e809d5f0SChris Down 	if (sb->s_flags & SB_KERNMOUNT) {
3646e809d5f0SChris Down 		sbinfo->ino_batch = alloc_percpu(ino_t);
3647e809d5f0SChris Down 		if (!sbinfo->ino_batch)
3648e809d5f0SChris Down 			goto failed;
3649e809d5f0SChris Down 	}
3650f3235626SDavid Howells 	sbinfo->uid = ctx->uid;
3651f3235626SDavid Howells 	sbinfo->gid = ctx->gid;
3652ea3271f7SChris Down 	sbinfo->full_inums = ctx->full_inums;
3653f3235626SDavid Howells 	sbinfo->mode = ctx->mode;
3654f3235626SDavid Howells 	sbinfo->huge = ctx->huge;
3655f3235626SDavid Howells 	sbinfo->mpol = ctx->mpol;
3656f3235626SDavid Howells 	ctx->mpol = NULL;
36571da177e4SLinus Torvalds 
3658bf11b9a8SSebastian Andrzej Siewior 	raw_spin_lock_init(&sbinfo->stat_lock);
3659908c7f19STejun Heo 	if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3660602586a8SHugh Dickins 		goto failed;
3661779750d2SKirill A. Shutemov 	spin_lock_init(&sbinfo->shrinklist_lock);
3662779750d2SKirill A. Shutemov 	INIT_LIST_HEAD(&sbinfo->shrinklist);
36631da177e4SLinus Torvalds 
3664285b2c4fSHugh Dickins 	sb->s_maxbytes = MAX_LFS_FILESIZE;
366509cbfeafSKirill A. Shutemov 	sb->s_blocksize = PAGE_SIZE;
366609cbfeafSKirill A. Shutemov 	sb->s_blocksize_bits = PAGE_SHIFT;
36671da177e4SLinus Torvalds 	sb->s_magic = TMPFS_MAGIC;
36681da177e4SLinus Torvalds 	sb->s_op = &shmem_ops;
3669cfd95a9cSRobin H. Johnson 	sb->s_time_gran = 1;
3670b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
367139f0247dSAndreas Gruenbacher 	sb->s_xattr = shmem_xattr_handlers;
3672b09e0fa4SEric Paris #endif
3673b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
36741751e8a6SLinus Torvalds 	sb->s_flags |= SB_POSIXACL;
367539f0247dSAndreas Gruenbacher #endif
36762b4db796SAmir Goldstein 	uuid_gen(&sb->s_uuid);
36770edd73b3SHugh Dickins 
3678454abafeSDmitry Monakhov 	inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
36791da177e4SLinus Torvalds 	if (!inode)
36801da177e4SLinus Torvalds 		goto failed;
3681680d794bSakpm@linux-foundation.org 	inode->i_uid = sbinfo->uid;
3682680d794bSakpm@linux-foundation.org 	inode->i_gid = sbinfo->gid;
3683318ceed0SAl Viro 	sb->s_root = d_make_root(inode);
3684318ceed0SAl Viro 	if (!sb->s_root)
368548fde701SAl Viro 		goto failed;
36861da177e4SLinus Torvalds 	return 0;
36871da177e4SLinus Torvalds 
36881da177e4SLinus Torvalds failed:
36891da177e4SLinus Torvalds 	shmem_put_super(sb);
3690f2b346e4SMiaohe Lin 	return -ENOMEM;
36911da177e4SLinus Torvalds }
36921da177e4SLinus Torvalds 
3693f3235626SDavid Howells static int shmem_get_tree(struct fs_context *fc)
3694f3235626SDavid Howells {
3695f3235626SDavid Howells 	return get_tree_nodev(fc, shmem_fill_super);
3696f3235626SDavid Howells }
3697f3235626SDavid Howells 
3698f3235626SDavid Howells static void shmem_free_fc(struct fs_context *fc)
3699f3235626SDavid Howells {
3700f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3701f3235626SDavid Howells 
3702f3235626SDavid Howells 	if (ctx) {
3703f3235626SDavid Howells 		mpol_put(ctx->mpol);
3704f3235626SDavid Howells 		kfree(ctx);
3705f3235626SDavid Howells 	}
3706f3235626SDavid Howells }
3707f3235626SDavid Howells 
3708f3235626SDavid Howells static const struct fs_context_operations shmem_fs_context_ops = {
3709f3235626SDavid Howells 	.free			= shmem_free_fc,
3710f3235626SDavid Howells 	.get_tree		= shmem_get_tree,
3711f3235626SDavid Howells #ifdef CONFIG_TMPFS
3712f3235626SDavid Howells 	.parse_monolithic	= shmem_parse_options,
3713f3235626SDavid Howells 	.parse_param		= shmem_parse_one,
3714f3235626SDavid Howells 	.reconfigure		= shmem_reconfigure,
3715f3235626SDavid Howells #endif
3716f3235626SDavid Howells };
3717f3235626SDavid Howells 
3718fcc234f8SPekka Enberg static struct kmem_cache *shmem_inode_cachep;
37191da177e4SLinus Torvalds 
37201da177e4SLinus Torvalds static struct inode *shmem_alloc_inode(struct super_block *sb)
37211da177e4SLinus Torvalds {
372241ffe5d5SHugh Dickins 	struct shmem_inode_info *info;
3723fd60b288SMuchun Song 	info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL);
372441ffe5d5SHugh Dickins 	if (!info)
37251da177e4SLinus Torvalds 		return NULL;
372641ffe5d5SHugh Dickins 	return &info->vfs_inode;
37271da177e4SLinus Torvalds }
37281da177e4SLinus Torvalds 
372974b1da56SAl Viro static void shmem_free_in_core_inode(struct inode *inode)
3730fa0d7e3dSNick Piggin {
373184e710daSAl Viro 	if (S_ISLNK(inode->i_mode))
37323ed47db3SAl Viro 		kfree(inode->i_link);
3733fa0d7e3dSNick Piggin 	kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3734fa0d7e3dSNick Piggin }
3735fa0d7e3dSNick Piggin 
37361da177e4SLinus Torvalds static void shmem_destroy_inode(struct inode *inode)
37371da177e4SLinus Torvalds {
373809208d15SAl Viro 	if (S_ISREG(inode->i_mode))
37391da177e4SLinus Torvalds 		mpol_free_shared_policy(&SHMEM_I(inode)->policy);
37401da177e4SLinus Torvalds }
37411da177e4SLinus Torvalds 
374241ffe5d5SHugh Dickins static void shmem_init_inode(void *foo)
37431da177e4SLinus Torvalds {
374441ffe5d5SHugh Dickins 	struct shmem_inode_info *info = foo;
374541ffe5d5SHugh Dickins 	inode_init_once(&info->vfs_inode);
37461da177e4SLinus Torvalds }
37471da177e4SLinus Torvalds 
37489a8ec03eSweiping zhang static void shmem_init_inodecache(void)
37491da177e4SLinus Torvalds {
37501da177e4SLinus Torvalds 	shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
37511da177e4SLinus Torvalds 				sizeof(struct shmem_inode_info),
37525d097056SVladimir Davydov 				0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
37531da177e4SLinus Torvalds }
37541da177e4SLinus Torvalds 
375541ffe5d5SHugh Dickins static void shmem_destroy_inodecache(void)
37561da177e4SLinus Torvalds {
37571a1d92c1SAlexey Dobriyan 	kmem_cache_destroy(shmem_inode_cachep);
37581da177e4SLinus Torvalds }
37591da177e4SLinus Torvalds 
3760a7605426SYang Shi /* Keep the page in page cache instead of truncating it */
3761a7605426SYang Shi static int shmem_error_remove_page(struct address_space *mapping,
3762a7605426SYang Shi 				   struct page *page)
3763a7605426SYang Shi {
3764a7605426SYang Shi 	return 0;
3765a7605426SYang Shi }
3766a7605426SYang Shi 
376730e6a51dSHui Su const struct address_space_operations shmem_aops = {
37681da177e4SLinus Torvalds 	.writepage	= shmem_writepage,
376946de8b97SMatthew Wilcox (Oracle) 	.dirty_folio	= noop_dirty_folio,
37701da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3771800d15a5SNick Piggin 	.write_begin	= shmem_write_begin,
3772800d15a5SNick Piggin 	.write_end	= shmem_write_end,
37731da177e4SLinus Torvalds #endif
37741c93923cSAndrew Morton #ifdef CONFIG_MIGRATION
3775304dbdb7SLee Schermerhorn 	.migratepage	= migrate_page,
37761c93923cSAndrew Morton #endif
3777a7605426SYang Shi 	.error_remove_page = shmem_error_remove_page,
37781da177e4SLinus Torvalds };
377930e6a51dSHui Su EXPORT_SYMBOL(shmem_aops);
37801da177e4SLinus Torvalds 
378115ad7cdcSHelge Deller static const struct file_operations shmem_file_operations = {
37821da177e4SLinus Torvalds 	.mmap		= shmem_mmap,
3783c01d5b30SHugh Dickins 	.get_unmapped_area = shmem_get_unmapped_area,
37841da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3785220f2ac9SHugh Dickins 	.llseek		= shmem_file_llseek,
37862ba5bbedSAl Viro 	.read_iter	= shmem_file_read_iter,
37878174202bSAl Viro 	.write_iter	= generic_file_write_iter,
37881b061d92SChristoph Hellwig 	.fsync		= noop_fsync,
378982c156f8SAl Viro 	.splice_read	= generic_file_splice_read,
3790f6cb85d0SAl Viro 	.splice_write	= iter_file_splice_write,
379183e4fa9cSHugh Dickins 	.fallocate	= shmem_fallocate,
37921da177e4SLinus Torvalds #endif
37931da177e4SLinus Torvalds };
37941da177e4SLinus Torvalds 
379592e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations = {
379644a30220SYu Zhao 	.getattr	= shmem_getattr,
379794c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3798b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3799b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3800feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
3801b09e0fa4SEric Paris #endif
38021da177e4SLinus Torvalds };
38031da177e4SLinus Torvalds 
380492e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations = {
38051da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3806f7cd16a5SXavier Roche 	.getattr	= shmem_getattr,
38071da177e4SLinus Torvalds 	.create		= shmem_create,
38081da177e4SLinus Torvalds 	.lookup		= simple_lookup,
38091da177e4SLinus Torvalds 	.link		= shmem_link,
38101da177e4SLinus Torvalds 	.unlink		= shmem_unlink,
38111da177e4SLinus Torvalds 	.symlink	= shmem_symlink,
38121da177e4SLinus Torvalds 	.mkdir		= shmem_mkdir,
38131da177e4SLinus Torvalds 	.rmdir		= shmem_rmdir,
38141da177e4SLinus Torvalds 	.mknod		= shmem_mknod,
38152773bf00SMiklos Szeredi 	.rename		= shmem_rename2,
381660545d0dSAl Viro 	.tmpfile	= shmem_tmpfile,
38171da177e4SLinus Torvalds #endif
3818b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3819b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3820b09e0fa4SEric Paris #endif
382139f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
382294c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3823feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
382439f0247dSAndreas Gruenbacher #endif
382539f0247dSAndreas Gruenbacher };
382639f0247dSAndreas Gruenbacher 
382792e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations = {
3828f7cd16a5SXavier Roche 	.getattr	= shmem_getattr,
3829b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3830b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3831b09e0fa4SEric Paris #endif
383239f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
383394c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3834feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
383539f0247dSAndreas Gruenbacher #endif
38361da177e4SLinus Torvalds };
38371da177e4SLinus Torvalds 
3838759b9775SHugh Dickins static const struct super_operations shmem_ops = {
38391da177e4SLinus Torvalds 	.alloc_inode	= shmem_alloc_inode,
384074b1da56SAl Viro 	.free_inode	= shmem_free_in_core_inode,
38411da177e4SLinus Torvalds 	.destroy_inode	= shmem_destroy_inode,
38421da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
38431da177e4SLinus Torvalds 	.statfs		= shmem_statfs,
3844680d794bSakpm@linux-foundation.org 	.show_options	= shmem_show_options,
38451da177e4SLinus Torvalds #endif
38461f895f75SAl Viro 	.evict_inode	= shmem_evict_inode,
38471da177e4SLinus Torvalds 	.drop_inode	= generic_delete_inode,
38481da177e4SLinus Torvalds 	.put_super	= shmem_put_super,
3849396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3850779750d2SKirill A. Shutemov 	.nr_cached_objects	= shmem_unused_huge_count,
3851779750d2SKirill A. Shutemov 	.free_cached_objects	= shmem_unused_huge_scan,
3852779750d2SKirill A. Shutemov #endif
38531da177e4SLinus Torvalds };
38541da177e4SLinus Torvalds 
3855f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops = {
385654cb8821SNick Piggin 	.fault		= shmem_fault,
3857d7c17551SNing Qu 	.map_pages	= filemap_map_pages,
38581da177e4SLinus Torvalds #ifdef CONFIG_NUMA
38591da177e4SLinus Torvalds 	.set_policy     = shmem_set_policy,
38601da177e4SLinus Torvalds 	.get_policy     = shmem_get_policy,
38611da177e4SLinus Torvalds #endif
38621da177e4SLinus Torvalds };
38631da177e4SLinus Torvalds 
3864f3235626SDavid Howells int shmem_init_fs_context(struct fs_context *fc)
38651da177e4SLinus Torvalds {
3866f3235626SDavid Howells 	struct shmem_options *ctx;
3867f3235626SDavid Howells 
3868f3235626SDavid Howells 	ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL);
3869f3235626SDavid Howells 	if (!ctx)
3870f3235626SDavid Howells 		return -ENOMEM;
3871f3235626SDavid Howells 
3872f3235626SDavid Howells 	ctx->mode = 0777 | S_ISVTX;
3873f3235626SDavid Howells 	ctx->uid = current_fsuid();
3874f3235626SDavid Howells 	ctx->gid = current_fsgid();
3875f3235626SDavid Howells 
3876f3235626SDavid Howells 	fc->fs_private = ctx;
3877f3235626SDavid Howells 	fc->ops = &shmem_fs_context_ops;
3878f3235626SDavid Howells 	return 0;
38791da177e4SLinus Torvalds }
38801da177e4SLinus Torvalds 
388141ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
38821da177e4SLinus Torvalds 	.owner		= THIS_MODULE,
38831da177e4SLinus Torvalds 	.name		= "tmpfs",
3884f3235626SDavid Howells 	.init_fs_context = shmem_init_fs_context,
3885f3235626SDavid Howells #ifdef CONFIG_TMPFS
3886d7167b14SAl Viro 	.parameters	= shmem_fs_parameters,
3887f3235626SDavid Howells #endif
38881da177e4SLinus Torvalds 	.kill_sb	= kill_litter_super,
3889ff36da69SMatthew Wilcox (Oracle) 	.fs_flags	= FS_USERNS_MOUNT,
38901da177e4SLinus Torvalds };
38911da177e4SLinus Torvalds 
38929096bbe9SMiaohe Lin void __init shmem_init(void)
38931da177e4SLinus Torvalds {
38941da177e4SLinus Torvalds 	int error;
38951da177e4SLinus Torvalds 
38969a8ec03eSweiping zhang 	shmem_init_inodecache();
38971da177e4SLinus Torvalds 
389841ffe5d5SHugh Dickins 	error = register_filesystem(&shmem_fs_type);
38991da177e4SLinus Torvalds 	if (error) {
39001170532bSJoe Perches 		pr_err("Could not register tmpfs\n");
39011da177e4SLinus Torvalds 		goto out2;
39021da177e4SLinus Torvalds 	}
390395dc112aSGreg Kroah-Hartman 
3904ca4e0519SAl Viro 	shm_mnt = kern_mount(&shmem_fs_type);
39051da177e4SLinus Torvalds 	if (IS_ERR(shm_mnt)) {
39061da177e4SLinus Torvalds 		error = PTR_ERR(shm_mnt);
39071170532bSJoe Perches 		pr_err("Could not kern_mount tmpfs\n");
39081da177e4SLinus Torvalds 		goto out1;
39091da177e4SLinus Torvalds 	}
39105a6e75f8SKirill A. Shutemov 
3911396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3912435c0b87SKirill A. Shutemov 	if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
39135a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
39145a6e75f8SKirill A. Shutemov 	else
39155e6e5a12SHugh Dickins 		shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
39165a6e75f8SKirill A. Shutemov #endif
39179096bbe9SMiaohe Lin 	return;
39181da177e4SLinus Torvalds 
39191da177e4SLinus Torvalds out1:
392041ffe5d5SHugh Dickins 	unregister_filesystem(&shmem_fs_type);
39211da177e4SLinus Torvalds out2:
392241ffe5d5SHugh Dickins 	shmem_destroy_inodecache();
39231da177e4SLinus Torvalds 	shm_mnt = ERR_PTR(error);
39241da177e4SLinus Torvalds }
3925853ac43aSMatt Mackall 
3926396bcc52SMatthew Wilcox (Oracle) #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
39275a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_show(struct kobject *kobj,
39285a6e75f8SKirill A. Shutemov 				  struct kobj_attribute *attr, char *buf)
39295a6e75f8SKirill A. Shutemov {
393026083eb6SColin Ian King 	static const int values[] = {
39315a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ALWAYS,
39325a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_WITHIN_SIZE,
39335a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ADVISE,
39345a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_NEVER,
39355a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_DENY,
39365a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_FORCE,
39375a6e75f8SKirill A. Shutemov 	};
393879d4d38aSJoe Perches 	int len = 0;
393979d4d38aSJoe Perches 	int i;
39405a6e75f8SKirill A. Shutemov 
394179d4d38aSJoe Perches 	for (i = 0; i < ARRAY_SIZE(values); i++) {
394279d4d38aSJoe Perches 		len += sysfs_emit_at(buf, len,
394379d4d38aSJoe Perches 				     shmem_huge == values[i] ? "%s[%s]" : "%s%s",
394479d4d38aSJoe Perches 				     i ? " " : "",
39455a6e75f8SKirill A. Shutemov 				     shmem_format_huge(values[i]));
39465a6e75f8SKirill A. Shutemov 	}
394779d4d38aSJoe Perches 
394879d4d38aSJoe Perches 	len += sysfs_emit_at(buf, len, "\n");
394979d4d38aSJoe Perches 
395079d4d38aSJoe Perches 	return len;
39515a6e75f8SKirill A. Shutemov }
39525a6e75f8SKirill A. Shutemov 
39535a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_store(struct kobject *kobj,
39545a6e75f8SKirill A. Shutemov 		struct kobj_attribute *attr, const char *buf, size_t count)
39555a6e75f8SKirill A. Shutemov {
39565a6e75f8SKirill A. Shutemov 	char tmp[16];
39575a6e75f8SKirill A. Shutemov 	int huge;
39585a6e75f8SKirill A. Shutemov 
39595a6e75f8SKirill A. Shutemov 	if (count + 1 > sizeof(tmp))
39605a6e75f8SKirill A. Shutemov 		return -EINVAL;
39615a6e75f8SKirill A. Shutemov 	memcpy(tmp, buf, count);
39625a6e75f8SKirill A. Shutemov 	tmp[count] = '\0';
39635a6e75f8SKirill A. Shutemov 	if (count && tmp[count - 1] == '\n')
39645a6e75f8SKirill A. Shutemov 		tmp[count - 1] = '\0';
39655a6e75f8SKirill A. Shutemov 
39665a6e75f8SKirill A. Shutemov 	huge = shmem_parse_huge(tmp);
39675a6e75f8SKirill A. Shutemov 	if (huge == -EINVAL)
39685a6e75f8SKirill A. Shutemov 		return -EINVAL;
39695a6e75f8SKirill A. Shutemov 	if (!has_transparent_hugepage() &&
39705a6e75f8SKirill A. Shutemov 			huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
39715a6e75f8SKirill A. Shutemov 		return -EINVAL;
39725a6e75f8SKirill A. Shutemov 
39735a6e75f8SKirill A. Shutemov 	shmem_huge = huge;
3974435c0b87SKirill A. Shutemov 	if (shmem_huge > SHMEM_HUGE_DENY)
39755a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
39765a6e75f8SKirill A. Shutemov 	return count;
39775a6e75f8SKirill A. Shutemov }
39785a6e75f8SKirill A. Shutemov 
39794bfa8adaSMiaohe Lin struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);
3980396bcc52SMatthew Wilcox (Oracle) #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
3981f3f0e1d2SKirill A. Shutemov 
3982853ac43aSMatt Mackall #else /* !CONFIG_SHMEM */
3983853ac43aSMatt Mackall 
3984853ac43aSMatt Mackall /*
3985853ac43aSMatt Mackall  * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3986853ac43aSMatt Mackall  *
3987853ac43aSMatt Mackall  * This is intended for small system where the benefits of the full
3988853ac43aSMatt Mackall  * shmem code (swap-backed and resource-limited) are outweighed by
3989853ac43aSMatt Mackall  * their complexity. On systems without swap this code should be
3990853ac43aSMatt Mackall  * effectively equivalent, but much lighter weight.
3991853ac43aSMatt Mackall  */
3992853ac43aSMatt Mackall 
399341ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
3994853ac43aSMatt Mackall 	.name		= "tmpfs",
3995f3235626SDavid Howells 	.init_fs_context = ramfs_init_fs_context,
3996d7167b14SAl Viro 	.parameters	= ramfs_fs_parameters,
3997853ac43aSMatt Mackall 	.kill_sb	= kill_litter_super,
39982b8576cbSEric W. Biederman 	.fs_flags	= FS_USERNS_MOUNT,
3999853ac43aSMatt Mackall };
4000853ac43aSMatt Mackall 
40019096bbe9SMiaohe Lin void __init shmem_init(void)
4002853ac43aSMatt Mackall {
400341ffe5d5SHugh Dickins 	BUG_ON(register_filesystem(&shmem_fs_type) != 0);
4004853ac43aSMatt Mackall 
400541ffe5d5SHugh Dickins 	shm_mnt = kern_mount(&shmem_fs_type);
4006853ac43aSMatt Mackall 	BUG_ON(IS_ERR(shm_mnt));
4007853ac43aSMatt Mackall }
4008853ac43aSMatt Mackall 
400910a9c496SChristoph Hellwig int shmem_unuse(unsigned int type)
4010853ac43aSMatt Mackall {
4011853ac43aSMatt Mackall 	return 0;
4012853ac43aSMatt Mackall }
4013853ac43aSMatt Mackall 
4014d7c9e99aSAlexey Gladkov int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
40153f96b79aSHugh Dickins {
40163f96b79aSHugh Dickins 	return 0;
40173f96b79aSHugh Dickins }
40183f96b79aSHugh Dickins 
401924513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
402024513264SHugh Dickins {
402124513264SHugh Dickins }
402224513264SHugh Dickins 
4023c01d5b30SHugh Dickins #ifdef CONFIG_MMU
4024c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
4025c01d5b30SHugh Dickins 				      unsigned long addr, unsigned long len,
4026c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
4027c01d5b30SHugh Dickins {
4028c01d5b30SHugh Dickins 	return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
4029c01d5b30SHugh Dickins }
4030c01d5b30SHugh Dickins #endif
4031c01d5b30SHugh Dickins 
403241ffe5d5SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
403394c1e62dSHugh Dickins {
403441ffe5d5SHugh Dickins 	truncate_inode_pages_range(inode->i_mapping, lstart, lend);
403594c1e62dSHugh Dickins }
403694c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
403794c1e62dSHugh Dickins 
4038853ac43aSMatt Mackall #define shmem_vm_ops				generic_file_vm_ops
40390b0a0806SHugh Dickins #define shmem_file_operations			ramfs_file_operations
4040454abafeSDmitry Monakhov #define shmem_get_inode(sb, dir, mode, dev, flags)	ramfs_get_inode(sb, dir, mode, dev)
40410b0a0806SHugh Dickins #define shmem_acct_size(flags, size)		0
40420b0a0806SHugh Dickins #define shmem_unacct_size(flags, size)		do {} while (0)
4043853ac43aSMatt Mackall 
4044853ac43aSMatt Mackall #endif /* CONFIG_SHMEM */
4045853ac43aSMatt Mackall 
4046853ac43aSMatt Mackall /* common code */
40471da177e4SLinus Torvalds 
4048703321b6SMatthew Auld static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
4049c7277090SEric Paris 				       unsigned long flags, unsigned int i_flags)
40501da177e4SLinus Torvalds {
40511da177e4SLinus Torvalds 	struct inode *inode;
405293dec2daSAl Viro 	struct file *res;
40531da177e4SLinus Torvalds 
4054703321b6SMatthew Auld 	if (IS_ERR(mnt))
4055703321b6SMatthew Auld 		return ERR_CAST(mnt);
40561da177e4SLinus Torvalds 
4057285b2c4fSHugh Dickins 	if (size < 0 || size > MAX_LFS_FILESIZE)
40581da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
40591da177e4SLinus Torvalds 
40601da177e4SLinus Torvalds 	if (shmem_acct_size(flags, size))
40611da177e4SLinus Torvalds 		return ERR_PTR(-ENOMEM);
40621da177e4SLinus Torvalds 
406393dec2daSAl Viro 	inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
406493dec2daSAl Viro 				flags);
4065dac2d1f6SAl Viro 	if (unlikely(!inode)) {
4066dac2d1f6SAl Viro 		shmem_unacct_size(flags, size);
4067dac2d1f6SAl Viro 		return ERR_PTR(-ENOSPC);
4068dac2d1f6SAl Viro 	}
4069c7277090SEric Paris 	inode->i_flags |= i_flags;
40701da177e4SLinus Torvalds 	inode->i_size = size;
40716d6b77f1SMiklos Szeredi 	clear_nlink(inode);	/* It is unlinked */
407226567cdbSAl Viro 	res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
407393dec2daSAl Viro 	if (!IS_ERR(res))
407493dec2daSAl Viro 		res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
40754b42af81SAl Viro 				&shmem_file_operations);
40766b4d0b27SAl Viro 	if (IS_ERR(res))
407793dec2daSAl Viro 		iput(inode);
40786b4d0b27SAl Viro 	return res;
40791da177e4SLinus Torvalds }
4080c7277090SEric Paris 
4081c7277090SEric Paris /**
4082c7277090SEric Paris  * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4083c7277090SEric Paris  * 	kernel internal.  There will be NO LSM permission checks against the
4084c7277090SEric Paris  * 	underlying inode.  So users of this interface must do LSM checks at a
4085e1832f29SStephen Smalley  *	higher layer.  The users are the big_key and shm implementations.  LSM
4086e1832f29SStephen Smalley  *	checks are provided at the key or shm level rather than the inode.
4087c7277090SEric Paris  * @name: name for dentry (to be seen in /proc/<pid>/maps
4088c7277090SEric Paris  * @size: size to be set for the file
4089c7277090SEric Paris  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4090c7277090SEric Paris  */
4091c7277090SEric Paris struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4092c7277090SEric Paris {
4093703321b6SMatthew Auld 	return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
4094c7277090SEric Paris }
4095c7277090SEric Paris 
4096c7277090SEric Paris /**
4097c7277090SEric Paris  * shmem_file_setup - get an unlinked file living in tmpfs
4098c7277090SEric Paris  * @name: name for dentry (to be seen in /proc/<pid>/maps
4099c7277090SEric Paris  * @size: size to be set for the file
4100c7277090SEric Paris  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4101c7277090SEric Paris  */
4102c7277090SEric Paris struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4103c7277090SEric Paris {
4104703321b6SMatthew Auld 	return __shmem_file_setup(shm_mnt, name, size, flags, 0);
4105c7277090SEric Paris }
4106395e0ddcSKeith Packard EXPORT_SYMBOL_GPL(shmem_file_setup);
41071da177e4SLinus Torvalds 
410846711810SRandy Dunlap /**
4109703321b6SMatthew Auld  * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4110703321b6SMatthew Auld  * @mnt: the tmpfs mount where the file will be created
4111703321b6SMatthew Auld  * @name: name for dentry (to be seen in /proc/<pid>/maps
4112703321b6SMatthew Auld  * @size: size to be set for the file
4113703321b6SMatthew Auld  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4114703321b6SMatthew Auld  */
4115703321b6SMatthew Auld struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4116703321b6SMatthew Auld 				       loff_t size, unsigned long flags)
4117703321b6SMatthew Auld {
4118703321b6SMatthew Auld 	return __shmem_file_setup(mnt, name, size, flags, 0);
4119703321b6SMatthew Auld }
4120703321b6SMatthew Auld EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4121703321b6SMatthew Auld 
4122703321b6SMatthew Auld /**
41231da177e4SLinus Torvalds  * shmem_zero_setup - setup a shared anonymous mapping
412445e55300SPeter Collingbourne  * @vma: the vma to be mmapped is prepared by do_mmap
41251da177e4SLinus Torvalds  */
41261da177e4SLinus Torvalds int shmem_zero_setup(struct vm_area_struct *vma)
41271da177e4SLinus Torvalds {
41281da177e4SLinus Torvalds 	struct file *file;
41291da177e4SLinus Torvalds 	loff_t size = vma->vm_end - vma->vm_start;
41301da177e4SLinus Torvalds 
413166fc1303SHugh Dickins 	/*
4132c1e8d7c6SMichel Lespinasse 	 * Cloning a new file under mmap_lock leads to a lock ordering conflict
413366fc1303SHugh Dickins 	 * between XFS directory reading and selinux: since this file is only
413466fc1303SHugh Dickins 	 * accessible to the user through its mapping, use S_PRIVATE flag to
413566fc1303SHugh Dickins 	 * bypass file security, in the same way as shmem_kernel_file_setup().
413666fc1303SHugh Dickins 	 */
4137703321b6SMatthew Auld 	file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
41381da177e4SLinus Torvalds 	if (IS_ERR(file))
41391da177e4SLinus Torvalds 		return PTR_ERR(file);
41401da177e4SLinus Torvalds 
41411da177e4SLinus Torvalds 	if (vma->vm_file)
41421da177e4SLinus Torvalds 		fput(vma->vm_file);
41431da177e4SLinus Torvalds 	vma->vm_file = file;
41441da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
4145f3f0e1d2SKirill A. Shutemov 
4146396bcc52SMatthew Wilcox (Oracle) 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
4147f3f0e1d2SKirill A. Shutemov 			((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4148f3f0e1d2SKirill A. Shutemov 			(vma->vm_end & HPAGE_PMD_MASK)) {
4149f3f0e1d2SKirill A. Shutemov 		khugepaged_enter(vma, vma->vm_flags);
4150f3f0e1d2SKirill A. Shutemov 	}
4151f3f0e1d2SKirill A. Shutemov 
41521da177e4SLinus Torvalds 	return 0;
41531da177e4SLinus Torvalds }
4154d9d90e5eSHugh Dickins 
4155d9d90e5eSHugh Dickins /**
4156d9d90e5eSHugh Dickins  * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4157d9d90e5eSHugh Dickins  * @mapping:	the page's address_space
4158d9d90e5eSHugh Dickins  * @index:	the page index
4159d9d90e5eSHugh Dickins  * @gfp:	the page allocator flags to use if allocating
4160d9d90e5eSHugh Dickins  *
4161d9d90e5eSHugh Dickins  * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4162d9d90e5eSHugh Dickins  * with any new page allocations done using the specified allocation flags.
4163d9d90e5eSHugh Dickins  * But read_cache_page_gfp() uses the ->readpage() method: which does not
4164d9d90e5eSHugh Dickins  * suit tmpfs, since it may have pages in swapcache, and needs to find those
4165d9d90e5eSHugh Dickins  * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4166d9d90e5eSHugh Dickins  *
416768da9f05SHugh Dickins  * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
416868da9f05SHugh Dickins  * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4169d9d90e5eSHugh Dickins  */
4170d9d90e5eSHugh Dickins struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4171d9d90e5eSHugh Dickins 					 pgoff_t index, gfp_t gfp)
4172d9d90e5eSHugh Dickins {
417368da9f05SHugh Dickins #ifdef CONFIG_SHMEM
417468da9f05SHugh Dickins 	struct inode *inode = mapping->host;
41759276aad6SHugh Dickins 	struct page *page;
417668da9f05SHugh Dickins 	int error;
417768da9f05SHugh Dickins 
417830e6a51dSHui Su 	BUG_ON(!shmem_mapping(mapping));
41799e18eb29SAndres Lagar-Cavilla 	error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4180cfda0526SMike Rapoport 				  gfp, NULL, NULL, NULL);
418168da9f05SHugh Dickins 	if (error)
4182a7605426SYang Shi 		return ERR_PTR(error);
4183a7605426SYang Shi 
418468da9f05SHugh Dickins 	unlock_page(page);
4185a7605426SYang Shi 	if (PageHWPoison(page)) {
4186a7605426SYang Shi 		put_page(page);
4187a7605426SYang Shi 		return ERR_PTR(-EIO);
4188a7605426SYang Shi 	}
4189a7605426SYang Shi 
419068da9f05SHugh Dickins 	return page;
419168da9f05SHugh Dickins #else
419268da9f05SHugh Dickins 	/*
419368da9f05SHugh Dickins 	 * The tiny !SHMEM case uses ramfs without swap
419468da9f05SHugh Dickins 	 */
4195d9d90e5eSHugh Dickins 	return read_cache_page_gfp(mapping, index, gfp);
419668da9f05SHugh Dickins #endif
4197d9d90e5eSHugh Dickins }
4198d9d90e5eSHugh Dickins EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
4199