xref: /openbmc/linux/mm/shmem.c (revision 1e6decf30af5c5c75445ed6ad4e65a26de578a03)
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>
39b56a2d8aSVineeth Remanan Pillai #include <linux/frontswap.h>
40626c3920SAl Viro #include <linux/fs_parser.h>
4186a2f3f2SMiaohe Lin #include <linux/swapfile.h>
42853ac43aSMatt Mackall 
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>
621da177e4SLinus Torvalds #include <linux/blkdev.h>
63bda97eabSHugh Dickins #include <linux/pagevec.h>
6441ffe5d5SHugh Dickins #include <linux/percpu_counter.h>
6583e4fa9cSHugh Dickins #include <linux/falloc.h>
66708e3508SHugh Dickins #include <linux/splice.h>
671da177e4SLinus Torvalds #include <linux/security.h>
681da177e4SLinus Torvalds #include <linux/swapops.h>
691da177e4SLinus Torvalds #include <linux/mempolicy.h>
701da177e4SLinus Torvalds #include <linux/namei.h>
71b00dc3adSHugh Dickins #include <linux/ctype.h>
72304dbdb7SLee Schermerhorn #include <linux/migrate.h>
73c1f60a5aSChristoph Lameter #include <linux/highmem.h>
74680d794bSakpm@linux-foundation.org #include <linux/seq_file.h>
7592562927SMimi Zohar #include <linux/magic.h>
769183df25SDavid Herrmann #include <linux/syscalls.h>
7740e041a2SDavid Herrmann #include <linux/fcntl.h>
789183df25SDavid Herrmann #include <uapi/linux/memfd.h>
79cfda0526SMike Rapoport #include <linux/userfaultfd_k.h>
804c27fe4cSMike Rapoport #include <linux/rmap.h>
812b4db796SAmir Goldstein #include <linux/uuid.h>
82304dbdb7SLee Schermerhorn 
837c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
841da177e4SLinus Torvalds 
85dd56b046SMel Gorman #include "internal.h"
86dd56b046SMel Gorman 
8709cbfeafSKirill A. Shutemov #define BLOCKS_PER_PAGE  (PAGE_SIZE/512)
8809cbfeafSKirill A. Shutemov #define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
891da177e4SLinus Torvalds 
901da177e4SLinus Torvalds /* Pretend that each entry is of this size in directory's i_size */
911da177e4SLinus Torvalds #define BOGO_DIRENT_SIZE 20
921da177e4SLinus Torvalds 
9369f07ec9SHugh Dickins /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
9469f07ec9SHugh Dickins #define SHORT_SYMLINK_LEN 128
9569f07ec9SHugh Dickins 
961aac1400SHugh Dickins /*
97f00cdc6dSHugh Dickins  * shmem_fallocate communicates with shmem_fault or shmem_writepage via
98f00cdc6dSHugh Dickins  * inode->i_private (with i_mutex making sure that it has only one user at
99f00cdc6dSHugh Dickins  * a time): we would prefer not to enlarge the shmem inode just for that.
1001aac1400SHugh Dickins  */
1011aac1400SHugh Dickins struct shmem_falloc {
1028e205f77SHugh Dickins 	wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
1031aac1400SHugh Dickins 	pgoff_t start;		/* start of range currently being fallocated */
1041aac1400SHugh Dickins 	pgoff_t next;		/* the next page offset to be fallocated */
1051aac1400SHugh Dickins 	pgoff_t nr_falloced;	/* how many new pages have been fallocated */
1061aac1400SHugh Dickins 	pgoff_t nr_unswapped;	/* how often writepage refused to swap out */
1071aac1400SHugh Dickins };
1081aac1400SHugh Dickins 
1090b5071ddSAl Viro struct shmem_options {
1100b5071ddSAl Viro 	unsigned long long blocks;
1110b5071ddSAl Viro 	unsigned long long inodes;
1120b5071ddSAl Viro 	struct mempolicy *mpol;
1130b5071ddSAl Viro 	kuid_t uid;
1140b5071ddSAl Viro 	kgid_t gid;
1150b5071ddSAl Viro 	umode_t mode;
116ea3271f7SChris Down 	bool full_inums;
1170b5071ddSAl Viro 	int huge;
1180b5071ddSAl Viro 	int seen;
1190b5071ddSAl Viro #define SHMEM_SEEN_BLOCKS 1
1200b5071ddSAl Viro #define SHMEM_SEEN_INODES 2
1210b5071ddSAl Viro #define SHMEM_SEEN_HUGE 4
122ea3271f7SChris Down #define SHMEM_SEEN_INUMS 8
1230b5071ddSAl Viro };
1240b5071ddSAl Viro 
125b76db735SAndrew Morton #ifdef CONFIG_TMPFS
126680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_blocks(void)
127680d794bSakpm@linux-foundation.org {
128ca79b0c2SArun KS 	return totalram_pages() / 2;
129680d794bSakpm@linux-foundation.org }
130680d794bSakpm@linux-foundation.org 
131680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_inodes(void)
132680d794bSakpm@linux-foundation.org {
133ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
134ca79b0c2SArun KS 
135ca79b0c2SArun KS 	return min(nr_pages - totalhigh_pages(), nr_pages / 2);
136680d794bSakpm@linux-foundation.org }
137b76db735SAndrew Morton #endif
138680d794bSakpm@linux-foundation.org 
139c5bf121eSVineeth Remanan Pillai static int shmem_swapin_page(struct inode *inode, pgoff_t index,
140c5bf121eSVineeth Remanan Pillai 			     struct page **pagep, enum sgp_type sgp,
141c5bf121eSVineeth Remanan Pillai 			     gfp_t gfp, struct vm_area_struct *vma,
142c5bf121eSVineeth Remanan Pillai 			     vm_fault_t *fault_type);
14368da9f05SHugh Dickins static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1449e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp,
145cfda0526SMike Rapoport 		gfp_t gfp, struct vm_area_struct *vma,
1462b740303SSouptick Joarder 		struct vm_fault *vmf, vm_fault_t *fault_type);
14768da9f05SHugh Dickins 
148f3f0e1d2SKirill A. Shutemov int shmem_getpage(struct inode *inode, pgoff_t index,
1499e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp)
15068da9f05SHugh Dickins {
15168da9f05SHugh Dickins 	return shmem_getpage_gfp(inode, index, pagep, sgp,
152cfda0526SMike Rapoport 		mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
15368da9f05SHugh Dickins }
1541da177e4SLinus Torvalds 
1551da177e4SLinus Torvalds static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
1561da177e4SLinus Torvalds {
1571da177e4SLinus Torvalds 	return sb->s_fs_info;
1581da177e4SLinus Torvalds }
1591da177e4SLinus Torvalds 
1601da177e4SLinus Torvalds /*
1611da177e4SLinus Torvalds  * shmem_file_setup pre-accounts the whole fixed size of a VM object,
1621da177e4SLinus Torvalds  * for shared memory and for shared anonymous (/dev/zero) mappings
1631da177e4SLinus Torvalds  * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
1641da177e4SLinus Torvalds  * consistent with the pre-accounting of private mappings ...
1651da177e4SLinus Torvalds  */
1661da177e4SLinus Torvalds static inline int shmem_acct_size(unsigned long flags, loff_t size)
1671da177e4SLinus Torvalds {
1680b0a0806SHugh Dickins 	return (flags & VM_NORESERVE) ?
169191c5424SAl Viro 		0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
1701da177e4SLinus Torvalds }
1711da177e4SLinus Torvalds 
1721da177e4SLinus Torvalds static inline void shmem_unacct_size(unsigned long flags, loff_t size)
1731da177e4SLinus Torvalds {
1740b0a0806SHugh Dickins 	if (!(flags & VM_NORESERVE))
1751da177e4SLinus Torvalds 		vm_unacct_memory(VM_ACCT(size));
1761da177e4SLinus Torvalds }
1771da177e4SLinus Torvalds 
17877142517SKonstantin Khlebnikov static inline int shmem_reacct_size(unsigned long flags,
17977142517SKonstantin Khlebnikov 		loff_t oldsize, loff_t newsize)
18077142517SKonstantin Khlebnikov {
18177142517SKonstantin Khlebnikov 	if (!(flags & VM_NORESERVE)) {
18277142517SKonstantin Khlebnikov 		if (VM_ACCT(newsize) > VM_ACCT(oldsize))
18377142517SKonstantin Khlebnikov 			return security_vm_enough_memory_mm(current->mm,
18477142517SKonstantin Khlebnikov 					VM_ACCT(newsize) - VM_ACCT(oldsize));
18577142517SKonstantin Khlebnikov 		else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
18677142517SKonstantin Khlebnikov 			vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
18777142517SKonstantin Khlebnikov 	}
18877142517SKonstantin Khlebnikov 	return 0;
18977142517SKonstantin Khlebnikov }
19077142517SKonstantin Khlebnikov 
1911da177e4SLinus Torvalds /*
1921da177e4SLinus Torvalds  * ... whereas tmpfs objects are accounted incrementally as
19375edd345SHugh Dickins  * pages are allocated, in order to allow large sparse files.
1941da177e4SLinus Torvalds  * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
1951da177e4SLinus Torvalds  * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
1961da177e4SLinus Torvalds  */
197800d8c63SKirill A. Shutemov static inline int shmem_acct_block(unsigned long flags, long pages)
1981da177e4SLinus Torvalds {
199800d8c63SKirill A. Shutemov 	if (!(flags & VM_NORESERVE))
200800d8c63SKirill A. Shutemov 		return 0;
201800d8c63SKirill A. Shutemov 
202800d8c63SKirill A. Shutemov 	return security_vm_enough_memory_mm(current->mm,
203800d8c63SKirill A. Shutemov 			pages * VM_ACCT(PAGE_SIZE));
2041da177e4SLinus Torvalds }
2051da177e4SLinus Torvalds 
2061da177e4SLinus Torvalds static inline void shmem_unacct_blocks(unsigned long flags, long pages)
2071da177e4SLinus Torvalds {
2080b0a0806SHugh Dickins 	if (flags & VM_NORESERVE)
20909cbfeafSKirill A. Shutemov 		vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
2101da177e4SLinus Torvalds }
2111da177e4SLinus Torvalds 
2120f079694SMike Rapoport static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
2130f079694SMike Rapoport {
2140f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
2150f079694SMike Rapoport 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2160f079694SMike Rapoport 
2170f079694SMike Rapoport 	if (shmem_acct_block(info->flags, pages))
2180f079694SMike Rapoport 		return false;
2190f079694SMike Rapoport 
2200f079694SMike Rapoport 	if (sbinfo->max_blocks) {
2210f079694SMike Rapoport 		if (percpu_counter_compare(&sbinfo->used_blocks,
2220f079694SMike Rapoport 					   sbinfo->max_blocks - pages) > 0)
2230f079694SMike Rapoport 			goto unacct;
2240f079694SMike Rapoport 		percpu_counter_add(&sbinfo->used_blocks, pages);
2250f079694SMike Rapoport 	}
2260f079694SMike Rapoport 
2270f079694SMike Rapoport 	return true;
2280f079694SMike Rapoport 
2290f079694SMike Rapoport unacct:
2300f079694SMike Rapoport 	shmem_unacct_blocks(info->flags, pages);
2310f079694SMike Rapoport 	return false;
2320f079694SMike Rapoport }
2330f079694SMike Rapoport 
2340f079694SMike Rapoport static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
2350f079694SMike Rapoport {
2360f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
2370f079694SMike Rapoport 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2380f079694SMike Rapoport 
2390f079694SMike Rapoport 	if (sbinfo->max_blocks)
2400f079694SMike Rapoport 		percpu_counter_sub(&sbinfo->used_blocks, pages);
2410f079694SMike Rapoport 	shmem_unacct_blocks(info->flags, pages);
2420f079694SMike Rapoport }
2430f079694SMike Rapoport 
244759b9775SHugh Dickins static const struct super_operations shmem_ops;
24530e6a51dSHui Su const struct address_space_operations shmem_aops;
24615ad7cdcSHelge Deller static const struct file_operations shmem_file_operations;
24792e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations;
24892e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations;
24992e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations;
250f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops;
251779750d2SKirill A. Shutemov static struct file_system_type shmem_fs_type;
2521da177e4SLinus Torvalds 
253b0506e48SMike Rapoport bool vma_is_shmem(struct vm_area_struct *vma)
254b0506e48SMike Rapoport {
255b0506e48SMike Rapoport 	return vma->vm_ops == &shmem_vm_ops;
256b0506e48SMike Rapoport }
257b0506e48SMike Rapoport 
2581da177e4SLinus Torvalds static LIST_HEAD(shmem_swaplist);
259cb5f7b9aSHugh Dickins static DEFINE_MUTEX(shmem_swaplist_mutex);
2601da177e4SLinus Torvalds 
261e809d5f0SChris Down /*
262e809d5f0SChris Down  * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
263e809d5f0SChris Down  * produces a novel ino for the newly allocated inode.
264e809d5f0SChris Down  *
265e809d5f0SChris Down  * It may also be called when making a hard link to permit the space needed by
266e809d5f0SChris Down  * each dentry. However, in that case, no new inode number is needed since that
267e809d5f0SChris Down  * internally draws from another pool of inode numbers (currently global
268e809d5f0SChris Down  * get_next_ino()). This case is indicated by passing NULL as inop.
269e809d5f0SChris Down  */
270e809d5f0SChris Down #define SHMEM_INO_BATCH 1024
271e809d5f0SChris Down static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
2725b04c689SPavel Emelyanov {
2735b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
274e809d5f0SChris Down 	ino_t ino;
275e809d5f0SChris Down 
276e809d5f0SChris Down 	if (!(sb->s_flags & SB_KERNMOUNT)) {
277bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);
278bb3e96d6SByron Stanoszek 		if (sbinfo->max_inodes) {
2795b04c689SPavel Emelyanov 			if (!sbinfo->free_inodes) {
280bf11b9a8SSebastian Andrzej Siewior 				raw_spin_unlock(&sbinfo->stat_lock);
2815b04c689SPavel Emelyanov 				return -ENOSPC;
2825b04c689SPavel Emelyanov 			}
2835b04c689SPavel Emelyanov 			sbinfo->free_inodes--;
284bb3e96d6SByron Stanoszek 		}
285e809d5f0SChris Down 		if (inop) {
286e809d5f0SChris Down 			ino = sbinfo->next_ino++;
287e809d5f0SChris Down 			if (unlikely(is_zero_ino(ino)))
288e809d5f0SChris Down 				ino = sbinfo->next_ino++;
289ea3271f7SChris Down 			if (unlikely(!sbinfo->full_inums &&
290ea3271f7SChris Down 				     ino > UINT_MAX)) {
291e809d5f0SChris Down 				/*
292e809d5f0SChris Down 				 * Emulate get_next_ino uint wraparound for
293e809d5f0SChris Down 				 * compatibility
294e809d5f0SChris Down 				 */
295ea3271f7SChris Down 				if (IS_ENABLED(CONFIG_64BIT))
296ea3271f7SChris Down 					pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
297ea3271f7SChris Down 						__func__, MINOR(sb->s_dev));
298ea3271f7SChris Down 				sbinfo->next_ino = 1;
299ea3271f7SChris Down 				ino = sbinfo->next_ino++;
3005b04c689SPavel Emelyanov 			}
301e809d5f0SChris Down 			*inop = ino;
302e809d5f0SChris Down 		}
303bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
304e809d5f0SChris Down 	} else if (inop) {
305e809d5f0SChris Down 		/*
306e809d5f0SChris Down 		 * __shmem_file_setup, one of our callers, is lock-free: it
307e809d5f0SChris Down 		 * doesn't hold stat_lock in shmem_reserve_inode since
308e809d5f0SChris Down 		 * max_inodes is always 0, and is called from potentially
309e809d5f0SChris Down 		 * unknown contexts. As such, use a per-cpu batched allocator
310e809d5f0SChris Down 		 * which doesn't require the per-sb stat_lock unless we are at
311e809d5f0SChris Down 		 * the batch boundary.
312ea3271f7SChris Down 		 *
313ea3271f7SChris Down 		 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
314ea3271f7SChris Down 		 * shmem mounts are not exposed to userspace, so we don't need
315ea3271f7SChris Down 		 * to worry about things like glibc compatibility.
316e809d5f0SChris Down 		 */
317e809d5f0SChris Down 		ino_t *next_ino;
318bf11b9a8SSebastian Andrzej Siewior 
319e809d5f0SChris Down 		next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
320e809d5f0SChris Down 		ino = *next_ino;
321e809d5f0SChris Down 		if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
322bf11b9a8SSebastian Andrzej Siewior 			raw_spin_lock(&sbinfo->stat_lock);
323e809d5f0SChris Down 			ino = sbinfo->next_ino;
324e809d5f0SChris Down 			sbinfo->next_ino += SHMEM_INO_BATCH;
325bf11b9a8SSebastian Andrzej Siewior 			raw_spin_unlock(&sbinfo->stat_lock);
326e809d5f0SChris Down 			if (unlikely(is_zero_ino(ino)))
327e809d5f0SChris Down 				ino++;
328e809d5f0SChris Down 		}
329e809d5f0SChris Down 		*inop = ino;
330e809d5f0SChris Down 		*next_ino = ++ino;
331e809d5f0SChris Down 		put_cpu();
332e809d5f0SChris Down 	}
333e809d5f0SChris Down 
3345b04c689SPavel Emelyanov 	return 0;
3355b04c689SPavel Emelyanov }
3365b04c689SPavel Emelyanov 
3375b04c689SPavel Emelyanov static void shmem_free_inode(struct super_block *sb)
3385b04c689SPavel Emelyanov {
3395b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3405b04c689SPavel Emelyanov 	if (sbinfo->max_inodes) {
341bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);
3425b04c689SPavel Emelyanov 		sbinfo->free_inodes++;
343bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
3445b04c689SPavel Emelyanov 	}
3455b04c689SPavel Emelyanov }
3465b04c689SPavel Emelyanov 
34746711810SRandy Dunlap /**
34841ffe5d5SHugh Dickins  * shmem_recalc_inode - recalculate the block usage of an inode
3491da177e4SLinus Torvalds  * @inode: inode to recalc
3501da177e4SLinus Torvalds  *
3511da177e4SLinus Torvalds  * We have to calculate the free blocks since the mm can drop
3521da177e4SLinus Torvalds  * undirtied hole pages behind our back.
3531da177e4SLinus Torvalds  *
3541da177e4SLinus Torvalds  * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
3551da177e4SLinus Torvalds  * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
3561da177e4SLinus Torvalds  *
3571da177e4SLinus Torvalds  * It has to be called with the spinlock held.
3581da177e4SLinus Torvalds  */
3591da177e4SLinus Torvalds static void shmem_recalc_inode(struct inode *inode)
3601da177e4SLinus Torvalds {
3611da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
3621da177e4SLinus Torvalds 	long freed;
3631da177e4SLinus Torvalds 
3641da177e4SLinus Torvalds 	freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
3651da177e4SLinus Torvalds 	if (freed > 0) {
3661da177e4SLinus Torvalds 		info->alloced -= freed;
36754af6042SHugh Dickins 		inode->i_blocks -= freed * BLOCKS_PER_PAGE;
3680f079694SMike Rapoport 		shmem_inode_unacct_blocks(inode, freed);
3691da177e4SLinus Torvalds 	}
3701da177e4SLinus Torvalds }
3711da177e4SLinus Torvalds 
372800d8c63SKirill A. Shutemov bool shmem_charge(struct inode *inode, long pages)
373800d8c63SKirill A. Shutemov {
374800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
3754595ef88SKirill A. Shutemov 	unsigned long flags;
376800d8c63SKirill A. Shutemov 
3770f079694SMike Rapoport 	if (!shmem_inode_acct_block(inode, pages))
378800d8c63SKirill A. Shutemov 		return false;
379b1cc94abSMike Rapoport 
380aaa52e34SHugh Dickins 	/* nrpages adjustment first, then shmem_recalc_inode() when balanced */
381aaa52e34SHugh Dickins 	inode->i_mapping->nrpages += pages;
382aaa52e34SHugh Dickins 
3834595ef88SKirill A. Shutemov 	spin_lock_irqsave(&info->lock, flags);
384800d8c63SKirill A. Shutemov 	info->alloced += pages;
385800d8c63SKirill A. Shutemov 	inode->i_blocks += pages * BLOCKS_PER_PAGE;
386800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
3874595ef88SKirill A. Shutemov 	spin_unlock_irqrestore(&info->lock, flags);
388800d8c63SKirill A. Shutemov 
389800d8c63SKirill A. Shutemov 	return true;
390800d8c63SKirill A. Shutemov }
391800d8c63SKirill A. Shutemov 
392800d8c63SKirill A. Shutemov void shmem_uncharge(struct inode *inode, long pages)
393800d8c63SKirill A. Shutemov {
394800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
3954595ef88SKirill A. Shutemov 	unsigned long flags;
396800d8c63SKirill A. Shutemov 
397aaa52e34SHugh Dickins 	/* nrpages adjustment done by __delete_from_page_cache() or caller */
398aaa52e34SHugh Dickins 
3994595ef88SKirill A. Shutemov 	spin_lock_irqsave(&info->lock, flags);
400800d8c63SKirill A. Shutemov 	info->alloced -= pages;
401800d8c63SKirill A. Shutemov 	inode->i_blocks -= pages * BLOCKS_PER_PAGE;
402800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
4034595ef88SKirill A. Shutemov 	spin_unlock_irqrestore(&info->lock, flags);
404800d8c63SKirill A. Shutemov 
4050f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, pages);
406800d8c63SKirill A. Shutemov }
407800d8c63SKirill A. Shutemov 
4087a5d0fbbSHugh Dickins /*
40962f945b6SMatthew Wilcox  * Replace item expected in xarray by a new item, while holding xa_lock.
4107a5d0fbbSHugh Dickins  */
41162f945b6SMatthew Wilcox static int shmem_replace_entry(struct address_space *mapping,
4127a5d0fbbSHugh Dickins 			pgoff_t index, void *expected, void *replacement)
4137a5d0fbbSHugh Dickins {
41462f945b6SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, index);
4156dbaf22cSJohannes Weiner 	void *item;
4167a5d0fbbSHugh Dickins 
4177a5d0fbbSHugh Dickins 	VM_BUG_ON(!expected);
4186dbaf22cSJohannes Weiner 	VM_BUG_ON(!replacement);
41962f945b6SMatthew Wilcox 	item = xas_load(&xas);
4207a5d0fbbSHugh Dickins 	if (item != expected)
4217a5d0fbbSHugh Dickins 		return -ENOENT;
42262f945b6SMatthew Wilcox 	xas_store(&xas, replacement);
4237a5d0fbbSHugh Dickins 	return 0;
4247a5d0fbbSHugh Dickins }
4257a5d0fbbSHugh Dickins 
4267a5d0fbbSHugh Dickins /*
427d1899228SHugh Dickins  * Sometimes, before we decide whether to proceed or to fail, we must check
428d1899228SHugh Dickins  * that an entry was not already brought back from swap by a racing thread.
429d1899228SHugh Dickins  *
430d1899228SHugh Dickins  * Checking page is not enough: by the time a SwapCache page is locked, it
431d1899228SHugh Dickins  * might be reused, and again be SwapCache, using the same swap as before.
432d1899228SHugh Dickins  */
433d1899228SHugh Dickins static bool shmem_confirm_swap(struct address_space *mapping,
434d1899228SHugh Dickins 			       pgoff_t index, swp_entry_t swap)
435d1899228SHugh Dickins {
436a12831bfSMatthew Wilcox 	return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
437d1899228SHugh Dickins }
438d1899228SHugh Dickins 
439d1899228SHugh Dickins /*
4405a6e75f8SKirill A. Shutemov  * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
4415a6e75f8SKirill A. Shutemov  *
4425a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_NEVER:
4435a6e75f8SKirill A. Shutemov  *	disables huge pages for the mount;
4445a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ALWAYS:
4455a6e75f8SKirill A. Shutemov  *	enables huge pages for the mount;
4465a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_WITHIN_SIZE:
4475a6e75f8SKirill A. Shutemov  *	only allocate huge pages if the page will be fully within i_size,
4485a6e75f8SKirill A. Shutemov  *	also respect fadvise()/madvise() hints;
4495a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ADVISE:
4505a6e75f8SKirill A. Shutemov  *	only allocate huge pages if requested with fadvise()/madvise();
4515a6e75f8SKirill A. Shutemov  */
4525a6e75f8SKirill A. Shutemov 
4535a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_NEVER	0
4545a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ALWAYS	1
4555a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_WITHIN_SIZE	2
4565a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ADVISE	3
4575a6e75f8SKirill A. Shutemov 
4585a6e75f8SKirill A. Shutemov /*
4595a6e75f8SKirill A. Shutemov  * Special values.
4605a6e75f8SKirill A. Shutemov  * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
4615a6e75f8SKirill A. Shutemov  *
4625a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_DENY:
4635a6e75f8SKirill A. Shutemov  *	disables huge on shm_mnt and all mounts, for emergency use;
4645a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_FORCE:
4655a6e75f8SKirill A. Shutemov  *	enables huge on shm_mnt and all mounts, w/o needing option, for testing;
4665a6e75f8SKirill A. Shutemov  *
4675a6e75f8SKirill A. Shutemov  */
4685a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_DENY		(-1)
4695a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_FORCE	(-2)
4705a6e75f8SKirill A. Shutemov 
471396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4725a6e75f8SKirill A. Shutemov /* ifdef here to avoid bloating shmem.o when not necessary */
4735a6e75f8SKirill A. Shutemov 
4745e6e5a12SHugh Dickins static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER;
4755a6e75f8SKirill A. Shutemov 
4765e6e5a12SHugh Dickins bool shmem_is_huge(struct vm_area_struct *vma,
4775e6e5a12SHugh Dickins 		   struct inode *inode, pgoff_t index)
478c852023eSHugh Dickins {
479c852023eSHugh Dickins 	loff_t i_size;
480c852023eSHugh Dickins 
4815e6e5a12SHugh Dickins 	if (shmem_huge == SHMEM_HUGE_DENY)
4825e6e5a12SHugh Dickins 		return false;
4835e6e5a12SHugh Dickins 	if (vma && ((vma->vm_flags & VM_NOHUGEPAGE) ||
4845e6e5a12SHugh Dickins 	    test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags)))
485c852023eSHugh Dickins 		return false;
486c852023eSHugh Dickins 	if (shmem_huge == SHMEM_HUGE_FORCE)
487c852023eSHugh Dickins 		return true;
4885e6e5a12SHugh Dickins 
4895e6e5a12SHugh Dickins 	switch (SHMEM_SB(inode->i_sb)->huge) {
490c852023eSHugh Dickins 	case SHMEM_HUGE_ALWAYS:
491c852023eSHugh Dickins 		return true;
492c852023eSHugh Dickins 	case SHMEM_HUGE_WITHIN_SIZE:
4935e6e5a12SHugh Dickins 		index = round_up(index, HPAGE_PMD_NR);
494c852023eSHugh Dickins 		i_size = round_up(i_size_read(inode), PAGE_SIZE);
4955e6e5a12SHugh Dickins 		if (i_size >= HPAGE_PMD_SIZE && (i_size >> PAGE_SHIFT) >= index)
496c852023eSHugh Dickins 			return true;
497c852023eSHugh Dickins 		fallthrough;
498c852023eSHugh Dickins 	case SHMEM_HUGE_ADVISE:
4995e6e5a12SHugh Dickins 		if (vma && (vma->vm_flags & VM_HUGEPAGE))
5005e6e5a12SHugh Dickins 			return true;
5015e6e5a12SHugh Dickins 		fallthrough;
502c852023eSHugh Dickins 	default:
503c852023eSHugh Dickins 		return false;
504c852023eSHugh Dickins 	}
505c852023eSHugh Dickins }
506c852023eSHugh Dickins 
507e5f2249aSArnd Bergmann #if defined(CONFIG_SYSFS)
5085a6e75f8SKirill A. Shutemov static int shmem_parse_huge(const char *str)
5095a6e75f8SKirill A. Shutemov {
5105a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "never"))
5115a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_NEVER;
5125a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "always"))
5135a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ALWAYS;
5145a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "within_size"))
5155a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_WITHIN_SIZE;
5165a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "advise"))
5175a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ADVISE;
5185a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "deny"))
5195a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_DENY;
5205a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "force"))
5215a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_FORCE;
5225a6e75f8SKirill A. Shutemov 	return -EINVAL;
5235a6e75f8SKirill A. Shutemov }
524e5f2249aSArnd Bergmann #endif
5255a6e75f8SKirill A. Shutemov 
526e5f2249aSArnd Bergmann #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
5275a6e75f8SKirill A. Shutemov static const char *shmem_format_huge(int huge)
5285a6e75f8SKirill A. Shutemov {
5295a6e75f8SKirill A. Shutemov 	switch (huge) {
5305a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_NEVER:
5315a6e75f8SKirill A. Shutemov 		return "never";
5325a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ALWAYS:
5335a6e75f8SKirill A. Shutemov 		return "always";
5345a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_WITHIN_SIZE:
5355a6e75f8SKirill A. Shutemov 		return "within_size";
5365a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ADVISE:
5375a6e75f8SKirill A. Shutemov 		return "advise";
5385a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_DENY:
5395a6e75f8SKirill A. Shutemov 		return "deny";
5405a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_FORCE:
5415a6e75f8SKirill A. Shutemov 		return "force";
5425a6e75f8SKirill A. Shutemov 	default:
5435a6e75f8SKirill A. Shutemov 		VM_BUG_ON(1);
5445a6e75f8SKirill A. Shutemov 		return "bad_val";
5455a6e75f8SKirill A. Shutemov 	}
5465a6e75f8SKirill A. Shutemov }
547f1f5929cSJérémy Lefaure #endif
5485a6e75f8SKirill A. Shutemov 
549779750d2SKirill A. Shutemov static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
550779750d2SKirill A. Shutemov 		struct shrink_control *sc, unsigned long nr_to_split)
551779750d2SKirill A. Shutemov {
552779750d2SKirill A. Shutemov 	LIST_HEAD(list), *pos, *next;
553253fd0f0SKirill A. Shutemov 	LIST_HEAD(to_remove);
554779750d2SKirill A. Shutemov 	struct inode *inode;
555779750d2SKirill A. Shutemov 	struct shmem_inode_info *info;
556779750d2SKirill A. Shutemov 	struct page *page;
557779750d2SKirill A. Shutemov 	unsigned long batch = sc ? sc->nr_to_scan : 128;
558779750d2SKirill A. Shutemov 	int removed = 0, split = 0;
559779750d2SKirill A. Shutemov 
560779750d2SKirill A. Shutemov 	if (list_empty(&sbinfo->shrinklist))
561779750d2SKirill A. Shutemov 		return SHRINK_STOP;
562779750d2SKirill A. Shutemov 
563779750d2SKirill A. Shutemov 	spin_lock(&sbinfo->shrinklist_lock);
564779750d2SKirill A. Shutemov 	list_for_each_safe(pos, next, &sbinfo->shrinklist) {
565779750d2SKirill A. Shutemov 		info = list_entry(pos, struct shmem_inode_info, shrinklist);
566779750d2SKirill A. Shutemov 
567779750d2SKirill A. Shutemov 		/* pin the inode */
568779750d2SKirill A. Shutemov 		inode = igrab(&info->vfs_inode);
569779750d2SKirill A. Shutemov 
570779750d2SKirill A. Shutemov 		/* inode is about to be evicted */
571779750d2SKirill A. Shutemov 		if (!inode) {
572779750d2SKirill A. Shutemov 			list_del_init(&info->shrinklist);
573779750d2SKirill A. Shutemov 			removed++;
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 			removed++;
582779750d2SKirill A. Shutemov 			goto next;
583779750d2SKirill A. Shutemov 		}
584779750d2SKirill A. Shutemov 
585779750d2SKirill A. Shutemov 		list_move(&info->shrinklist, &list);
586779750d2SKirill A. Shutemov next:
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)
606b3cd54b2SKirill A. Shutemov 			goto leave;
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 		/*
620b3cd54b2SKirill A. Shutemov 		 * Leave the inode on the list if we failed to lock
621b3cd54b2SKirill A. Shutemov 		 * 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);
628b3cd54b2SKirill A. Shutemov 			goto leave;
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 
635b3cd54b2SKirill A. Shutemov 		/* If split failed leave the inode on the list */
636b3cd54b2SKirill A. Shutemov 		if (ret)
637b3cd54b2SKirill A. Shutemov 			goto leave;
638779750d2SKirill A. Shutemov 
639779750d2SKirill A. Shutemov 		split++;
640779750d2SKirill A. Shutemov drop:
641779750d2SKirill A. Shutemov 		list_del_init(&info->shrinklist);
642779750d2SKirill A. Shutemov 		removed++;
643b3cd54b2SKirill A. Shutemov leave:
644779750d2SKirill A. Shutemov 		iput(inode);
645779750d2SKirill A. Shutemov 	}
646779750d2SKirill A. Shutemov 
647779750d2SKirill A. Shutemov 	spin_lock(&sbinfo->shrinklist_lock);
648779750d2SKirill A. Shutemov 	list_splice_tail(&list, &sbinfo->shrinklist);
649779750d2SKirill A. Shutemov 	sbinfo->shrinklist_len -= removed;
650779750d2SKirill A. Shutemov 	spin_unlock(&sbinfo->shrinklist_lock);
651779750d2SKirill A. Shutemov 
652779750d2SKirill A. Shutemov 	return split;
653779750d2SKirill A. Shutemov }
654779750d2SKirill A. Shutemov 
655779750d2SKirill A. Shutemov static long shmem_unused_huge_scan(struct super_block *sb,
656779750d2SKirill A. Shutemov 		struct shrink_control *sc)
657779750d2SKirill A. Shutemov {
658779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
659779750d2SKirill A. Shutemov 
660779750d2SKirill A. Shutemov 	if (!READ_ONCE(sbinfo->shrinklist_len))
661779750d2SKirill A. Shutemov 		return SHRINK_STOP;
662779750d2SKirill A. Shutemov 
663779750d2SKirill A. Shutemov 	return shmem_unused_huge_shrink(sbinfo, sc, 0);
664779750d2SKirill A. Shutemov }
665779750d2SKirill A. Shutemov 
666779750d2SKirill A. Shutemov static long shmem_unused_huge_count(struct super_block *sb,
667779750d2SKirill A. Shutemov 		struct shrink_control *sc)
668779750d2SKirill A. Shutemov {
669779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
670779750d2SKirill A. Shutemov 	return READ_ONCE(sbinfo->shrinklist_len);
671779750d2SKirill A. Shutemov }
672396bcc52SMatthew Wilcox (Oracle) #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
6735a6e75f8SKirill A. Shutemov 
6745a6e75f8SKirill A. Shutemov #define shmem_huge SHMEM_HUGE_DENY
6755a6e75f8SKirill A. Shutemov 
6765e6e5a12SHugh Dickins bool shmem_is_huge(struct vm_area_struct *vma,
6775e6e5a12SHugh Dickins 		   struct inode *inode, pgoff_t index)
6785e6e5a12SHugh Dickins {
6795e6e5a12SHugh Dickins 	return false;
6805e6e5a12SHugh Dickins }
6815e6e5a12SHugh Dickins 
682779750d2SKirill A. Shutemov static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
683779750d2SKirill A. Shutemov 		struct shrink_control *sc, unsigned long nr_to_split)
684779750d2SKirill A. Shutemov {
685779750d2SKirill A. Shutemov 	return 0;
686779750d2SKirill A. Shutemov }
687396bcc52SMatthew Wilcox (Oracle) #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
6885a6e75f8SKirill A. Shutemov 
6895a6e75f8SKirill A. Shutemov /*
69046f65ec1SHugh Dickins  * Like add_to_page_cache_locked, but error if expected item has gone.
69146f65ec1SHugh Dickins  */
69246f65ec1SHugh Dickins static int shmem_add_to_page_cache(struct page *page,
69346f65ec1SHugh Dickins 				   struct address_space *mapping,
6943fea5a49SJohannes Weiner 				   pgoff_t index, void *expected, gfp_t gfp,
6953fea5a49SJohannes Weiner 				   struct mm_struct *charge_mm)
69646f65ec1SHugh Dickins {
697552446a4SMatthew Wilcox 	XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
698552446a4SMatthew Wilcox 	unsigned long i = 0;
699d8c6546bSMatthew Wilcox (Oracle) 	unsigned long nr = compound_nr(page);
7003fea5a49SJohannes Weiner 	int error;
70146f65ec1SHugh Dickins 
702800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageTail(page), page);
703800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(index != round_down(index, nr), page);
704309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
705309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
706800d8c63SKirill A. Shutemov 	VM_BUG_ON(expected && PageTransHuge(page));
70746f65ec1SHugh Dickins 
708800d8c63SKirill A. Shutemov 	page_ref_add(page, nr);
70946f65ec1SHugh Dickins 	page->mapping = mapping;
71046f65ec1SHugh Dickins 	page->index = index;
71146f65ec1SHugh Dickins 
7124c6355b2SJohannes Weiner 	if (!PageSwapCache(page)) {
713d9eb1ea2SJohannes Weiner 		error = mem_cgroup_charge(page, charge_mm, gfp);
7143fea5a49SJohannes Weiner 		if (error) {
7154c6355b2SJohannes Weiner 			if (PageTransHuge(page)) {
7163fea5a49SJohannes Weiner 				count_vm_event(THP_FILE_FALLBACK);
7173fea5a49SJohannes Weiner 				count_vm_event(THP_FILE_FALLBACK_CHARGE);
7183fea5a49SJohannes Weiner 			}
7193fea5a49SJohannes Weiner 			goto error;
7203fea5a49SJohannes Weiner 		}
7214c6355b2SJohannes Weiner 	}
7223fea5a49SJohannes Weiner 	cgroup_throttle_swaprate(page, gfp);
7233fea5a49SJohannes Weiner 
724552446a4SMatthew Wilcox 	do {
725552446a4SMatthew Wilcox 		void *entry;
726552446a4SMatthew Wilcox 		xas_lock_irq(&xas);
727552446a4SMatthew Wilcox 		entry = xas_find_conflict(&xas);
728552446a4SMatthew Wilcox 		if (entry != expected)
729552446a4SMatthew Wilcox 			xas_set_err(&xas, -EEXIST);
730552446a4SMatthew Wilcox 		xas_create_range(&xas);
731552446a4SMatthew Wilcox 		if (xas_error(&xas))
732552446a4SMatthew Wilcox 			goto unlock;
733552446a4SMatthew Wilcox next:
7344101196bSMatthew Wilcox (Oracle) 		xas_store(&xas, page);
735552446a4SMatthew Wilcox 		if (++i < nr) {
736552446a4SMatthew Wilcox 			xas_next(&xas);
737552446a4SMatthew Wilcox 			goto next;
738552446a4SMatthew Wilcox 		}
739800d8c63SKirill A. Shutemov 		if (PageTransHuge(page)) {
740800d8c63SKirill A. Shutemov 			count_vm_event(THP_FILE_ALLOC);
74157b2847dSMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_THPS, nr);
742552446a4SMatthew Wilcox 		}
743552446a4SMatthew Wilcox 		mapping->nrpages += nr;
7440d1c2072SJohannes Weiner 		__mod_lruvec_page_state(page, NR_FILE_PAGES, nr);
7450d1c2072SJohannes Weiner 		__mod_lruvec_page_state(page, NR_SHMEM, nr);
746552446a4SMatthew Wilcox unlock:
747552446a4SMatthew Wilcox 		xas_unlock_irq(&xas);
748552446a4SMatthew Wilcox 	} while (xas_nomem(&xas, gfp));
749552446a4SMatthew Wilcox 
750552446a4SMatthew Wilcox 	if (xas_error(&xas)) {
7513fea5a49SJohannes Weiner 		error = xas_error(&xas);
7523fea5a49SJohannes Weiner 		goto error;
75346f65ec1SHugh Dickins 	}
754552446a4SMatthew Wilcox 
755552446a4SMatthew Wilcox 	return 0;
7563fea5a49SJohannes Weiner error:
7573fea5a49SJohannes Weiner 	page->mapping = NULL;
7583fea5a49SJohannes Weiner 	page_ref_sub(page, nr);
7593fea5a49SJohannes Weiner 	return error;
76046f65ec1SHugh Dickins }
76146f65ec1SHugh Dickins 
76246f65ec1SHugh Dickins /*
7636922c0c7SHugh Dickins  * Like delete_from_page_cache, but substitutes swap for page.
7646922c0c7SHugh Dickins  */
7656922c0c7SHugh Dickins static void shmem_delete_from_page_cache(struct page *page, void *radswap)
7666922c0c7SHugh Dickins {
7676922c0c7SHugh Dickins 	struct address_space *mapping = page->mapping;
7686922c0c7SHugh Dickins 	int error;
7696922c0c7SHugh Dickins 
770800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageCompound(page), page);
771800d8c63SKirill A. Shutemov 
772b93b0163SMatthew Wilcox 	xa_lock_irq(&mapping->i_pages);
77362f945b6SMatthew Wilcox 	error = shmem_replace_entry(mapping, page->index, page, radswap);
7746922c0c7SHugh Dickins 	page->mapping = NULL;
7756922c0c7SHugh Dickins 	mapping->nrpages--;
7760d1c2072SJohannes Weiner 	__dec_lruvec_page_state(page, NR_FILE_PAGES);
7770d1c2072SJohannes Weiner 	__dec_lruvec_page_state(page, NR_SHMEM);
778b93b0163SMatthew Wilcox 	xa_unlock_irq(&mapping->i_pages);
77909cbfeafSKirill A. Shutemov 	put_page(page);
7806922c0c7SHugh Dickins 	BUG_ON(error);
7816922c0c7SHugh Dickins }
7826922c0c7SHugh Dickins 
7836922c0c7SHugh Dickins /*
784c121d3bbSMatthew Wilcox  * Remove swap entry from page cache, free the swap and its page cache.
7857a5d0fbbSHugh Dickins  */
7867a5d0fbbSHugh Dickins static int shmem_free_swap(struct address_space *mapping,
7877a5d0fbbSHugh Dickins 			   pgoff_t index, void *radswap)
7887a5d0fbbSHugh Dickins {
7896dbaf22cSJohannes Weiner 	void *old;
7907a5d0fbbSHugh Dickins 
79155f3f7eaSMatthew Wilcox 	old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
7926dbaf22cSJohannes Weiner 	if (old != radswap)
7936dbaf22cSJohannes Weiner 		return -ENOENT;
7947a5d0fbbSHugh Dickins 	free_swap_and_cache(radix_to_swp_entry(radswap));
7956dbaf22cSJohannes Weiner 	return 0;
7967a5d0fbbSHugh Dickins }
7977a5d0fbbSHugh Dickins 
7987a5d0fbbSHugh Dickins /*
7996a15a370SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
80048131e03SVlastimil Babka  * given offsets are swapped out.
8016a15a370SVlastimil Babka  *
802b93b0163SMatthew Wilcox  * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
8036a15a370SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
8046a15a370SVlastimil Babka  */
80548131e03SVlastimil Babka unsigned long shmem_partial_swap_usage(struct address_space *mapping,
80648131e03SVlastimil Babka 						pgoff_t start, pgoff_t end)
8076a15a370SVlastimil Babka {
8087ae3424fSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start);
8096a15a370SVlastimil Babka 	struct page *page;
81048131e03SVlastimil Babka 	unsigned long swapped = 0;
8116a15a370SVlastimil Babka 
8126a15a370SVlastimil Babka 	rcu_read_lock();
8137ae3424fSMatthew Wilcox 	xas_for_each(&xas, page, end - 1) {
8147ae3424fSMatthew Wilcox 		if (xas_retry(&xas, page))
8152cf938aaSMatthew Wilcox 			continue;
8163159f943SMatthew Wilcox 		if (xa_is_value(page))
8176a15a370SVlastimil Babka 			swapped++;
8186a15a370SVlastimil Babka 
8196a15a370SVlastimil Babka 		if (need_resched()) {
8207ae3424fSMatthew Wilcox 			xas_pause(&xas);
8216a15a370SVlastimil Babka 			cond_resched_rcu();
8226a15a370SVlastimil Babka 		}
8236a15a370SVlastimil Babka 	}
8246a15a370SVlastimil Babka 
8256a15a370SVlastimil Babka 	rcu_read_unlock();
8266a15a370SVlastimil Babka 
8276a15a370SVlastimil Babka 	return swapped << PAGE_SHIFT;
8286a15a370SVlastimil Babka }
8296a15a370SVlastimil Babka 
8306a15a370SVlastimil Babka /*
83148131e03SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
83248131e03SVlastimil Babka  * given vma is swapped out.
83348131e03SVlastimil Babka  *
834b93b0163SMatthew Wilcox  * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
83548131e03SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
83648131e03SVlastimil Babka  */
83748131e03SVlastimil Babka unsigned long shmem_swap_usage(struct vm_area_struct *vma)
83848131e03SVlastimil Babka {
83948131e03SVlastimil Babka 	struct inode *inode = file_inode(vma->vm_file);
84048131e03SVlastimil Babka 	struct shmem_inode_info *info = SHMEM_I(inode);
84148131e03SVlastimil Babka 	struct address_space *mapping = inode->i_mapping;
84248131e03SVlastimil Babka 	unsigned long swapped;
84348131e03SVlastimil Babka 
84448131e03SVlastimil Babka 	/* Be careful as we don't hold info->lock */
84548131e03SVlastimil Babka 	swapped = READ_ONCE(info->swapped);
84648131e03SVlastimil Babka 
84748131e03SVlastimil Babka 	/*
84848131e03SVlastimil Babka 	 * The easier cases are when the shmem object has nothing in swap, or
84948131e03SVlastimil Babka 	 * the vma maps it whole. Then we can simply use the stats that we
85048131e03SVlastimil Babka 	 * already track.
85148131e03SVlastimil Babka 	 */
85248131e03SVlastimil Babka 	if (!swapped)
85348131e03SVlastimil Babka 		return 0;
85448131e03SVlastimil Babka 
85548131e03SVlastimil Babka 	if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
85648131e03SVlastimil Babka 		return swapped << PAGE_SHIFT;
85748131e03SVlastimil Babka 
85848131e03SVlastimil Babka 	/* Here comes the more involved part */
85948131e03SVlastimil Babka 	return shmem_partial_swap_usage(mapping,
86048131e03SVlastimil Babka 			linear_page_index(vma, vma->vm_start),
86148131e03SVlastimil Babka 			linear_page_index(vma, vma->vm_end));
86248131e03SVlastimil Babka }
86348131e03SVlastimil Babka 
86448131e03SVlastimil Babka /*
86524513264SHugh Dickins  * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
86624513264SHugh Dickins  */
86724513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
86824513264SHugh Dickins {
86924513264SHugh Dickins 	struct pagevec pvec;
87024513264SHugh Dickins 	pgoff_t index = 0;
87124513264SHugh Dickins 
87286679820SMel Gorman 	pagevec_init(&pvec);
87324513264SHugh Dickins 	/*
87424513264SHugh Dickins 	 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
87524513264SHugh Dickins 	 */
87624513264SHugh Dickins 	while (!mapping_unevictable(mapping)) {
87796888e0aSMatthew Wilcox (Oracle) 		if (!pagevec_lookup(&pvec, mapping, &index))
87824513264SHugh Dickins 			break;
87964e3d12fSKuo-Hsin Yang 		check_move_unevictable_pages(&pvec);
88024513264SHugh Dickins 		pagevec_release(&pvec);
88124513264SHugh Dickins 		cond_resched();
88224513264SHugh Dickins 	}
8837a5d0fbbSHugh Dickins }
8847a5d0fbbSHugh Dickins 
8857a5d0fbbSHugh Dickins /*
88671725ed1SHugh Dickins  * Check whether a hole-punch or truncation needs to split a huge page,
88771725ed1SHugh Dickins  * returning true if no split was required, or the split has been successful.
88871725ed1SHugh Dickins  *
88971725ed1SHugh Dickins  * Eviction (or truncation to 0 size) should never need to split a huge page;
89071725ed1SHugh Dickins  * but in rare cases might do so, if shmem_undo_range() failed to trylock on
89171725ed1SHugh Dickins  * head, and then succeeded to trylock on tail.
89271725ed1SHugh Dickins  *
89371725ed1SHugh Dickins  * A split can only succeed when there are no additional references on the
89471725ed1SHugh Dickins  * huge page: so the split below relies upon find_get_entries() having stopped
89571725ed1SHugh Dickins  * when it found a subpage of the huge page, without getting further references.
89671725ed1SHugh Dickins  */
89771725ed1SHugh Dickins static bool shmem_punch_compound(struct page *page, pgoff_t start, pgoff_t end)
89871725ed1SHugh Dickins {
89971725ed1SHugh Dickins 	if (!PageTransCompound(page))
90071725ed1SHugh Dickins 		return true;
90171725ed1SHugh Dickins 
90271725ed1SHugh Dickins 	/* Just proceed to delete a huge page wholly within the range punched */
90371725ed1SHugh Dickins 	if (PageHead(page) &&
90471725ed1SHugh Dickins 	    page->index >= start && page->index + HPAGE_PMD_NR <= end)
90571725ed1SHugh Dickins 		return true;
90671725ed1SHugh Dickins 
90771725ed1SHugh Dickins 	/* Try to split huge page, so we can truly punch the hole or truncate */
90871725ed1SHugh Dickins 	return split_huge_page(page) >= 0;
90971725ed1SHugh Dickins }
91071725ed1SHugh Dickins 
91171725ed1SHugh Dickins /*
9127f4446eeSMatthew Wilcox  * Remove range of pages and swap entries from page cache, and free them.
9131635f6a7SHugh Dickins  * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
9147a5d0fbbSHugh Dickins  */
9151635f6a7SHugh Dickins static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
9161635f6a7SHugh Dickins 								 bool unfalloc)
9171da177e4SLinus Torvalds {
918285b2c4fSHugh Dickins 	struct address_space *mapping = inode->i_mapping;
9191da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
92009cbfeafSKirill A. Shutemov 	pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
92109cbfeafSKirill A. Shutemov 	pgoff_t end = (lend + 1) >> PAGE_SHIFT;
92209cbfeafSKirill A. Shutemov 	unsigned int partial_start = lstart & (PAGE_SIZE - 1);
92309cbfeafSKirill A. Shutemov 	unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
924bda97eabSHugh Dickins 	struct pagevec pvec;
9257a5d0fbbSHugh Dickins 	pgoff_t indices[PAGEVEC_SIZE];
9267a5d0fbbSHugh Dickins 	long nr_swaps_freed = 0;
927285b2c4fSHugh Dickins 	pgoff_t index;
928bda97eabSHugh Dickins 	int i;
9291da177e4SLinus Torvalds 
93083e4fa9cSHugh Dickins 	if (lend == -1)
93183e4fa9cSHugh Dickins 		end = -1;	/* unsigned, so actually very big */
932bda97eabSHugh Dickins 
933d144bf62SHugh Dickins 	if (info->fallocend > start && info->fallocend <= end && !unfalloc)
934d144bf62SHugh Dickins 		info->fallocend = start;
935d144bf62SHugh Dickins 
93686679820SMel Gorman 	pagevec_init(&pvec);
937bda97eabSHugh Dickins 	index = start;
9385c211ba2SMatthew Wilcox (Oracle) 	while (index < end && find_lock_entries(mapping, index, end - 1,
9395c211ba2SMatthew Wilcox (Oracle) 			&pvec, indices)) {
940bda97eabSHugh Dickins 		for (i = 0; i < pagevec_count(&pvec); i++) {
941bda97eabSHugh Dickins 			struct page *page = pvec.pages[i];
942bda97eabSHugh Dickins 
9437a5d0fbbSHugh Dickins 			index = indices[i];
944bda97eabSHugh Dickins 
9453159f943SMatthew Wilcox 			if (xa_is_value(page)) {
9461635f6a7SHugh Dickins 				if (unfalloc)
9471635f6a7SHugh Dickins 					continue;
9487a5d0fbbSHugh Dickins 				nr_swaps_freed += !shmem_free_swap(mapping,
9497a5d0fbbSHugh Dickins 								index, page);
9507a5d0fbbSHugh Dickins 				continue;
9517a5d0fbbSHugh Dickins 			}
9525c211ba2SMatthew Wilcox (Oracle) 			index += thp_nr_pages(page) - 1;
9537a5d0fbbSHugh Dickins 
9545c211ba2SMatthew Wilcox (Oracle) 			if (!unfalloc || !PageUptodate(page))
955bda97eabSHugh Dickins 				truncate_inode_page(mapping, page);
956bda97eabSHugh Dickins 			unlock_page(page);
957bda97eabSHugh Dickins 		}
9580cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
95924513264SHugh Dickins 		pagevec_release(&pvec);
960bda97eabSHugh Dickins 		cond_resched();
961bda97eabSHugh Dickins 		index++;
962bda97eabSHugh Dickins 	}
963bda97eabSHugh Dickins 
96483e4fa9cSHugh Dickins 	if (partial_start) {
965bda97eabSHugh Dickins 		struct page *page = NULL;
9669e18eb29SAndres Lagar-Cavilla 		shmem_getpage(inode, start - 1, &page, SGP_READ);
967bda97eabSHugh Dickins 		if (page) {
96809cbfeafSKirill A. Shutemov 			unsigned int top = PAGE_SIZE;
96983e4fa9cSHugh Dickins 			if (start > end) {
97083e4fa9cSHugh Dickins 				top = partial_end;
97183e4fa9cSHugh Dickins 				partial_end = 0;
97283e4fa9cSHugh Dickins 			}
97383e4fa9cSHugh Dickins 			zero_user_segment(page, partial_start, top);
974bda97eabSHugh Dickins 			set_page_dirty(page);
975bda97eabSHugh Dickins 			unlock_page(page);
97609cbfeafSKirill A. Shutemov 			put_page(page);
977bda97eabSHugh Dickins 		}
978bda97eabSHugh Dickins 	}
97983e4fa9cSHugh Dickins 	if (partial_end) {
98083e4fa9cSHugh Dickins 		struct page *page = NULL;
9819e18eb29SAndres Lagar-Cavilla 		shmem_getpage(inode, end, &page, SGP_READ);
98283e4fa9cSHugh Dickins 		if (page) {
98383e4fa9cSHugh Dickins 			zero_user_segment(page, 0, partial_end);
98483e4fa9cSHugh Dickins 			set_page_dirty(page);
98583e4fa9cSHugh Dickins 			unlock_page(page);
98609cbfeafSKirill A. Shutemov 			put_page(page);
98783e4fa9cSHugh Dickins 		}
98883e4fa9cSHugh Dickins 	}
98983e4fa9cSHugh Dickins 	if (start >= end)
99083e4fa9cSHugh Dickins 		return;
991bda97eabSHugh Dickins 
992bda97eabSHugh Dickins 	index = start;
993b1a36650SHugh Dickins 	while (index < end) {
994bda97eabSHugh Dickins 		cond_resched();
9950cd6144aSJohannes Weiner 
996cf2039afSMatthew Wilcox (Oracle) 		if (!find_get_entries(mapping, index, end - 1, &pvec,
997cf2039afSMatthew Wilcox (Oracle) 				indices)) {
998b1a36650SHugh Dickins 			/* If all gone or hole-punch or unfalloc, we're done */
999b1a36650SHugh Dickins 			if (index == start || end != -1)
1000bda97eabSHugh Dickins 				break;
1001b1a36650SHugh Dickins 			/* But if truncating, restart to make sure all gone */
1002bda97eabSHugh Dickins 			index = start;
1003bda97eabSHugh Dickins 			continue;
1004bda97eabSHugh Dickins 		}
1005bda97eabSHugh Dickins 		for (i = 0; i < pagevec_count(&pvec); i++) {
1006bda97eabSHugh Dickins 			struct page *page = pvec.pages[i];
1007bda97eabSHugh Dickins 
10087a5d0fbbSHugh Dickins 			index = indices[i];
10093159f943SMatthew Wilcox 			if (xa_is_value(page)) {
10101635f6a7SHugh Dickins 				if (unfalloc)
10111635f6a7SHugh Dickins 					continue;
1012b1a36650SHugh Dickins 				if (shmem_free_swap(mapping, index, page)) {
1013b1a36650SHugh Dickins 					/* Swap was replaced by page: retry */
1014b1a36650SHugh Dickins 					index--;
1015b1a36650SHugh Dickins 					break;
1016b1a36650SHugh Dickins 				}
1017b1a36650SHugh Dickins 				nr_swaps_freed++;
10187a5d0fbbSHugh Dickins 				continue;
10197a5d0fbbSHugh Dickins 			}
10207a5d0fbbSHugh Dickins 
1021bda97eabSHugh Dickins 			lock_page(page);
1022800d8c63SKirill A. Shutemov 
10231635f6a7SHugh Dickins 			if (!unfalloc || !PageUptodate(page)) {
102471725ed1SHugh Dickins 				if (page_mapping(page) != mapping) {
1025b1a36650SHugh Dickins 					/* Page was replaced by swap: retry */
1026b1a36650SHugh Dickins 					unlock_page(page);
1027b1a36650SHugh Dickins 					index--;
1028b1a36650SHugh Dickins 					break;
10297a5d0fbbSHugh Dickins 				}
103071725ed1SHugh Dickins 				VM_BUG_ON_PAGE(PageWriteback(page), page);
103171725ed1SHugh Dickins 				if (shmem_punch_compound(page, start, end))
103271725ed1SHugh Dickins 					truncate_inode_page(mapping, page);
10330783ac95SHugh Dickins 				else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
103471725ed1SHugh Dickins 					/* Wipe the page and don't get stuck */
103571725ed1SHugh Dickins 					clear_highpage(page);
103671725ed1SHugh Dickins 					flush_dcache_page(page);
103771725ed1SHugh Dickins 					set_page_dirty(page);
103871725ed1SHugh Dickins 					if (index <
103971725ed1SHugh Dickins 					    round_up(start, HPAGE_PMD_NR))
104071725ed1SHugh Dickins 						start = index + 1;
104171725ed1SHugh Dickins 				}
10421635f6a7SHugh Dickins 			}
1043bda97eabSHugh Dickins 			unlock_page(page);
1044bda97eabSHugh Dickins 		}
10450cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
104624513264SHugh Dickins 		pagevec_release(&pvec);
1047bda97eabSHugh Dickins 		index++;
1048bda97eabSHugh Dickins 	}
104994c1e62dSHugh Dickins 
10504595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
10517a5d0fbbSHugh Dickins 	info->swapped -= nr_swaps_freed;
10521da177e4SLinus Torvalds 	shmem_recalc_inode(inode);
10534595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
10541635f6a7SHugh Dickins }
10551da177e4SLinus Torvalds 
10561635f6a7SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
10571635f6a7SHugh Dickins {
10581635f6a7SHugh Dickins 	shmem_undo_range(inode, lstart, lend, false);
1059078cd827SDeepa Dinamani 	inode->i_ctime = inode->i_mtime = current_time(inode);
10601da177e4SLinus Torvalds }
106194c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
10621da177e4SLinus Torvalds 
1063549c7297SChristian Brauner static int shmem_getattr(struct user_namespace *mnt_userns,
1064549c7297SChristian Brauner 			 const struct path *path, struct kstat *stat,
1065a528d35eSDavid Howells 			 u32 request_mask, unsigned int query_flags)
106644a30220SYu Zhao {
1067a528d35eSDavid Howells 	struct inode *inode = path->dentry->d_inode;
106844a30220SYu Zhao 	struct shmem_inode_info *info = SHMEM_I(inode);
106944a30220SYu Zhao 
1070d0424c42SHugh Dickins 	if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
10714595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
107244a30220SYu Zhao 		shmem_recalc_inode(inode);
10734595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
1074d0424c42SHugh Dickins 	}
10750d56a451SChristian Brauner 	generic_fillattr(&init_user_ns, inode, stat);
107689fdcd26SYang Shi 
1077a7fddc36SHugh Dickins 	if (shmem_is_huge(NULL, inode, 0))
107889fdcd26SYang Shi 		stat->blksize = HPAGE_PMD_SIZE;
107989fdcd26SYang Shi 
108044a30220SYu Zhao 	return 0;
108144a30220SYu Zhao }
108244a30220SYu Zhao 
1083549c7297SChristian Brauner static int shmem_setattr(struct user_namespace *mnt_userns,
1084549c7297SChristian Brauner 			 struct dentry *dentry, struct iattr *attr)
10851da177e4SLinus Torvalds {
108675c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
108740e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
10881da177e4SLinus Torvalds 	int error;
10891da177e4SLinus Torvalds 
10902f221d6fSChristian Brauner 	error = setattr_prepare(&init_user_ns, dentry, attr);
1091db78b877SChristoph Hellwig 	if (error)
1092db78b877SChristoph Hellwig 		return error;
1093db78b877SChristoph Hellwig 
109494c1e62dSHugh Dickins 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
109594c1e62dSHugh Dickins 		loff_t oldsize = inode->i_size;
109694c1e62dSHugh Dickins 		loff_t newsize = attr->ia_size;
10973889e6e7Snpiggin@suse.de 
109840e041a2SDavid Herrmann 		/* protected by i_mutex */
109940e041a2SDavid Herrmann 		if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
110040e041a2SDavid Herrmann 		    (newsize > oldsize && (info->seals & F_SEAL_GROW)))
110140e041a2SDavid Herrmann 			return -EPERM;
110240e041a2SDavid Herrmann 
110394c1e62dSHugh Dickins 		if (newsize != oldsize) {
110477142517SKonstantin Khlebnikov 			error = shmem_reacct_size(SHMEM_I(inode)->flags,
110577142517SKonstantin Khlebnikov 					oldsize, newsize);
110677142517SKonstantin Khlebnikov 			if (error)
110777142517SKonstantin Khlebnikov 				return error;
110894c1e62dSHugh Dickins 			i_size_write(inode, newsize);
1109078cd827SDeepa Dinamani 			inode->i_ctime = inode->i_mtime = current_time(inode);
111094c1e62dSHugh Dickins 		}
1111afa2db2fSJosef Bacik 		if (newsize <= oldsize) {
111294c1e62dSHugh Dickins 			loff_t holebegin = round_up(newsize, PAGE_SIZE);
1113d0424c42SHugh Dickins 			if (oldsize > holebegin)
1114d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
1115d0424c42SHugh Dickins 							holebegin, 0, 1);
1116d0424c42SHugh Dickins 			if (info->alloced)
1117d0424c42SHugh Dickins 				shmem_truncate_range(inode,
1118d0424c42SHugh Dickins 							newsize, (loff_t)-1);
111994c1e62dSHugh Dickins 			/* unmap again to remove racily COWed private pages */
1120d0424c42SHugh Dickins 			if (oldsize > holebegin)
1121d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
1122d0424c42SHugh Dickins 							holebegin, 0, 1);
112394c1e62dSHugh Dickins 		}
11241da177e4SLinus Torvalds 	}
11251da177e4SLinus Torvalds 
11262f221d6fSChristian Brauner 	setattr_copy(&init_user_ns, inode, attr);
1127db78b877SChristoph Hellwig 	if (attr->ia_valid & ATTR_MODE)
1128e65ce2a5SChristian Brauner 		error = posix_acl_chmod(&init_user_ns, inode, inode->i_mode);
11291da177e4SLinus Torvalds 	return error;
11301da177e4SLinus Torvalds }
11311da177e4SLinus Torvalds 
11321f895f75SAl Viro static void shmem_evict_inode(struct inode *inode)
11331da177e4SLinus Torvalds {
11341da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
1135779750d2SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
11361da177e4SLinus Torvalds 
113730e6a51dSHui Su 	if (shmem_mapping(inode->i_mapping)) {
11381da177e4SLinus Torvalds 		shmem_unacct_size(info->flags, inode->i_size);
11391da177e4SLinus Torvalds 		inode->i_size = 0;
11403889e6e7Snpiggin@suse.de 		shmem_truncate_range(inode, 0, (loff_t)-1);
1141779750d2SKirill A. Shutemov 		if (!list_empty(&info->shrinklist)) {
1142779750d2SKirill A. Shutemov 			spin_lock(&sbinfo->shrinklist_lock);
1143779750d2SKirill A. Shutemov 			if (!list_empty(&info->shrinklist)) {
1144779750d2SKirill A. Shutemov 				list_del_init(&info->shrinklist);
1145779750d2SKirill A. Shutemov 				sbinfo->shrinklist_len--;
1146779750d2SKirill A. Shutemov 			}
1147779750d2SKirill A. Shutemov 			spin_unlock(&sbinfo->shrinklist_lock);
1148779750d2SKirill A. Shutemov 		}
1149af53d3e9SHugh Dickins 		while (!list_empty(&info->swaplist)) {
1150af53d3e9SHugh Dickins 			/* Wait while shmem_unuse() is scanning this inode... */
1151af53d3e9SHugh Dickins 			wait_var_event(&info->stop_eviction,
1152af53d3e9SHugh Dickins 				       !atomic_read(&info->stop_eviction));
1153cb5f7b9aSHugh Dickins 			mutex_lock(&shmem_swaplist_mutex);
1154af53d3e9SHugh Dickins 			/* ...but beware of the race if we peeked too early */
1155af53d3e9SHugh Dickins 			if (!atomic_read(&info->stop_eviction))
11561da177e4SLinus Torvalds 				list_del_init(&info->swaplist);
1157cb5f7b9aSHugh Dickins 			mutex_unlock(&shmem_swaplist_mutex);
11581da177e4SLinus Torvalds 		}
11593ed47db3SAl Viro 	}
1160b09e0fa4SEric Paris 
116138f38657SAristeu Rozanski 	simple_xattrs_free(&info->xattrs);
11620f3c42f5SHugh Dickins 	WARN_ON(inode->i_blocks);
11635b04c689SPavel Emelyanov 	shmem_free_inode(inode->i_sb);
1164dbd5768fSJan Kara 	clear_inode(inode);
11651da177e4SLinus Torvalds }
11661da177e4SLinus Torvalds 
1167b56a2d8aSVineeth Remanan Pillai static int shmem_find_swap_entries(struct address_space *mapping,
1168b56a2d8aSVineeth Remanan Pillai 				   pgoff_t start, unsigned int nr_entries,
1169b56a2d8aSVineeth Remanan Pillai 				   struct page **entries, pgoff_t *indices,
117087039546SHugh Dickins 				   unsigned int type, bool frontswap)
1171478922e2SMatthew Wilcox {
1172b56a2d8aSVineeth Remanan Pillai 	XA_STATE(xas, &mapping->i_pages, start);
1173b56a2d8aSVineeth Remanan Pillai 	struct page *page;
117487039546SHugh Dickins 	swp_entry_t entry;
1175b56a2d8aSVineeth Remanan Pillai 	unsigned int ret = 0;
1176b56a2d8aSVineeth Remanan Pillai 
1177b56a2d8aSVineeth Remanan Pillai 	if (!nr_entries)
1178b56a2d8aSVineeth Remanan Pillai 		return 0;
1179478922e2SMatthew Wilcox 
1180478922e2SMatthew Wilcox 	rcu_read_lock();
1181b56a2d8aSVineeth Remanan Pillai 	xas_for_each(&xas, page, ULONG_MAX) {
1182b56a2d8aSVineeth Remanan Pillai 		if (xas_retry(&xas, page))
11835b9c98f3SMike Kravetz 			continue;
1184b56a2d8aSVineeth Remanan Pillai 
1185b56a2d8aSVineeth Remanan Pillai 		if (!xa_is_value(page))
1186478922e2SMatthew Wilcox 			continue;
1187b56a2d8aSVineeth Remanan Pillai 
118887039546SHugh Dickins 		entry = radix_to_swp_entry(page);
118987039546SHugh Dickins 		if (swp_type(entry) != type)
1190b56a2d8aSVineeth Remanan Pillai 			continue;
119187039546SHugh Dickins 		if (frontswap &&
119287039546SHugh Dickins 		    !frontswap_test(swap_info[type], swp_offset(entry)))
119387039546SHugh Dickins 			continue;
1194b56a2d8aSVineeth Remanan Pillai 
1195b56a2d8aSVineeth Remanan Pillai 		indices[ret] = xas.xa_index;
1196b56a2d8aSVineeth Remanan Pillai 		entries[ret] = page;
1197b56a2d8aSVineeth Remanan Pillai 
1198b56a2d8aSVineeth Remanan Pillai 		if (need_resched()) {
1199e21a2955SMatthew Wilcox 			xas_pause(&xas);
1200478922e2SMatthew Wilcox 			cond_resched_rcu();
1201478922e2SMatthew Wilcox 		}
1202b56a2d8aSVineeth Remanan Pillai 		if (++ret == nr_entries)
1203b56a2d8aSVineeth Remanan Pillai 			break;
1204b56a2d8aSVineeth Remanan Pillai 	}
1205478922e2SMatthew Wilcox 	rcu_read_unlock();
1206e21a2955SMatthew Wilcox 
1207b56a2d8aSVineeth Remanan Pillai 	return ret;
1208b56a2d8aSVineeth Remanan Pillai }
1209b56a2d8aSVineeth Remanan Pillai 
1210b56a2d8aSVineeth Remanan Pillai /*
1211b56a2d8aSVineeth Remanan Pillai  * Move the swapped pages for an inode to page cache. Returns the count
1212b56a2d8aSVineeth Remanan Pillai  * of pages swapped in, or the error in case of failure.
1213b56a2d8aSVineeth Remanan Pillai  */
1214b56a2d8aSVineeth Remanan Pillai static int shmem_unuse_swap_entries(struct inode *inode, struct pagevec pvec,
1215b56a2d8aSVineeth Remanan Pillai 				    pgoff_t *indices)
1216b56a2d8aSVineeth Remanan Pillai {
1217b56a2d8aSVineeth Remanan Pillai 	int i = 0;
1218b56a2d8aSVineeth Remanan Pillai 	int ret = 0;
1219b56a2d8aSVineeth Remanan Pillai 	int error = 0;
1220b56a2d8aSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1221b56a2d8aSVineeth Remanan Pillai 
1222b56a2d8aSVineeth Remanan Pillai 	for (i = 0; i < pvec.nr; i++) {
1223b56a2d8aSVineeth Remanan Pillai 		struct page *page = pvec.pages[i];
1224b56a2d8aSVineeth Remanan Pillai 
1225b56a2d8aSVineeth Remanan Pillai 		if (!xa_is_value(page))
1226b56a2d8aSVineeth Remanan Pillai 			continue;
1227b56a2d8aSVineeth Remanan Pillai 		error = shmem_swapin_page(inode, indices[i],
1228b56a2d8aSVineeth Remanan Pillai 					  &page, SGP_CACHE,
1229b56a2d8aSVineeth Remanan Pillai 					  mapping_gfp_mask(mapping),
1230b56a2d8aSVineeth Remanan Pillai 					  NULL, NULL);
1231b56a2d8aSVineeth Remanan Pillai 		if (error == 0) {
1232b56a2d8aSVineeth Remanan Pillai 			unlock_page(page);
1233b56a2d8aSVineeth Remanan Pillai 			put_page(page);
1234b56a2d8aSVineeth Remanan Pillai 			ret++;
1235b56a2d8aSVineeth Remanan Pillai 		}
1236b56a2d8aSVineeth Remanan Pillai 		if (error == -ENOMEM)
1237b56a2d8aSVineeth Remanan Pillai 			break;
1238b56a2d8aSVineeth Remanan Pillai 		error = 0;
1239b56a2d8aSVineeth Remanan Pillai 	}
1240b56a2d8aSVineeth Remanan Pillai 	return error ? error : ret;
1241478922e2SMatthew Wilcox }
1242478922e2SMatthew Wilcox 
124346f65ec1SHugh Dickins /*
124446f65ec1SHugh Dickins  * If swap found in inode, free it and move page from swapcache to filecache.
124546f65ec1SHugh Dickins  */
1246b56a2d8aSVineeth Remanan Pillai static int shmem_unuse_inode(struct inode *inode, unsigned int type,
1247b56a2d8aSVineeth Remanan Pillai 			     bool frontswap, unsigned long *fs_pages_to_unuse)
12481da177e4SLinus Torvalds {
1249b56a2d8aSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1250b56a2d8aSVineeth Remanan Pillai 	pgoff_t start = 0;
1251b56a2d8aSVineeth Remanan Pillai 	struct pagevec pvec;
1252b56a2d8aSVineeth Remanan Pillai 	pgoff_t indices[PAGEVEC_SIZE];
1253b56a2d8aSVineeth Remanan Pillai 	bool frontswap_partial = (frontswap && *fs_pages_to_unuse > 0);
1254b56a2d8aSVineeth Remanan Pillai 	int ret = 0;
12551da177e4SLinus Torvalds 
1256b56a2d8aSVineeth Remanan Pillai 	pagevec_init(&pvec);
1257b56a2d8aSVineeth Remanan Pillai 	do {
1258b56a2d8aSVineeth Remanan Pillai 		unsigned int nr_entries = PAGEVEC_SIZE;
12592e0e26c7SHugh Dickins 
1260b56a2d8aSVineeth Remanan Pillai 		if (frontswap_partial && *fs_pages_to_unuse < PAGEVEC_SIZE)
1261b56a2d8aSVineeth Remanan Pillai 			nr_entries = *fs_pages_to_unuse;
12622e0e26c7SHugh Dickins 
1263b56a2d8aSVineeth Remanan Pillai 		pvec.nr = shmem_find_swap_entries(mapping, start, nr_entries,
1264b56a2d8aSVineeth Remanan Pillai 						  pvec.pages, indices,
126587039546SHugh Dickins 						  type, frontswap);
1266b56a2d8aSVineeth Remanan Pillai 		if (pvec.nr == 0) {
1267b56a2d8aSVineeth Remanan Pillai 			ret = 0;
1268778dd893SHugh Dickins 			break;
1269b56a2d8aSVineeth Remanan Pillai 		}
1270b56a2d8aSVineeth Remanan Pillai 
1271b56a2d8aSVineeth Remanan Pillai 		ret = shmem_unuse_swap_entries(inode, pvec, indices);
1272b56a2d8aSVineeth Remanan Pillai 		if (ret < 0)
1273b56a2d8aSVineeth Remanan Pillai 			break;
1274b56a2d8aSVineeth Remanan Pillai 
1275b56a2d8aSVineeth Remanan Pillai 		if (frontswap_partial) {
1276b56a2d8aSVineeth Remanan Pillai 			*fs_pages_to_unuse -= ret;
1277b56a2d8aSVineeth Remanan Pillai 			if (*fs_pages_to_unuse == 0) {
1278b56a2d8aSVineeth Remanan Pillai 				ret = FRONTSWAP_PAGES_UNUSED;
1279b56a2d8aSVineeth Remanan Pillai 				break;
1280b56a2d8aSVineeth Remanan Pillai 			}
1281b56a2d8aSVineeth Remanan Pillai 		}
1282b56a2d8aSVineeth Remanan Pillai 
1283b56a2d8aSVineeth Remanan Pillai 		start = indices[pvec.nr - 1];
1284b56a2d8aSVineeth Remanan Pillai 	} while (true);
1285b56a2d8aSVineeth Remanan Pillai 
1286b56a2d8aSVineeth Remanan Pillai 	return ret;
1287b56a2d8aSVineeth Remanan Pillai }
1288b56a2d8aSVineeth Remanan Pillai 
1289b56a2d8aSVineeth Remanan Pillai /*
1290b56a2d8aSVineeth Remanan Pillai  * Read all the shared memory data that resides in the swap
1291b56a2d8aSVineeth Remanan Pillai  * device 'type' back into memory, so the swap device can be
1292b56a2d8aSVineeth Remanan Pillai  * unused.
1293b56a2d8aSVineeth Remanan Pillai  */
1294b56a2d8aSVineeth Remanan Pillai int shmem_unuse(unsigned int type, bool frontswap,
1295b56a2d8aSVineeth Remanan Pillai 		unsigned long *fs_pages_to_unuse)
1296b56a2d8aSVineeth Remanan Pillai {
1297b56a2d8aSVineeth Remanan Pillai 	struct shmem_inode_info *info, *next;
1298b56a2d8aSVineeth Remanan Pillai 	int error = 0;
1299b56a2d8aSVineeth Remanan Pillai 
1300b56a2d8aSVineeth Remanan Pillai 	if (list_empty(&shmem_swaplist))
1301b56a2d8aSVineeth Remanan Pillai 		return 0;
1302b56a2d8aSVineeth Remanan Pillai 
1303b56a2d8aSVineeth Remanan Pillai 	mutex_lock(&shmem_swaplist_mutex);
1304b56a2d8aSVineeth Remanan Pillai 	list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1305b56a2d8aSVineeth Remanan Pillai 		if (!info->swapped) {
1306b56a2d8aSVineeth Remanan Pillai 			list_del_init(&info->swaplist);
1307b56a2d8aSVineeth Remanan Pillai 			continue;
1308b56a2d8aSVineeth Remanan Pillai 		}
1309af53d3e9SHugh Dickins 		/*
1310af53d3e9SHugh Dickins 		 * Drop the swaplist mutex while searching the inode for swap;
1311af53d3e9SHugh Dickins 		 * but before doing so, make sure shmem_evict_inode() will not
1312af53d3e9SHugh Dickins 		 * remove placeholder inode from swaplist, nor let it be freed
1313af53d3e9SHugh Dickins 		 * (igrab() would protect from unlink, but not from unmount).
1314af53d3e9SHugh Dickins 		 */
1315af53d3e9SHugh Dickins 		atomic_inc(&info->stop_eviction);
1316b56a2d8aSVineeth Remanan Pillai 		mutex_unlock(&shmem_swaplist_mutex);
1317b56a2d8aSVineeth Remanan Pillai 
1318af53d3e9SHugh Dickins 		error = shmem_unuse_inode(&info->vfs_inode, type, frontswap,
1319b56a2d8aSVineeth Remanan Pillai 					  fs_pages_to_unuse);
1320b56a2d8aSVineeth Remanan Pillai 		cond_resched();
1321b56a2d8aSVineeth Remanan Pillai 
1322b56a2d8aSVineeth Remanan Pillai 		mutex_lock(&shmem_swaplist_mutex);
1323b56a2d8aSVineeth Remanan Pillai 		next = list_next_entry(info, swaplist);
1324b56a2d8aSVineeth Remanan Pillai 		if (!info->swapped)
1325b56a2d8aSVineeth Remanan Pillai 			list_del_init(&info->swaplist);
1326af53d3e9SHugh Dickins 		if (atomic_dec_and_test(&info->stop_eviction))
1327af53d3e9SHugh Dickins 			wake_up_var(&info->stop_eviction);
1328b56a2d8aSVineeth Remanan Pillai 		if (error)
1329b56a2d8aSVineeth Remanan Pillai 			break;
13301da177e4SLinus Torvalds 	}
1331cb5f7b9aSHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
1332778dd893SHugh Dickins 
1333778dd893SHugh Dickins 	return error;
13341da177e4SLinus Torvalds }
13351da177e4SLinus Torvalds 
13361da177e4SLinus Torvalds /*
13371da177e4SLinus Torvalds  * Move the page from the page cache to the swap cache.
13381da177e4SLinus Torvalds  */
13391da177e4SLinus Torvalds static int shmem_writepage(struct page *page, struct writeback_control *wbc)
13401da177e4SLinus Torvalds {
13411da177e4SLinus Torvalds 	struct shmem_inode_info *info;
13421da177e4SLinus Torvalds 	struct address_space *mapping;
13431da177e4SLinus Torvalds 	struct inode *inode;
13446922c0c7SHugh Dickins 	swp_entry_t swap;
13456922c0c7SHugh Dickins 	pgoff_t index;
13461da177e4SLinus Torvalds 
1347*1e6decf3SHugh Dickins 	/*
1348*1e6decf3SHugh Dickins 	 * If /sys/kernel/mm/transparent_hugepage/shmem_enabled is "always" or
1349*1e6decf3SHugh Dickins 	 * "force", drivers/gpu/drm/i915/gem/i915_gem_shmem.c gets huge pages,
1350*1e6decf3SHugh Dickins 	 * and its shmem_writeback() needs them to be split when swapping.
1351*1e6decf3SHugh Dickins 	 */
1352*1e6decf3SHugh Dickins 	if (PageTransCompound(page)) {
1353*1e6decf3SHugh Dickins 		/* Ensure the subpages are still dirty */
1354*1e6decf3SHugh Dickins 		SetPageDirty(page);
1355*1e6decf3SHugh Dickins 		if (split_huge_page(page) < 0)
1356*1e6decf3SHugh Dickins 			goto redirty;
1357*1e6decf3SHugh Dickins 		ClearPageDirty(page);
1358*1e6decf3SHugh Dickins 	}
1359*1e6decf3SHugh Dickins 
13601da177e4SLinus Torvalds 	BUG_ON(!PageLocked(page));
13611da177e4SLinus Torvalds 	mapping = page->mapping;
13621da177e4SLinus Torvalds 	index = page->index;
13631da177e4SLinus Torvalds 	inode = mapping->host;
13641da177e4SLinus Torvalds 	info = SHMEM_I(inode);
13651da177e4SLinus Torvalds 	if (info->flags & VM_LOCKED)
13661da177e4SLinus Torvalds 		goto redirty;
1367d9fe526aSHugh Dickins 	if (!total_swap_pages)
13681da177e4SLinus Torvalds 		goto redirty;
13691da177e4SLinus Torvalds 
1370d9fe526aSHugh Dickins 	/*
137197b713baSChristoph Hellwig 	 * Our capabilities prevent regular writeback or sync from ever calling
137297b713baSChristoph Hellwig 	 * shmem_writepage; but a stacking filesystem might use ->writepage of
137397b713baSChristoph Hellwig 	 * its underlying filesystem, in which case tmpfs should write out to
137497b713baSChristoph Hellwig 	 * swap only in response to memory pressure, and not for the writeback
137597b713baSChristoph Hellwig 	 * threads or sync.
1376d9fe526aSHugh Dickins 	 */
137748f170fbSHugh Dickins 	if (!wbc->for_reclaim) {
137848f170fbSHugh Dickins 		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
137948f170fbSHugh Dickins 		goto redirty;
138048f170fbSHugh Dickins 	}
13811635f6a7SHugh Dickins 
13821635f6a7SHugh Dickins 	/*
13831635f6a7SHugh Dickins 	 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
13841635f6a7SHugh Dickins 	 * value into swapfile.c, the only way we can correctly account for a
13851635f6a7SHugh Dickins 	 * fallocated page arriving here is now to initialize it and write it.
13861aac1400SHugh Dickins 	 *
13871aac1400SHugh Dickins 	 * That's okay for a page already fallocated earlier, but if we have
13881aac1400SHugh Dickins 	 * not yet completed the fallocation, then (a) we want to keep track
13891aac1400SHugh Dickins 	 * of this page in case we have to undo it, and (b) it may not be a
13901aac1400SHugh Dickins 	 * good idea to continue anyway, once we're pushing into swap.  So
13911aac1400SHugh Dickins 	 * reactivate the page, and let shmem_fallocate() quit when too many.
13921635f6a7SHugh Dickins 	 */
13931635f6a7SHugh Dickins 	if (!PageUptodate(page)) {
13941aac1400SHugh Dickins 		if (inode->i_private) {
13951aac1400SHugh Dickins 			struct shmem_falloc *shmem_falloc;
13961aac1400SHugh Dickins 			spin_lock(&inode->i_lock);
13971aac1400SHugh Dickins 			shmem_falloc = inode->i_private;
13981aac1400SHugh Dickins 			if (shmem_falloc &&
13998e205f77SHugh Dickins 			    !shmem_falloc->waitq &&
14001aac1400SHugh Dickins 			    index >= shmem_falloc->start &&
14011aac1400SHugh Dickins 			    index < shmem_falloc->next)
14021aac1400SHugh Dickins 				shmem_falloc->nr_unswapped++;
14031aac1400SHugh Dickins 			else
14041aac1400SHugh Dickins 				shmem_falloc = NULL;
14051aac1400SHugh Dickins 			spin_unlock(&inode->i_lock);
14061aac1400SHugh Dickins 			if (shmem_falloc)
14071aac1400SHugh Dickins 				goto redirty;
14081aac1400SHugh Dickins 		}
14091635f6a7SHugh Dickins 		clear_highpage(page);
14101635f6a7SHugh Dickins 		flush_dcache_page(page);
14111635f6a7SHugh Dickins 		SetPageUptodate(page);
14121635f6a7SHugh Dickins 	}
14131635f6a7SHugh Dickins 
141438d8b4e6SHuang Ying 	swap = get_swap_page(page);
141548f170fbSHugh Dickins 	if (!swap.val)
141648f170fbSHugh Dickins 		goto redirty;
1417d9fe526aSHugh Dickins 
1418b1dea800SHugh Dickins 	/*
1419b1dea800SHugh Dickins 	 * Add inode to shmem_unuse()'s list of swapped-out inodes,
14206922c0c7SHugh Dickins 	 * if it's not already there.  Do it now before the page is
14216922c0c7SHugh Dickins 	 * moved to swap cache, when its pagelock no longer protects
1422b1dea800SHugh Dickins 	 * the inode from eviction.  But don't unlock the mutex until
14236922c0c7SHugh Dickins 	 * we've incremented swapped, because shmem_unuse_inode() will
14246922c0c7SHugh Dickins 	 * prune a !swapped inode from the swaplist under this mutex.
1425b1dea800SHugh Dickins 	 */
1426b1dea800SHugh Dickins 	mutex_lock(&shmem_swaplist_mutex);
142705bf86b4SHugh Dickins 	if (list_empty(&info->swaplist))
1428b56a2d8aSVineeth Remanan Pillai 		list_add(&info->swaplist, &shmem_swaplist);
1429b1dea800SHugh Dickins 
14304afab1cdSYang Shi 	if (add_to_swap_cache(page, swap,
14313852f676SJoonsoo Kim 			__GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN,
14323852f676SJoonsoo Kim 			NULL) == 0) {
14334595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
1434267a4c76SHugh Dickins 		shmem_recalc_inode(inode);
1435267a4c76SHugh Dickins 		info->swapped++;
14364595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
1437267a4c76SHugh Dickins 
1438aaa46865SHugh Dickins 		swap_shmem_alloc(swap);
14396922c0c7SHugh Dickins 		shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
14406922c0c7SHugh Dickins 
14416922c0c7SHugh Dickins 		mutex_unlock(&shmem_swaplist_mutex);
1442d9fe526aSHugh Dickins 		BUG_ON(page_mapped(page));
14439fab5619SHugh Dickins 		swap_writepage(page, wbc);
14441da177e4SLinus Torvalds 		return 0;
14451da177e4SLinus Torvalds 	}
14461da177e4SLinus Torvalds 
14476922c0c7SHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
144875f6d6d2SMinchan Kim 	put_swap_page(page, swap);
14491da177e4SLinus Torvalds redirty:
14501da177e4SLinus Torvalds 	set_page_dirty(page);
1451d9fe526aSHugh Dickins 	if (wbc->for_reclaim)
1452d9fe526aSHugh Dickins 		return AOP_WRITEPAGE_ACTIVATE;	/* Return with page locked */
1453d9fe526aSHugh Dickins 	unlock_page(page);
1454d9fe526aSHugh Dickins 	return 0;
14551da177e4SLinus Torvalds }
14561da177e4SLinus Torvalds 
145775edd345SHugh Dickins #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
145871fe804bSLee Schermerhorn static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1459680d794bSakpm@linux-foundation.org {
1460680d794bSakpm@linux-foundation.org 	char buffer[64];
1461680d794bSakpm@linux-foundation.org 
146271fe804bSLee Schermerhorn 	if (!mpol || mpol->mode == MPOL_DEFAULT)
1463095f1fc4SLee Schermerhorn 		return;		/* show nothing */
1464095f1fc4SLee Schermerhorn 
1465a7a88b23SHugh Dickins 	mpol_to_str(buffer, sizeof(buffer), mpol);
1466095f1fc4SLee Schermerhorn 
1467095f1fc4SLee Schermerhorn 	seq_printf(seq, ",mpol=%s", buffer);
1468680d794bSakpm@linux-foundation.org }
146971fe804bSLee Schermerhorn 
147071fe804bSLee Schermerhorn static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
147171fe804bSLee Schermerhorn {
147271fe804bSLee Schermerhorn 	struct mempolicy *mpol = NULL;
147371fe804bSLee Schermerhorn 	if (sbinfo->mpol) {
1474bf11b9a8SSebastian Andrzej Siewior 		raw_spin_lock(&sbinfo->stat_lock);	/* prevent replace/use races */
147571fe804bSLee Schermerhorn 		mpol = sbinfo->mpol;
147671fe804bSLee Schermerhorn 		mpol_get(mpol);
1477bf11b9a8SSebastian Andrzej Siewior 		raw_spin_unlock(&sbinfo->stat_lock);
147871fe804bSLee Schermerhorn 	}
147971fe804bSLee Schermerhorn 	return mpol;
148071fe804bSLee Schermerhorn }
148175edd345SHugh Dickins #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
148275edd345SHugh Dickins static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
148375edd345SHugh Dickins {
148475edd345SHugh Dickins }
148575edd345SHugh Dickins static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
148675edd345SHugh Dickins {
148775edd345SHugh Dickins 	return NULL;
148875edd345SHugh Dickins }
148975edd345SHugh Dickins #endif /* CONFIG_NUMA && CONFIG_TMPFS */
149075edd345SHugh Dickins #ifndef CONFIG_NUMA
149175edd345SHugh Dickins #define vm_policy vm_private_data
149275edd345SHugh Dickins #endif
1493680d794bSakpm@linux-foundation.org 
1494800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1495800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1496800d8c63SKirill A. Shutemov {
1497800d8c63SKirill A. Shutemov 	/* Create a pseudo vma that just contains the policy */
14982c4541e2SKirill A. Shutemov 	vma_init(vma, NULL);
1499800d8c63SKirill A. Shutemov 	/* Bias interleave by inode number to distribute better across nodes */
1500800d8c63SKirill A. Shutemov 	vma->vm_pgoff = index + info->vfs_inode.i_ino;
1501800d8c63SKirill A. Shutemov 	vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1502800d8c63SKirill A. Shutemov }
1503800d8c63SKirill A. Shutemov 
1504800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1505800d8c63SKirill A. Shutemov {
1506800d8c63SKirill A. Shutemov 	/* Drop reference taken by mpol_shared_policy_lookup() */
1507800d8c63SKirill A. Shutemov 	mpol_cond_put(vma->vm_policy);
1508800d8c63SKirill A. Shutemov }
1509800d8c63SKirill A. Shutemov 
151041ffe5d5SHugh Dickins static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
151141ffe5d5SHugh Dickins 			struct shmem_inode_info *info, pgoff_t index)
15121da177e4SLinus Torvalds {
15131da177e4SLinus Torvalds 	struct vm_area_struct pvma;
151418a2f371SMel Gorman 	struct page *page;
15158c63ca5bSWill Deacon 	struct vm_fault vmf = {
15168c63ca5bSWill Deacon 		.vma = &pvma,
15178c63ca5bSWill Deacon 	};
15181da177e4SLinus Torvalds 
1519800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
1520e9e9b7ecSMinchan Kim 	page = swap_cluster_readahead(swap, gfp, &vmf);
1521800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
152218a2f371SMel Gorman 
1523800d8c63SKirill A. Shutemov 	return page;
1524800d8c63SKirill A. Shutemov }
152518a2f371SMel Gorman 
152678cc8cdcSRik van Riel /*
152778cc8cdcSRik van Riel  * Make sure huge_gfp is always more limited than limit_gfp.
152878cc8cdcSRik van Riel  * Some of the flags set permissions, while others set limitations.
152978cc8cdcSRik van Riel  */
153078cc8cdcSRik van Riel static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
153178cc8cdcSRik van Riel {
153278cc8cdcSRik van Riel 	gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
153378cc8cdcSRik van Riel 	gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
1534187df5ddSRik van Riel 	gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
1535187df5ddSRik van Riel 	gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
1536187df5ddSRik van Riel 
1537187df5ddSRik van Riel 	/* Allow allocations only from the originally specified zones. */
1538187df5ddSRik van Riel 	result |= zoneflags;
153978cc8cdcSRik van Riel 
154078cc8cdcSRik van Riel 	/*
154178cc8cdcSRik van Riel 	 * Minimize the result gfp by taking the union with the deny flags,
154278cc8cdcSRik van Riel 	 * and the intersection of the allow flags.
154378cc8cdcSRik van Riel 	 */
154478cc8cdcSRik van Riel 	result |= (limit_gfp & denyflags);
154578cc8cdcSRik van Riel 	result |= (huge_gfp & limit_gfp) & allowflags;
154678cc8cdcSRik van Riel 
154778cc8cdcSRik van Riel 	return result;
154878cc8cdcSRik van Riel }
154978cc8cdcSRik van Riel 
1550800d8c63SKirill A. Shutemov static struct page *shmem_alloc_hugepage(gfp_t gfp,
1551800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1552800d8c63SKirill A. Shutemov {
1553800d8c63SKirill A. Shutemov 	struct vm_area_struct pvma;
15547b8d046fSMatthew Wilcox 	struct address_space *mapping = info->vfs_inode.i_mapping;
15557b8d046fSMatthew Wilcox 	pgoff_t hindex;
1556800d8c63SKirill A. Shutemov 	struct page *page;
1557800d8c63SKirill A. Shutemov 
15584620a06eSGeert Uytterhoeven 	hindex = round_down(index, HPAGE_PMD_NR);
15597b8d046fSMatthew Wilcox 	if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
15607b8d046fSMatthew Wilcox 								XA_PRESENT))
1561800d8c63SKirill A. Shutemov 		return NULL;
1562800d8c63SKirill A. Shutemov 
1563800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, hindex);
1564164cc4feSRik van Riel 	page = alloc_pages_vma(gfp, HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(),
1565164cc4feSRik van Riel 			       true);
1566800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
1567800d8c63SKirill A. Shutemov 	if (page)
1568800d8c63SKirill A. Shutemov 		prep_transhuge_page(page);
1569dcdf11eeSDavid Rientjes 	else
1570dcdf11eeSDavid Rientjes 		count_vm_event(THP_FILE_FALLBACK);
157118a2f371SMel Gorman 	return page;
157218a2f371SMel Gorman }
157318a2f371SMel Gorman 
157418a2f371SMel Gorman static struct page *shmem_alloc_page(gfp_t gfp,
157518a2f371SMel Gorman 			struct shmem_inode_info *info, pgoff_t index)
157618a2f371SMel Gorman {
157718a2f371SMel Gorman 	struct vm_area_struct pvma;
157818a2f371SMel Gorman 	struct page *page;
157918a2f371SMel Gorman 
1580800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
1581800d8c63SKirill A. Shutemov 	page = alloc_page_vma(gfp, &pvma, 0);
1582800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
158318a2f371SMel Gorman 
1584800d8c63SKirill A. Shutemov 	return page;
1585800d8c63SKirill A. Shutemov }
1586800d8c63SKirill A. Shutemov 
1587800d8c63SKirill A. Shutemov static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
15880f079694SMike Rapoport 		struct inode *inode,
1589800d8c63SKirill A. Shutemov 		pgoff_t index, bool huge)
1590800d8c63SKirill A. Shutemov {
15910f079694SMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
1592800d8c63SKirill A. Shutemov 	struct page *page;
1593800d8c63SKirill A. Shutemov 	int nr;
1594800d8c63SKirill A. Shutemov 	int err = -ENOSPC;
1595800d8c63SKirill A. Shutemov 
1596396bcc52SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1597800d8c63SKirill A. Shutemov 		huge = false;
1598800d8c63SKirill A. Shutemov 	nr = huge ? HPAGE_PMD_NR : 1;
1599800d8c63SKirill A. Shutemov 
16000f079694SMike Rapoport 	if (!shmem_inode_acct_block(inode, nr))
1601800d8c63SKirill A. Shutemov 		goto failed;
1602800d8c63SKirill A. Shutemov 
1603800d8c63SKirill A. Shutemov 	if (huge)
1604800d8c63SKirill A. Shutemov 		page = shmem_alloc_hugepage(gfp, info, index);
1605800d8c63SKirill A. Shutemov 	else
1606800d8c63SKirill A. Shutemov 		page = shmem_alloc_page(gfp, info, index);
160775edd345SHugh Dickins 	if (page) {
160875edd345SHugh Dickins 		__SetPageLocked(page);
160975edd345SHugh Dickins 		__SetPageSwapBacked(page);
1610800d8c63SKirill A. Shutemov 		return page;
161175edd345SHugh Dickins 	}
161218a2f371SMel Gorman 
1613800d8c63SKirill A. Shutemov 	err = -ENOMEM;
16140f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, nr);
1615800d8c63SKirill A. Shutemov failed:
1616800d8c63SKirill A. Shutemov 	return ERR_PTR(err);
16171da177e4SLinus Torvalds }
161871fe804bSLee Schermerhorn 
16191da177e4SLinus Torvalds /*
1620bde05d1cSHugh Dickins  * When a page is moved from swapcache to shmem filecache (either by the
1621bde05d1cSHugh Dickins  * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1622bde05d1cSHugh Dickins  * shmem_unuse_inode()), it may have been read in earlier from swap, in
1623bde05d1cSHugh Dickins  * ignorance of the mapping it belongs to.  If that mapping has special
1624bde05d1cSHugh Dickins  * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1625bde05d1cSHugh Dickins  * we may need to copy to a suitable page before moving to filecache.
1626bde05d1cSHugh Dickins  *
1627bde05d1cSHugh Dickins  * In a future release, this may well be extended to respect cpuset and
1628bde05d1cSHugh Dickins  * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1629bde05d1cSHugh Dickins  * but for now it is a simple matter of zone.
1630bde05d1cSHugh Dickins  */
1631bde05d1cSHugh Dickins static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1632bde05d1cSHugh Dickins {
1633bde05d1cSHugh Dickins 	return page_zonenum(page) > gfp_zone(gfp);
1634bde05d1cSHugh Dickins }
1635bde05d1cSHugh Dickins 
1636bde05d1cSHugh Dickins static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1637bde05d1cSHugh Dickins 				struct shmem_inode_info *info, pgoff_t index)
1638bde05d1cSHugh Dickins {
1639bde05d1cSHugh Dickins 	struct page *oldpage, *newpage;
1640bde05d1cSHugh Dickins 	struct address_space *swap_mapping;
1641c1cb20d4SYu Zhao 	swp_entry_t entry;
1642bde05d1cSHugh Dickins 	pgoff_t swap_index;
1643bde05d1cSHugh Dickins 	int error;
1644bde05d1cSHugh Dickins 
1645bde05d1cSHugh Dickins 	oldpage = *pagep;
1646c1cb20d4SYu Zhao 	entry.val = page_private(oldpage);
1647c1cb20d4SYu Zhao 	swap_index = swp_offset(entry);
1648bde05d1cSHugh Dickins 	swap_mapping = page_mapping(oldpage);
1649bde05d1cSHugh Dickins 
1650bde05d1cSHugh Dickins 	/*
1651bde05d1cSHugh Dickins 	 * We have arrived here because our zones are constrained, so don't
1652bde05d1cSHugh Dickins 	 * limit chance of success by further cpuset and node constraints.
1653bde05d1cSHugh Dickins 	 */
1654bde05d1cSHugh Dickins 	gfp &= ~GFP_CONSTRAINT_MASK;
1655bde05d1cSHugh Dickins 	newpage = shmem_alloc_page(gfp, info, index);
1656bde05d1cSHugh Dickins 	if (!newpage)
1657bde05d1cSHugh Dickins 		return -ENOMEM;
1658bde05d1cSHugh Dickins 
165909cbfeafSKirill A. Shutemov 	get_page(newpage);
1660bde05d1cSHugh Dickins 	copy_highpage(newpage, oldpage);
16610142ef6cSHugh Dickins 	flush_dcache_page(newpage);
1662bde05d1cSHugh Dickins 
16639956edf3SHugh Dickins 	__SetPageLocked(newpage);
16649956edf3SHugh Dickins 	__SetPageSwapBacked(newpage);
1665bde05d1cSHugh Dickins 	SetPageUptodate(newpage);
1666c1cb20d4SYu Zhao 	set_page_private(newpage, entry.val);
1667bde05d1cSHugh Dickins 	SetPageSwapCache(newpage);
1668bde05d1cSHugh Dickins 
1669bde05d1cSHugh Dickins 	/*
1670bde05d1cSHugh Dickins 	 * Our caller will very soon move newpage out of swapcache, but it's
1671bde05d1cSHugh Dickins 	 * a nice clean interface for us to replace oldpage by newpage there.
1672bde05d1cSHugh Dickins 	 */
1673b93b0163SMatthew Wilcox 	xa_lock_irq(&swap_mapping->i_pages);
167462f945b6SMatthew Wilcox 	error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
16750142ef6cSHugh Dickins 	if (!error) {
16760d1c2072SJohannes Weiner 		mem_cgroup_migrate(oldpage, newpage);
16770d1c2072SJohannes Weiner 		__inc_lruvec_page_state(newpage, NR_FILE_PAGES);
16780d1c2072SJohannes Weiner 		__dec_lruvec_page_state(oldpage, NR_FILE_PAGES);
16790142ef6cSHugh Dickins 	}
1680b93b0163SMatthew Wilcox 	xa_unlock_irq(&swap_mapping->i_pages);
1681bde05d1cSHugh Dickins 
16820142ef6cSHugh Dickins 	if (unlikely(error)) {
16830142ef6cSHugh Dickins 		/*
16840142ef6cSHugh Dickins 		 * Is this possible?  I think not, now that our callers check
16850142ef6cSHugh Dickins 		 * both PageSwapCache and page_private after getting page lock;
16860142ef6cSHugh Dickins 		 * but be defensive.  Reverse old to newpage for clear and free.
16870142ef6cSHugh Dickins 		 */
16880142ef6cSHugh Dickins 		oldpage = newpage;
16890142ef6cSHugh Dickins 	} else {
16906058eaecSJohannes Weiner 		lru_cache_add(newpage);
16910142ef6cSHugh Dickins 		*pagep = newpage;
16920142ef6cSHugh Dickins 	}
1693bde05d1cSHugh Dickins 
1694bde05d1cSHugh Dickins 	ClearPageSwapCache(oldpage);
1695bde05d1cSHugh Dickins 	set_page_private(oldpage, 0);
1696bde05d1cSHugh Dickins 
1697bde05d1cSHugh Dickins 	unlock_page(oldpage);
169809cbfeafSKirill A. Shutemov 	put_page(oldpage);
169909cbfeafSKirill A. Shutemov 	put_page(oldpage);
17000142ef6cSHugh Dickins 	return error;
1701bde05d1cSHugh Dickins }
1702bde05d1cSHugh Dickins 
1703bde05d1cSHugh Dickins /*
1704c5bf121eSVineeth Remanan Pillai  * Swap in the page pointed to by *pagep.
1705c5bf121eSVineeth Remanan Pillai  * Caller has to make sure that *pagep contains a valid swapped page.
1706c5bf121eSVineeth Remanan Pillai  * Returns 0 and the page in pagep if success. On failure, returns the
1707af44c12fSRandy Dunlap  * error code and NULL in *pagep.
17081da177e4SLinus Torvalds  */
1709c5bf121eSVineeth Remanan Pillai static int shmem_swapin_page(struct inode *inode, pgoff_t index,
1710c5bf121eSVineeth Remanan Pillai 			     struct page **pagep, enum sgp_type sgp,
1711c5bf121eSVineeth Remanan Pillai 			     gfp_t gfp, struct vm_area_struct *vma,
17122b740303SSouptick Joarder 			     vm_fault_t *fault_type)
17131da177e4SLinus Torvalds {
17141da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
171523f919d4SArnd Bergmann 	struct shmem_inode_info *info = SHMEM_I(inode);
171604f94e3fSDan Schatzberg 	struct mm_struct *charge_mm = vma ? vma->vm_mm : NULL;
1717b1e1ef34SYang Shi 	struct page *page;
17181da177e4SLinus Torvalds 	swp_entry_t swap;
17191da177e4SLinus Torvalds 	int error;
17201da177e4SLinus Torvalds 
1721c5bf121eSVineeth Remanan Pillai 	VM_BUG_ON(!*pagep || !xa_is_value(*pagep));
1722c5bf121eSVineeth Remanan Pillai 	swap = radix_to_swp_entry(*pagep);
1723c5bf121eSVineeth Remanan Pillai 	*pagep = NULL;
172454af6042SHugh Dickins 
17251da177e4SLinus Torvalds 	/* Look it up and read it in.. */
1726ec560175SHuang Ying 	page = lookup_swap_cache(swap, NULL, 0);
172727ab7006SHugh Dickins 	if (!page) {
17289e18eb29SAndres Lagar-Cavilla 		/* Or update major stats only when swapin succeeds?? */
17299e18eb29SAndres Lagar-Cavilla 		if (fault_type) {
173068da9f05SHugh Dickins 			*fault_type |= VM_FAULT_MAJOR;
17319e18eb29SAndres Lagar-Cavilla 			count_vm_event(PGMAJFAULT);
17322262185cSRoman Gushchin 			count_memcg_event_mm(charge_mm, PGMAJFAULT);
17339e18eb29SAndres Lagar-Cavilla 		}
17349e18eb29SAndres Lagar-Cavilla 		/* Here we actually start the io */
173541ffe5d5SHugh Dickins 		page = shmem_swapin(swap, gfp, info, index);
173627ab7006SHugh Dickins 		if (!page) {
17371da177e4SLinus Torvalds 			error = -ENOMEM;
173854af6042SHugh Dickins 			goto failed;
1739285b2c4fSHugh Dickins 		}
17401da177e4SLinus Torvalds 	}
17411da177e4SLinus Torvalds 
17421da177e4SLinus Torvalds 	/* We have to do this with page locked to prevent races */
174354af6042SHugh Dickins 	lock_page(page);
17440142ef6cSHugh Dickins 	if (!PageSwapCache(page) || page_private(page) != swap.val ||
1745d1899228SHugh Dickins 	    !shmem_confirm_swap(mapping, index, swap)) {
1746c5bf121eSVineeth Remanan Pillai 		error = -EEXIST;
1747d1899228SHugh Dickins 		goto unlock;
1748bde05d1cSHugh Dickins 	}
174927ab7006SHugh Dickins 	if (!PageUptodate(page)) {
17501da177e4SLinus Torvalds 		error = -EIO;
175154af6042SHugh Dickins 		goto failed;
175254af6042SHugh Dickins 	}
175354af6042SHugh Dickins 	wait_on_page_writeback(page);
175454af6042SHugh Dickins 
17558a84802eSSteven Price 	/*
17568a84802eSSteven Price 	 * Some architectures may have to restore extra metadata to the
17578a84802eSSteven Price 	 * physical page after reading from swap.
17588a84802eSSteven Price 	 */
17598a84802eSSteven Price 	arch_swap_restore(swap, page);
17608a84802eSSteven Price 
1761bde05d1cSHugh Dickins 	if (shmem_should_replace_page(page, gfp)) {
1762bde05d1cSHugh Dickins 		error = shmem_replace_page(&page, gfp, info, index);
1763bde05d1cSHugh Dickins 		if (error)
176454af6042SHugh Dickins 			goto failed;
17651da177e4SLinus Torvalds 	}
17661da177e4SLinus Torvalds 
17673fea5a49SJohannes Weiner 	error = shmem_add_to_page_cache(page, mapping, index,
17683fea5a49SJohannes Weiner 					swp_to_radix_entry(swap), gfp,
17693fea5a49SJohannes Weiner 					charge_mm);
177054af6042SHugh Dickins 	if (error)
177154af6042SHugh Dickins 		goto failed;
177254af6042SHugh Dickins 
17734595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
177454af6042SHugh Dickins 	info->swapped--;
177554af6042SHugh Dickins 	shmem_recalc_inode(inode);
17764595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
177727ab7006SHugh Dickins 
177866d2f4d2SHugh Dickins 	if (sgp == SGP_WRITE)
177966d2f4d2SHugh Dickins 		mark_page_accessed(page);
178066d2f4d2SHugh Dickins 
178127ab7006SHugh Dickins 	delete_from_swap_cache(page);
178227ab7006SHugh Dickins 	set_page_dirty(page);
178327ab7006SHugh Dickins 	swap_free(swap);
178427ab7006SHugh Dickins 
1785c5bf121eSVineeth Remanan Pillai 	*pagep = page;
1786c5bf121eSVineeth Remanan Pillai 	return 0;
1787c5bf121eSVineeth Remanan Pillai failed:
1788c5bf121eSVineeth Remanan Pillai 	if (!shmem_confirm_swap(mapping, index, swap))
1789c5bf121eSVineeth Remanan Pillai 		error = -EEXIST;
1790c5bf121eSVineeth Remanan Pillai unlock:
1791c5bf121eSVineeth Remanan Pillai 	if (page) {
1792c5bf121eSVineeth Remanan Pillai 		unlock_page(page);
1793c5bf121eSVineeth Remanan Pillai 		put_page(page);
1794c5bf121eSVineeth Remanan Pillai 	}
1795c5bf121eSVineeth Remanan Pillai 
1796c5bf121eSVineeth Remanan Pillai 	return error;
1797c5bf121eSVineeth Remanan Pillai }
1798c5bf121eSVineeth Remanan Pillai 
1799c5bf121eSVineeth Remanan Pillai /*
1800c5bf121eSVineeth Remanan Pillai  * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1801c5bf121eSVineeth Remanan Pillai  *
1802c5bf121eSVineeth Remanan Pillai  * If we allocate a new one we do not mark it dirty. That's up to the
1803c5bf121eSVineeth Remanan Pillai  * vm. If we swap it in we mark it dirty since we also free the swap
1804c5bf121eSVineeth Remanan Pillai  * entry since a page cannot live in both the swap and page cache.
1805c5bf121eSVineeth Remanan Pillai  *
1806c949b097SAxel Rasmussen  * vma, vmf, and fault_type are only supplied by shmem_fault:
1807c5bf121eSVineeth Remanan Pillai  * otherwise they are NULL.
1808c5bf121eSVineeth Remanan Pillai  */
1809c5bf121eSVineeth Remanan Pillai static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1810c5bf121eSVineeth Remanan Pillai 	struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1811c5bf121eSVineeth Remanan Pillai 	struct vm_area_struct *vma, struct vm_fault *vmf,
1812c5bf121eSVineeth Remanan Pillai 			vm_fault_t *fault_type)
1813c5bf121eSVineeth Remanan Pillai {
1814c5bf121eSVineeth Remanan Pillai 	struct address_space *mapping = inode->i_mapping;
1815c5bf121eSVineeth Remanan Pillai 	struct shmem_inode_info *info = SHMEM_I(inode);
1816c5bf121eSVineeth Remanan Pillai 	struct shmem_sb_info *sbinfo;
1817c5bf121eSVineeth Remanan Pillai 	struct mm_struct *charge_mm;
1818c5bf121eSVineeth Remanan Pillai 	struct page *page;
1819c5bf121eSVineeth Remanan Pillai 	pgoff_t hindex = index;
1820164cc4feSRik van Riel 	gfp_t huge_gfp;
1821c5bf121eSVineeth Remanan Pillai 	int error;
1822c5bf121eSVineeth Remanan Pillai 	int once = 0;
1823c5bf121eSVineeth Remanan Pillai 	int alloced = 0;
1824c5bf121eSVineeth Remanan Pillai 
1825c5bf121eSVineeth Remanan Pillai 	if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1826c5bf121eSVineeth Remanan Pillai 		return -EFBIG;
1827c5bf121eSVineeth Remanan Pillai repeat:
1828c5bf121eSVineeth Remanan Pillai 	if (sgp <= SGP_CACHE &&
1829c5bf121eSVineeth Remanan Pillai 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1830c5bf121eSVineeth Remanan Pillai 		return -EINVAL;
1831c5bf121eSVineeth Remanan Pillai 	}
1832c5bf121eSVineeth Remanan Pillai 
1833c5bf121eSVineeth Remanan Pillai 	sbinfo = SHMEM_SB(inode->i_sb);
183404f94e3fSDan Schatzberg 	charge_mm = vma ? vma->vm_mm : NULL;
1835c5bf121eSVineeth Remanan Pillai 
183644835d20SMatthew Wilcox (Oracle) 	page = pagecache_get_page(mapping, index,
183744835d20SMatthew Wilcox (Oracle) 					FGP_ENTRY | FGP_HEAD | FGP_LOCK, 0);
1838c949b097SAxel Rasmussen 
1839c949b097SAxel Rasmussen 	if (page && vma && userfaultfd_minor(vma)) {
1840c949b097SAxel Rasmussen 		if (!xa_is_value(page)) {
1841c949b097SAxel Rasmussen 			unlock_page(page);
1842c949b097SAxel Rasmussen 			put_page(page);
1843c949b097SAxel Rasmussen 		}
1844c949b097SAxel Rasmussen 		*fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
1845c949b097SAxel Rasmussen 		return 0;
1846c949b097SAxel Rasmussen 	}
1847c949b097SAxel Rasmussen 
1848c5bf121eSVineeth Remanan Pillai 	if (xa_is_value(page)) {
1849c5bf121eSVineeth Remanan Pillai 		error = shmem_swapin_page(inode, index, &page,
1850c5bf121eSVineeth Remanan Pillai 					  sgp, gfp, vma, fault_type);
1851c5bf121eSVineeth Remanan Pillai 		if (error == -EEXIST)
1852c5bf121eSVineeth Remanan Pillai 			goto repeat;
1853c5bf121eSVineeth Remanan Pillai 
1854c5bf121eSVineeth Remanan Pillai 		*pagep = page;
1855c5bf121eSVineeth Remanan Pillai 		return error;
1856c5bf121eSVineeth Remanan Pillai 	}
1857c5bf121eSVineeth Remanan Pillai 
1858acdd9f8eSHugh Dickins 	if (page) {
185963ec1973SMatthew Wilcox (Oracle) 		hindex = page->index;
1860acdd9f8eSHugh Dickins 		if (sgp == SGP_WRITE)
1861c5bf121eSVineeth Remanan Pillai 			mark_page_accessed(page);
1862acdd9f8eSHugh Dickins 		if (PageUptodate(page))
1863acdd9f8eSHugh Dickins 			goto out;
1864acdd9f8eSHugh Dickins 		/* fallocated page */
1865c5bf121eSVineeth Remanan Pillai 		if (sgp != SGP_READ)
1866c5bf121eSVineeth Remanan Pillai 			goto clear;
1867c5bf121eSVineeth Remanan Pillai 		unlock_page(page);
1868c5bf121eSVineeth Remanan Pillai 		put_page(page);
1869c5bf121eSVineeth Remanan Pillai 	}
1870c5bf121eSVineeth Remanan Pillai 
1871c5bf121eSVineeth Remanan Pillai 	/*
1872acdd9f8eSHugh Dickins 	 * SGP_READ: succeed on hole, with NULL page, letting caller zero.
1873acdd9f8eSHugh Dickins 	 * SGP_NOALLOC: fail on hole, with NULL page, letting caller fail.
1874acdd9f8eSHugh Dickins 	 */
1875acdd9f8eSHugh Dickins 	*pagep = NULL;
1876acdd9f8eSHugh Dickins 	if (sgp == SGP_READ)
1877acdd9f8eSHugh Dickins 		return 0;
1878acdd9f8eSHugh Dickins 	if (sgp == SGP_NOALLOC)
1879acdd9f8eSHugh Dickins 		return -ENOENT;
1880acdd9f8eSHugh Dickins 
1881acdd9f8eSHugh Dickins 	/*
1882acdd9f8eSHugh Dickins 	 * Fast cache lookup and swap lookup did not find it: allocate.
1883c5bf121eSVineeth Remanan Pillai 	 */
1884c5bf121eSVineeth Remanan Pillai 
1885cfda0526SMike Rapoport 	if (vma && userfaultfd_missing(vma)) {
1886cfda0526SMike Rapoport 		*fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1887cfda0526SMike Rapoport 		return 0;
1888cfda0526SMike Rapoport 	}
1889cfda0526SMike Rapoport 
18905e6e5a12SHugh Dickins 	/* Never use a huge page for shmem_symlink() */
18915e6e5a12SHugh Dickins 	if (S_ISLNK(inode->i_mode))
1892800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
18935e6e5a12SHugh Dickins 	if (!shmem_is_huge(vma, inode, index))
1894800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
189527d80fa2SKees Cook 
1896164cc4feSRik van Riel 	huge_gfp = vma_thp_gfp_mask(vma);
189778cc8cdcSRik van Riel 	huge_gfp = limit_gfp_mask(huge_gfp, gfp);
1898164cc4feSRik van Riel 	page = shmem_alloc_and_acct_page(huge_gfp, inode, index, true);
1899800d8c63SKirill A. Shutemov 	if (IS_ERR(page)) {
1900c5bf121eSVineeth Remanan Pillai alloc_nohuge:
1901c5bf121eSVineeth Remanan Pillai 		page = shmem_alloc_and_acct_page(gfp, inode,
1902800d8c63SKirill A. Shutemov 						 index, false);
190354af6042SHugh Dickins 	}
1904800d8c63SKirill A. Shutemov 	if (IS_ERR(page)) {
1905779750d2SKirill A. Shutemov 		int retry = 5;
1906c5bf121eSVineeth Remanan Pillai 
1907800d8c63SKirill A. Shutemov 		error = PTR_ERR(page);
1908800d8c63SKirill A. Shutemov 		page = NULL;
1909779750d2SKirill A. Shutemov 		if (error != -ENOSPC)
1910c5bf121eSVineeth Remanan Pillai 			goto unlock;
1911779750d2SKirill A. Shutemov 		/*
1912c5bf121eSVineeth Remanan Pillai 		 * Try to reclaim some space by splitting a huge page
1913779750d2SKirill A. Shutemov 		 * beyond i_size on the filesystem.
1914779750d2SKirill A. Shutemov 		 */
1915779750d2SKirill A. Shutemov 		while (retry--) {
1916779750d2SKirill A. Shutemov 			int ret;
1917c5bf121eSVineeth Remanan Pillai 
1918779750d2SKirill A. Shutemov 			ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1919779750d2SKirill A. Shutemov 			if (ret == SHRINK_STOP)
1920779750d2SKirill A. Shutemov 				break;
1921779750d2SKirill A. Shutemov 			if (ret)
1922779750d2SKirill A. Shutemov 				goto alloc_nohuge;
1923779750d2SKirill A. Shutemov 		}
1924c5bf121eSVineeth Remanan Pillai 		goto unlock;
1925800d8c63SKirill A. Shutemov 	}
1926800d8c63SKirill A. Shutemov 
1927800d8c63SKirill A. Shutemov 	if (PageTransHuge(page))
1928800d8c63SKirill A. Shutemov 		hindex = round_down(index, HPAGE_PMD_NR);
1929800d8c63SKirill A. Shutemov 	else
1930800d8c63SKirill A. Shutemov 		hindex = index;
1931800d8c63SKirill A. Shutemov 
193266d2f4d2SHugh Dickins 	if (sgp == SGP_WRITE)
1933eb39d618SHugh Dickins 		__SetPageReferenced(page);
193466d2f4d2SHugh Dickins 
1935800d8c63SKirill A. Shutemov 	error = shmem_add_to_page_cache(page, mapping, hindex,
19363fea5a49SJohannes Weiner 					NULL, gfp & GFP_RECLAIM_MASK,
19373fea5a49SJohannes Weiner 					charge_mm);
19383fea5a49SJohannes Weiner 	if (error)
1939800d8c63SKirill A. Shutemov 		goto unacct;
19406058eaecSJohannes Weiner 	lru_cache_add(page);
194154af6042SHugh Dickins 
19424595ef88SKirill A. Shutemov 	spin_lock_irq(&info->lock);
1943d8c6546bSMatthew Wilcox (Oracle) 	info->alloced += compound_nr(page);
1944800d8c63SKirill A. Shutemov 	inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
194554af6042SHugh Dickins 	shmem_recalc_inode(inode);
19464595ef88SKirill A. Shutemov 	spin_unlock_irq(&info->lock);
19471635f6a7SHugh Dickins 	alloced = true;
194854af6042SHugh Dickins 
1949779750d2SKirill A. Shutemov 	if (PageTransHuge(page) &&
1950779750d2SKirill A. Shutemov 	    DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1951779750d2SKirill A. Shutemov 			hindex + HPAGE_PMD_NR - 1) {
1952779750d2SKirill A. Shutemov 		/*
1953779750d2SKirill A. Shutemov 		 * Part of the huge page is beyond i_size: subject
1954779750d2SKirill A. Shutemov 		 * to shrink under memory pressure.
1955779750d2SKirill A. Shutemov 		 */
1956779750d2SKirill A. Shutemov 		spin_lock(&sbinfo->shrinklist_lock);
1957d041353dSCong Wang 		/*
1958d041353dSCong Wang 		 * _careful to defend against unlocked access to
1959d041353dSCong Wang 		 * ->shrink_list in shmem_unused_huge_shrink()
1960d041353dSCong Wang 		 */
1961d041353dSCong Wang 		if (list_empty_careful(&info->shrinklist)) {
1962779750d2SKirill A. Shutemov 			list_add_tail(&info->shrinklist,
1963779750d2SKirill A. Shutemov 				      &sbinfo->shrinklist);
1964779750d2SKirill A. Shutemov 			sbinfo->shrinklist_len++;
1965779750d2SKirill A. Shutemov 		}
1966779750d2SKirill A. Shutemov 		spin_unlock(&sbinfo->shrinklist_lock);
1967779750d2SKirill A. Shutemov 	}
1968779750d2SKirill A. Shutemov 
1969ec9516fbSHugh Dickins 	/*
19701635f6a7SHugh Dickins 	 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
19711635f6a7SHugh Dickins 	 */
19721635f6a7SHugh Dickins 	if (sgp == SGP_FALLOC)
19731635f6a7SHugh Dickins 		sgp = SGP_WRITE;
19741635f6a7SHugh Dickins clear:
19751635f6a7SHugh Dickins 	/*
19761635f6a7SHugh Dickins 	 * Let SGP_WRITE caller clear ends if write does not fill page;
19771635f6a7SHugh Dickins 	 * but SGP_FALLOC on a page fallocated earlier must initialize
19781635f6a7SHugh Dickins 	 * it now, lest undo on failure cancel our earlier guarantee.
1979ec9516fbSHugh Dickins 	 */
1980800d8c63SKirill A. Shutemov 	if (sgp != SGP_WRITE && !PageUptodate(page)) {
1981800d8c63SKirill A. Shutemov 		int i;
1982800d8c63SKirill A. Shutemov 
198363ec1973SMatthew Wilcox (Oracle) 		for (i = 0; i < compound_nr(page); i++) {
198463ec1973SMatthew Wilcox (Oracle) 			clear_highpage(page + i);
198563ec1973SMatthew Wilcox (Oracle) 			flush_dcache_page(page + i);
1986800d8c63SKirill A. Shutemov 		}
198763ec1973SMatthew Wilcox (Oracle) 		SetPageUptodate(page);
1988ec9516fbSHugh Dickins 	}
1989bde05d1cSHugh Dickins 
199054af6042SHugh Dickins 	/* Perhaps the file has been truncated since we checked */
199175edd345SHugh Dickins 	if (sgp <= SGP_CACHE &&
199209cbfeafSKirill A. Shutemov 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1993267a4c76SHugh Dickins 		if (alloced) {
1994267a4c76SHugh Dickins 			ClearPageDirty(page);
1995267a4c76SHugh Dickins 			delete_from_page_cache(page);
19964595ef88SKirill A. Shutemov 			spin_lock_irq(&info->lock);
1997267a4c76SHugh Dickins 			shmem_recalc_inode(inode);
19984595ef88SKirill A. Shutemov 			spin_unlock_irq(&info->lock);
1999267a4c76SHugh Dickins 		}
200054af6042SHugh Dickins 		error = -EINVAL;
2001267a4c76SHugh Dickins 		goto unlock;
2002ff36b801SShaohua Li 	}
200363ec1973SMatthew Wilcox (Oracle) out:
2004800d8c63SKirill A. Shutemov 	*pagep = page + index - hindex;
200554af6042SHugh Dickins 	return 0;
2006d00806b1SNick Piggin 
2007d0217ac0SNick Piggin 	/*
200854af6042SHugh Dickins 	 * Error recovery.
20091da177e4SLinus Torvalds 	 */
201054af6042SHugh Dickins unacct:
2011d8c6546bSMatthew Wilcox (Oracle) 	shmem_inode_unacct_blocks(inode, compound_nr(page));
2012800d8c63SKirill A. Shutemov 
2013800d8c63SKirill A. Shutemov 	if (PageTransHuge(page)) {
2014800d8c63SKirill A. Shutemov 		unlock_page(page);
2015800d8c63SKirill A. Shutemov 		put_page(page);
2016800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
2017800d8c63SKirill A. Shutemov 	}
2018d1899228SHugh Dickins unlock:
201927ab7006SHugh Dickins 	if (page) {
202054af6042SHugh Dickins 		unlock_page(page);
202109cbfeafSKirill A. Shutemov 		put_page(page);
202254af6042SHugh Dickins 	}
202354af6042SHugh Dickins 	if (error == -ENOSPC && !once++) {
20244595ef88SKirill A. Shutemov 		spin_lock_irq(&info->lock);
202554af6042SHugh Dickins 		shmem_recalc_inode(inode);
20264595ef88SKirill A. Shutemov 		spin_unlock_irq(&info->lock);
20271da177e4SLinus Torvalds 		goto repeat;
2028d8dc74f2SAdrian Bunk 	}
20297f4446eeSMatthew Wilcox 	if (error == -EEXIST)
203054af6042SHugh Dickins 		goto repeat;
203154af6042SHugh Dickins 	return error;
20321da177e4SLinus Torvalds }
20331da177e4SLinus Torvalds 
203410d20bd2SLinus Torvalds /*
203510d20bd2SLinus Torvalds  * This is like autoremove_wake_function, but it removes the wait queue
203610d20bd2SLinus Torvalds  * entry unconditionally - even if something else had already woken the
203710d20bd2SLinus Torvalds  * target.
203810d20bd2SLinus Torvalds  */
2039ac6424b9SIngo Molnar static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
204010d20bd2SLinus Torvalds {
204110d20bd2SLinus Torvalds 	int ret = default_wake_function(wait, mode, sync, key);
20422055da97SIngo Molnar 	list_del_init(&wait->entry);
204310d20bd2SLinus Torvalds 	return ret;
204410d20bd2SLinus Torvalds }
204510d20bd2SLinus Torvalds 
204620acce67SSouptick Joarder static vm_fault_t shmem_fault(struct vm_fault *vmf)
20471da177e4SLinus Torvalds {
204811bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
2049496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
20509e18eb29SAndres Lagar-Cavilla 	gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
205120acce67SSouptick Joarder 	int err;
205220acce67SSouptick Joarder 	vm_fault_t ret = VM_FAULT_LOCKED;
20531da177e4SLinus Torvalds 
2054f00cdc6dSHugh Dickins 	/*
2055f00cdc6dSHugh Dickins 	 * Trinity finds that probing a hole which tmpfs is punching can
2056f00cdc6dSHugh Dickins 	 * prevent the hole-punch from ever completing: which in turn
2057f00cdc6dSHugh Dickins 	 * locks writers out with its hold on i_mutex.  So refrain from
20588e205f77SHugh Dickins 	 * faulting pages into the hole while it's being punched.  Although
20598e205f77SHugh Dickins 	 * shmem_undo_range() does remove the additions, it may be unable to
20608e205f77SHugh Dickins 	 * keep up, as each new page needs its own unmap_mapping_range() call,
20618e205f77SHugh Dickins 	 * and the i_mmap tree grows ever slower to scan if new vmas are added.
20628e205f77SHugh Dickins 	 *
20638e205f77SHugh Dickins 	 * It does not matter if we sometimes reach this check just before the
20648e205f77SHugh Dickins 	 * hole-punch begins, so that one fault then races with the punch:
20658e205f77SHugh Dickins 	 * we just need to make racing faults a rare case.
20668e205f77SHugh Dickins 	 *
20678e205f77SHugh Dickins 	 * The implementation below would be much simpler if we just used a
20688e205f77SHugh Dickins 	 * standard mutex or completion: but we cannot take i_mutex in fault,
20698e205f77SHugh Dickins 	 * and bloating every shmem inode for this unlikely case would be sad.
2070f00cdc6dSHugh Dickins 	 */
2071f00cdc6dSHugh Dickins 	if (unlikely(inode->i_private)) {
2072f00cdc6dSHugh Dickins 		struct shmem_falloc *shmem_falloc;
2073f00cdc6dSHugh Dickins 
2074f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
2075f00cdc6dSHugh Dickins 		shmem_falloc = inode->i_private;
20768e205f77SHugh Dickins 		if (shmem_falloc &&
20778e205f77SHugh Dickins 		    shmem_falloc->waitq &&
20788e205f77SHugh Dickins 		    vmf->pgoff >= shmem_falloc->start &&
20798e205f77SHugh Dickins 		    vmf->pgoff < shmem_falloc->next) {
20808897c1b1SKirill A. Shutemov 			struct file *fpin;
20818e205f77SHugh Dickins 			wait_queue_head_t *shmem_falloc_waitq;
208210d20bd2SLinus Torvalds 			DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
20838e205f77SHugh Dickins 
20848e205f77SHugh Dickins 			ret = VM_FAULT_NOPAGE;
20858897c1b1SKirill A. Shutemov 			fpin = maybe_unlock_mmap_for_io(vmf, NULL);
20868897c1b1SKirill A. Shutemov 			if (fpin)
20878e205f77SHugh Dickins 				ret = VM_FAULT_RETRY;
20888e205f77SHugh Dickins 
20898e205f77SHugh Dickins 			shmem_falloc_waitq = shmem_falloc->waitq;
20908e205f77SHugh Dickins 			prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
20918e205f77SHugh Dickins 					TASK_UNINTERRUPTIBLE);
20928e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
20938e205f77SHugh Dickins 			schedule();
20948e205f77SHugh Dickins 
20958e205f77SHugh Dickins 			/*
20968e205f77SHugh Dickins 			 * shmem_falloc_waitq points into the shmem_fallocate()
20978e205f77SHugh Dickins 			 * stack of the hole-punching task: shmem_falloc_waitq
20988e205f77SHugh Dickins 			 * is usually invalid by the time we reach here, but
20998e205f77SHugh Dickins 			 * finish_wait() does not dereference it in that case;
21008e205f77SHugh Dickins 			 * though i_lock needed lest racing with wake_up_all().
21018e205f77SHugh Dickins 			 */
21028e205f77SHugh Dickins 			spin_lock(&inode->i_lock);
21038e205f77SHugh Dickins 			finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
21048e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
21058897c1b1SKirill A. Shutemov 
21068897c1b1SKirill A. Shutemov 			if (fpin)
21078897c1b1SKirill A. Shutemov 				fput(fpin);
21088e205f77SHugh Dickins 			return ret;
2109f00cdc6dSHugh Dickins 		}
21108e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
2111f00cdc6dSHugh Dickins 	}
2112f00cdc6dSHugh Dickins 
21135e6e5a12SHugh Dickins 	err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, SGP_CACHE,
2114cfda0526SMike Rapoport 				  gfp, vma, vmf, &ret);
211520acce67SSouptick Joarder 	if (err)
211620acce67SSouptick Joarder 		return vmf_error(err);
211768da9f05SHugh Dickins 	return ret;
21181da177e4SLinus Torvalds }
21191da177e4SLinus Torvalds 
2120c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
2121c01d5b30SHugh Dickins 				      unsigned long uaddr, unsigned long len,
2122c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
2123c01d5b30SHugh Dickins {
2124c01d5b30SHugh Dickins 	unsigned long (*get_area)(struct file *,
2125c01d5b30SHugh Dickins 		unsigned long, unsigned long, unsigned long, unsigned long);
2126c01d5b30SHugh Dickins 	unsigned long addr;
2127c01d5b30SHugh Dickins 	unsigned long offset;
2128c01d5b30SHugh Dickins 	unsigned long inflated_len;
2129c01d5b30SHugh Dickins 	unsigned long inflated_addr;
2130c01d5b30SHugh Dickins 	unsigned long inflated_offset;
2131c01d5b30SHugh Dickins 
2132c01d5b30SHugh Dickins 	if (len > TASK_SIZE)
2133c01d5b30SHugh Dickins 		return -ENOMEM;
2134c01d5b30SHugh Dickins 
2135c01d5b30SHugh Dickins 	get_area = current->mm->get_unmapped_area;
2136c01d5b30SHugh Dickins 	addr = get_area(file, uaddr, len, pgoff, flags);
2137c01d5b30SHugh Dickins 
2138396bcc52SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
2139c01d5b30SHugh Dickins 		return addr;
2140c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(addr))
2141c01d5b30SHugh Dickins 		return addr;
2142c01d5b30SHugh Dickins 	if (addr & ~PAGE_MASK)
2143c01d5b30SHugh Dickins 		return addr;
2144c01d5b30SHugh Dickins 	if (addr > TASK_SIZE - len)
2145c01d5b30SHugh Dickins 		return addr;
2146c01d5b30SHugh Dickins 
2147c01d5b30SHugh Dickins 	if (shmem_huge == SHMEM_HUGE_DENY)
2148c01d5b30SHugh Dickins 		return addr;
2149c01d5b30SHugh Dickins 	if (len < HPAGE_PMD_SIZE)
2150c01d5b30SHugh Dickins 		return addr;
2151c01d5b30SHugh Dickins 	if (flags & MAP_FIXED)
2152c01d5b30SHugh Dickins 		return addr;
2153c01d5b30SHugh Dickins 	/*
2154c01d5b30SHugh Dickins 	 * Our priority is to support MAP_SHARED mapped hugely;
2155c01d5b30SHugh Dickins 	 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
215699158997SKirill A. Shutemov 	 * But if caller specified an address hint and we allocated area there
215799158997SKirill A. Shutemov 	 * successfully, respect that as before.
2158c01d5b30SHugh Dickins 	 */
215999158997SKirill A. Shutemov 	if (uaddr == addr)
2160c01d5b30SHugh Dickins 		return addr;
2161c01d5b30SHugh Dickins 
2162c01d5b30SHugh Dickins 	if (shmem_huge != SHMEM_HUGE_FORCE) {
2163c01d5b30SHugh Dickins 		struct super_block *sb;
2164c01d5b30SHugh Dickins 
2165c01d5b30SHugh Dickins 		if (file) {
2166c01d5b30SHugh Dickins 			VM_BUG_ON(file->f_op != &shmem_file_operations);
2167c01d5b30SHugh Dickins 			sb = file_inode(file)->i_sb;
2168c01d5b30SHugh Dickins 		} else {
2169c01d5b30SHugh Dickins 			/*
2170c01d5b30SHugh Dickins 			 * Called directly from mm/mmap.c, or drivers/char/mem.c
2171c01d5b30SHugh Dickins 			 * for "/dev/zero", to create a shared anonymous object.
2172c01d5b30SHugh Dickins 			 */
2173c01d5b30SHugh Dickins 			if (IS_ERR(shm_mnt))
2174c01d5b30SHugh Dickins 				return addr;
2175c01d5b30SHugh Dickins 			sb = shm_mnt->mnt_sb;
2176c01d5b30SHugh Dickins 		}
21773089bf61SToshi Kani 		if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2178c01d5b30SHugh Dickins 			return addr;
2179c01d5b30SHugh Dickins 	}
2180c01d5b30SHugh Dickins 
2181c01d5b30SHugh Dickins 	offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2182c01d5b30SHugh Dickins 	if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2183c01d5b30SHugh Dickins 		return addr;
2184c01d5b30SHugh Dickins 	if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2185c01d5b30SHugh Dickins 		return addr;
2186c01d5b30SHugh Dickins 
2187c01d5b30SHugh Dickins 	inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2188c01d5b30SHugh Dickins 	if (inflated_len > TASK_SIZE)
2189c01d5b30SHugh Dickins 		return addr;
2190c01d5b30SHugh Dickins 	if (inflated_len < len)
2191c01d5b30SHugh Dickins 		return addr;
2192c01d5b30SHugh Dickins 
219399158997SKirill A. Shutemov 	inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
2194c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(inflated_addr))
2195c01d5b30SHugh Dickins 		return addr;
2196c01d5b30SHugh Dickins 	if (inflated_addr & ~PAGE_MASK)
2197c01d5b30SHugh Dickins 		return addr;
2198c01d5b30SHugh Dickins 
2199c01d5b30SHugh Dickins 	inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2200c01d5b30SHugh Dickins 	inflated_addr += offset - inflated_offset;
2201c01d5b30SHugh Dickins 	if (inflated_offset > offset)
2202c01d5b30SHugh Dickins 		inflated_addr += HPAGE_PMD_SIZE;
2203c01d5b30SHugh Dickins 
2204c01d5b30SHugh Dickins 	if (inflated_addr > TASK_SIZE - len)
2205c01d5b30SHugh Dickins 		return addr;
2206c01d5b30SHugh Dickins 	return inflated_addr;
2207c01d5b30SHugh Dickins }
2208c01d5b30SHugh Dickins 
22091da177e4SLinus Torvalds #ifdef CONFIG_NUMA
221041ffe5d5SHugh Dickins static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
22111da177e4SLinus Torvalds {
2212496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
221341ffe5d5SHugh Dickins 	return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
22141da177e4SLinus Torvalds }
22151da177e4SLinus Torvalds 
2216d8dc74f2SAdrian Bunk static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2217d8dc74f2SAdrian Bunk 					  unsigned long addr)
22181da177e4SLinus Torvalds {
2219496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
222041ffe5d5SHugh Dickins 	pgoff_t index;
22211da177e4SLinus Torvalds 
222241ffe5d5SHugh Dickins 	index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
222341ffe5d5SHugh Dickins 	return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
22241da177e4SLinus Torvalds }
22251da177e4SLinus Torvalds #endif
22261da177e4SLinus Torvalds 
2227d7c9e99aSAlexey Gladkov int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
22281da177e4SLinus Torvalds {
2229496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
22301da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
22311da177e4SLinus Torvalds 	int retval = -ENOMEM;
22321da177e4SLinus Torvalds 
2233ea0dfeb4SHugh Dickins 	/*
2234ea0dfeb4SHugh Dickins 	 * What serializes the accesses to info->flags?
2235ea0dfeb4SHugh Dickins 	 * ipc_lock_object() when called from shmctl_do_lock(),
2236ea0dfeb4SHugh Dickins 	 * no serialization needed when called from shm_destroy().
2237ea0dfeb4SHugh Dickins 	 */
22381da177e4SLinus Torvalds 	if (lock && !(info->flags & VM_LOCKED)) {
2239d7c9e99aSAlexey Gladkov 		if (!user_shm_lock(inode->i_size, ucounts))
22401da177e4SLinus Torvalds 			goto out_nomem;
22411da177e4SLinus Torvalds 		info->flags |= VM_LOCKED;
224289e004eaSLee Schermerhorn 		mapping_set_unevictable(file->f_mapping);
22431da177e4SLinus Torvalds 	}
2244d7c9e99aSAlexey Gladkov 	if (!lock && (info->flags & VM_LOCKED) && ucounts) {
2245d7c9e99aSAlexey Gladkov 		user_shm_unlock(inode->i_size, ucounts);
22461da177e4SLinus Torvalds 		info->flags &= ~VM_LOCKED;
224789e004eaSLee Schermerhorn 		mapping_clear_unevictable(file->f_mapping);
22481da177e4SLinus Torvalds 	}
22491da177e4SLinus Torvalds 	retval = 0;
225089e004eaSLee Schermerhorn 
22511da177e4SLinus Torvalds out_nomem:
22521da177e4SLinus Torvalds 	return retval;
22531da177e4SLinus Torvalds }
22541da177e4SLinus Torvalds 
22559b83a6a8SAdrian Bunk static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
22561da177e4SLinus Torvalds {
2257ab3948f5SJoel Fernandes (Google) 	struct shmem_inode_info *info = SHMEM_I(file_inode(file));
225822247efdSPeter Xu 	int ret;
2259ab3948f5SJoel Fernandes (Google) 
226022247efdSPeter Xu 	ret = seal_check_future_write(info->seals, vma);
226122247efdSPeter Xu 	if (ret)
226222247efdSPeter Xu 		return ret;
2263ab3948f5SJoel Fernandes (Google) 
226451b0bff2SCatalin Marinas 	/* arm64 - allow memory tagging on RAM-based files */
226551b0bff2SCatalin Marinas 	vma->vm_flags |= VM_MTE_ALLOWED;
226651b0bff2SCatalin Marinas 
22671da177e4SLinus Torvalds 	file_accessed(file);
22681da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
2269396bcc52SMatthew Wilcox (Oracle) 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
2270f3f0e1d2SKirill A. Shutemov 			((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2271f3f0e1d2SKirill A. Shutemov 			(vma->vm_end & HPAGE_PMD_MASK)) {
2272f3f0e1d2SKirill A. Shutemov 		khugepaged_enter(vma, vma->vm_flags);
2273f3f0e1d2SKirill A. Shutemov 	}
22741da177e4SLinus Torvalds 	return 0;
22751da177e4SLinus Torvalds }
22761da177e4SLinus Torvalds 
2277454abafeSDmitry Monakhov static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
227809208d15SAl Viro 				     umode_t mode, dev_t dev, unsigned long flags)
22791da177e4SLinus Torvalds {
22801da177e4SLinus Torvalds 	struct inode *inode;
22811da177e4SLinus Torvalds 	struct shmem_inode_info *info;
22821da177e4SLinus Torvalds 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2283e809d5f0SChris Down 	ino_t ino;
22841da177e4SLinus Torvalds 
2285e809d5f0SChris Down 	if (shmem_reserve_inode(sb, &ino))
22861da177e4SLinus Torvalds 		return NULL;
22871da177e4SLinus Torvalds 
22881da177e4SLinus Torvalds 	inode = new_inode(sb);
22891da177e4SLinus Torvalds 	if (inode) {
2290e809d5f0SChris Down 		inode->i_ino = ino;
229121cb47beSChristian Brauner 		inode_init_owner(&init_user_ns, inode, dir, mode);
22921da177e4SLinus Torvalds 		inode->i_blocks = 0;
2293078cd827SDeepa Dinamani 		inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
229446c9a946SArnd Bergmann 		inode->i_generation = prandom_u32();
22951da177e4SLinus Torvalds 		info = SHMEM_I(inode);
22961da177e4SLinus Torvalds 		memset(info, 0, (char *)inode - (char *)info);
22971da177e4SLinus Torvalds 		spin_lock_init(&info->lock);
2298af53d3e9SHugh Dickins 		atomic_set(&info->stop_eviction, 0);
229940e041a2SDavid Herrmann 		info->seals = F_SEAL_SEAL;
23000b0a0806SHugh Dickins 		info->flags = flags & VM_NORESERVE;
2301779750d2SKirill A. Shutemov 		INIT_LIST_HEAD(&info->shrinklist);
23021da177e4SLinus Torvalds 		INIT_LIST_HEAD(&info->swaplist);
230338f38657SAristeu Rozanski 		simple_xattrs_init(&info->xattrs);
230472c04902SAl Viro 		cache_no_acl(inode);
23051da177e4SLinus Torvalds 
23061da177e4SLinus Torvalds 		switch (mode & S_IFMT) {
23071da177e4SLinus Torvalds 		default:
230839f0247dSAndreas Gruenbacher 			inode->i_op = &shmem_special_inode_operations;
23091da177e4SLinus Torvalds 			init_special_inode(inode, mode, dev);
23101da177e4SLinus Torvalds 			break;
23111da177e4SLinus Torvalds 		case S_IFREG:
231214fcc23fSHugh Dickins 			inode->i_mapping->a_ops = &shmem_aops;
23131da177e4SLinus Torvalds 			inode->i_op = &shmem_inode_operations;
23141da177e4SLinus Torvalds 			inode->i_fop = &shmem_file_operations;
231571fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy,
231671fe804bSLee Schermerhorn 						 shmem_get_sbmpol(sbinfo));
23171da177e4SLinus Torvalds 			break;
23181da177e4SLinus Torvalds 		case S_IFDIR:
2319d8c76e6fSDave Hansen 			inc_nlink(inode);
23201da177e4SLinus Torvalds 			/* Some things misbehave if size == 0 on a directory */
23211da177e4SLinus Torvalds 			inode->i_size = 2 * BOGO_DIRENT_SIZE;
23221da177e4SLinus Torvalds 			inode->i_op = &shmem_dir_inode_operations;
23231da177e4SLinus Torvalds 			inode->i_fop = &simple_dir_operations;
23241da177e4SLinus Torvalds 			break;
23251da177e4SLinus Torvalds 		case S_IFLNK:
23261da177e4SLinus Torvalds 			/*
23271da177e4SLinus Torvalds 			 * Must not load anything in the rbtree,
23281da177e4SLinus Torvalds 			 * mpol_free_shared_policy will not be called.
23291da177e4SLinus Torvalds 			 */
233071fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy, NULL);
23311da177e4SLinus Torvalds 			break;
23321da177e4SLinus Torvalds 		}
2333b45d71fbSJoel Fernandes (Google) 
2334b45d71fbSJoel Fernandes (Google) 		lockdep_annotate_inode_mutex_key(inode);
23355b04c689SPavel Emelyanov 	} else
23365b04c689SPavel Emelyanov 		shmem_free_inode(sb);
23371da177e4SLinus Torvalds 	return inode;
23381da177e4SLinus Torvalds }
23391da177e4SLinus Torvalds 
23403460f6e5SAxel Rasmussen #ifdef CONFIG_USERFAULTFD
23413460f6e5SAxel Rasmussen int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
23424c27fe4cSMike Rapoport 			   pmd_t *dst_pmd,
23434c27fe4cSMike Rapoport 			   struct vm_area_struct *dst_vma,
23444c27fe4cSMike Rapoport 			   unsigned long dst_addr,
23454c27fe4cSMike Rapoport 			   unsigned long src_addr,
23468d103963SMike Rapoport 			   bool zeropage,
23474c27fe4cSMike Rapoport 			   struct page **pagep)
23484c27fe4cSMike Rapoport {
23494c27fe4cSMike Rapoport 	struct inode *inode = file_inode(dst_vma->vm_file);
23504c27fe4cSMike Rapoport 	struct shmem_inode_info *info = SHMEM_I(inode);
23514c27fe4cSMike Rapoport 	struct address_space *mapping = inode->i_mapping;
23524c27fe4cSMike Rapoport 	gfp_t gfp = mapping_gfp_mask(mapping);
23534c27fe4cSMike Rapoport 	pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
23544c27fe4cSMike Rapoport 	void *page_kaddr;
23554c27fe4cSMike Rapoport 	struct page *page;
23564c27fe4cSMike Rapoport 	int ret;
23573460f6e5SAxel Rasmussen 	pgoff_t max_off;
23584c27fe4cSMike Rapoport 
23597ed9d238SAxel Rasmussen 	if (!shmem_inode_acct_block(inode, 1)) {
23607ed9d238SAxel Rasmussen 		/*
23617ed9d238SAxel Rasmussen 		 * We may have got a page, returned -ENOENT triggering a retry,
23627ed9d238SAxel Rasmussen 		 * and now we find ourselves with -ENOMEM. Release the page, to
23637ed9d238SAxel Rasmussen 		 * avoid a BUG_ON in our caller.
23647ed9d238SAxel Rasmussen 		 */
23657ed9d238SAxel Rasmussen 		if (unlikely(*pagep)) {
23667ed9d238SAxel Rasmussen 			put_page(*pagep);
23677ed9d238SAxel Rasmussen 			*pagep = NULL;
23687ed9d238SAxel Rasmussen 		}
23697d64ae3aSAxel Rasmussen 		return -ENOMEM;
23707ed9d238SAxel Rasmussen 	}
23714c27fe4cSMike Rapoport 
2372cb658a45SAndrea Arcangeli 	if (!*pagep) {
23737d64ae3aSAxel Rasmussen 		ret = -ENOMEM;
23744c27fe4cSMike Rapoport 		page = shmem_alloc_page(gfp, info, pgoff);
23754c27fe4cSMike Rapoport 		if (!page)
23760f079694SMike Rapoport 			goto out_unacct_blocks;
23774c27fe4cSMike Rapoport 
23783460f6e5SAxel Rasmussen 		if (!zeropage) {	/* COPY */
23794c27fe4cSMike Rapoport 			page_kaddr = kmap_atomic(page);
23808d103963SMike Rapoport 			ret = copy_from_user(page_kaddr,
23818d103963SMike Rapoport 					     (const void __user *)src_addr,
23824c27fe4cSMike Rapoport 					     PAGE_SIZE);
23834c27fe4cSMike Rapoport 			kunmap_atomic(page_kaddr);
23844c27fe4cSMike Rapoport 
2385c1e8d7c6SMichel Lespinasse 			/* fallback to copy_from_user outside mmap_lock */
23864c27fe4cSMike Rapoport 			if (unlikely(ret)) {
23874c27fe4cSMike Rapoport 				*pagep = page;
23887d64ae3aSAxel Rasmussen 				ret = -ENOENT;
23894c27fe4cSMike Rapoport 				/* don't free the page */
23907d64ae3aSAxel Rasmussen 				goto out_unacct_blocks;
23914c27fe4cSMike Rapoport 			}
23923460f6e5SAxel Rasmussen 		} else {		/* ZEROPAGE */
23938d103963SMike Rapoport 			clear_highpage(page);
23948d103963SMike Rapoport 		}
23954c27fe4cSMike Rapoport 	} else {
23964c27fe4cSMike Rapoport 		page = *pagep;
23974c27fe4cSMike Rapoport 		*pagep = NULL;
23984c27fe4cSMike Rapoport 	}
23994c27fe4cSMike Rapoport 
24003460f6e5SAxel Rasmussen 	VM_BUG_ON(PageLocked(page));
24013460f6e5SAxel Rasmussen 	VM_BUG_ON(PageSwapBacked(page));
24029cc90c66SAndrea Arcangeli 	__SetPageLocked(page);
24039cc90c66SAndrea Arcangeli 	__SetPageSwapBacked(page);
2404a425d358SAndrea Arcangeli 	__SetPageUptodate(page);
24059cc90c66SAndrea Arcangeli 
2406e2a50c1fSAndrea Arcangeli 	ret = -EFAULT;
2407e2a50c1fSAndrea Arcangeli 	max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
24083460f6e5SAxel Rasmussen 	if (unlikely(pgoff >= max_off))
2409e2a50c1fSAndrea Arcangeli 		goto out_release;
2410e2a50c1fSAndrea Arcangeli 
24113fea5a49SJohannes Weiner 	ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
24123fea5a49SJohannes Weiner 				      gfp & GFP_RECLAIM_MASK, dst_mm);
24134c27fe4cSMike Rapoport 	if (ret)
24144c27fe4cSMike Rapoport 		goto out_release;
24154c27fe4cSMike Rapoport 
24167d64ae3aSAxel Rasmussen 	ret = mfill_atomic_install_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
24177d64ae3aSAxel Rasmussen 				       page, true, false);
24187d64ae3aSAxel Rasmussen 	if (ret)
24197d64ae3aSAxel Rasmussen 		goto out_delete_from_cache;
24204c27fe4cSMike Rapoport 
242194b7cc01SYang Shi 	spin_lock_irq(&info->lock);
24224c27fe4cSMike Rapoport 	info->alloced++;
24234c27fe4cSMike Rapoport 	inode->i_blocks += BLOCKS_PER_PAGE;
24244c27fe4cSMike Rapoport 	shmem_recalc_inode(inode);
242594b7cc01SYang Shi 	spin_unlock_irq(&info->lock);
24264c27fe4cSMike Rapoport 
24277d64ae3aSAxel Rasmussen 	SetPageDirty(page);
2428e2a50c1fSAndrea Arcangeli 	unlock_page(page);
24297d64ae3aSAxel Rasmussen 	return 0;
24307d64ae3aSAxel Rasmussen out_delete_from_cache:
2431e2a50c1fSAndrea Arcangeli 	delete_from_page_cache(page);
24324c27fe4cSMike Rapoport out_release:
24339cc90c66SAndrea Arcangeli 	unlock_page(page);
24344c27fe4cSMike Rapoport 	put_page(page);
24354c27fe4cSMike Rapoport out_unacct_blocks:
24360f079694SMike Rapoport 	shmem_inode_unacct_blocks(inode, 1);
24377d64ae3aSAxel Rasmussen 	return ret;
24384c27fe4cSMike Rapoport }
24393460f6e5SAxel Rasmussen #endif /* CONFIG_USERFAULTFD */
24408d103963SMike Rapoport 
24411da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
244292e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations;
244369f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations;
24441da177e4SLinus Torvalds 
24456d9d88d0SJarkko Sakkinen #ifdef CONFIG_TMPFS_XATTR
24466d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
24476d9d88d0SJarkko Sakkinen #else
24486d9d88d0SJarkko Sakkinen #define shmem_initxattrs NULL
24496d9d88d0SJarkko Sakkinen #endif
24506d9d88d0SJarkko Sakkinen 
24511da177e4SLinus Torvalds static int
2452800d15a5SNick Piggin shmem_write_begin(struct file *file, struct address_space *mapping,
2453800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned flags,
2454800d15a5SNick Piggin 			struct page **pagep, void **fsdata)
24551da177e4SLinus Torvalds {
2456800d15a5SNick Piggin 	struct inode *inode = mapping->host;
245740e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
245809cbfeafSKirill A. Shutemov 	pgoff_t index = pos >> PAGE_SHIFT;
245940e041a2SDavid Herrmann 
246040e041a2SDavid Herrmann 	/* i_mutex is held by caller */
2461ab3948f5SJoel Fernandes (Google) 	if (unlikely(info->seals & (F_SEAL_GROW |
2462ab3948f5SJoel Fernandes (Google) 				   F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
2463ab3948f5SJoel Fernandes (Google) 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
246440e041a2SDavid Herrmann 			return -EPERM;
246540e041a2SDavid Herrmann 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
246640e041a2SDavid Herrmann 			return -EPERM;
246740e041a2SDavid Herrmann 	}
246840e041a2SDavid Herrmann 
24699e18eb29SAndres Lagar-Cavilla 	return shmem_getpage(inode, index, pagep, SGP_WRITE);
2470800d15a5SNick Piggin }
2471800d15a5SNick Piggin 
2472800d15a5SNick Piggin static int
2473800d15a5SNick Piggin shmem_write_end(struct file *file, struct address_space *mapping,
2474800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned copied,
2475800d15a5SNick Piggin 			struct page *page, void *fsdata)
2476800d15a5SNick Piggin {
2477800d15a5SNick Piggin 	struct inode *inode = mapping->host;
2478800d15a5SNick Piggin 
2479800d15a5SNick Piggin 	if (pos + copied > inode->i_size)
2480800d15a5SNick Piggin 		i_size_write(inode, pos + copied);
2481800d15a5SNick Piggin 
2482ec9516fbSHugh Dickins 	if (!PageUptodate(page)) {
2483800d8c63SKirill A. Shutemov 		struct page *head = compound_head(page);
2484800d8c63SKirill A. Shutemov 		if (PageTransCompound(page)) {
2485800d8c63SKirill A. Shutemov 			int i;
2486800d8c63SKirill A. Shutemov 
2487800d8c63SKirill A. Shutemov 			for (i = 0; i < HPAGE_PMD_NR; i++) {
2488800d8c63SKirill A. Shutemov 				if (head + i == page)
2489800d8c63SKirill A. Shutemov 					continue;
2490800d8c63SKirill A. Shutemov 				clear_highpage(head + i);
2491800d8c63SKirill A. Shutemov 				flush_dcache_page(head + i);
2492800d8c63SKirill A. Shutemov 			}
2493800d8c63SKirill A. Shutemov 		}
249409cbfeafSKirill A. Shutemov 		if (copied < PAGE_SIZE) {
249509cbfeafSKirill A. Shutemov 			unsigned from = pos & (PAGE_SIZE - 1);
2496ec9516fbSHugh Dickins 			zero_user_segments(page, 0, from,
249709cbfeafSKirill A. Shutemov 					from + copied, PAGE_SIZE);
2498ec9516fbSHugh Dickins 		}
2499800d8c63SKirill A. Shutemov 		SetPageUptodate(head);
2500ec9516fbSHugh Dickins 	}
2501d3602444SHugh Dickins 	set_page_dirty(page);
25026746aff7SWu Fengguang 	unlock_page(page);
250309cbfeafSKirill A. Shutemov 	put_page(page);
2504d3602444SHugh Dickins 
2505800d15a5SNick Piggin 	return copied;
25061da177e4SLinus Torvalds }
25071da177e4SLinus Torvalds 
25082ba5bbedSAl Viro static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
25091da177e4SLinus Torvalds {
25106e58e79dSAl Viro 	struct file *file = iocb->ki_filp;
25116e58e79dSAl Viro 	struct inode *inode = file_inode(file);
25121da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
251341ffe5d5SHugh Dickins 	pgoff_t index;
251441ffe5d5SHugh Dickins 	unsigned long offset;
2515a0ee5ec5SHugh Dickins 	enum sgp_type sgp = SGP_READ;
2516f7c1d074SGeert Uytterhoeven 	int error = 0;
2517cb66a7a1SAl Viro 	ssize_t retval = 0;
25186e58e79dSAl Viro 	loff_t *ppos = &iocb->ki_pos;
2519a0ee5ec5SHugh Dickins 
2520a0ee5ec5SHugh Dickins 	/*
2521a0ee5ec5SHugh Dickins 	 * Might this read be for a stacking filesystem?  Then when reading
2522a0ee5ec5SHugh Dickins 	 * holes of a sparse file, we actually need to allocate those pages,
2523a0ee5ec5SHugh Dickins 	 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2524a0ee5ec5SHugh Dickins 	 */
2525777eda2cSAl Viro 	if (!iter_is_iovec(to))
252675edd345SHugh Dickins 		sgp = SGP_CACHE;
25271da177e4SLinus Torvalds 
252809cbfeafSKirill A. Shutemov 	index = *ppos >> PAGE_SHIFT;
252909cbfeafSKirill A. Shutemov 	offset = *ppos & ~PAGE_MASK;
25301da177e4SLinus Torvalds 
25311da177e4SLinus Torvalds 	for (;;) {
25321da177e4SLinus Torvalds 		struct page *page = NULL;
253341ffe5d5SHugh Dickins 		pgoff_t end_index;
253441ffe5d5SHugh Dickins 		unsigned long nr, ret;
25351da177e4SLinus Torvalds 		loff_t i_size = i_size_read(inode);
25361da177e4SLinus Torvalds 
253709cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
25381da177e4SLinus Torvalds 		if (index > end_index)
25391da177e4SLinus Torvalds 			break;
25401da177e4SLinus Torvalds 		if (index == end_index) {
254109cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
25421da177e4SLinus Torvalds 			if (nr <= offset)
25431da177e4SLinus Torvalds 				break;
25441da177e4SLinus Torvalds 		}
25451da177e4SLinus Torvalds 
25469e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, index, &page, sgp);
25476e58e79dSAl Viro 		if (error) {
25486e58e79dSAl Viro 			if (error == -EINVAL)
25496e58e79dSAl Viro 				error = 0;
25501da177e4SLinus Torvalds 			break;
25511da177e4SLinus Torvalds 		}
255275edd345SHugh Dickins 		if (page) {
255375edd345SHugh Dickins 			if (sgp == SGP_CACHE)
255475edd345SHugh Dickins 				set_page_dirty(page);
2555d3602444SHugh Dickins 			unlock_page(page);
255675edd345SHugh Dickins 		}
25571da177e4SLinus Torvalds 
25581da177e4SLinus Torvalds 		/*
25591da177e4SLinus Torvalds 		 * We must evaluate after, since reads (unlike writes)
25601b1dcc1bSJes Sorensen 		 * are called without i_mutex protection against truncate
25611da177e4SLinus Torvalds 		 */
256209cbfeafSKirill A. Shutemov 		nr = PAGE_SIZE;
25631da177e4SLinus Torvalds 		i_size = i_size_read(inode);
256409cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
25651da177e4SLinus Torvalds 		if (index == end_index) {
256609cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
25671da177e4SLinus Torvalds 			if (nr <= offset) {
25681da177e4SLinus Torvalds 				if (page)
256909cbfeafSKirill A. Shutemov 					put_page(page);
25701da177e4SLinus Torvalds 				break;
25711da177e4SLinus Torvalds 			}
25721da177e4SLinus Torvalds 		}
25731da177e4SLinus Torvalds 		nr -= offset;
25741da177e4SLinus Torvalds 
25751da177e4SLinus Torvalds 		if (page) {
25761da177e4SLinus Torvalds 			/*
25771da177e4SLinus Torvalds 			 * If users can be writing to this page using arbitrary
25781da177e4SLinus Torvalds 			 * virtual addresses, take care about potential aliasing
25791da177e4SLinus Torvalds 			 * before reading the page on the kernel side.
25801da177e4SLinus Torvalds 			 */
25811da177e4SLinus Torvalds 			if (mapping_writably_mapped(mapping))
25821da177e4SLinus Torvalds 				flush_dcache_page(page);
25831da177e4SLinus Torvalds 			/*
25841da177e4SLinus Torvalds 			 * Mark the page accessed if we read the beginning.
25851da177e4SLinus Torvalds 			 */
25861da177e4SLinus Torvalds 			if (!offset)
25871da177e4SLinus Torvalds 				mark_page_accessed(page);
2588b5810039SNick Piggin 		} else {
25891da177e4SLinus Torvalds 			page = ZERO_PAGE(0);
259009cbfeafSKirill A. Shutemov 			get_page(page);
2591b5810039SNick Piggin 		}
25921da177e4SLinus Torvalds 
25931da177e4SLinus Torvalds 		/*
25941da177e4SLinus Torvalds 		 * Ok, we have the page, and it's up-to-date, so
25951da177e4SLinus Torvalds 		 * now we can copy it to user space...
25961da177e4SLinus Torvalds 		 */
25972ba5bbedSAl Viro 		ret = copy_page_to_iter(page, offset, nr, to);
25986e58e79dSAl Viro 		retval += ret;
25991da177e4SLinus Torvalds 		offset += ret;
260009cbfeafSKirill A. Shutemov 		index += offset >> PAGE_SHIFT;
260109cbfeafSKirill A. Shutemov 		offset &= ~PAGE_MASK;
26021da177e4SLinus Torvalds 
260309cbfeafSKirill A. Shutemov 		put_page(page);
26042ba5bbedSAl Viro 		if (!iov_iter_count(to))
26051da177e4SLinus Torvalds 			break;
26066e58e79dSAl Viro 		if (ret < nr) {
26076e58e79dSAl Viro 			error = -EFAULT;
26086e58e79dSAl Viro 			break;
26096e58e79dSAl Viro 		}
26101da177e4SLinus Torvalds 		cond_resched();
26111da177e4SLinus Torvalds 	}
26121da177e4SLinus Torvalds 
261309cbfeafSKirill A. Shutemov 	*ppos = ((loff_t) index << PAGE_SHIFT) + offset;
26146e58e79dSAl Viro 	file_accessed(file);
26156e58e79dSAl Viro 	return retval ? retval : error;
26161da177e4SLinus Torvalds }
26171da177e4SLinus Torvalds 
2618965c8e59SAndrew Morton static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2619220f2ac9SHugh Dickins {
2620220f2ac9SHugh Dickins 	struct address_space *mapping = file->f_mapping;
2621220f2ac9SHugh Dickins 	struct inode *inode = mapping->host;
2622220f2ac9SHugh Dickins 
2623965c8e59SAndrew Morton 	if (whence != SEEK_DATA && whence != SEEK_HOLE)
2624965c8e59SAndrew Morton 		return generic_file_llseek_size(file, offset, whence,
2625220f2ac9SHugh Dickins 					MAX_LFS_FILESIZE, i_size_read(inode));
262641139aa4SMatthew Wilcox (Oracle) 	if (offset < 0)
262741139aa4SMatthew Wilcox (Oracle) 		return -ENXIO;
262841139aa4SMatthew Wilcox (Oracle) 
26295955102cSAl Viro 	inode_lock(inode);
2630220f2ac9SHugh Dickins 	/* We're holding i_mutex so we can access i_size directly */
263141139aa4SMatthew Wilcox (Oracle) 	offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
2632387aae6fSHugh Dickins 	if (offset >= 0)
263346a1c2c7SJie Liu 		offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
26345955102cSAl Viro 	inode_unlock(inode);
2635220f2ac9SHugh Dickins 	return offset;
2636220f2ac9SHugh Dickins }
2637220f2ac9SHugh Dickins 
263883e4fa9cSHugh Dickins static long shmem_fallocate(struct file *file, int mode, loff_t offset,
263983e4fa9cSHugh Dickins 							 loff_t len)
264083e4fa9cSHugh Dickins {
2641496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2642e2d12e22SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
264340e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
26441aac1400SHugh Dickins 	struct shmem_falloc shmem_falloc;
2645d144bf62SHugh Dickins 	pgoff_t start, index, end, undo_fallocend;
2646e2d12e22SHugh Dickins 	int error;
264783e4fa9cSHugh Dickins 
264813ace4d0SHugh Dickins 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
264913ace4d0SHugh Dickins 		return -EOPNOTSUPP;
265013ace4d0SHugh Dickins 
26515955102cSAl Viro 	inode_lock(inode);
265283e4fa9cSHugh Dickins 
265383e4fa9cSHugh Dickins 	if (mode & FALLOC_FL_PUNCH_HOLE) {
265483e4fa9cSHugh Dickins 		struct address_space *mapping = file->f_mapping;
265583e4fa9cSHugh Dickins 		loff_t unmap_start = round_up(offset, PAGE_SIZE);
265683e4fa9cSHugh Dickins 		loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
26578e205f77SHugh Dickins 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
265883e4fa9cSHugh Dickins 
265940e041a2SDavid Herrmann 		/* protected by i_mutex */
2660ab3948f5SJoel Fernandes (Google) 		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
266140e041a2SDavid Herrmann 			error = -EPERM;
266240e041a2SDavid Herrmann 			goto out;
266340e041a2SDavid Herrmann 		}
266440e041a2SDavid Herrmann 
26658e205f77SHugh Dickins 		shmem_falloc.waitq = &shmem_falloc_waitq;
2666aa71ecd8SChen Jun 		shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
2667f00cdc6dSHugh Dickins 		shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2668f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
2669f00cdc6dSHugh Dickins 		inode->i_private = &shmem_falloc;
2670f00cdc6dSHugh Dickins 		spin_unlock(&inode->i_lock);
2671f00cdc6dSHugh Dickins 
267283e4fa9cSHugh Dickins 		if ((u64)unmap_end > (u64)unmap_start)
267383e4fa9cSHugh Dickins 			unmap_mapping_range(mapping, unmap_start,
267483e4fa9cSHugh Dickins 					    1 + unmap_end - unmap_start, 0);
267583e4fa9cSHugh Dickins 		shmem_truncate_range(inode, offset, offset + len - 1);
267683e4fa9cSHugh Dickins 		/* No need to unmap again: hole-punching leaves COWed pages */
26778e205f77SHugh Dickins 
26788e205f77SHugh Dickins 		spin_lock(&inode->i_lock);
26798e205f77SHugh Dickins 		inode->i_private = NULL;
26808e205f77SHugh Dickins 		wake_up_all(&shmem_falloc_waitq);
26812055da97SIngo Molnar 		WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
26828e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
268383e4fa9cSHugh Dickins 		error = 0;
26848e205f77SHugh Dickins 		goto out;
268583e4fa9cSHugh Dickins 	}
268683e4fa9cSHugh Dickins 
2687e2d12e22SHugh Dickins 	/* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2688e2d12e22SHugh Dickins 	error = inode_newsize_ok(inode, offset + len);
2689e2d12e22SHugh Dickins 	if (error)
2690e2d12e22SHugh Dickins 		goto out;
2691e2d12e22SHugh Dickins 
269240e041a2SDavid Herrmann 	if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
269340e041a2SDavid Herrmann 		error = -EPERM;
269440e041a2SDavid Herrmann 		goto out;
269540e041a2SDavid Herrmann 	}
269640e041a2SDavid Herrmann 
269709cbfeafSKirill A. Shutemov 	start = offset >> PAGE_SHIFT;
269809cbfeafSKirill A. Shutemov 	end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2699e2d12e22SHugh Dickins 	/* Try to avoid a swapstorm if len is impossible to satisfy */
2700e2d12e22SHugh Dickins 	if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2701e2d12e22SHugh Dickins 		error = -ENOSPC;
2702e2d12e22SHugh Dickins 		goto out;
2703e2d12e22SHugh Dickins 	}
2704e2d12e22SHugh Dickins 
27058e205f77SHugh Dickins 	shmem_falloc.waitq = NULL;
27061aac1400SHugh Dickins 	shmem_falloc.start = start;
27071aac1400SHugh Dickins 	shmem_falloc.next  = start;
27081aac1400SHugh Dickins 	shmem_falloc.nr_falloced = 0;
27091aac1400SHugh Dickins 	shmem_falloc.nr_unswapped = 0;
27101aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
27111aac1400SHugh Dickins 	inode->i_private = &shmem_falloc;
27121aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
27131aac1400SHugh Dickins 
2714d144bf62SHugh Dickins 	/*
2715d144bf62SHugh Dickins 	 * info->fallocend is only relevant when huge pages might be
2716d144bf62SHugh Dickins 	 * involved: to prevent split_huge_page() freeing fallocated
2717d144bf62SHugh Dickins 	 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
2718d144bf62SHugh Dickins 	 */
2719d144bf62SHugh Dickins 	undo_fallocend = info->fallocend;
2720d144bf62SHugh Dickins 	if (info->fallocend < end)
2721d144bf62SHugh Dickins 		info->fallocend = end;
2722d144bf62SHugh Dickins 
2723050dcb5cSHugh Dickins 	for (index = start; index < end; ) {
2724e2d12e22SHugh Dickins 		struct page *page;
2725e2d12e22SHugh Dickins 
2726e2d12e22SHugh Dickins 		/*
2727e2d12e22SHugh Dickins 		 * Good, the fallocate(2) manpage permits EINTR: we may have
2728e2d12e22SHugh Dickins 		 * been interrupted because we are using up too much memory.
2729e2d12e22SHugh Dickins 		 */
2730e2d12e22SHugh Dickins 		if (signal_pending(current))
2731e2d12e22SHugh Dickins 			error = -EINTR;
27321aac1400SHugh Dickins 		else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
27331aac1400SHugh Dickins 			error = -ENOMEM;
2734e2d12e22SHugh Dickins 		else
27359e18eb29SAndres Lagar-Cavilla 			error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2736e2d12e22SHugh Dickins 		if (error) {
2737d144bf62SHugh Dickins 			info->fallocend = undo_fallocend;
27381635f6a7SHugh Dickins 			/* Remove the !PageUptodate pages we added */
27397f556567SHugh Dickins 			if (index > start) {
27401635f6a7SHugh Dickins 				shmem_undo_range(inode,
274109cbfeafSKirill A. Shutemov 				    (loff_t)start << PAGE_SHIFT,
2742b9b4bb26SAnthony Romano 				    ((loff_t)index << PAGE_SHIFT) - 1, true);
27437f556567SHugh Dickins 			}
27441aac1400SHugh Dickins 			goto undone;
2745e2d12e22SHugh Dickins 		}
2746e2d12e22SHugh Dickins 
2747050dcb5cSHugh Dickins 		index++;
2748050dcb5cSHugh Dickins 		/*
2749050dcb5cSHugh Dickins 		 * Here is a more important optimization than it appears:
2750050dcb5cSHugh Dickins 		 * a second SGP_FALLOC on the same huge page will clear it,
2751050dcb5cSHugh Dickins 		 * making it PageUptodate and un-undoable if we fail later.
2752050dcb5cSHugh Dickins 		 */
2753050dcb5cSHugh Dickins 		if (PageTransCompound(page)) {
2754050dcb5cSHugh Dickins 			index = round_up(index, HPAGE_PMD_NR);
2755050dcb5cSHugh Dickins 			/* Beware 32-bit wraparound */
2756050dcb5cSHugh Dickins 			if (!index)
2757050dcb5cSHugh Dickins 				index--;
2758050dcb5cSHugh Dickins 		}
2759050dcb5cSHugh Dickins 
2760e2d12e22SHugh Dickins 		/*
27611aac1400SHugh Dickins 		 * Inform shmem_writepage() how far we have reached.
27621aac1400SHugh Dickins 		 * No need for lock or barrier: we have the page lock.
27631aac1400SHugh Dickins 		 */
27641aac1400SHugh Dickins 		if (!PageUptodate(page))
2765050dcb5cSHugh Dickins 			shmem_falloc.nr_falloced += index - shmem_falloc.next;
2766050dcb5cSHugh Dickins 		shmem_falloc.next = index;
27671aac1400SHugh Dickins 
27681aac1400SHugh Dickins 		/*
27691635f6a7SHugh Dickins 		 * If !PageUptodate, leave it that way so that freeable pages
27701635f6a7SHugh Dickins 		 * can be recognized if we need to rollback on error later.
27711635f6a7SHugh Dickins 		 * But set_page_dirty so that memory pressure will swap rather
2772e2d12e22SHugh Dickins 		 * than free the pages we are allocating (and SGP_CACHE pages
2773e2d12e22SHugh Dickins 		 * might still be clean: we now need to mark those dirty too).
2774e2d12e22SHugh Dickins 		 */
2775e2d12e22SHugh Dickins 		set_page_dirty(page);
2776e2d12e22SHugh Dickins 		unlock_page(page);
277709cbfeafSKirill A. Shutemov 		put_page(page);
2778e2d12e22SHugh Dickins 		cond_resched();
2779e2d12e22SHugh Dickins 	}
2780e2d12e22SHugh Dickins 
2781e2d12e22SHugh Dickins 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2782e2d12e22SHugh Dickins 		i_size_write(inode, offset + len);
2783078cd827SDeepa Dinamani 	inode->i_ctime = current_time(inode);
27841aac1400SHugh Dickins undone:
27851aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
27861aac1400SHugh Dickins 	inode->i_private = NULL;
27871aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
2788e2d12e22SHugh Dickins out:
27895955102cSAl Viro 	inode_unlock(inode);
279083e4fa9cSHugh Dickins 	return error;
279183e4fa9cSHugh Dickins }
279283e4fa9cSHugh Dickins 
2793726c3342SDavid Howells static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
27941da177e4SLinus Torvalds {
2795726c3342SDavid Howells 	struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
27961da177e4SLinus Torvalds 
27971da177e4SLinus Torvalds 	buf->f_type = TMPFS_MAGIC;
279809cbfeafSKirill A. Shutemov 	buf->f_bsize = PAGE_SIZE;
27991da177e4SLinus Torvalds 	buf->f_namelen = NAME_MAX;
28000edd73b3SHugh Dickins 	if (sbinfo->max_blocks) {
28011da177e4SLinus Torvalds 		buf->f_blocks = sbinfo->max_blocks;
280241ffe5d5SHugh Dickins 		buf->f_bavail =
280341ffe5d5SHugh Dickins 		buf->f_bfree  = sbinfo->max_blocks -
280441ffe5d5SHugh Dickins 				percpu_counter_sum(&sbinfo->used_blocks);
28050edd73b3SHugh Dickins 	}
28060edd73b3SHugh Dickins 	if (sbinfo->max_inodes) {
28071da177e4SLinus Torvalds 		buf->f_files = sbinfo->max_inodes;
28081da177e4SLinus Torvalds 		buf->f_ffree = sbinfo->free_inodes;
28091da177e4SLinus Torvalds 	}
28101da177e4SLinus Torvalds 	/* else leave those fields 0 like simple_statfs */
281159cda49eSAmir Goldstein 
281259cda49eSAmir Goldstein 	buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
281359cda49eSAmir Goldstein 
28141da177e4SLinus Torvalds 	return 0;
28151da177e4SLinus Torvalds }
28161da177e4SLinus Torvalds 
28171da177e4SLinus Torvalds /*
28181da177e4SLinus Torvalds  * File creation. Allocate an inode, and we're done..
28191da177e4SLinus Torvalds  */
28201da177e4SLinus Torvalds static int
2821549c7297SChristian Brauner shmem_mknod(struct user_namespace *mnt_userns, struct inode *dir,
2822549c7297SChristian Brauner 	    struct dentry *dentry, umode_t mode, dev_t dev)
28231da177e4SLinus Torvalds {
28240b0a0806SHugh Dickins 	struct inode *inode;
28251da177e4SLinus Torvalds 	int error = -ENOSPC;
28261da177e4SLinus Torvalds 
2827454abafeSDmitry Monakhov 	inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
28281da177e4SLinus Torvalds 	if (inode) {
2829feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2830feda821eSChristoph Hellwig 		if (error)
2831feda821eSChristoph Hellwig 			goto out_iput;
28322a7dba39SEric Paris 		error = security_inode_init_security(inode, dir,
28339d8f13baSMimi Zohar 						     &dentry->d_name,
28346d9d88d0SJarkko Sakkinen 						     shmem_initxattrs, NULL);
2835feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2836feda821eSChristoph Hellwig 			goto out_iput;
283737ec43cdSMimi Zohar 
2838718deb6bSAl Viro 		error = 0;
28391da177e4SLinus Torvalds 		dir->i_size += BOGO_DIRENT_SIZE;
2840078cd827SDeepa Dinamani 		dir->i_ctime = dir->i_mtime = current_time(dir);
28411da177e4SLinus Torvalds 		d_instantiate(dentry, inode);
28421da177e4SLinus Torvalds 		dget(dentry); /* Extra count - pin the dentry in core */
28431da177e4SLinus Torvalds 	}
28441da177e4SLinus Torvalds 	return error;
2845feda821eSChristoph Hellwig out_iput:
2846feda821eSChristoph Hellwig 	iput(inode);
2847feda821eSChristoph Hellwig 	return error;
28481da177e4SLinus Torvalds }
28491da177e4SLinus Torvalds 
285060545d0dSAl Viro static int
2851549c7297SChristian Brauner shmem_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
2852549c7297SChristian Brauner 	      struct dentry *dentry, umode_t mode)
285360545d0dSAl Viro {
285460545d0dSAl Viro 	struct inode *inode;
285560545d0dSAl Viro 	int error = -ENOSPC;
285660545d0dSAl Viro 
285760545d0dSAl Viro 	inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
285860545d0dSAl Viro 	if (inode) {
285960545d0dSAl Viro 		error = security_inode_init_security(inode, dir,
286060545d0dSAl Viro 						     NULL,
286160545d0dSAl Viro 						     shmem_initxattrs, NULL);
2862feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2863feda821eSChristoph Hellwig 			goto out_iput;
2864feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2865feda821eSChristoph Hellwig 		if (error)
2866feda821eSChristoph Hellwig 			goto out_iput;
286760545d0dSAl Viro 		d_tmpfile(dentry, inode);
286860545d0dSAl Viro 	}
286960545d0dSAl Viro 	return error;
2870feda821eSChristoph Hellwig out_iput:
2871feda821eSChristoph Hellwig 	iput(inode);
2872feda821eSChristoph Hellwig 	return error;
287360545d0dSAl Viro }
287460545d0dSAl Viro 
2875549c7297SChristian Brauner static int shmem_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
2876549c7297SChristian Brauner 		       struct dentry *dentry, umode_t mode)
28771da177e4SLinus Torvalds {
28781da177e4SLinus Torvalds 	int error;
28791da177e4SLinus Torvalds 
2880549c7297SChristian Brauner 	if ((error = shmem_mknod(&init_user_ns, dir, dentry,
2881549c7297SChristian Brauner 				 mode | S_IFDIR, 0)))
28821da177e4SLinus Torvalds 		return error;
2883d8c76e6fSDave Hansen 	inc_nlink(dir);
28841da177e4SLinus Torvalds 	return 0;
28851da177e4SLinus Torvalds }
28861da177e4SLinus Torvalds 
2887549c7297SChristian Brauner static int shmem_create(struct user_namespace *mnt_userns, struct inode *dir,
2888549c7297SChristian Brauner 			struct dentry *dentry, umode_t mode, bool excl)
28891da177e4SLinus Torvalds {
2890549c7297SChristian Brauner 	return shmem_mknod(&init_user_ns, dir, dentry, mode | S_IFREG, 0);
28911da177e4SLinus Torvalds }
28921da177e4SLinus Torvalds 
28931da177e4SLinus Torvalds /*
28941da177e4SLinus Torvalds  * Link a file..
28951da177e4SLinus Torvalds  */
28961da177e4SLinus Torvalds static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
28971da177e4SLinus Torvalds {
289875c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
289929b00e60SDarrick J. Wong 	int ret = 0;
29001da177e4SLinus Torvalds 
29011da177e4SLinus Torvalds 	/*
29021da177e4SLinus Torvalds 	 * No ordinary (disk based) filesystem counts links as inodes;
29031da177e4SLinus Torvalds 	 * but each new link needs a new dentry, pinning lowmem, and
29041da177e4SLinus Torvalds 	 * tmpfs dentries cannot be pruned until they are unlinked.
29051062af92SDarrick J. Wong 	 * But if an O_TMPFILE file is linked into the tmpfs, the
29061062af92SDarrick J. Wong 	 * first link must skip that, to get the accounting right.
29071da177e4SLinus Torvalds 	 */
29081062af92SDarrick J. Wong 	if (inode->i_nlink) {
2909e809d5f0SChris Down 		ret = shmem_reserve_inode(inode->i_sb, NULL);
29105b04c689SPavel Emelyanov 		if (ret)
29115b04c689SPavel Emelyanov 			goto out;
29121062af92SDarrick J. Wong 	}
29131da177e4SLinus Torvalds 
29141da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
2915078cd827SDeepa Dinamani 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2916d8c76e6fSDave Hansen 	inc_nlink(inode);
29177de9c6eeSAl Viro 	ihold(inode);	/* New dentry reference */
29181da177e4SLinus Torvalds 	dget(dentry);		/* Extra pinning count for the created dentry */
29191da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
29205b04c689SPavel Emelyanov out:
29215b04c689SPavel Emelyanov 	return ret;
29221da177e4SLinus Torvalds }
29231da177e4SLinus Torvalds 
29241da177e4SLinus Torvalds static int shmem_unlink(struct inode *dir, struct dentry *dentry)
29251da177e4SLinus Torvalds {
292675c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
29271da177e4SLinus Torvalds 
29285b04c689SPavel Emelyanov 	if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
29295b04c689SPavel Emelyanov 		shmem_free_inode(inode->i_sb);
29301da177e4SLinus Torvalds 
29311da177e4SLinus Torvalds 	dir->i_size -= BOGO_DIRENT_SIZE;
2932078cd827SDeepa Dinamani 	inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
29339a53c3a7SDave Hansen 	drop_nlink(inode);
29341da177e4SLinus Torvalds 	dput(dentry);	/* Undo the count from "create" - this does all the work */
29351da177e4SLinus Torvalds 	return 0;
29361da177e4SLinus Torvalds }
29371da177e4SLinus Torvalds 
29381da177e4SLinus Torvalds static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
29391da177e4SLinus Torvalds {
29401da177e4SLinus Torvalds 	if (!simple_empty(dentry))
29411da177e4SLinus Torvalds 		return -ENOTEMPTY;
29421da177e4SLinus Torvalds 
294375c3cfa8SDavid Howells 	drop_nlink(d_inode(dentry));
29449a53c3a7SDave Hansen 	drop_nlink(dir);
29451da177e4SLinus Torvalds 	return shmem_unlink(dir, dentry);
29461da177e4SLinus Torvalds }
29471da177e4SLinus Torvalds 
294837456771SMiklos Szeredi static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
294937456771SMiklos Szeredi {
2950e36cb0b8SDavid Howells 	bool old_is_dir = d_is_dir(old_dentry);
2951e36cb0b8SDavid Howells 	bool new_is_dir = d_is_dir(new_dentry);
295237456771SMiklos Szeredi 
295337456771SMiklos Szeredi 	if (old_dir != new_dir && old_is_dir != new_is_dir) {
295437456771SMiklos Szeredi 		if (old_is_dir) {
295537456771SMiklos Szeredi 			drop_nlink(old_dir);
295637456771SMiklos Szeredi 			inc_nlink(new_dir);
295737456771SMiklos Szeredi 		} else {
295837456771SMiklos Szeredi 			drop_nlink(new_dir);
295937456771SMiklos Szeredi 			inc_nlink(old_dir);
296037456771SMiklos Szeredi 		}
296137456771SMiklos Szeredi 	}
296237456771SMiklos Szeredi 	old_dir->i_ctime = old_dir->i_mtime =
296337456771SMiklos Szeredi 	new_dir->i_ctime = new_dir->i_mtime =
296475c3cfa8SDavid Howells 	d_inode(old_dentry)->i_ctime =
2965078cd827SDeepa Dinamani 	d_inode(new_dentry)->i_ctime = current_time(old_dir);
296637456771SMiklos Szeredi 
296737456771SMiklos Szeredi 	return 0;
296837456771SMiklos Szeredi }
296937456771SMiklos Szeredi 
2970549c7297SChristian Brauner static int shmem_whiteout(struct user_namespace *mnt_userns,
2971549c7297SChristian Brauner 			  struct inode *old_dir, struct dentry *old_dentry)
297246fdb794SMiklos Szeredi {
297346fdb794SMiklos Szeredi 	struct dentry *whiteout;
297446fdb794SMiklos Szeredi 	int error;
297546fdb794SMiklos Szeredi 
297646fdb794SMiklos Szeredi 	whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
297746fdb794SMiklos Szeredi 	if (!whiteout)
297846fdb794SMiklos Szeredi 		return -ENOMEM;
297946fdb794SMiklos Szeredi 
2980549c7297SChristian Brauner 	error = shmem_mknod(&init_user_ns, old_dir, whiteout,
298146fdb794SMiklos Szeredi 			    S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
298246fdb794SMiklos Szeredi 	dput(whiteout);
298346fdb794SMiklos Szeredi 	if (error)
298446fdb794SMiklos Szeredi 		return error;
298546fdb794SMiklos Szeredi 
298646fdb794SMiklos Szeredi 	/*
298746fdb794SMiklos Szeredi 	 * Cheat and hash the whiteout while the old dentry is still in
298846fdb794SMiklos Szeredi 	 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
298946fdb794SMiklos Szeredi 	 *
299046fdb794SMiklos Szeredi 	 * d_lookup() will consistently find one of them at this point,
299146fdb794SMiklos Szeredi 	 * not sure which one, but that isn't even important.
299246fdb794SMiklos Szeredi 	 */
299346fdb794SMiklos Szeredi 	d_rehash(whiteout);
299446fdb794SMiklos Szeredi 	return 0;
299546fdb794SMiklos Szeredi }
299646fdb794SMiklos Szeredi 
29971da177e4SLinus Torvalds /*
29981da177e4SLinus Torvalds  * The VFS layer already does all the dentry stuff for rename,
29991da177e4SLinus Torvalds  * we just have to decrement the usage count for the target if
30001da177e4SLinus Torvalds  * it exists so that the VFS layer correctly free's it when it
30011da177e4SLinus Torvalds  * gets overwritten.
30021da177e4SLinus Torvalds  */
3003549c7297SChristian Brauner static int shmem_rename2(struct user_namespace *mnt_userns,
3004549c7297SChristian Brauner 			 struct inode *old_dir, struct dentry *old_dentry,
3005549c7297SChristian Brauner 			 struct inode *new_dir, struct dentry *new_dentry,
3006549c7297SChristian Brauner 			 unsigned int flags)
30071da177e4SLinus Torvalds {
300875c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
30091da177e4SLinus Torvalds 	int they_are_dirs = S_ISDIR(inode->i_mode);
30101da177e4SLinus Torvalds 
301146fdb794SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
30123b69ff51SMiklos Szeredi 		return -EINVAL;
30133b69ff51SMiklos Szeredi 
301437456771SMiklos Szeredi 	if (flags & RENAME_EXCHANGE)
301537456771SMiklos Szeredi 		return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
301637456771SMiklos Szeredi 
30171da177e4SLinus Torvalds 	if (!simple_empty(new_dentry))
30181da177e4SLinus Torvalds 		return -ENOTEMPTY;
30191da177e4SLinus Torvalds 
302046fdb794SMiklos Szeredi 	if (flags & RENAME_WHITEOUT) {
302146fdb794SMiklos Szeredi 		int error;
302246fdb794SMiklos Szeredi 
3023549c7297SChristian Brauner 		error = shmem_whiteout(&init_user_ns, old_dir, old_dentry);
302446fdb794SMiklos Szeredi 		if (error)
302546fdb794SMiklos Szeredi 			return error;
302646fdb794SMiklos Szeredi 	}
302746fdb794SMiklos Szeredi 
302875c3cfa8SDavid Howells 	if (d_really_is_positive(new_dentry)) {
30291da177e4SLinus Torvalds 		(void) shmem_unlink(new_dir, new_dentry);
3030b928095bSMiklos Szeredi 		if (they_are_dirs) {
303175c3cfa8SDavid Howells 			drop_nlink(d_inode(new_dentry));
30329a53c3a7SDave Hansen 			drop_nlink(old_dir);
3033b928095bSMiklos Szeredi 		}
30341da177e4SLinus Torvalds 	} else if (they_are_dirs) {
30359a53c3a7SDave Hansen 		drop_nlink(old_dir);
3036d8c76e6fSDave Hansen 		inc_nlink(new_dir);
30371da177e4SLinus Torvalds 	}
30381da177e4SLinus Torvalds 
30391da177e4SLinus Torvalds 	old_dir->i_size -= BOGO_DIRENT_SIZE;
30401da177e4SLinus Torvalds 	new_dir->i_size += BOGO_DIRENT_SIZE;
30411da177e4SLinus Torvalds 	old_dir->i_ctime = old_dir->i_mtime =
30421da177e4SLinus Torvalds 	new_dir->i_ctime = new_dir->i_mtime =
3043078cd827SDeepa Dinamani 	inode->i_ctime = current_time(old_dir);
30441da177e4SLinus Torvalds 	return 0;
30451da177e4SLinus Torvalds }
30461da177e4SLinus Torvalds 
3047549c7297SChristian Brauner static int shmem_symlink(struct user_namespace *mnt_userns, struct inode *dir,
3048549c7297SChristian Brauner 			 struct dentry *dentry, const char *symname)
30491da177e4SLinus Torvalds {
30501da177e4SLinus Torvalds 	int error;
30511da177e4SLinus Torvalds 	int len;
30521da177e4SLinus Torvalds 	struct inode *inode;
30539276aad6SHugh Dickins 	struct page *page;
30541da177e4SLinus Torvalds 
30551da177e4SLinus Torvalds 	len = strlen(symname) + 1;
305609cbfeafSKirill A. Shutemov 	if (len > PAGE_SIZE)
30571da177e4SLinus Torvalds 		return -ENAMETOOLONG;
30581da177e4SLinus Torvalds 
30590825a6f9SJoe Perches 	inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
30600825a6f9SJoe Perches 				VM_NORESERVE);
30611da177e4SLinus Torvalds 	if (!inode)
30621da177e4SLinus Torvalds 		return -ENOSPC;
30631da177e4SLinus Torvalds 
30649d8f13baSMimi Zohar 	error = security_inode_init_security(inode, dir, &dentry->d_name,
30656d9d88d0SJarkko Sakkinen 					     shmem_initxattrs, NULL);
3066343c3d7fSMateusz Nosek 	if (error && error != -EOPNOTSUPP) {
3067570bc1c2SStephen Smalley 		iput(inode);
3068570bc1c2SStephen Smalley 		return error;
3069570bc1c2SStephen Smalley 	}
3070570bc1c2SStephen Smalley 
30711da177e4SLinus Torvalds 	inode->i_size = len-1;
307269f07ec9SHugh Dickins 	if (len <= SHORT_SYMLINK_LEN) {
30733ed47db3SAl Viro 		inode->i_link = kmemdup(symname, len, GFP_KERNEL);
30743ed47db3SAl Viro 		if (!inode->i_link) {
307569f07ec9SHugh Dickins 			iput(inode);
307669f07ec9SHugh Dickins 			return -ENOMEM;
307769f07ec9SHugh Dickins 		}
307869f07ec9SHugh Dickins 		inode->i_op = &shmem_short_symlink_operations;
30791da177e4SLinus Torvalds 	} else {
3080e8ecde25SAl Viro 		inode_nohighmem(inode);
30819e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_WRITE);
30821da177e4SLinus Torvalds 		if (error) {
30831da177e4SLinus Torvalds 			iput(inode);
30841da177e4SLinus Torvalds 			return error;
30851da177e4SLinus Torvalds 		}
308614fcc23fSHugh Dickins 		inode->i_mapping->a_ops = &shmem_aops;
30871da177e4SLinus Torvalds 		inode->i_op = &shmem_symlink_inode_operations;
308821fc61c7SAl Viro 		memcpy(page_address(page), symname, len);
3089ec9516fbSHugh Dickins 		SetPageUptodate(page);
30901da177e4SLinus Torvalds 		set_page_dirty(page);
30916746aff7SWu Fengguang 		unlock_page(page);
309209cbfeafSKirill A. Shutemov 		put_page(page);
30931da177e4SLinus Torvalds 	}
30941da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
3095078cd827SDeepa Dinamani 	dir->i_ctime = dir->i_mtime = current_time(dir);
30961da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
30971da177e4SLinus Torvalds 	dget(dentry);
30981da177e4SLinus Torvalds 	return 0;
30991da177e4SLinus Torvalds }
31001da177e4SLinus Torvalds 
3101fceef393SAl Viro static void shmem_put_link(void *arg)
3102fceef393SAl Viro {
3103fceef393SAl Viro 	mark_page_accessed(arg);
3104fceef393SAl Viro 	put_page(arg);
3105fceef393SAl Viro }
3106fceef393SAl Viro 
31076b255391SAl Viro static const char *shmem_get_link(struct dentry *dentry,
3108fceef393SAl Viro 				  struct inode *inode,
3109fceef393SAl Viro 				  struct delayed_call *done)
31101da177e4SLinus Torvalds {
31111da177e4SLinus Torvalds 	struct page *page = NULL;
31126b255391SAl Viro 	int error;
31136a6c9904SAl Viro 	if (!dentry) {
31146a6c9904SAl Viro 		page = find_get_page(inode->i_mapping, 0);
31156a6c9904SAl Viro 		if (!page)
31166b255391SAl Viro 			return ERR_PTR(-ECHILD);
31176a6c9904SAl Viro 		if (!PageUptodate(page)) {
31186a6c9904SAl Viro 			put_page(page);
31196a6c9904SAl Viro 			return ERR_PTR(-ECHILD);
31206a6c9904SAl Viro 		}
31216a6c9904SAl Viro 	} else {
31229e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_READ);
3123680baacbSAl Viro 		if (error)
3124680baacbSAl Viro 			return ERR_PTR(error);
3125d3602444SHugh Dickins 		unlock_page(page);
31261da177e4SLinus Torvalds 	}
3127fceef393SAl Viro 	set_delayed_call(done, shmem_put_link, page);
312821fc61c7SAl Viro 	return page_address(page);
31291da177e4SLinus Torvalds }
31301da177e4SLinus Torvalds 
3131b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3132b09e0fa4SEric Paris /*
3133b09e0fa4SEric Paris  * Superblocks without xattr inode operations may get some security.* xattr
3134b09e0fa4SEric Paris  * support from the LSM "for free". As soon as we have any other xattrs
3135b09e0fa4SEric Paris  * like ACLs, we also need to implement the security.* handlers at
3136b09e0fa4SEric Paris  * filesystem level, though.
3137b09e0fa4SEric Paris  */
3138b09e0fa4SEric Paris 
31396d9d88d0SJarkko Sakkinen /*
31406d9d88d0SJarkko Sakkinen  * Callback for security_inode_init_security() for acquiring xattrs.
31416d9d88d0SJarkko Sakkinen  */
31426d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *inode,
31436d9d88d0SJarkko Sakkinen 			    const struct xattr *xattr_array,
31446d9d88d0SJarkko Sakkinen 			    void *fs_info)
31456d9d88d0SJarkko Sakkinen {
31466d9d88d0SJarkko Sakkinen 	struct shmem_inode_info *info = SHMEM_I(inode);
31476d9d88d0SJarkko Sakkinen 	const struct xattr *xattr;
314838f38657SAristeu Rozanski 	struct simple_xattr *new_xattr;
31496d9d88d0SJarkko Sakkinen 	size_t len;
31506d9d88d0SJarkko Sakkinen 
31516d9d88d0SJarkko Sakkinen 	for (xattr = xattr_array; xattr->name != NULL; xattr++) {
315238f38657SAristeu Rozanski 		new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
31536d9d88d0SJarkko Sakkinen 		if (!new_xattr)
31546d9d88d0SJarkko Sakkinen 			return -ENOMEM;
31556d9d88d0SJarkko Sakkinen 
31566d9d88d0SJarkko Sakkinen 		len = strlen(xattr->name) + 1;
31576d9d88d0SJarkko Sakkinen 		new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
31586d9d88d0SJarkko Sakkinen 					  GFP_KERNEL);
31596d9d88d0SJarkko Sakkinen 		if (!new_xattr->name) {
31603bef735aSChengguang Xu 			kvfree(new_xattr);
31616d9d88d0SJarkko Sakkinen 			return -ENOMEM;
31626d9d88d0SJarkko Sakkinen 		}
31636d9d88d0SJarkko Sakkinen 
31646d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
31656d9d88d0SJarkko Sakkinen 		       XATTR_SECURITY_PREFIX_LEN);
31666d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
31676d9d88d0SJarkko Sakkinen 		       xattr->name, len);
31686d9d88d0SJarkko Sakkinen 
316938f38657SAristeu Rozanski 		simple_xattr_list_add(&info->xattrs, new_xattr);
31706d9d88d0SJarkko Sakkinen 	}
31716d9d88d0SJarkko Sakkinen 
31726d9d88d0SJarkko Sakkinen 	return 0;
31736d9d88d0SJarkko Sakkinen }
31746d9d88d0SJarkko Sakkinen 
3175aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3176b296821aSAl Viro 				   struct dentry *unused, struct inode *inode,
3177b296821aSAl Viro 				   const char *name, void *buffer, size_t size)
3178aa7c5241SAndreas Gruenbacher {
3179b296821aSAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3180aa7c5241SAndreas Gruenbacher 
3181aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3182aa7c5241SAndreas Gruenbacher 	return simple_xattr_get(&info->xattrs, name, buffer, size);
3183aa7c5241SAndreas Gruenbacher }
3184aa7c5241SAndreas Gruenbacher 
3185aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3186e65ce2a5SChristian Brauner 				   struct user_namespace *mnt_userns,
318759301226SAl Viro 				   struct dentry *unused, struct inode *inode,
318859301226SAl Viro 				   const char *name, const void *value,
318959301226SAl Viro 				   size_t size, int flags)
3190aa7c5241SAndreas Gruenbacher {
319159301226SAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3192aa7c5241SAndreas Gruenbacher 
3193aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3194a46a2295SDaniel Xu 	return simple_xattr_set(&info->xattrs, name, value, size, flags, NULL);
3195aa7c5241SAndreas Gruenbacher }
3196aa7c5241SAndreas Gruenbacher 
3197aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_security_xattr_handler = {
3198aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_SECURITY_PREFIX,
3199aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3200aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3201aa7c5241SAndreas Gruenbacher };
3202aa7c5241SAndreas Gruenbacher 
3203aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_trusted_xattr_handler = {
3204aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_TRUSTED_PREFIX,
3205aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3206aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3207aa7c5241SAndreas Gruenbacher };
3208aa7c5241SAndreas Gruenbacher 
3209b09e0fa4SEric Paris static const struct xattr_handler *shmem_xattr_handlers[] = {
3210b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
3211feda821eSChristoph Hellwig 	&posix_acl_access_xattr_handler,
3212feda821eSChristoph Hellwig 	&posix_acl_default_xattr_handler,
3213b09e0fa4SEric Paris #endif
3214aa7c5241SAndreas Gruenbacher 	&shmem_security_xattr_handler,
3215aa7c5241SAndreas Gruenbacher 	&shmem_trusted_xattr_handler,
3216b09e0fa4SEric Paris 	NULL
3217b09e0fa4SEric Paris };
3218b09e0fa4SEric Paris 
3219b09e0fa4SEric Paris static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3220b09e0fa4SEric Paris {
322175c3cfa8SDavid Howells 	struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3222786534b9SAndreas Gruenbacher 	return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3223b09e0fa4SEric Paris }
3224b09e0fa4SEric Paris #endif /* CONFIG_TMPFS_XATTR */
3225b09e0fa4SEric Paris 
322669f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations = {
32276b255391SAl Viro 	.get_link	= simple_get_link,
3228b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3229b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3230b09e0fa4SEric Paris #endif
32311da177e4SLinus Torvalds };
32321da177e4SLinus Torvalds 
323392e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations = {
32346b255391SAl Viro 	.get_link	= shmem_get_link,
3235b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3236b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
323739f0247dSAndreas Gruenbacher #endif
3238b09e0fa4SEric Paris };
323939f0247dSAndreas Gruenbacher 
324091828a40SDavid M. Grimes static struct dentry *shmem_get_parent(struct dentry *child)
324191828a40SDavid M. Grimes {
324291828a40SDavid M. Grimes 	return ERR_PTR(-ESTALE);
324391828a40SDavid M. Grimes }
324491828a40SDavid M. Grimes 
324591828a40SDavid M. Grimes static int shmem_match(struct inode *ino, void *vfh)
324691828a40SDavid M. Grimes {
324791828a40SDavid M. Grimes 	__u32 *fh = vfh;
324891828a40SDavid M. Grimes 	__u64 inum = fh[2];
324991828a40SDavid M. Grimes 	inum = (inum << 32) | fh[1];
325091828a40SDavid M. Grimes 	return ino->i_ino == inum && fh[0] == ino->i_generation;
325191828a40SDavid M. Grimes }
325291828a40SDavid M. Grimes 
325312ba780dSAmir Goldstein /* Find any alias of inode, but prefer a hashed alias */
325412ba780dSAmir Goldstein static struct dentry *shmem_find_alias(struct inode *inode)
325512ba780dSAmir Goldstein {
325612ba780dSAmir Goldstein 	struct dentry *alias = d_find_alias(inode);
325712ba780dSAmir Goldstein 
325812ba780dSAmir Goldstein 	return alias ?: d_find_any_alias(inode);
325912ba780dSAmir Goldstein }
326012ba780dSAmir Goldstein 
326112ba780dSAmir Goldstein 
3262480b116cSChristoph Hellwig static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3263480b116cSChristoph Hellwig 		struct fid *fid, int fh_len, int fh_type)
326491828a40SDavid M. Grimes {
326591828a40SDavid M. Grimes 	struct inode *inode;
3266480b116cSChristoph Hellwig 	struct dentry *dentry = NULL;
326735c2a7f4SHugh Dickins 	u64 inum;
326891828a40SDavid M. Grimes 
3269480b116cSChristoph Hellwig 	if (fh_len < 3)
3270480b116cSChristoph Hellwig 		return NULL;
3271480b116cSChristoph Hellwig 
327235c2a7f4SHugh Dickins 	inum = fid->raw[2];
327335c2a7f4SHugh Dickins 	inum = (inum << 32) | fid->raw[1];
327435c2a7f4SHugh Dickins 
3275480b116cSChristoph Hellwig 	inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3276480b116cSChristoph Hellwig 			shmem_match, fid->raw);
327791828a40SDavid M. Grimes 	if (inode) {
327812ba780dSAmir Goldstein 		dentry = shmem_find_alias(inode);
327991828a40SDavid M. Grimes 		iput(inode);
328091828a40SDavid M. Grimes 	}
328191828a40SDavid M. Grimes 
3282480b116cSChristoph Hellwig 	return dentry;
328391828a40SDavid M. Grimes }
328491828a40SDavid M. Grimes 
3285b0b0382bSAl Viro static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3286b0b0382bSAl Viro 				struct inode *parent)
328791828a40SDavid M. Grimes {
32885fe0c237SAneesh Kumar K.V 	if (*len < 3) {
32895fe0c237SAneesh Kumar K.V 		*len = 3;
329094e07a75SNamjae Jeon 		return FILEID_INVALID;
32915fe0c237SAneesh Kumar K.V 	}
329291828a40SDavid M. Grimes 
32931d3382cbSAl Viro 	if (inode_unhashed(inode)) {
329491828a40SDavid M. Grimes 		/* Unfortunately insert_inode_hash is not idempotent,
329591828a40SDavid M. Grimes 		 * so as we hash inodes here rather than at creation
329691828a40SDavid M. Grimes 		 * time, we need a lock to ensure we only try
329791828a40SDavid M. Grimes 		 * to do it once
329891828a40SDavid M. Grimes 		 */
329991828a40SDavid M. Grimes 		static DEFINE_SPINLOCK(lock);
330091828a40SDavid M. Grimes 		spin_lock(&lock);
33011d3382cbSAl Viro 		if (inode_unhashed(inode))
330291828a40SDavid M. Grimes 			__insert_inode_hash(inode,
330391828a40SDavid M. Grimes 					    inode->i_ino + inode->i_generation);
330491828a40SDavid M. Grimes 		spin_unlock(&lock);
330591828a40SDavid M. Grimes 	}
330691828a40SDavid M. Grimes 
330791828a40SDavid M. Grimes 	fh[0] = inode->i_generation;
330891828a40SDavid M. Grimes 	fh[1] = inode->i_ino;
330991828a40SDavid M. Grimes 	fh[2] = ((__u64)inode->i_ino) >> 32;
331091828a40SDavid M. Grimes 
331191828a40SDavid M. Grimes 	*len = 3;
331291828a40SDavid M. Grimes 	return 1;
331391828a40SDavid M. Grimes }
331491828a40SDavid M. Grimes 
331539655164SChristoph Hellwig static const struct export_operations shmem_export_ops = {
331691828a40SDavid M. Grimes 	.get_parent     = shmem_get_parent,
331791828a40SDavid M. Grimes 	.encode_fh      = shmem_encode_fh,
3318480b116cSChristoph Hellwig 	.fh_to_dentry	= shmem_fh_to_dentry,
331991828a40SDavid M. Grimes };
332091828a40SDavid M. Grimes 
3321626c3920SAl Viro enum shmem_param {
3322626c3920SAl Viro 	Opt_gid,
3323626c3920SAl Viro 	Opt_huge,
3324626c3920SAl Viro 	Opt_mode,
3325626c3920SAl Viro 	Opt_mpol,
3326626c3920SAl Viro 	Opt_nr_blocks,
3327626c3920SAl Viro 	Opt_nr_inodes,
3328626c3920SAl Viro 	Opt_size,
3329626c3920SAl Viro 	Opt_uid,
3330ea3271f7SChris Down 	Opt_inode32,
3331ea3271f7SChris Down 	Opt_inode64,
3332626c3920SAl Viro };
33331da177e4SLinus Torvalds 
33345eede625SAl Viro static const struct constant_table shmem_param_enums_huge[] = {
33352710c957SAl Viro 	{"never",	SHMEM_HUGE_NEVER },
33362710c957SAl Viro 	{"always",	SHMEM_HUGE_ALWAYS },
33372710c957SAl Viro 	{"within_size",	SHMEM_HUGE_WITHIN_SIZE },
33382710c957SAl Viro 	{"advise",	SHMEM_HUGE_ADVISE },
33392710c957SAl Viro 	{}
33402710c957SAl Viro };
33412710c957SAl Viro 
3342d7167b14SAl Viro const struct fs_parameter_spec shmem_fs_parameters[] = {
3343626c3920SAl Viro 	fsparam_u32   ("gid",		Opt_gid),
33442710c957SAl Viro 	fsparam_enum  ("huge",		Opt_huge,  shmem_param_enums_huge),
3345626c3920SAl Viro 	fsparam_u32oct("mode",		Opt_mode),
3346626c3920SAl Viro 	fsparam_string("mpol",		Opt_mpol),
3347626c3920SAl Viro 	fsparam_string("nr_blocks",	Opt_nr_blocks),
3348626c3920SAl Viro 	fsparam_string("nr_inodes",	Opt_nr_inodes),
3349626c3920SAl Viro 	fsparam_string("size",		Opt_size),
3350626c3920SAl Viro 	fsparam_u32   ("uid",		Opt_uid),
3351ea3271f7SChris Down 	fsparam_flag  ("inode32",	Opt_inode32),
3352ea3271f7SChris Down 	fsparam_flag  ("inode64",	Opt_inode64),
3353626c3920SAl Viro 	{}
3354626c3920SAl Viro };
3355626c3920SAl Viro 
3356f3235626SDavid Howells static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
3357626c3920SAl Viro {
3358f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3359626c3920SAl Viro 	struct fs_parse_result result;
3360e04dc423SAl Viro 	unsigned long long size;
3361626c3920SAl Viro 	char *rest;
3362626c3920SAl Viro 	int opt;
3363626c3920SAl Viro 
3364d7167b14SAl Viro 	opt = fs_parse(fc, shmem_fs_parameters, param, &result);
3365f3235626SDavid Howells 	if (opt < 0)
3366626c3920SAl Viro 		return opt;
3367626c3920SAl Viro 
3368626c3920SAl Viro 	switch (opt) {
3369626c3920SAl Viro 	case Opt_size:
3370626c3920SAl Viro 		size = memparse(param->string, &rest);
3371e04dc423SAl Viro 		if (*rest == '%') {
3372e04dc423SAl Viro 			size <<= PAGE_SHIFT;
3373e04dc423SAl Viro 			size *= totalram_pages();
3374e04dc423SAl Viro 			do_div(size, 100);
3375e04dc423SAl Viro 			rest++;
3376e04dc423SAl Viro 		}
3377e04dc423SAl Viro 		if (*rest)
3378626c3920SAl Viro 			goto bad_value;
3379e04dc423SAl Viro 		ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
3380e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3381626c3920SAl Viro 		break;
3382626c3920SAl Viro 	case Opt_nr_blocks:
3383626c3920SAl Viro 		ctx->blocks = memparse(param->string, &rest);
3384e04dc423SAl Viro 		if (*rest)
3385626c3920SAl Viro 			goto bad_value;
3386e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_BLOCKS;
3387626c3920SAl Viro 		break;
3388626c3920SAl Viro 	case Opt_nr_inodes:
3389626c3920SAl Viro 		ctx->inodes = memparse(param->string, &rest);
3390e04dc423SAl Viro 		if (*rest)
3391626c3920SAl Viro 			goto bad_value;
3392e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_INODES;
3393626c3920SAl Viro 		break;
3394626c3920SAl Viro 	case Opt_mode:
3395626c3920SAl Viro 		ctx->mode = result.uint_32 & 07777;
3396626c3920SAl Viro 		break;
3397626c3920SAl Viro 	case Opt_uid:
3398626c3920SAl Viro 		ctx->uid = make_kuid(current_user_ns(), result.uint_32);
3399e04dc423SAl Viro 		if (!uid_valid(ctx->uid))
3400626c3920SAl Viro 			goto bad_value;
3401626c3920SAl Viro 		break;
3402626c3920SAl Viro 	case Opt_gid:
3403626c3920SAl Viro 		ctx->gid = make_kgid(current_user_ns(), result.uint_32);
3404e04dc423SAl Viro 		if (!gid_valid(ctx->gid))
3405626c3920SAl Viro 			goto bad_value;
3406626c3920SAl Viro 		break;
3407626c3920SAl Viro 	case Opt_huge:
3408626c3920SAl Viro 		ctx->huge = result.uint_32;
3409626c3920SAl Viro 		if (ctx->huge != SHMEM_HUGE_NEVER &&
3410396bcc52SMatthew Wilcox (Oracle) 		    !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
3411626c3920SAl Viro 		      has_transparent_hugepage()))
3412626c3920SAl Viro 			goto unsupported_parameter;
3413e04dc423SAl Viro 		ctx->seen |= SHMEM_SEEN_HUGE;
3414626c3920SAl Viro 		break;
3415626c3920SAl Viro 	case Opt_mpol:
3416626c3920SAl Viro 		if (IS_ENABLED(CONFIG_NUMA)) {
3417e04dc423SAl Viro 			mpol_put(ctx->mpol);
3418e04dc423SAl Viro 			ctx->mpol = NULL;
3419626c3920SAl Viro 			if (mpol_parse_str(param->string, &ctx->mpol))
3420626c3920SAl Viro 				goto bad_value;
3421626c3920SAl Viro 			break;
3422626c3920SAl Viro 		}
3423626c3920SAl Viro 		goto unsupported_parameter;
3424ea3271f7SChris Down 	case Opt_inode32:
3425ea3271f7SChris Down 		ctx->full_inums = false;
3426ea3271f7SChris Down 		ctx->seen |= SHMEM_SEEN_INUMS;
3427ea3271f7SChris Down 		break;
3428ea3271f7SChris Down 	case Opt_inode64:
3429ea3271f7SChris Down 		if (sizeof(ino_t) < 8) {
3430ea3271f7SChris Down 			return invalfc(fc,
3431ea3271f7SChris Down 				       "Cannot use inode64 with <64bit inums in kernel\n");
3432ea3271f7SChris Down 		}
3433ea3271f7SChris Down 		ctx->full_inums = true;
3434ea3271f7SChris Down 		ctx->seen |= SHMEM_SEEN_INUMS;
3435ea3271f7SChris Down 		break;
3436e04dc423SAl Viro 	}
3437e04dc423SAl Viro 	return 0;
3438e04dc423SAl Viro 
3439626c3920SAl Viro unsupported_parameter:
3440f35aa2bcSAl Viro 	return invalfc(fc, "Unsupported parameter '%s'", param->key);
3441626c3920SAl Viro bad_value:
3442f35aa2bcSAl Viro 	return invalfc(fc, "Bad value for '%s'", param->key);
3443e04dc423SAl Viro }
3444e04dc423SAl Viro 
3445f3235626SDavid Howells static int shmem_parse_options(struct fs_context *fc, void *data)
3446e04dc423SAl Viro {
3447f3235626SDavid Howells 	char *options = data;
3448f3235626SDavid Howells 
344933f37c64SAl Viro 	if (options) {
345033f37c64SAl Viro 		int err = security_sb_eat_lsm_opts(options, &fc->security);
345133f37c64SAl Viro 		if (err)
345233f37c64SAl Viro 			return err;
345333f37c64SAl Viro 	}
345433f37c64SAl Viro 
3455b00dc3adSHugh Dickins 	while (options != NULL) {
3456626c3920SAl Viro 		char *this_char = options;
3457b00dc3adSHugh Dickins 		for (;;) {
3458b00dc3adSHugh Dickins 			/*
3459b00dc3adSHugh Dickins 			 * NUL-terminate this option: unfortunately,
3460b00dc3adSHugh Dickins 			 * mount options form a comma-separated list,
3461b00dc3adSHugh Dickins 			 * but mpol's nodelist may also contain commas.
3462b00dc3adSHugh Dickins 			 */
3463b00dc3adSHugh Dickins 			options = strchr(options, ',');
3464b00dc3adSHugh Dickins 			if (options == NULL)
3465b00dc3adSHugh Dickins 				break;
3466b00dc3adSHugh Dickins 			options++;
3467b00dc3adSHugh Dickins 			if (!isdigit(*options)) {
3468b00dc3adSHugh Dickins 				options[-1] = '\0';
3469b00dc3adSHugh Dickins 				break;
3470b00dc3adSHugh Dickins 			}
3471b00dc3adSHugh Dickins 		}
3472626c3920SAl Viro 		if (*this_char) {
3473626c3920SAl Viro 			char *value = strchr(this_char, '=');
3474f3235626SDavid Howells 			size_t len = 0;
3475626c3920SAl Viro 			int err;
3476626c3920SAl Viro 
3477626c3920SAl Viro 			if (value) {
3478626c3920SAl Viro 				*value++ = '\0';
3479f3235626SDavid Howells 				len = strlen(value);
34801da177e4SLinus Torvalds 			}
3481f3235626SDavid Howells 			err = vfs_parse_fs_string(fc, this_char, value, len);
3482f3235626SDavid Howells 			if (err < 0)
3483f3235626SDavid Howells 				return err;
34841da177e4SLinus Torvalds 		}
3485626c3920SAl Viro 	}
34861da177e4SLinus Torvalds 	return 0;
34871da177e4SLinus Torvalds }
34881da177e4SLinus Torvalds 
3489f3235626SDavid Howells /*
3490f3235626SDavid Howells  * Reconfigure a shmem filesystem.
3491f3235626SDavid Howells  *
3492f3235626SDavid Howells  * Note that we disallow change from limited->unlimited blocks/inodes while any
3493f3235626SDavid Howells  * are in use; but we must separately disallow unlimited->limited, because in
3494f3235626SDavid Howells  * that case we have no record of how much is already in use.
3495f3235626SDavid Howells  */
3496f3235626SDavid Howells static int shmem_reconfigure(struct fs_context *fc)
34971da177e4SLinus Torvalds {
3498f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3499f3235626SDavid Howells 	struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
35000edd73b3SHugh Dickins 	unsigned long inodes;
3501bf11b9a8SSebastian Andrzej Siewior 	struct mempolicy *mpol = NULL;
3502f3235626SDavid Howells 	const char *err;
35030edd73b3SHugh Dickins 
3504bf11b9a8SSebastian Andrzej Siewior 	raw_spin_lock(&sbinfo->stat_lock);
35050edd73b3SHugh Dickins 	inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3506f3235626SDavid Howells 	if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
3507f3235626SDavid Howells 		if (!sbinfo->max_blocks) {
3508f3235626SDavid Howells 			err = "Cannot retroactively limit size";
35090edd73b3SHugh Dickins 			goto out;
35100b5071ddSAl Viro 		}
3511f3235626SDavid Howells 		if (percpu_counter_compare(&sbinfo->used_blocks,
3512f3235626SDavid Howells 					   ctx->blocks) > 0) {
3513f3235626SDavid Howells 			err = "Too small a size for current use";
35140b5071ddSAl Viro 			goto out;
3515f3235626SDavid Howells 		}
3516f3235626SDavid Howells 	}
3517f3235626SDavid Howells 	if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
3518f3235626SDavid Howells 		if (!sbinfo->max_inodes) {
3519f3235626SDavid Howells 			err = "Cannot retroactively limit inodes";
35200b5071ddSAl Viro 			goto out;
35210b5071ddSAl Viro 		}
3522f3235626SDavid Howells 		if (ctx->inodes < inodes) {
3523f3235626SDavid Howells 			err = "Too few inodes for current use";
3524f3235626SDavid Howells 			goto out;
3525f3235626SDavid Howells 		}
3526f3235626SDavid Howells 	}
35270edd73b3SHugh Dickins 
3528ea3271f7SChris Down 	if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
3529ea3271f7SChris Down 	    sbinfo->next_ino > UINT_MAX) {
3530ea3271f7SChris Down 		err = "Current inum too high to switch to 32-bit inums";
3531ea3271f7SChris Down 		goto out;
3532ea3271f7SChris Down 	}
3533ea3271f7SChris Down 
3534f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_HUGE)
3535f3235626SDavid Howells 		sbinfo->huge = ctx->huge;
3536ea3271f7SChris Down 	if (ctx->seen & SHMEM_SEEN_INUMS)
3537ea3271f7SChris Down 		sbinfo->full_inums = ctx->full_inums;
3538f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_BLOCKS)
3539f3235626SDavid Howells 		sbinfo->max_blocks  = ctx->blocks;
3540f3235626SDavid Howells 	if (ctx->seen & SHMEM_SEEN_INODES) {
3541f3235626SDavid Howells 		sbinfo->max_inodes  = ctx->inodes;
3542f3235626SDavid Howells 		sbinfo->free_inodes = ctx->inodes - inodes;
35430b5071ddSAl Viro 	}
354471fe804bSLee Schermerhorn 
35455f00110fSGreg Thelen 	/*
35465f00110fSGreg Thelen 	 * Preserve previous mempolicy unless mpol remount option was specified.
35475f00110fSGreg Thelen 	 */
3548f3235626SDavid Howells 	if (ctx->mpol) {
3549bf11b9a8SSebastian Andrzej Siewior 		mpol = sbinfo->mpol;
3550f3235626SDavid Howells 		sbinfo->mpol = ctx->mpol;	/* transfers initial ref */
3551f3235626SDavid Howells 		ctx->mpol = NULL;
35525f00110fSGreg Thelen 	}
3553bf11b9a8SSebastian Andrzej Siewior 	raw_spin_unlock(&sbinfo->stat_lock);
3554bf11b9a8SSebastian Andrzej Siewior 	mpol_put(mpol);
3555f3235626SDavid Howells 	return 0;
35560edd73b3SHugh Dickins out:
3557bf11b9a8SSebastian Andrzej Siewior 	raw_spin_unlock(&sbinfo->stat_lock);
3558f35aa2bcSAl Viro 	return invalfc(fc, "%s", err);
35591da177e4SLinus Torvalds }
3560680d794bSakpm@linux-foundation.org 
356134c80b1dSAl Viro static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3562680d794bSakpm@linux-foundation.org {
356334c80b1dSAl Viro 	struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3564680d794bSakpm@linux-foundation.org 
3565680d794bSakpm@linux-foundation.org 	if (sbinfo->max_blocks != shmem_default_max_blocks())
3566680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",size=%luk",
356709cbfeafSKirill A. Shutemov 			sbinfo->max_blocks << (PAGE_SHIFT - 10));
3568680d794bSakpm@linux-foundation.org 	if (sbinfo->max_inodes != shmem_default_max_inodes())
3569680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
35700825a6f9SJoe Perches 	if (sbinfo->mode != (0777 | S_ISVTX))
357109208d15SAl Viro 		seq_printf(seq, ",mode=%03ho", sbinfo->mode);
35728751e039SEric W. Biederman 	if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
35738751e039SEric W. Biederman 		seq_printf(seq, ",uid=%u",
35748751e039SEric W. Biederman 				from_kuid_munged(&init_user_ns, sbinfo->uid));
35758751e039SEric W. Biederman 	if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
35768751e039SEric W. Biederman 		seq_printf(seq, ",gid=%u",
35778751e039SEric W. Biederman 				from_kgid_munged(&init_user_ns, sbinfo->gid));
3578ea3271f7SChris Down 
3579ea3271f7SChris Down 	/*
3580ea3271f7SChris Down 	 * Showing inode{64,32} might be useful even if it's the system default,
3581ea3271f7SChris Down 	 * since then people don't have to resort to checking both here and
3582ea3271f7SChris Down 	 * /proc/config.gz to confirm 64-bit inums were successfully applied
3583ea3271f7SChris Down 	 * (which may not even exist if IKCONFIG_PROC isn't enabled).
3584ea3271f7SChris Down 	 *
3585ea3271f7SChris Down 	 * We hide it when inode64 isn't the default and we are using 32-bit
3586ea3271f7SChris Down 	 * inodes, since that probably just means the feature isn't even under
3587ea3271f7SChris Down 	 * consideration.
3588ea3271f7SChris Down 	 *
3589ea3271f7SChris Down 	 * As such:
3590ea3271f7SChris Down 	 *
3591ea3271f7SChris Down 	 *                     +-----------------+-----------------+
3592ea3271f7SChris Down 	 *                     | TMPFS_INODE64=y | TMPFS_INODE64=n |
3593ea3271f7SChris Down 	 *  +------------------+-----------------+-----------------+
3594ea3271f7SChris Down 	 *  | full_inums=true  | show            | show            |
3595ea3271f7SChris Down 	 *  | full_inums=false | show            | hide            |
3596ea3271f7SChris Down 	 *  +------------------+-----------------+-----------------+
3597ea3271f7SChris Down 	 *
3598ea3271f7SChris Down 	 */
3599ea3271f7SChris Down 	if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
3600ea3271f7SChris Down 		seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
3601396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
36025a6e75f8SKirill A. Shutemov 	/* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
36035a6e75f8SKirill A. Shutemov 	if (sbinfo->huge)
36045a6e75f8SKirill A. Shutemov 		seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
36055a6e75f8SKirill A. Shutemov #endif
360671fe804bSLee Schermerhorn 	shmem_show_mpol(seq, sbinfo->mpol);
3607680d794bSakpm@linux-foundation.org 	return 0;
3608680d794bSakpm@linux-foundation.org }
36099183df25SDavid Herrmann 
3610680d794bSakpm@linux-foundation.org #endif /* CONFIG_TMPFS */
36111da177e4SLinus Torvalds 
36121da177e4SLinus Torvalds static void shmem_put_super(struct super_block *sb)
36131da177e4SLinus Torvalds {
3614602586a8SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3615602586a8SHugh Dickins 
3616e809d5f0SChris Down 	free_percpu(sbinfo->ino_batch);
3617602586a8SHugh Dickins 	percpu_counter_destroy(&sbinfo->used_blocks);
361849cd0a5cSGreg Thelen 	mpol_put(sbinfo->mpol);
3619602586a8SHugh Dickins 	kfree(sbinfo);
36201da177e4SLinus Torvalds 	sb->s_fs_info = NULL;
36211da177e4SLinus Torvalds }
36221da177e4SLinus Torvalds 
3623f3235626SDavid Howells static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
36241da177e4SLinus Torvalds {
3625f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
36261da177e4SLinus Torvalds 	struct inode *inode;
36270edd73b3SHugh Dickins 	struct shmem_sb_info *sbinfo;
3628680d794bSakpm@linux-foundation.org 
3629680d794bSakpm@linux-foundation.org 	/* Round up to L1_CACHE_BYTES to resist false sharing */
3630425fbf04SPekka Enberg 	sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3631680d794bSakpm@linux-foundation.org 				L1_CACHE_BYTES), GFP_KERNEL);
3632680d794bSakpm@linux-foundation.org 	if (!sbinfo)
3633680d794bSakpm@linux-foundation.org 		return -ENOMEM;
3634680d794bSakpm@linux-foundation.org 
3635680d794bSakpm@linux-foundation.org 	sb->s_fs_info = sbinfo;
36361da177e4SLinus Torvalds 
36370edd73b3SHugh Dickins #ifdef CONFIG_TMPFS
36381da177e4SLinus Torvalds 	/*
36391da177e4SLinus Torvalds 	 * Per default we only allow half of the physical ram per
36401da177e4SLinus Torvalds 	 * tmpfs instance, limiting inodes to one per page of lowmem;
36411da177e4SLinus Torvalds 	 * but the internal instance is left unlimited.
36421da177e4SLinus Torvalds 	 */
36431751e8a6SLinus Torvalds 	if (!(sb->s_flags & SB_KERNMOUNT)) {
3644f3235626SDavid Howells 		if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
3645f3235626SDavid Howells 			ctx->blocks = shmem_default_max_blocks();
3646f3235626SDavid Howells 		if (!(ctx->seen & SHMEM_SEEN_INODES))
3647f3235626SDavid Howells 			ctx->inodes = shmem_default_max_inodes();
3648ea3271f7SChris Down 		if (!(ctx->seen & SHMEM_SEEN_INUMS))
3649ea3271f7SChris Down 			ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
3650ca4e0519SAl Viro 	} else {
36511751e8a6SLinus Torvalds 		sb->s_flags |= SB_NOUSER;
36521da177e4SLinus Torvalds 	}
365391828a40SDavid M. Grimes 	sb->s_export_op = &shmem_export_ops;
36541751e8a6SLinus Torvalds 	sb->s_flags |= SB_NOSEC;
36550edd73b3SHugh Dickins #else
36561751e8a6SLinus Torvalds 	sb->s_flags |= SB_NOUSER;
36570edd73b3SHugh Dickins #endif
3658f3235626SDavid Howells 	sbinfo->max_blocks = ctx->blocks;
3659f3235626SDavid Howells 	sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes;
3660e809d5f0SChris Down 	if (sb->s_flags & SB_KERNMOUNT) {
3661e809d5f0SChris Down 		sbinfo->ino_batch = alloc_percpu(ino_t);
3662e809d5f0SChris Down 		if (!sbinfo->ino_batch)
3663e809d5f0SChris Down 			goto failed;
3664e809d5f0SChris Down 	}
3665f3235626SDavid Howells 	sbinfo->uid = ctx->uid;
3666f3235626SDavid Howells 	sbinfo->gid = ctx->gid;
3667ea3271f7SChris Down 	sbinfo->full_inums = ctx->full_inums;
3668f3235626SDavid Howells 	sbinfo->mode = ctx->mode;
3669f3235626SDavid Howells 	sbinfo->huge = ctx->huge;
3670f3235626SDavid Howells 	sbinfo->mpol = ctx->mpol;
3671f3235626SDavid Howells 	ctx->mpol = NULL;
36721da177e4SLinus Torvalds 
3673bf11b9a8SSebastian Andrzej Siewior 	raw_spin_lock_init(&sbinfo->stat_lock);
3674908c7f19STejun Heo 	if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3675602586a8SHugh Dickins 		goto failed;
3676779750d2SKirill A. Shutemov 	spin_lock_init(&sbinfo->shrinklist_lock);
3677779750d2SKirill A. Shutemov 	INIT_LIST_HEAD(&sbinfo->shrinklist);
36781da177e4SLinus Torvalds 
3679285b2c4fSHugh Dickins 	sb->s_maxbytes = MAX_LFS_FILESIZE;
368009cbfeafSKirill A. Shutemov 	sb->s_blocksize = PAGE_SIZE;
368109cbfeafSKirill A. Shutemov 	sb->s_blocksize_bits = PAGE_SHIFT;
36821da177e4SLinus Torvalds 	sb->s_magic = TMPFS_MAGIC;
36831da177e4SLinus Torvalds 	sb->s_op = &shmem_ops;
3684cfd95a9cSRobin H. Johnson 	sb->s_time_gran = 1;
3685b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
368639f0247dSAndreas Gruenbacher 	sb->s_xattr = shmem_xattr_handlers;
3687b09e0fa4SEric Paris #endif
3688b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
36891751e8a6SLinus Torvalds 	sb->s_flags |= SB_POSIXACL;
369039f0247dSAndreas Gruenbacher #endif
36912b4db796SAmir Goldstein 	uuid_gen(&sb->s_uuid);
36920edd73b3SHugh Dickins 
3693454abafeSDmitry Monakhov 	inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
36941da177e4SLinus Torvalds 	if (!inode)
36951da177e4SLinus Torvalds 		goto failed;
3696680d794bSakpm@linux-foundation.org 	inode->i_uid = sbinfo->uid;
3697680d794bSakpm@linux-foundation.org 	inode->i_gid = sbinfo->gid;
3698318ceed0SAl Viro 	sb->s_root = d_make_root(inode);
3699318ceed0SAl Viro 	if (!sb->s_root)
370048fde701SAl Viro 		goto failed;
37011da177e4SLinus Torvalds 	return 0;
37021da177e4SLinus Torvalds 
37031da177e4SLinus Torvalds failed:
37041da177e4SLinus Torvalds 	shmem_put_super(sb);
3705f2b346e4SMiaohe Lin 	return -ENOMEM;
37061da177e4SLinus Torvalds }
37071da177e4SLinus Torvalds 
3708f3235626SDavid Howells static int shmem_get_tree(struct fs_context *fc)
3709f3235626SDavid Howells {
3710f3235626SDavid Howells 	return get_tree_nodev(fc, shmem_fill_super);
3711f3235626SDavid Howells }
3712f3235626SDavid Howells 
3713f3235626SDavid Howells static void shmem_free_fc(struct fs_context *fc)
3714f3235626SDavid Howells {
3715f3235626SDavid Howells 	struct shmem_options *ctx = fc->fs_private;
3716f3235626SDavid Howells 
3717f3235626SDavid Howells 	if (ctx) {
3718f3235626SDavid Howells 		mpol_put(ctx->mpol);
3719f3235626SDavid Howells 		kfree(ctx);
3720f3235626SDavid Howells 	}
3721f3235626SDavid Howells }
3722f3235626SDavid Howells 
3723f3235626SDavid Howells static const struct fs_context_operations shmem_fs_context_ops = {
3724f3235626SDavid Howells 	.free			= shmem_free_fc,
3725f3235626SDavid Howells 	.get_tree		= shmem_get_tree,
3726f3235626SDavid Howells #ifdef CONFIG_TMPFS
3727f3235626SDavid Howells 	.parse_monolithic	= shmem_parse_options,
3728f3235626SDavid Howells 	.parse_param		= shmem_parse_one,
3729f3235626SDavid Howells 	.reconfigure		= shmem_reconfigure,
3730f3235626SDavid Howells #endif
3731f3235626SDavid Howells };
3732f3235626SDavid Howells 
3733fcc234f8SPekka Enberg static struct kmem_cache *shmem_inode_cachep;
37341da177e4SLinus Torvalds 
37351da177e4SLinus Torvalds static struct inode *shmem_alloc_inode(struct super_block *sb)
37361da177e4SLinus Torvalds {
373741ffe5d5SHugh Dickins 	struct shmem_inode_info *info;
373841ffe5d5SHugh Dickins 	info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
373941ffe5d5SHugh Dickins 	if (!info)
37401da177e4SLinus Torvalds 		return NULL;
374141ffe5d5SHugh Dickins 	return &info->vfs_inode;
37421da177e4SLinus Torvalds }
37431da177e4SLinus Torvalds 
374474b1da56SAl Viro static void shmem_free_in_core_inode(struct inode *inode)
3745fa0d7e3dSNick Piggin {
374684e710daSAl Viro 	if (S_ISLNK(inode->i_mode))
37473ed47db3SAl Viro 		kfree(inode->i_link);
3748fa0d7e3dSNick Piggin 	kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3749fa0d7e3dSNick Piggin }
3750fa0d7e3dSNick Piggin 
37511da177e4SLinus Torvalds static void shmem_destroy_inode(struct inode *inode)
37521da177e4SLinus Torvalds {
375309208d15SAl Viro 	if (S_ISREG(inode->i_mode))
37541da177e4SLinus Torvalds 		mpol_free_shared_policy(&SHMEM_I(inode)->policy);
37551da177e4SLinus Torvalds }
37561da177e4SLinus Torvalds 
375741ffe5d5SHugh Dickins static void shmem_init_inode(void *foo)
37581da177e4SLinus Torvalds {
375941ffe5d5SHugh Dickins 	struct shmem_inode_info *info = foo;
376041ffe5d5SHugh Dickins 	inode_init_once(&info->vfs_inode);
37611da177e4SLinus Torvalds }
37621da177e4SLinus Torvalds 
37639a8ec03eSweiping zhang static void shmem_init_inodecache(void)
37641da177e4SLinus Torvalds {
37651da177e4SLinus Torvalds 	shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
37661da177e4SLinus Torvalds 				sizeof(struct shmem_inode_info),
37675d097056SVladimir Davydov 				0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
37681da177e4SLinus Torvalds }
37691da177e4SLinus Torvalds 
377041ffe5d5SHugh Dickins static void shmem_destroy_inodecache(void)
37711da177e4SLinus Torvalds {
37721a1d92c1SAlexey Dobriyan 	kmem_cache_destroy(shmem_inode_cachep);
37731da177e4SLinus Torvalds }
37741da177e4SLinus Torvalds 
377530e6a51dSHui Su const struct address_space_operations shmem_aops = {
37761da177e4SLinus Torvalds 	.writepage	= shmem_writepage,
377776719325SKen Chen 	.set_page_dirty	= __set_page_dirty_no_writeback,
37781da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3779800d15a5SNick Piggin 	.write_begin	= shmem_write_begin,
3780800d15a5SNick Piggin 	.write_end	= shmem_write_end,
37811da177e4SLinus Torvalds #endif
37821c93923cSAndrew Morton #ifdef CONFIG_MIGRATION
3783304dbdb7SLee Schermerhorn 	.migratepage	= migrate_page,
37841c93923cSAndrew Morton #endif
3785aa261f54SAndi Kleen 	.error_remove_page = generic_error_remove_page,
37861da177e4SLinus Torvalds };
378730e6a51dSHui Su EXPORT_SYMBOL(shmem_aops);
37881da177e4SLinus Torvalds 
378915ad7cdcSHelge Deller static const struct file_operations shmem_file_operations = {
37901da177e4SLinus Torvalds 	.mmap		= shmem_mmap,
3791c01d5b30SHugh Dickins 	.get_unmapped_area = shmem_get_unmapped_area,
37921da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3793220f2ac9SHugh Dickins 	.llseek		= shmem_file_llseek,
37942ba5bbedSAl Viro 	.read_iter	= shmem_file_read_iter,
37958174202bSAl Viro 	.write_iter	= generic_file_write_iter,
37961b061d92SChristoph Hellwig 	.fsync		= noop_fsync,
379782c156f8SAl Viro 	.splice_read	= generic_file_splice_read,
3798f6cb85d0SAl Viro 	.splice_write	= iter_file_splice_write,
379983e4fa9cSHugh Dickins 	.fallocate	= shmem_fallocate,
38001da177e4SLinus Torvalds #endif
38011da177e4SLinus Torvalds };
38021da177e4SLinus Torvalds 
380392e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations = {
380444a30220SYu Zhao 	.getattr	= shmem_getattr,
380594c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3806b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3807b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3808feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
3809b09e0fa4SEric Paris #endif
38101da177e4SLinus Torvalds };
38111da177e4SLinus Torvalds 
381292e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations = {
38131da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
38141da177e4SLinus Torvalds 	.create		= shmem_create,
38151da177e4SLinus Torvalds 	.lookup		= simple_lookup,
38161da177e4SLinus Torvalds 	.link		= shmem_link,
38171da177e4SLinus Torvalds 	.unlink		= shmem_unlink,
38181da177e4SLinus Torvalds 	.symlink	= shmem_symlink,
38191da177e4SLinus Torvalds 	.mkdir		= shmem_mkdir,
38201da177e4SLinus Torvalds 	.rmdir		= shmem_rmdir,
38211da177e4SLinus Torvalds 	.mknod		= shmem_mknod,
38222773bf00SMiklos Szeredi 	.rename		= shmem_rename2,
382360545d0dSAl Viro 	.tmpfile	= shmem_tmpfile,
38241da177e4SLinus Torvalds #endif
3825b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3826b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3827b09e0fa4SEric Paris #endif
382839f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
382994c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3830feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
383139f0247dSAndreas Gruenbacher #endif
383239f0247dSAndreas Gruenbacher };
383339f0247dSAndreas Gruenbacher 
383492e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations = {
3835b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3836b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3837b09e0fa4SEric Paris #endif
383839f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
383994c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3840feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
384139f0247dSAndreas Gruenbacher #endif
38421da177e4SLinus Torvalds };
38431da177e4SLinus Torvalds 
3844759b9775SHugh Dickins static const struct super_operations shmem_ops = {
38451da177e4SLinus Torvalds 	.alloc_inode	= shmem_alloc_inode,
384674b1da56SAl Viro 	.free_inode	= shmem_free_in_core_inode,
38471da177e4SLinus Torvalds 	.destroy_inode	= shmem_destroy_inode,
38481da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
38491da177e4SLinus Torvalds 	.statfs		= shmem_statfs,
3850680d794bSakpm@linux-foundation.org 	.show_options	= shmem_show_options,
38511da177e4SLinus Torvalds #endif
38521f895f75SAl Viro 	.evict_inode	= shmem_evict_inode,
38531da177e4SLinus Torvalds 	.drop_inode	= generic_delete_inode,
38541da177e4SLinus Torvalds 	.put_super	= shmem_put_super,
3855396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3856779750d2SKirill A. Shutemov 	.nr_cached_objects	= shmem_unused_huge_count,
3857779750d2SKirill A. Shutemov 	.free_cached_objects	= shmem_unused_huge_scan,
3858779750d2SKirill A. Shutemov #endif
38591da177e4SLinus Torvalds };
38601da177e4SLinus Torvalds 
3861f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops = {
386254cb8821SNick Piggin 	.fault		= shmem_fault,
3863d7c17551SNing Qu 	.map_pages	= filemap_map_pages,
38641da177e4SLinus Torvalds #ifdef CONFIG_NUMA
38651da177e4SLinus Torvalds 	.set_policy     = shmem_set_policy,
38661da177e4SLinus Torvalds 	.get_policy     = shmem_get_policy,
38671da177e4SLinus Torvalds #endif
38681da177e4SLinus Torvalds };
38691da177e4SLinus Torvalds 
3870f3235626SDavid Howells int shmem_init_fs_context(struct fs_context *fc)
38711da177e4SLinus Torvalds {
3872f3235626SDavid Howells 	struct shmem_options *ctx;
3873f3235626SDavid Howells 
3874f3235626SDavid Howells 	ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL);
3875f3235626SDavid Howells 	if (!ctx)
3876f3235626SDavid Howells 		return -ENOMEM;
3877f3235626SDavid Howells 
3878f3235626SDavid Howells 	ctx->mode = 0777 | S_ISVTX;
3879f3235626SDavid Howells 	ctx->uid = current_fsuid();
3880f3235626SDavid Howells 	ctx->gid = current_fsgid();
3881f3235626SDavid Howells 
3882f3235626SDavid Howells 	fc->fs_private = ctx;
3883f3235626SDavid Howells 	fc->ops = &shmem_fs_context_ops;
3884f3235626SDavid Howells 	return 0;
38851da177e4SLinus Torvalds }
38861da177e4SLinus Torvalds 
388741ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
38881da177e4SLinus Torvalds 	.owner		= THIS_MODULE,
38891da177e4SLinus Torvalds 	.name		= "tmpfs",
3890f3235626SDavid Howells 	.init_fs_context = shmem_init_fs_context,
3891f3235626SDavid Howells #ifdef CONFIG_TMPFS
3892d7167b14SAl Viro 	.parameters	= shmem_fs_parameters,
3893f3235626SDavid Howells #endif
38941da177e4SLinus Torvalds 	.kill_sb	= kill_litter_super,
389501c70267SMatthew Wilcox (Oracle) 	.fs_flags	= FS_USERNS_MOUNT | FS_THP_SUPPORT,
38961da177e4SLinus Torvalds };
38971da177e4SLinus Torvalds 
389841ffe5d5SHugh Dickins int __init shmem_init(void)
38991da177e4SLinus Torvalds {
39001da177e4SLinus Torvalds 	int error;
39011da177e4SLinus Torvalds 
39029a8ec03eSweiping zhang 	shmem_init_inodecache();
39031da177e4SLinus Torvalds 
390441ffe5d5SHugh Dickins 	error = register_filesystem(&shmem_fs_type);
39051da177e4SLinus Torvalds 	if (error) {
39061170532bSJoe Perches 		pr_err("Could not register tmpfs\n");
39071da177e4SLinus Torvalds 		goto out2;
39081da177e4SLinus Torvalds 	}
390995dc112aSGreg Kroah-Hartman 
3910ca4e0519SAl Viro 	shm_mnt = kern_mount(&shmem_fs_type);
39111da177e4SLinus Torvalds 	if (IS_ERR(shm_mnt)) {
39121da177e4SLinus Torvalds 		error = PTR_ERR(shm_mnt);
39131170532bSJoe Perches 		pr_err("Could not kern_mount tmpfs\n");
39141da177e4SLinus Torvalds 		goto out1;
39151da177e4SLinus Torvalds 	}
39165a6e75f8SKirill A. Shutemov 
3917396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3918435c0b87SKirill A. Shutemov 	if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
39195a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
39205a6e75f8SKirill A. Shutemov 	else
39215e6e5a12SHugh Dickins 		shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
39225a6e75f8SKirill A. Shutemov #endif
39231da177e4SLinus Torvalds 	return 0;
39241da177e4SLinus Torvalds 
39251da177e4SLinus Torvalds out1:
392641ffe5d5SHugh Dickins 	unregister_filesystem(&shmem_fs_type);
39271da177e4SLinus Torvalds out2:
392841ffe5d5SHugh Dickins 	shmem_destroy_inodecache();
39291da177e4SLinus Torvalds 	shm_mnt = ERR_PTR(error);
39301da177e4SLinus Torvalds 	return error;
39311da177e4SLinus Torvalds }
3932853ac43aSMatt Mackall 
3933396bcc52SMatthew Wilcox (Oracle) #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
39345a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_show(struct kobject *kobj,
39355a6e75f8SKirill A. Shutemov 				  struct kobj_attribute *attr, char *buf)
39365a6e75f8SKirill A. Shutemov {
393726083eb6SColin Ian King 	static const int values[] = {
39385a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ALWAYS,
39395a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_WITHIN_SIZE,
39405a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ADVISE,
39415a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_NEVER,
39425a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_DENY,
39435a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_FORCE,
39445a6e75f8SKirill A. Shutemov 	};
394579d4d38aSJoe Perches 	int len = 0;
394679d4d38aSJoe Perches 	int i;
39475a6e75f8SKirill A. Shutemov 
394879d4d38aSJoe Perches 	for (i = 0; i < ARRAY_SIZE(values); i++) {
394979d4d38aSJoe Perches 		len += sysfs_emit_at(buf, len,
395079d4d38aSJoe Perches 				     shmem_huge == values[i] ? "%s[%s]" : "%s%s",
395179d4d38aSJoe Perches 				     i ? " " : "",
39525a6e75f8SKirill A. Shutemov 				     shmem_format_huge(values[i]));
39535a6e75f8SKirill A. Shutemov 	}
395479d4d38aSJoe Perches 
395579d4d38aSJoe Perches 	len += sysfs_emit_at(buf, len, "\n");
395679d4d38aSJoe Perches 
395779d4d38aSJoe Perches 	return len;
39585a6e75f8SKirill A. Shutemov }
39595a6e75f8SKirill A. Shutemov 
39605a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_store(struct kobject *kobj,
39615a6e75f8SKirill A. Shutemov 		struct kobj_attribute *attr, const char *buf, size_t count)
39625a6e75f8SKirill A. Shutemov {
39635a6e75f8SKirill A. Shutemov 	char tmp[16];
39645a6e75f8SKirill A. Shutemov 	int huge;
39655a6e75f8SKirill A. Shutemov 
39665a6e75f8SKirill A. Shutemov 	if (count + 1 > sizeof(tmp))
39675a6e75f8SKirill A. Shutemov 		return -EINVAL;
39685a6e75f8SKirill A. Shutemov 	memcpy(tmp, buf, count);
39695a6e75f8SKirill A. Shutemov 	tmp[count] = '\0';
39705a6e75f8SKirill A. Shutemov 	if (count && tmp[count - 1] == '\n')
39715a6e75f8SKirill A. Shutemov 		tmp[count - 1] = '\0';
39725a6e75f8SKirill A. Shutemov 
39735a6e75f8SKirill A. Shutemov 	huge = shmem_parse_huge(tmp);
39745a6e75f8SKirill A. Shutemov 	if (huge == -EINVAL)
39755a6e75f8SKirill A. Shutemov 		return -EINVAL;
39765a6e75f8SKirill A. Shutemov 	if (!has_transparent_hugepage() &&
39775a6e75f8SKirill A. Shutemov 			huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
39785a6e75f8SKirill A. Shutemov 		return -EINVAL;
39795a6e75f8SKirill A. Shutemov 
39805a6e75f8SKirill A. Shutemov 	shmem_huge = huge;
3981435c0b87SKirill A. Shutemov 	if (shmem_huge > SHMEM_HUGE_DENY)
39825a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
39835a6e75f8SKirill A. Shutemov 	return count;
39845a6e75f8SKirill A. Shutemov }
39855a6e75f8SKirill A. Shutemov 
39865a6e75f8SKirill A. Shutemov struct kobj_attribute shmem_enabled_attr =
39875a6e75f8SKirill A. Shutemov 	__ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
3988396bcc52SMatthew Wilcox (Oracle) #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
3989f3f0e1d2SKirill A. Shutemov 
3990853ac43aSMatt Mackall #else /* !CONFIG_SHMEM */
3991853ac43aSMatt Mackall 
3992853ac43aSMatt Mackall /*
3993853ac43aSMatt Mackall  * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3994853ac43aSMatt Mackall  *
3995853ac43aSMatt Mackall  * This is intended for small system where the benefits of the full
3996853ac43aSMatt Mackall  * shmem code (swap-backed and resource-limited) are outweighed by
3997853ac43aSMatt Mackall  * their complexity. On systems without swap this code should be
3998853ac43aSMatt Mackall  * effectively equivalent, but much lighter weight.
3999853ac43aSMatt Mackall  */
4000853ac43aSMatt Mackall 
400141ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
4002853ac43aSMatt Mackall 	.name		= "tmpfs",
4003f3235626SDavid Howells 	.init_fs_context = ramfs_init_fs_context,
4004d7167b14SAl Viro 	.parameters	= ramfs_fs_parameters,
4005853ac43aSMatt Mackall 	.kill_sb	= kill_litter_super,
40062b8576cbSEric W. Biederman 	.fs_flags	= FS_USERNS_MOUNT,
4007853ac43aSMatt Mackall };
4008853ac43aSMatt Mackall 
400941ffe5d5SHugh Dickins int __init shmem_init(void)
4010853ac43aSMatt Mackall {
401141ffe5d5SHugh Dickins 	BUG_ON(register_filesystem(&shmem_fs_type) != 0);
4012853ac43aSMatt Mackall 
401341ffe5d5SHugh Dickins 	shm_mnt = kern_mount(&shmem_fs_type);
4014853ac43aSMatt Mackall 	BUG_ON(IS_ERR(shm_mnt));
4015853ac43aSMatt Mackall 
4016853ac43aSMatt Mackall 	return 0;
4017853ac43aSMatt Mackall }
4018853ac43aSMatt Mackall 
4019b56a2d8aSVineeth Remanan Pillai int shmem_unuse(unsigned int type, bool frontswap,
4020b56a2d8aSVineeth Remanan Pillai 		unsigned long *fs_pages_to_unuse)
4021853ac43aSMatt Mackall {
4022853ac43aSMatt Mackall 	return 0;
4023853ac43aSMatt Mackall }
4024853ac43aSMatt Mackall 
4025d7c9e99aSAlexey Gladkov int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
40263f96b79aSHugh Dickins {
40273f96b79aSHugh Dickins 	return 0;
40283f96b79aSHugh Dickins }
40293f96b79aSHugh Dickins 
403024513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
403124513264SHugh Dickins {
403224513264SHugh Dickins }
403324513264SHugh Dickins 
4034c01d5b30SHugh Dickins #ifdef CONFIG_MMU
4035c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
4036c01d5b30SHugh Dickins 				      unsigned long addr, unsigned long len,
4037c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
4038c01d5b30SHugh Dickins {
4039c01d5b30SHugh Dickins 	return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
4040c01d5b30SHugh Dickins }
4041c01d5b30SHugh Dickins #endif
4042c01d5b30SHugh Dickins 
404341ffe5d5SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
404494c1e62dSHugh Dickins {
404541ffe5d5SHugh Dickins 	truncate_inode_pages_range(inode->i_mapping, lstart, lend);
404694c1e62dSHugh Dickins }
404794c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
404894c1e62dSHugh Dickins 
4049853ac43aSMatt Mackall #define shmem_vm_ops				generic_file_vm_ops
40500b0a0806SHugh Dickins #define shmem_file_operations			ramfs_file_operations
4051454abafeSDmitry Monakhov #define shmem_get_inode(sb, dir, mode, dev, flags)	ramfs_get_inode(sb, dir, mode, dev)
40520b0a0806SHugh Dickins #define shmem_acct_size(flags, size)		0
40530b0a0806SHugh Dickins #define shmem_unacct_size(flags, size)		do {} while (0)
4054853ac43aSMatt Mackall 
4055853ac43aSMatt Mackall #endif /* CONFIG_SHMEM */
4056853ac43aSMatt Mackall 
4057853ac43aSMatt Mackall /* common code */
40581da177e4SLinus Torvalds 
4059703321b6SMatthew Auld static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
4060c7277090SEric Paris 				       unsigned long flags, unsigned int i_flags)
40611da177e4SLinus Torvalds {
40621da177e4SLinus Torvalds 	struct inode *inode;
406393dec2daSAl Viro 	struct file *res;
40641da177e4SLinus Torvalds 
4065703321b6SMatthew Auld 	if (IS_ERR(mnt))
4066703321b6SMatthew Auld 		return ERR_CAST(mnt);
40671da177e4SLinus Torvalds 
4068285b2c4fSHugh Dickins 	if (size < 0 || size > MAX_LFS_FILESIZE)
40691da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
40701da177e4SLinus Torvalds 
40711da177e4SLinus Torvalds 	if (shmem_acct_size(flags, size))
40721da177e4SLinus Torvalds 		return ERR_PTR(-ENOMEM);
40731da177e4SLinus Torvalds 
407493dec2daSAl Viro 	inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
407593dec2daSAl Viro 				flags);
4076dac2d1f6SAl Viro 	if (unlikely(!inode)) {
4077dac2d1f6SAl Viro 		shmem_unacct_size(flags, size);
4078dac2d1f6SAl Viro 		return ERR_PTR(-ENOSPC);
4079dac2d1f6SAl Viro 	}
4080c7277090SEric Paris 	inode->i_flags |= i_flags;
40811da177e4SLinus Torvalds 	inode->i_size = size;
40826d6b77f1SMiklos Szeredi 	clear_nlink(inode);	/* It is unlinked */
408326567cdbSAl Viro 	res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
408493dec2daSAl Viro 	if (!IS_ERR(res))
408593dec2daSAl Viro 		res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
40864b42af81SAl Viro 				&shmem_file_operations);
40876b4d0b27SAl Viro 	if (IS_ERR(res))
408893dec2daSAl Viro 		iput(inode);
40896b4d0b27SAl Viro 	return res;
40901da177e4SLinus Torvalds }
4091c7277090SEric Paris 
4092c7277090SEric Paris /**
4093c7277090SEric Paris  * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4094c7277090SEric Paris  * 	kernel internal.  There will be NO LSM permission checks against the
4095c7277090SEric Paris  * 	underlying inode.  So users of this interface must do LSM checks at a
4096e1832f29SStephen Smalley  *	higher layer.  The users are the big_key and shm implementations.  LSM
4097e1832f29SStephen Smalley  *	checks are provided at the key or shm level rather than the inode.
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_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4103c7277090SEric Paris {
4104703321b6SMatthew Auld 	return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
4105c7277090SEric Paris }
4106c7277090SEric Paris 
4107c7277090SEric Paris /**
4108c7277090SEric Paris  * shmem_file_setup - get an unlinked file living in tmpfs
4109c7277090SEric Paris  * @name: name for dentry (to be seen in /proc/<pid>/maps
4110c7277090SEric Paris  * @size: size to be set for the file
4111c7277090SEric Paris  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4112c7277090SEric Paris  */
4113c7277090SEric Paris struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4114c7277090SEric Paris {
4115703321b6SMatthew Auld 	return __shmem_file_setup(shm_mnt, name, size, flags, 0);
4116c7277090SEric Paris }
4117395e0ddcSKeith Packard EXPORT_SYMBOL_GPL(shmem_file_setup);
41181da177e4SLinus Torvalds 
411946711810SRandy Dunlap /**
4120703321b6SMatthew Auld  * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4121703321b6SMatthew Auld  * @mnt: the tmpfs mount where the file will be created
4122703321b6SMatthew Auld  * @name: name for dentry (to be seen in /proc/<pid>/maps
4123703321b6SMatthew Auld  * @size: size to be set for the file
4124703321b6SMatthew Auld  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4125703321b6SMatthew Auld  */
4126703321b6SMatthew Auld struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4127703321b6SMatthew Auld 				       loff_t size, unsigned long flags)
4128703321b6SMatthew Auld {
4129703321b6SMatthew Auld 	return __shmem_file_setup(mnt, name, size, flags, 0);
4130703321b6SMatthew Auld }
4131703321b6SMatthew Auld EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4132703321b6SMatthew Auld 
4133703321b6SMatthew Auld /**
41341da177e4SLinus Torvalds  * shmem_zero_setup - setup a shared anonymous mapping
413545e55300SPeter Collingbourne  * @vma: the vma to be mmapped is prepared by do_mmap
41361da177e4SLinus Torvalds  */
41371da177e4SLinus Torvalds int shmem_zero_setup(struct vm_area_struct *vma)
41381da177e4SLinus Torvalds {
41391da177e4SLinus Torvalds 	struct file *file;
41401da177e4SLinus Torvalds 	loff_t size = vma->vm_end - vma->vm_start;
41411da177e4SLinus Torvalds 
414266fc1303SHugh Dickins 	/*
4143c1e8d7c6SMichel Lespinasse 	 * Cloning a new file under mmap_lock leads to a lock ordering conflict
414466fc1303SHugh Dickins 	 * between XFS directory reading and selinux: since this file is only
414566fc1303SHugh Dickins 	 * accessible to the user through its mapping, use S_PRIVATE flag to
414666fc1303SHugh Dickins 	 * bypass file security, in the same way as shmem_kernel_file_setup().
414766fc1303SHugh Dickins 	 */
4148703321b6SMatthew Auld 	file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
41491da177e4SLinus Torvalds 	if (IS_ERR(file))
41501da177e4SLinus Torvalds 		return PTR_ERR(file);
41511da177e4SLinus Torvalds 
41521da177e4SLinus Torvalds 	if (vma->vm_file)
41531da177e4SLinus Torvalds 		fput(vma->vm_file);
41541da177e4SLinus Torvalds 	vma->vm_file = file;
41551da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
4156f3f0e1d2SKirill A. Shutemov 
4157396bcc52SMatthew Wilcox (Oracle) 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
4158f3f0e1d2SKirill A. Shutemov 			((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4159f3f0e1d2SKirill A. Shutemov 			(vma->vm_end & HPAGE_PMD_MASK)) {
4160f3f0e1d2SKirill A. Shutemov 		khugepaged_enter(vma, vma->vm_flags);
4161f3f0e1d2SKirill A. Shutemov 	}
4162f3f0e1d2SKirill A. Shutemov 
41631da177e4SLinus Torvalds 	return 0;
41641da177e4SLinus Torvalds }
4165d9d90e5eSHugh Dickins 
4166d9d90e5eSHugh Dickins /**
4167d9d90e5eSHugh Dickins  * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4168d9d90e5eSHugh Dickins  * @mapping:	the page's address_space
4169d9d90e5eSHugh Dickins  * @index:	the page index
4170d9d90e5eSHugh Dickins  * @gfp:	the page allocator flags to use if allocating
4171d9d90e5eSHugh Dickins  *
4172d9d90e5eSHugh Dickins  * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4173d9d90e5eSHugh Dickins  * with any new page allocations done using the specified allocation flags.
4174d9d90e5eSHugh Dickins  * But read_cache_page_gfp() uses the ->readpage() method: which does not
4175d9d90e5eSHugh Dickins  * suit tmpfs, since it may have pages in swapcache, and needs to find those
4176d9d90e5eSHugh Dickins  * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4177d9d90e5eSHugh Dickins  *
417868da9f05SHugh Dickins  * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
417968da9f05SHugh Dickins  * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4180d9d90e5eSHugh Dickins  */
4181d9d90e5eSHugh Dickins struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4182d9d90e5eSHugh Dickins 					 pgoff_t index, gfp_t gfp)
4183d9d90e5eSHugh Dickins {
418468da9f05SHugh Dickins #ifdef CONFIG_SHMEM
418568da9f05SHugh Dickins 	struct inode *inode = mapping->host;
41869276aad6SHugh Dickins 	struct page *page;
418768da9f05SHugh Dickins 	int error;
418868da9f05SHugh Dickins 
418930e6a51dSHui Su 	BUG_ON(!shmem_mapping(mapping));
41909e18eb29SAndres Lagar-Cavilla 	error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4191cfda0526SMike Rapoport 				  gfp, NULL, NULL, NULL);
419268da9f05SHugh Dickins 	if (error)
419368da9f05SHugh Dickins 		page = ERR_PTR(error);
419468da9f05SHugh Dickins 	else
419568da9f05SHugh Dickins 		unlock_page(page);
419668da9f05SHugh Dickins 	return page;
419768da9f05SHugh Dickins #else
419868da9f05SHugh Dickins 	/*
419968da9f05SHugh Dickins 	 * The tiny !SHMEM case uses ramfs without swap
420068da9f05SHugh Dickins 	 */
4201d9d90e5eSHugh Dickins 	return read_cache_page_gfp(mapping, index, gfp);
420268da9f05SHugh Dickins #endif
4203d9d90e5eSHugh Dickins }
4204d9d90e5eSHugh Dickins EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
4205