xref: /openbmc/linux/mm/shmem.c (revision 657e3038c4e6fcd3cef41f2b01c655a685a7b8c7)
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>
32b95f1b31SPaul Gortmaker #include <linux/export.h>
33853ac43aSMatt Mackall #include <linux/swap.h>
34e2e40f2cSChristoph Hellwig #include <linux/uio.h>
35853ac43aSMatt Mackall 
36853ac43aSMatt Mackall static struct vfsmount *shm_mnt;
37853ac43aSMatt Mackall 
38853ac43aSMatt Mackall #ifdef CONFIG_SHMEM
391da177e4SLinus Torvalds /*
401da177e4SLinus Torvalds  * This virtual memory filesystem is heavily based on the ramfs. It
411da177e4SLinus Torvalds  * extends ramfs by the ability to use swap and honor resource limits
421da177e4SLinus Torvalds  * which makes it a completely usable filesystem.
431da177e4SLinus Torvalds  */
441da177e4SLinus Torvalds 
4539f0247dSAndreas Gruenbacher #include <linux/xattr.h>
46a5694255SChristoph Hellwig #include <linux/exportfs.h>
471c7c474cSChristoph Hellwig #include <linux/posix_acl.h>
48feda821eSChristoph Hellwig #include <linux/posix_acl_xattr.h>
491da177e4SLinus Torvalds #include <linux/mman.h>
501da177e4SLinus Torvalds #include <linux/string.h>
511da177e4SLinus Torvalds #include <linux/slab.h>
521da177e4SLinus Torvalds #include <linux/backing-dev.h>
531da177e4SLinus Torvalds #include <linux/shmem_fs.h>
541da177e4SLinus Torvalds #include <linux/writeback.h>
551da177e4SLinus Torvalds #include <linux/blkdev.h>
56bda97eabSHugh Dickins #include <linux/pagevec.h>
5741ffe5d5SHugh Dickins #include <linux/percpu_counter.h>
5883e4fa9cSHugh Dickins #include <linux/falloc.h>
59708e3508SHugh Dickins #include <linux/splice.h>
601da177e4SLinus Torvalds #include <linux/security.h>
611da177e4SLinus Torvalds #include <linux/swapops.h>
621da177e4SLinus Torvalds #include <linux/mempolicy.h>
631da177e4SLinus Torvalds #include <linux/namei.h>
64b00dc3adSHugh Dickins #include <linux/ctype.h>
65304dbdb7SLee Schermerhorn #include <linux/migrate.h>
66c1f60a5aSChristoph Lameter #include <linux/highmem.h>
67680d794bSakpm@linux-foundation.org #include <linux/seq_file.h>
6892562927SMimi Zohar #include <linux/magic.h>
699183df25SDavid Herrmann #include <linux/syscalls.h>
7040e041a2SDavid Herrmann #include <linux/fcntl.h>
719183df25SDavid Herrmann #include <uapi/linux/memfd.h>
72304dbdb7SLee Schermerhorn 
731da177e4SLinus Torvalds #include <asm/uaccess.h>
741da177e4SLinus Torvalds #include <asm/pgtable.h>
751da177e4SLinus Torvalds 
76dd56b046SMel Gorman #include "internal.h"
77dd56b046SMel Gorman 
7809cbfeafSKirill A. Shutemov #define BLOCKS_PER_PAGE  (PAGE_SIZE/512)
7909cbfeafSKirill A. Shutemov #define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
801da177e4SLinus Torvalds 
811da177e4SLinus Torvalds /* Pretend that each entry is of this size in directory's i_size */
821da177e4SLinus Torvalds #define BOGO_DIRENT_SIZE 20
831da177e4SLinus Torvalds 
8469f07ec9SHugh Dickins /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
8569f07ec9SHugh Dickins #define SHORT_SYMLINK_LEN 128
8669f07ec9SHugh Dickins 
871aac1400SHugh Dickins /*
88f00cdc6dSHugh Dickins  * shmem_fallocate communicates with shmem_fault or shmem_writepage via
89f00cdc6dSHugh Dickins  * inode->i_private (with i_mutex making sure that it has only one user at
90f00cdc6dSHugh Dickins  * a time): we would prefer not to enlarge the shmem inode just for that.
911aac1400SHugh Dickins  */
921aac1400SHugh Dickins struct shmem_falloc {
938e205f77SHugh Dickins 	wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
941aac1400SHugh Dickins 	pgoff_t start;		/* start of range currently being fallocated */
951aac1400SHugh Dickins 	pgoff_t next;		/* the next page offset to be fallocated */
961aac1400SHugh Dickins 	pgoff_t nr_falloced;	/* how many new pages have been fallocated */
971aac1400SHugh Dickins 	pgoff_t nr_unswapped;	/* how often writepage refused to swap out */
981aac1400SHugh Dickins };
991aac1400SHugh Dickins 
100285b2c4fSHugh Dickins /* Flag allocation requirements to shmem_getpage */
1011da177e4SLinus Torvalds enum sgp_type {
1021da177e4SLinus Torvalds 	SGP_READ,	/* don't exceed i_size, don't allocate page */
1031da177e4SLinus Torvalds 	SGP_CACHE,	/* don't exceed i_size, may allocate page */
104*657e3038SKirill A. Shutemov 	SGP_NOHUGE,	/* like SGP_CACHE, but no huge pages */
105*657e3038SKirill A. Shutemov 	SGP_HUGE,	/* like SGP_CACHE, huge pages preferred */
1061635f6a7SHugh Dickins 	SGP_WRITE,	/* may exceed i_size, may allocate !Uptodate page */
1071635f6a7SHugh Dickins 	SGP_FALLOC,	/* like SGP_WRITE, but make existing page Uptodate */
1081da177e4SLinus Torvalds };
1091da177e4SLinus Torvalds 
110b76db735SAndrew Morton #ifdef CONFIG_TMPFS
111680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_blocks(void)
112680d794bSakpm@linux-foundation.org {
113680d794bSakpm@linux-foundation.org 	return totalram_pages / 2;
114680d794bSakpm@linux-foundation.org }
115680d794bSakpm@linux-foundation.org 
116680d794bSakpm@linux-foundation.org static unsigned long shmem_default_max_inodes(void)
117680d794bSakpm@linux-foundation.org {
118680d794bSakpm@linux-foundation.org 	return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
119680d794bSakpm@linux-foundation.org }
120b76db735SAndrew Morton #endif
121680d794bSakpm@linux-foundation.org 
122bde05d1cSHugh Dickins static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
123bde05d1cSHugh Dickins static int shmem_replace_page(struct page **pagep, gfp_t gfp,
124bde05d1cSHugh Dickins 				struct shmem_inode_info *info, pgoff_t index);
12568da9f05SHugh Dickins static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1269e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp,
1279e18eb29SAndres Lagar-Cavilla 		gfp_t gfp, struct mm_struct *fault_mm, int *fault_type);
12868da9f05SHugh Dickins 
12968da9f05SHugh Dickins static inline int shmem_getpage(struct inode *inode, pgoff_t index,
1309e18eb29SAndres Lagar-Cavilla 		struct page **pagep, enum sgp_type sgp)
13168da9f05SHugh Dickins {
13268da9f05SHugh Dickins 	return shmem_getpage_gfp(inode, index, pagep, sgp,
1339e18eb29SAndres Lagar-Cavilla 		mapping_gfp_mask(inode->i_mapping), NULL, NULL);
13468da9f05SHugh Dickins }
1351da177e4SLinus Torvalds 
1361da177e4SLinus Torvalds static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
1371da177e4SLinus Torvalds {
1381da177e4SLinus Torvalds 	return sb->s_fs_info;
1391da177e4SLinus Torvalds }
1401da177e4SLinus Torvalds 
1411da177e4SLinus Torvalds /*
1421da177e4SLinus Torvalds  * shmem_file_setup pre-accounts the whole fixed size of a VM object,
1431da177e4SLinus Torvalds  * for shared memory and for shared anonymous (/dev/zero) mappings
1441da177e4SLinus Torvalds  * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
1451da177e4SLinus Torvalds  * consistent with the pre-accounting of private mappings ...
1461da177e4SLinus Torvalds  */
1471da177e4SLinus Torvalds static inline int shmem_acct_size(unsigned long flags, loff_t size)
1481da177e4SLinus Torvalds {
1490b0a0806SHugh Dickins 	return (flags & VM_NORESERVE) ?
150191c5424SAl Viro 		0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
1511da177e4SLinus Torvalds }
1521da177e4SLinus Torvalds 
1531da177e4SLinus Torvalds static inline void shmem_unacct_size(unsigned long flags, loff_t size)
1541da177e4SLinus Torvalds {
1550b0a0806SHugh Dickins 	if (!(flags & VM_NORESERVE))
1561da177e4SLinus Torvalds 		vm_unacct_memory(VM_ACCT(size));
1571da177e4SLinus Torvalds }
1581da177e4SLinus Torvalds 
15977142517SKonstantin Khlebnikov static inline int shmem_reacct_size(unsigned long flags,
16077142517SKonstantin Khlebnikov 		loff_t oldsize, loff_t newsize)
16177142517SKonstantin Khlebnikov {
16277142517SKonstantin Khlebnikov 	if (!(flags & VM_NORESERVE)) {
16377142517SKonstantin Khlebnikov 		if (VM_ACCT(newsize) > VM_ACCT(oldsize))
16477142517SKonstantin Khlebnikov 			return security_vm_enough_memory_mm(current->mm,
16577142517SKonstantin Khlebnikov 					VM_ACCT(newsize) - VM_ACCT(oldsize));
16677142517SKonstantin Khlebnikov 		else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
16777142517SKonstantin Khlebnikov 			vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
16877142517SKonstantin Khlebnikov 	}
16977142517SKonstantin Khlebnikov 	return 0;
17077142517SKonstantin Khlebnikov }
17177142517SKonstantin Khlebnikov 
1721da177e4SLinus Torvalds /*
1731da177e4SLinus Torvalds  * ... whereas tmpfs objects are accounted incrementally as
17475edd345SHugh Dickins  * pages are allocated, in order to allow large sparse files.
1751da177e4SLinus Torvalds  * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
1761da177e4SLinus Torvalds  * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
1771da177e4SLinus Torvalds  */
178800d8c63SKirill A. Shutemov static inline int shmem_acct_block(unsigned long flags, long pages)
1791da177e4SLinus Torvalds {
180800d8c63SKirill A. Shutemov 	if (!(flags & VM_NORESERVE))
181800d8c63SKirill A. Shutemov 		return 0;
182800d8c63SKirill A. Shutemov 
183800d8c63SKirill A. Shutemov 	return security_vm_enough_memory_mm(current->mm,
184800d8c63SKirill A. Shutemov 			pages * VM_ACCT(PAGE_SIZE));
1851da177e4SLinus Torvalds }
1861da177e4SLinus Torvalds 
1871da177e4SLinus Torvalds static inline void shmem_unacct_blocks(unsigned long flags, long pages)
1881da177e4SLinus Torvalds {
1890b0a0806SHugh Dickins 	if (flags & VM_NORESERVE)
19009cbfeafSKirill A. Shutemov 		vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
1911da177e4SLinus Torvalds }
1921da177e4SLinus Torvalds 
193759b9775SHugh Dickins static const struct super_operations shmem_ops;
194f5e54d6eSChristoph Hellwig static const struct address_space_operations shmem_aops;
19515ad7cdcSHelge Deller static const struct file_operations shmem_file_operations;
19692e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations;
19792e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations;
19892e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations;
199f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops;
2001da177e4SLinus Torvalds 
2011da177e4SLinus Torvalds static LIST_HEAD(shmem_swaplist);
202cb5f7b9aSHugh Dickins static DEFINE_MUTEX(shmem_swaplist_mutex);
2031da177e4SLinus Torvalds 
2045b04c689SPavel Emelyanov static int shmem_reserve_inode(struct super_block *sb)
2055b04c689SPavel Emelyanov {
2065b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2075b04c689SPavel Emelyanov 	if (sbinfo->max_inodes) {
2085b04c689SPavel Emelyanov 		spin_lock(&sbinfo->stat_lock);
2095b04c689SPavel Emelyanov 		if (!sbinfo->free_inodes) {
2105b04c689SPavel Emelyanov 			spin_unlock(&sbinfo->stat_lock);
2115b04c689SPavel Emelyanov 			return -ENOSPC;
2125b04c689SPavel Emelyanov 		}
2135b04c689SPavel Emelyanov 		sbinfo->free_inodes--;
2145b04c689SPavel Emelyanov 		spin_unlock(&sbinfo->stat_lock);
2155b04c689SPavel Emelyanov 	}
2165b04c689SPavel Emelyanov 	return 0;
2175b04c689SPavel Emelyanov }
2185b04c689SPavel Emelyanov 
2195b04c689SPavel Emelyanov static void shmem_free_inode(struct super_block *sb)
2205b04c689SPavel Emelyanov {
2215b04c689SPavel Emelyanov 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2225b04c689SPavel Emelyanov 	if (sbinfo->max_inodes) {
2235b04c689SPavel Emelyanov 		spin_lock(&sbinfo->stat_lock);
2245b04c689SPavel Emelyanov 		sbinfo->free_inodes++;
2255b04c689SPavel Emelyanov 		spin_unlock(&sbinfo->stat_lock);
2265b04c689SPavel Emelyanov 	}
2275b04c689SPavel Emelyanov }
2285b04c689SPavel Emelyanov 
22946711810SRandy Dunlap /**
23041ffe5d5SHugh Dickins  * shmem_recalc_inode - recalculate the block usage of an inode
2311da177e4SLinus Torvalds  * @inode: inode to recalc
2321da177e4SLinus Torvalds  *
2331da177e4SLinus Torvalds  * We have to calculate the free blocks since the mm can drop
2341da177e4SLinus Torvalds  * undirtied hole pages behind our back.
2351da177e4SLinus Torvalds  *
2361da177e4SLinus Torvalds  * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
2371da177e4SLinus Torvalds  * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
2381da177e4SLinus Torvalds  *
2391da177e4SLinus Torvalds  * It has to be called with the spinlock held.
2401da177e4SLinus Torvalds  */
2411da177e4SLinus Torvalds static void shmem_recalc_inode(struct inode *inode)
2421da177e4SLinus Torvalds {
2431da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
2441da177e4SLinus Torvalds 	long freed;
2451da177e4SLinus Torvalds 
2461da177e4SLinus Torvalds 	freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
2471da177e4SLinus Torvalds 	if (freed > 0) {
24854af6042SHugh Dickins 		struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
24954af6042SHugh Dickins 		if (sbinfo->max_blocks)
25054af6042SHugh Dickins 			percpu_counter_add(&sbinfo->used_blocks, -freed);
2511da177e4SLinus Torvalds 		info->alloced -= freed;
25254af6042SHugh Dickins 		inode->i_blocks -= freed * BLOCKS_PER_PAGE;
2531da177e4SLinus Torvalds 		shmem_unacct_blocks(info->flags, freed);
2541da177e4SLinus Torvalds 	}
2551da177e4SLinus Torvalds }
2561da177e4SLinus Torvalds 
257800d8c63SKirill A. Shutemov bool shmem_charge(struct inode *inode, long pages)
258800d8c63SKirill A. Shutemov {
259800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
260800d8c63SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
261800d8c63SKirill A. Shutemov 
262800d8c63SKirill A. Shutemov 	if (shmem_acct_block(info->flags, pages))
263800d8c63SKirill A. Shutemov 		return false;
264800d8c63SKirill A. Shutemov 	spin_lock(&info->lock);
265800d8c63SKirill A. Shutemov 	info->alloced += pages;
266800d8c63SKirill A. Shutemov 	inode->i_blocks += pages * BLOCKS_PER_PAGE;
267800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
268800d8c63SKirill A. Shutemov 	spin_unlock(&info->lock);
269800d8c63SKirill A. Shutemov 	inode->i_mapping->nrpages += pages;
270800d8c63SKirill A. Shutemov 
271800d8c63SKirill A. Shutemov 	if (!sbinfo->max_blocks)
272800d8c63SKirill A. Shutemov 		return true;
273800d8c63SKirill A. Shutemov 	if (percpu_counter_compare(&sbinfo->used_blocks,
274800d8c63SKirill A. Shutemov 				sbinfo->max_blocks - pages) > 0) {
275800d8c63SKirill A. Shutemov 		inode->i_mapping->nrpages -= pages;
276800d8c63SKirill A. Shutemov 		spin_lock(&info->lock);
277800d8c63SKirill A. Shutemov 		info->alloced -= pages;
278800d8c63SKirill A. Shutemov 		shmem_recalc_inode(inode);
279800d8c63SKirill A. Shutemov 		spin_unlock(&info->lock);
280800d8c63SKirill A. Shutemov 
281800d8c63SKirill A. Shutemov 		return false;
282800d8c63SKirill A. Shutemov 	}
283800d8c63SKirill A. Shutemov 	percpu_counter_add(&sbinfo->used_blocks, pages);
284800d8c63SKirill A. Shutemov 	return true;
285800d8c63SKirill A. Shutemov }
286800d8c63SKirill A. Shutemov 
287800d8c63SKirill A. Shutemov void shmem_uncharge(struct inode *inode, long pages)
288800d8c63SKirill A. Shutemov {
289800d8c63SKirill A. Shutemov 	struct shmem_inode_info *info = SHMEM_I(inode);
290800d8c63SKirill A. Shutemov 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
291800d8c63SKirill A. Shutemov 
292800d8c63SKirill A. Shutemov 	spin_lock(&info->lock);
293800d8c63SKirill A. Shutemov 	info->alloced -= pages;
294800d8c63SKirill A. Shutemov 	inode->i_blocks -= pages * BLOCKS_PER_PAGE;
295800d8c63SKirill A. Shutemov 	shmem_recalc_inode(inode);
296800d8c63SKirill A. Shutemov 	spin_unlock(&info->lock);
297800d8c63SKirill A. Shutemov 
298800d8c63SKirill A. Shutemov 	if (sbinfo->max_blocks)
299800d8c63SKirill A. Shutemov 		percpu_counter_sub(&sbinfo->used_blocks, pages);
300800d8c63SKirill A. Shutemov }
301800d8c63SKirill A. Shutemov 
3027a5d0fbbSHugh Dickins /*
3037a5d0fbbSHugh Dickins  * Replace item expected in radix tree by a new item, while holding tree lock.
3047a5d0fbbSHugh Dickins  */
3057a5d0fbbSHugh Dickins static int shmem_radix_tree_replace(struct address_space *mapping,
3067a5d0fbbSHugh Dickins 			pgoff_t index, void *expected, void *replacement)
3077a5d0fbbSHugh Dickins {
3087a5d0fbbSHugh Dickins 	void **pslot;
3096dbaf22cSJohannes Weiner 	void *item;
3107a5d0fbbSHugh Dickins 
3117a5d0fbbSHugh Dickins 	VM_BUG_ON(!expected);
3126dbaf22cSJohannes Weiner 	VM_BUG_ON(!replacement);
3137a5d0fbbSHugh Dickins 	pslot = radix_tree_lookup_slot(&mapping->page_tree, index);
3146dbaf22cSJohannes Weiner 	if (!pslot)
3156dbaf22cSJohannes Weiner 		return -ENOENT;
3166dbaf22cSJohannes Weiner 	item = radix_tree_deref_slot_protected(pslot, &mapping->tree_lock);
3177a5d0fbbSHugh Dickins 	if (item != expected)
3187a5d0fbbSHugh Dickins 		return -ENOENT;
3197a5d0fbbSHugh Dickins 	radix_tree_replace_slot(pslot, replacement);
3207a5d0fbbSHugh Dickins 	return 0;
3217a5d0fbbSHugh Dickins }
3227a5d0fbbSHugh Dickins 
3237a5d0fbbSHugh Dickins /*
324d1899228SHugh Dickins  * Sometimes, before we decide whether to proceed or to fail, we must check
325d1899228SHugh Dickins  * that an entry was not already brought back from swap by a racing thread.
326d1899228SHugh Dickins  *
327d1899228SHugh Dickins  * Checking page is not enough: by the time a SwapCache page is locked, it
328d1899228SHugh Dickins  * might be reused, and again be SwapCache, using the same swap as before.
329d1899228SHugh Dickins  */
330d1899228SHugh Dickins static bool shmem_confirm_swap(struct address_space *mapping,
331d1899228SHugh Dickins 			       pgoff_t index, swp_entry_t swap)
332d1899228SHugh Dickins {
333d1899228SHugh Dickins 	void *item;
334d1899228SHugh Dickins 
335d1899228SHugh Dickins 	rcu_read_lock();
336d1899228SHugh Dickins 	item = radix_tree_lookup(&mapping->page_tree, index);
337d1899228SHugh Dickins 	rcu_read_unlock();
338d1899228SHugh Dickins 	return item == swp_to_radix_entry(swap);
339d1899228SHugh Dickins }
340d1899228SHugh Dickins 
341d1899228SHugh Dickins /*
3425a6e75f8SKirill A. Shutemov  * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
3435a6e75f8SKirill A. Shutemov  *
3445a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_NEVER:
3455a6e75f8SKirill A. Shutemov  *	disables huge pages for the mount;
3465a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ALWAYS:
3475a6e75f8SKirill A. Shutemov  *	enables huge pages for the mount;
3485a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_WITHIN_SIZE:
3495a6e75f8SKirill A. Shutemov  *	only allocate huge pages if the page will be fully within i_size,
3505a6e75f8SKirill A. Shutemov  *	also respect fadvise()/madvise() hints;
3515a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_ADVISE:
3525a6e75f8SKirill A. Shutemov  *	only allocate huge pages if requested with fadvise()/madvise();
3535a6e75f8SKirill A. Shutemov  */
3545a6e75f8SKirill A. Shutemov 
3555a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_NEVER	0
3565a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ALWAYS	1
3575a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_WITHIN_SIZE	2
3585a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_ADVISE	3
3595a6e75f8SKirill A. Shutemov 
3605a6e75f8SKirill A. Shutemov /*
3615a6e75f8SKirill A. Shutemov  * Special values.
3625a6e75f8SKirill A. Shutemov  * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
3635a6e75f8SKirill A. Shutemov  *
3645a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_DENY:
3655a6e75f8SKirill A. Shutemov  *	disables huge on shm_mnt and all mounts, for emergency use;
3665a6e75f8SKirill A. Shutemov  * SHMEM_HUGE_FORCE:
3675a6e75f8SKirill A. Shutemov  *	enables huge on shm_mnt and all mounts, w/o needing option, for testing;
3685a6e75f8SKirill A. Shutemov  *
3695a6e75f8SKirill A. Shutemov  */
3705a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_DENY		(-1)
3715a6e75f8SKirill A. Shutemov #define SHMEM_HUGE_FORCE	(-2)
3725a6e75f8SKirill A. Shutemov 
3735a6e75f8SKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3745a6e75f8SKirill A. Shutemov /* ifdef here to avoid bloating shmem.o when not necessary */
3755a6e75f8SKirill A. Shutemov 
3765a6e75f8SKirill A. Shutemov int shmem_huge __read_mostly;
3775a6e75f8SKirill A. Shutemov 
3785a6e75f8SKirill A. Shutemov static int shmem_parse_huge(const char *str)
3795a6e75f8SKirill A. Shutemov {
3805a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "never"))
3815a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_NEVER;
3825a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "always"))
3835a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ALWAYS;
3845a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "within_size"))
3855a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_WITHIN_SIZE;
3865a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "advise"))
3875a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_ADVISE;
3885a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "deny"))
3895a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_DENY;
3905a6e75f8SKirill A. Shutemov 	if (!strcmp(str, "force"))
3915a6e75f8SKirill A. Shutemov 		return SHMEM_HUGE_FORCE;
3925a6e75f8SKirill A. Shutemov 	return -EINVAL;
3935a6e75f8SKirill A. Shutemov }
3945a6e75f8SKirill A. Shutemov 
3955a6e75f8SKirill A. Shutemov static const char *shmem_format_huge(int huge)
3965a6e75f8SKirill A. Shutemov {
3975a6e75f8SKirill A. Shutemov 	switch (huge) {
3985a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_NEVER:
3995a6e75f8SKirill A. Shutemov 		return "never";
4005a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ALWAYS:
4015a6e75f8SKirill A. Shutemov 		return "always";
4025a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_WITHIN_SIZE:
4035a6e75f8SKirill A. Shutemov 		return "within_size";
4045a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_ADVISE:
4055a6e75f8SKirill A. Shutemov 		return "advise";
4065a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_DENY:
4075a6e75f8SKirill A. Shutemov 		return "deny";
4085a6e75f8SKirill A. Shutemov 	case SHMEM_HUGE_FORCE:
4095a6e75f8SKirill A. Shutemov 		return "force";
4105a6e75f8SKirill A. Shutemov 	default:
4115a6e75f8SKirill A. Shutemov 		VM_BUG_ON(1);
4125a6e75f8SKirill A. Shutemov 		return "bad_val";
4135a6e75f8SKirill A. Shutemov 	}
4145a6e75f8SKirill A. Shutemov }
4155a6e75f8SKirill A. Shutemov 
4165a6e75f8SKirill A. Shutemov #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
4175a6e75f8SKirill A. Shutemov 
4185a6e75f8SKirill A. Shutemov #define shmem_huge SHMEM_HUGE_DENY
4195a6e75f8SKirill A. Shutemov 
4205a6e75f8SKirill A. Shutemov #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4215a6e75f8SKirill A. Shutemov 
4225a6e75f8SKirill A. Shutemov /*
42346f65ec1SHugh Dickins  * Like add_to_page_cache_locked, but error if expected item has gone.
42446f65ec1SHugh Dickins  */
42546f65ec1SHugh Dickins static int shmem_add_to_page_cache(struct page *page,
42646f65ec1SHugh Dickins 				   struct address_space *mapping,
427fed400a1SWang Sheng-Hui 				   pgoff_t index, void *expected)
42846f65ec1SHugh Dickins {
429800d8c63SKirill A. Shutemov 	int error, nr = hpage_nr_pages(page);
43046f65ec1SHugh Dickins 
431800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageTail(page), page);
432800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(index != round_down(index, nr), page);
433309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
434309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
435800d8c63SKirill A. Shutemov 	VM_BUG_ON(expected && PageTransHuge(page));
43646f65ec1SHugh Dickins 
437800d8c63SKirill A. Shutemov 	page_ref_add(page, nr);
43846f65ec1SHugh Dickins 	page->mapping = mapping;
43946f65ec1SHugh Dickins 	page->index = index;
44046f65ec1SHugh Dickins 
44146f65ec1SHugh Dickins 	spin_lock_irq(&mapping->tree_lock);
442800d8c63SKirill A. Shutemov 	if (PageTransHuge(page)) {
443800d8c63SKirill A. Shutemov 		void __rcu **results;
444800d8c63SKirill A. Shutemov 		pgoff_t idx;
445800d8c63SKirill A. Shutemov 		int i;
446800d8c63SKirill A. Shutemov 
447800d8c63SKirill A. Shutemov 		error = 0;
448800d8c63SKirill A. Shutemov 		if (radix_tree_gang_lookup_slot(&mapping->page_tree,
449800d8c63SKirill A. Shutemov 					&results, &idx, index, 1) &&
450800d8c63SKirill A. Shutemov 				idx < index + HPAGE_PMD_NR) {
451800d8c63SKirill A. Shutemov 			error = -EEXIST;
452800d8c63SKirill A. Shutemov 		}
453800d8c63SKirill A. Shutemov 
454800d8c63SKirill A. Shutemov 		if (!error) {
455800d8c63SKirill A. Shutemov 			for (i = 0; i < HPAGE_PMD_NR; i++) {
456800d8c63SKirill A. Shutemov 				error = radix_tree_insert(&mapping->page_tree,
457800d8c63SKirill A. Shutemov 						index + i, page + i);
458800d8c63SKirill A. Shutemov 				VM_BUG_ON(error);
459800d8c63SKirill A. Shutemov 			}
460800d8c63SKirill A. Shutemov 			count_vm_event(THP_FILE_ALLOC);
461800d8c63SKirill A. Shutemov 		}
462800d8c63SKirill A. Shutemov 	} else if (!expected) {
463b065b432SHugh Dickins 		error = radix_tree_insert(&mapping->page_tree, index, page);
464800d8c63SKirill A. Shutemov 	} else {
465b065b432SHugh Dickins 		error = shmem_radix_tree_replace(mapping, index, expected,
466b065b432SHugh Dickins 								 page);
467800d8c63SKirill A. Shutemov 	}
468800d8c63SKirill A. Shutemov 
46946f65ec1SHugh Dickins 	if (!error) {
470800d8c63SKirill A. Shutemov 		mapping->nrpages += nr;
471800d8c63SKirill A. Shutemov 		if (PageTransHuge(page))
472800d8c63SKirill A. Shutemov 			__inc_zone_page_state(page, NR_SHMEM_THPS);
473800d8c63SKirill A. Shutemov 		__mod_zone_page_state(page_zone(page), NR_FILE_PAGES, nr);
474800d8c63SKirill A. Shutemov 		__mod_zone_page_state(page_zone(page), NR_SHMEM, nr);
47546f65ec1SHugh Dickins 		spin_unlock_irq(&mapping->tree_lock);
47646f65ec1SHugh Dickins 	} else {
47746f65ec1SHugh Dickins 		page->mapping = NULL;
47846f65ec1SHugh Dickins 		spin_unlock_irq(&mapping->tree_lock);
479800d8c63SKirill A. Shutemov 		page_ref_sub(page, nr);
48046f65ec1SHugh Dickins 	}
48146f65ec1SHugh Dickins 	return error;
48246f65ec1SHugh Dickins }
48346f65ec1SHugh Dickins 
48446f65ec1SHugh Dickins /*
4856922c0c7SHugh Dickins  * Like delete_from_page_cache, but substitutes swap for page.
4866922c0c7SHugh Dickins  */
4876922c0c7SHugh Dickins static void shmem_delete_from_page_cache(struct page *page, void *radswap)
4886922c0c7SHugh Dickins {
4896922c0c7SHugh Dickins 	struct address_space *mapping = page->mapping;
4906922c0c7SHugh Dickins 	int error;
4916922c0c7SHugh Dickins 
492800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageCompound(page), page);
493800d8c63SKirill A. Shutemov 
4946922c0c7SHugh Dickins 	spin_lock_irq(&mapping->tree_lock);
4956922c0c7SHugh Dickins 	error = shmem_radix_tree_replace(mapping, page->index, page, radswap);
4966922c0c7SHugh Dickins 	page->mapping = NULL;
4976922c0c7SHugh Dickins 	mapping->nrpages--;
4986922c0c7SHugh Dickins 	__dec_zone_page_state(page, NR_FILE_PAGES);
4996922c0c7SHugh Dickins 	__dec_zone_page_state(page, NR_SHMEM);
5006922c0c7SHugh Dickins 	spin_unlock_irq(&mapping->tree_lock);
50109cbfeafSKirill A. Shutemov 	put_page(page);
5026922c0c7SHugh Dickins 	BUG_ON(error);
5036922c0c7SHugh Dickins }
5046922c0c7SHugh Dickins 
5056922c0c7SHugh Dickins /*
5067a5d0fbbSHugh Dickins  * Remove swap entry from radix tree, free the swap and its page cache.
5077a5d0fbbSHugh Dickins  */
5087a5d0fbbSHugh Dickins static int shmem_free_swap(struct address_space *mapping,
5097a5d0fbbSHugh Dickins 			   pgoff_t index, void *radswap)
5107a5d0fbbSHugh Dickins {
5116dbaf22cSJohannes Weiner 	void *old;
5127a5d0fbbSHugh Dickins 
5137a5d0fbbSHugh Dickins 	spin_lock_irq(&mapping->tree_lock);
5146dbaf22cSJohannes Weiner 	old = radix_tree_delete_item(&mapping->page_tree, index, radswap);
5157a5d0fbbSHugh Dickins 	spin_unlock_irq(&mapping->tree_lock);
5166dbaf22cSJohannes Weiner 	if (old != radswap)
5176dbaf22cSJohannes Weiner 		return -ENOENT;
5187a5d0fbbSHugh Dickins 	free_swap_and_cache(radix_to_swp_entry(radswap));
5196dbaf22cSJohannes Weiner 	return 0;
5207a5d0fbbSHugh Dickins }
5217a5d0fbbSHugh Dickins 
5227a5d0fbbSHugh Dickins /*
5236a15a370SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
52448131e03SVlastimil Babka  * given offsets are swapped out.
5256a15a370SVlastimil Babka  *
5266a15a370SVlastimil Babka  * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
5276a15a370SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
5286a15a370SVlastimil Babka  */
52948131e03SVlastimil Babka unsigned long shmem_partial_swap_usage(struct address_space *mapping,
53048131e03SVlastimil Babka 						pgoff_t start, pgoff_t end)
5316a15a370SVlastimil Babka {
5326a15a370SVlastimil Babka 	struct radix_tree_iter iter;
5336a15a370SVlastimil Babka 	void **slot;
5346a15a370SVlastimil Babka 	struct page *page;
53548131e03SVlastimil Babka 	unsigned long swapped = 0;
5366a15a370SVlastimil Babka 
5376a15a370SVlastimil Babka 	rcu_read_lock();
5386a15a370SVlastimil Babka 
5396a15a370SVlastimil Babka 	radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
5406a15a370SVlastimil Babka 		if (iter.index >= end)
5416a15a370SVlastimil Babka 			break;
5426a15a370SVlastimil Babka 
5436a15a370SVlastimil Babka 		page = radix_tree_deref_slot(slot);
5446a15a370SVlastimil Babka 
5452cf938aaSMatthew Wilcox 		if (radix_tree_deref_retry(page)) {
5462cf938aaSMatthew Wilcox 			slot = radix_tree_iter_retry(&iter);
5472cf938aaSMatthew Wilcox 			continue;
5482cf938aaSMatthew Wilcox 		}
5496a15a370SVlastimil Babka 
5506a15a370SVlastimil Babka 		if (radix_tree_exceptional_entry(page))
5516a15a370SVlastimil Babka 			swapped++;
5526a15a370SVlastimil Babka 
5536a15a370SVlastimil Babka 		if (need_resched()) {
5546a15a370SVlastimil Babka 			cond_resched_rcu();
5557165092fSMatthew Wilcox 			slot = radix_tree_iter_next(&iter);
5566a15a370SVlastimil Babka 		}
5576a15a370SVlastimil Babka 	}
5586a15a370SVlastimil Babka 
5596a15a370SVlastimil Babka 	rcu_read_unlock();
5606a15a370SVlastimil Babka 
5616a15a370SVlastimil Babka 	return swapped << PAGE_SHIFT;
5626a15a370SVlastimil Babka }
5636a15a370SVlastimil Babka 
5646a15a370SVlastimil Babka /*
56548131e03SVlastimil Babka  * Determine (in bytes) how many of the shmem object's pages mapped by the
56648131e03SVlastimil Babka  * given vma is swapped out.
56748131e03SVlastimil Babka  *
56848131e03SVlastimil Babka  * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
56948131e03SVlastimil Babka  * as long as the inode doesn't go away and racy results are not a problem.
57048131e03SVlastimil Babka  */
57148131e03SVlastimil Babka unsigned long shmem_swap_usage(struct vm_area_struct *vma)
57248131e03SVlastimil Babka {
57348131e03SVlastimil Babka 	struct inode *inode = file_inode(vma->vm_file);
57448131e03SVlastimil Babka 	struct shmem_inode_info *info = SHMEM_I(inode);
57548131e03SVlastimil Babka 	struct address_space *mapping = inode->i_mapping;
57648131e03SVlastimil Babka 	unsigned long swapped;
57748131e03SVlastimil Babka 
57848131e03SVlastimil Babka 	/* Be careful as we don't hold info->lock */
57948131e03SVlastimil Babka 	swapped = READ_ONCE(info->swapped);
58048131e03SVlastimil Babka 
58148131e03SVlastimil Babka 	/*
58248131e03SVlastimil Babka 	 * The easier cases are when the shmem object has nothing in swap, or
58348131e03SVlastimil Babka 	 * the vma maps it whole. Then we can simply use the stats that we
58448131e03SVlastimil Babka 	 * already track.
58548131e03SVlastimil Babka 	 */
58648131e03SVlastimil Babka 	if (!swapped)
58748131e03SVlastimil Babka 		return 0;
58848131e03SVlastimil Babka 
58948131e03SVlastimil Babka 	if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
59048131e03SVlastimil Babka 		return swapped << PAGE_SHIFT;
59148131e03SVlastimil Babka 
59248131e03SVlastimil Babka 	/* Here comes the more involved part */
59348131e03SVlastimil Babka 	return shmem_partial_swap_usage(mapping,
59448131e03SVlastimil Babka 			linear_page_index(vma, vma->vm_start),
59548131e03SVlastimil Babka 			linear_page_index(vma, vma->vm_end));
59648131e03SVlastimil Babka }
59748131e03SVlastimil Babka 
59848131e03SVlastimil Babka /*
59924513264SHugh Dickins  * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
60024513264SHugh Dickins  */
60124513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
60224513264SHugh Dickins {
60324513264SHugh Dickins 	struct pagevec pvec;
60424513264SHugh Dickins 	pgoff_t indices[PAGEVEC_SIZE];
60524513264SHugh Dickins 	pgoff_t index = 0;
60624513264SHugh Dickins 
60724513264SHugh Dickins 	pagevec_init(&pvec, 0);
60824513264SHugh Dickins 	/*
60924513264SHugh Dickins 	 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
61024513264SHugh Dickins 	 */
61124513264SHugh Dickins 	while (!mapping_unevictable(mapping)) {
61224513264SHugh Dickins 		/*
61324513264SHugh Dickins 		 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
61424513264SHugh Dickins 		 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
61524513264SHugh Dickins 		 */
6160cd6144aSJohannes Weiner 		pvec.nr = find_get_entries(mapping, index,
61724513264SHugh Dickins 					   PAGEVEC_SIZE, pvec.pages, indices);
61824513264SHugh Dickins 		if (!pvec.nr)
61924513264SHugh Dickins 			break;
62024513264SHugh Dickins 		index = indices[pvec.nr - 1] + 1;
6210cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
62224513264SHugh Dickins 		check_move_unevictable_pages(pvec.pages, pvec.nr);
62324513264SHugh Dickins 		pagevec_release(&pvec);
62424513264SHugh Dickins 		cond_resched();
62524513264SHugh Dickins 	}
6267a5d0fbbSHugh Dickins }
6277a5d0fbbSHugh Dickins 
6287a5d0fbbSHugh Dickins /*
6297a5d0fbbSHugh Dickins  * Remove range of pages and swap entries from radix tree, and free them.
6301635f6a7SHugh Dickins  * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
6317a5d0fbbSHugh Dickins  */
6321635f6a7SHugh Dickins static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
6331635f6a7SHugh Dickins 								 bool unfalloc)
6341da177e4SLinus Torvalds {
635285b2c4fSHugh Dickins 	struct address_space *mapping = inode->i_mapping;
6361da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
63709cbfeafSKirill A. Shutemov 	pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
63809cbfeafSKirill A. Shutemov 	pgoff_t end = (lend + 1) >> PAGE_SHIFT;
63909cbfeafSKirill A. Shutemov 	unsigned int partial_start = lstart & (PAGE_SIZE - 1);
64009cbfeafSKirill A. Shutemov 	unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
641bda97eabSHugh Dickins 	struct pagevec pvec;
6427a5d0fbbSHugh Dickins 	pgoff_t indices[PAGEVEC_SIZE];
6437a5d0fbbSHugh Dickins 	long nr_swaps_freed = 0;
644285b2c4fSHugh Dickins 	pgoff_t index;
645bda97eabSHugh Dickins 	int i;
6461da177e4SLinus Torvalds 
64783e4fa9cSHugh Dickins 	if (lend == -1)
64883e4fa9cSHugh Dickins 		end = -1;	/* unsigned, so actually very big */
649bda97eabSHugh Dickins 
650bda97eabSHugh Dickins 	pagevec_init(&pvec, 0);
651bda97eabSHugh Dickins 	index = start;
65283e4fa9cSHugh Dickins 	while (index < end) {
6530cd6144aSJohannes Weiner 		pvec.nr = find_get_entries(mapping, index,
65483e4fa9cSHugh Dickins 			min(end - index, (pgoff_t)PAGEVEC_SIZE),
6557a5d0fbbSHugh Dickins 			pvec.pages, indices);
6567a5d0fbbSHugh Dickins 		if (!pvec.nr)
6577a5d0fbbSHugh Dickins 			break;
658bda97eabSHugh Dickins 		for (i = 0; i < pagevec_count(&pvec); i++) {
659bda97eabSHugh Dickins 			struct page *page = pvec.pages[i];
660bda97eabSHugh Dickins 
6617a5d0fbbSHugh Dickins 			index = indices[i];
66283e4fa9cSHugh Dickins 			if (index >= end)
663bda97eabSHugh Dickins 				break;
664bda97eabSHugh Dickins 
6657a5d0fbbSHugh Dickins 			if (radix_tree_exceptional_entry(page)) {
6661635f6a7SHugh Dickins 				if (unfalloc)
6671635f6a7SHugh Dickins 					continue;
6687a5d0fbbSHugh Dickins 				nr_swaps_freed += !shmem_free_swap(mapping,
6697a5d0fbbSHugh Dickins 								index, page);
6707a5d0fbbSHugh Dickins 				continue;
6717a5d0fbbSHugh Dickins 			}
6727a5d0fbbSHugh Dickins 
673800d8c63SKirill A. Shutemov 			VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
674800d8c63SKirill A. Shutemov 
675bda97eabSHugh Dickins 			if (!trylock_page(page))
676bda97eabSHugh Dickins 				continue;
677800d8c63SKirill A. Shutemov 
678800d8c63SKirill A. Shutemov 			if (PageTransTail(page)) {
679800d8c63SKirill A. Shutemov 				/* Middle of THP: zero out the page */
680800d8c63SKirill A. Shutemov 				clear_highpage(page);
681800d8c63SKirill A. Shutemov 				unlock_page(page);
682800d8c63SKirill A. Shutemov 				continue;
683800d8c63SKirill A. Shutemov 			} else if (PageTransHuge(page)) {
684800d8c63SKirill A. Shutemov 				if (index == round_down(end, HPAGE_PMD_NR)) {
685800d8c63SKirill A. Shutemov 					/*
686800d8c63SKirill A. Shutemov 					 * Range ends in the middle of THP:
687800d8c63SKirill A. Shutemov 					 * zero out the page
688800d8c63SKirill A. Shutemov 					 */
689800d8c63SKirill A. Shutemov 					clear_highpage(page);
690800d8c63SKirill A. Shutemov 					unlock_page(page);
691800d8c63SKirill A. Shutemov 					continue;
692800d8c63SKirill A. Shutemov 				}
693800d8c63SKirill A. Shutemov 				index += HPAGE_PMD_NR - 1;
694800d8c63SKirill A. Shutemov 				i += HPAGE_PMD_NR - 1;
695800d8c63SKirill A. Shutemov 			}
696800d8c63SKirill A. Shutemov 
6971635f6a7SHugh Dickins 			if (!unfalloc || !PageUptodate(page)) {
698800d8c63SKirill A. Shutemov 				VM_BUG_ON_PAGE(PageTail(page), page);
699800d8c63SKirill A. Shutemov 				if (page_mapping(page) == mapping) {
700309381feSSasha Levin 					VM_BUG_ON_PAGE(PageWriteback(page), page);
701bda97eabSHugh Dickins 					truncate_inode_page(mapping, page);
7027a5d0fbbSHugh Dickins 				}
7031635f6a7SHugh Dickins 			}
704bda97eabSHugh Dickins 			unlock_page(page);
705bda97eabSHugh Dickins 		}
7060cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
70724513264SHugh Dickins 		pagevec_release(&pvec);
708bda97eabSHugh Dickins 		cond_resched();
709bda97eabSHugh Dickins 		index++;
710bda97eabSHugh Dickins 	}
711bda97eabSHugh Dickins 
71283e4fa9cSHugh Dickins 	if (partial_start) {
713bda97eabSHugh Dickins 		struct page *page = NULL;
7149e18eb29SAndres Lagar-Cavilla 		shmem_getpage(inode, start - 1, &page, SGP_READ);
715bda97eabSHugh Dickins 		if (page) {
71609cbfeafSKirill A. Shutemov 			unsigned int top = PAGE_SIZE;
71783e4fa9cSHugh Dickins 			if (start > end) {
71883e4fa9cSHugh Dickins 				top = partial_end;
71983e4fa9cSHugh Dickins 				partial_end = 0;
72083e4fa9cSHugh Dickins 			}
72183e4fa9cSHugh Dickins 			zero_user_segment(page, partial_start, top);
722bda97eabSHugh Dickins 			set_page_dirty(page);
723bda97eabSHugh Dickins 			unlock_page(page);
72409cbfeafSKirill A. Shutemov 			put_page(page);
725bda97eabSHugh Dickins 		}
726bda97eabSHugh Dickins 	}
72783e4fa9cSHugh Dickins 	if (partial_end) {
72883e4fa9cSHugh Dickins 		struct page *page = NULL;
7299e18eb29SAndres Lagar-Cavilla 		shmem_getpage(inode, end, &page, SGP_READ);
73083e4fa9cSHugh Dickins 		if (page) {
73183e4fa9cSHugh Dickins 			zero_user_segment(page, 0, partial_end);
73283e4fa9cSHugh Dickins 			set_page_dirty(page);
73383e4fa9cSHugh Dickins 			unlock_page(page);
73409cbfeafSKirill A. Shutemov 			put_page(page);
73583e4fa9cSHugh Dickins 		}
73683e4fa9cSHugh Dickins 	}
73783e4fa9cSHugh Dickins 	if (start >= end)
73883e4fa9cSHugh Dickins 		return;
739bda97eabSHugh Dickins 
740bda97eabSHugh Dickins 	index = start;
741b1a36650SHugh Dickins 	while (index < end) {
742bda97eabSHugh Dickins 		cond_resched();
7430cd6144aSJohannes Weiner 
7440cd6144aSJohannes Weiner 		pvec.nr = find_get_entries(mapping, index,
74583e4fa9cSHugh Dickins 				min(end - index, (pgoff_t)PAGEVEC_SIZE),
7467a5d0fbbSHugh Dickins 				pvec.pages, indices);
7477a5d0fbbSHugh Dickins 		if (!pvec.nr) {
748b1a36650SHugh Dickins 			/* If all gone or hole-punch or unfalloc, we're done */
749b1a36650SHugh Dickins 			if (index == start || end != -1)
750bda97eabSHugh Dickins 				break;
751b1a36650SHugh Dickins 			/* But if truncating, restart to make sure all gone */
752bda97eabSHugh Dickins 			index = start;
753bda97eabSHugh Dickins 			continue;
754bda97eabSHugh Dickins 		}
755bda97eabSHugh Dickins 		for (i = 0; i < pagevec_count(&pvec); i++) {
756bda97eabSHugh Dickins 			struct page *page = pvec.pages[i];
757bda97eabSHugh Dickins 
7587a5d0fbbSHugh Dickins 			index = indices[i];
75983e4fa9cSHugh Dickins 			if (index >= end)
760bda97eabSHugh Dickins 				break;
761bda97eabSHugh Dickins 
7627a5d0fbbSHugh Dickins 			if (radix_tree_exceptional_entry(page)) {
7631635f6a7SHugh Dickins 				if (unfalloc)
7641635f6a7SHugh Dickins 					continue;
765b1a36650SHugh Dickins 				if (shmem_free_swap(mapping, index, page)) {
766b1a36650SHugh Dickins 					/* Swap was replaced by page: retry */
767b1a36650SHugh Dickins 					index--;
768b1a36650SHugh Dickins 					break;
769b1a36650SHugh Dickins 				}
770b1a36650SHugh Dickins 				nr_swaps_freed++;
7717a5d0fbbSHugh Dickins 				continue;
7727a5d0fbbSHugh Dickins 			}
7737a5d0fbbSHugh Dickins 
774bda97eabSHugh Dickins 			lock_page(page);
775800d8c63SKirill A. Shutemov 
776800d8c63SKirill A. Shutemov 			if (PageTransTail(page)) {
777800d8c63SKirill A. Shutemov 				/* Middle of THP: zero out the page */
778800d8c63SKirill A. Shutemov 				clear_highpage(page);
779800d8c63SKirill A. Shutemov 				unlock_page(page);
780800d8c63SKirill A. Shutemov 				/*
781800d8c63SKirill A. Shutemov 				 * Partial thp truncate due 'start' in middle
782800d8c63SKirill A. Shutemov 				 * of THP: don't need to look on these pages
783800d8c63SKirill A. Shutemov 				 * again on !pvec.nr restart.
784800d8c63SKirill A. Shutemov 				 */
785800d8c63SKirill A. Shutemov 				if (index != round_down(end, HPAGE_PMD_NR))
786800d8c63SKirill A. Shutemov 					start++;
787800d8c63SKirill A. Shutemov 				continue;
788800d8c63SKirill A. Shutemov 			} else if (PageTransHuge(page)) {
789800d8c63SKirill A. Shutemov 				if (index == round_down(end, HPAGE_PMD_NR)) {
790800d8c63SKirill A. Shutemov 					/*
791800d8c63SKirill A. Shutemov 					 * Range ends in the middle of THP:
792800d8c63SKirill A. Shutemov 					 * zero out the page
793800d8c63SKirill A. Shutemov 					 */
794800d8c63SKirill A. Shutemov 					clear_highpage(page);
795800d8c63SKirill A. Shutemov 					unlock_page(page);
796800d8c63SKirill A. Shutemov 					continue;
797800d8c63SKirill A. Shutemov 				}
798800d8c63SKirill A. Shutemov 				index += HPAGE_PMD_NR - 1;
799800d8c63SKirill A. Shutemov 				i += HPAGE_PMD_NR - 1;
800800d8c63SKirill A. Shutemov 			}
801800d8c63SKirill A. Shutemov 
8021635f6a7SHugh Dickins 			if (!unfalloc || !PageUptodate(page)) {
803800d8c63SKirill A. Shutemov 				VM_BUG_ON_PAGE(PageTail(page), page);
804800d8c63SKirill A. Shutemov 				if (page_mapping(page) == mapping) {
805309381feSSasha Levin 					VM_BUG_ON_PAGE(PageWriteback(page), page);
806bda97eabSHugh Dickins 					truncate_inode_page(mapping, page);
807b1a36650SHugh Dickins 				} else {
808b1a36650SHugh Dickins 					/* Page was replaced by swap: retry */
809b1a36650SHugh Dickins 					unlock_page(page);
810b1a36650SHugh Dickins 					index--;
811b1a36650SHugh Dickins 					break;
8127a5d0fbbSHugh Dickins 				}
8131635f6a7SHugh Dickins 			}
814bda97eabSHugh Dickins 			unlock_page(page);
815bda97eabSHugh Dickins 		}
8160cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
81724513264SHugh Dickins 		pagevec_release(&pvec);
818bda97eabSHugh Dickins 		index++;
819bda97eabSHugh Dickins 	}
82094c1e62dSHugh Dickins 
8211da177e4SLinus Torvalds 	spin_lock(&info->lock);
8227a5d0fbbSHugh Dickins 	info->swapped -= nr_swaps_freed;
8231da177e4SLinus Torvalds 	shmem_recalc_inode(inode);
8241da177e4SLinus Torvalds 	spin_unlock(&info->lock);
8251635f6a7SHugh Dickins }
8261da177e4SLinus Torvalds 
8271635f6a7SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
8281635f6a7SHugh Dickins {
8291635f6a7SHugh Dickins 	shmem_undo_range(inode, lstart, lend, false);
830285b2c4fSHugh Dickins 	inode->i_ctime = inode->i_mtime = CURRENT_TIME;
8311da177e4SLinus Torvalds }
83294c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
8331da177e4SLinus Torvalds 
83444a30220SYu Zhao static int shmem_getattr(struct vfsmount *mnt, struct dentry *dentry,
83544a30220SYu Zhao 			 struct kstat *stat)
83644a30220SYu Zhao {
83744a30220SYu Zhao 	struct inode *inode = dentry->d_inode;
83844a30220SYu Zhao 	struct shmem_inode_info *info = SHMEM_I(inode);
83944a30220SYu Zhao 
840d0424c42SHugh Dickins 	if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
84144a30220SYu Zhao 		spin_lock(&info->lock);
84244a30220SYu Zhao 		shmem_recalc_inode(inode);
84344a30220SYu Zhao 		spin_unlock(&info->lock);
844d0424c42SHugh Dickins 	}
84544a30220SYu Zhao 	generic_fillattr(inode, stat);
84644a30220SYu Zhao 	return 0;
84744a30220SYu Zhao }
84844a30220SYu Zhao 
84994c1e62dSHugh Dickins static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
8501da177e4SLinus Torvalds {
85175c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
85240e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
8531da177e4SLinus Torvalds 	int error;
8541da177e4SLinus Torvalds 
855db78b877SChristoph Hellwig 	error = inode_change_ok(inode, attr);
856db78b877SChristoph Hellwig 	if (error)
857db78b877SChristoph Hellwig 		return error;
858db78b877SChristoph Hellwig 
85994c1e62dSHugh Dickins 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
86094c1e62dSHugh Dickins 		loff_t oldsize = inode->i_size;
86194c1e62dSHugh Dickins 		loff_t newsize = attr->ia_size;
8623889e6e7Snpiggin@suse.de 
86340e041a2SDavid Herrmann 		/* protected by i_mutex */
86440e041a2SDavid Herrmann 		if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
86540e041a2SDavid Herrmann 		    (newsize > oldsize && (info->seals & F_SEAL_GROW)))
86640e041a2SDavid Herrmann 			return -EPERM;
86740e041a2SDavid Herrmann 
86894c1e62dSHugh Dickins 		if (newsize != oldsize) {
86977142517SKonstantin Khlebnikov 			error = shmem_reacct_size(SHMEM_I(inode)->flags,
87077142517SKonstantin Khlebnikov 					oldsize, newsize);
87177142517SKonstantin Khlebnikov 			if (error)
87277142517SKonstantin Khlebnikov 				return error;
87394c1e62dSHugh Dickins 			i_size_write(inode, newsize);
87494c1e62dSHugh Dickins 			inode->i_ctime = inode->i_mtime = CURRENT_TIME;
87594c1e62dSHugh Dickins 		}
876afa2db2fSJosef Bacik 		if (newsize <= oldsize) {
87794c1e62dSHugh Dickins 			loff_t holebegin = round_up(newsize, PAGE_SIZE);
878d0424c42SHugh Dickins 			if (oldsize > holebegin)
879d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
880d0424c42SHugh Dickins 							holebegin, 0, 1);
881d0424c42SHugh Dickins 			if (info->alloced)
882d0424c42SHugh Dickins 				shmem_truncate_range(inode,
883d0424c42SHugh Dickins 							newsize, (loff_t)-1);
88494c1e62dSHugh Dickins 			/* unmap again to remove racily COWed private pages */
885d0424c42SHugh Dickins 			if (oldsize > holebegin)
886d0424c42SHugh Dickins 				unmap_mapping_range(inode->i_mapping,
887d0424c42SHugh Dickins 							holebegin, 0, 1);
88894c1e62dSHugh Dickins 		}
8891da177e4SLinus Torvalds 	}
8901da177e4SLinus Torvalds 
8916a1a90adSChristoph Hellwig 	setattr_copy(inode, attr);
892db78b877SChristoph Hellwig 	if (attr->ia_valid & ATTR_MODE)
893feda821eSChristoph Hellwig 		error = posix_acl_chmod(inode, inode->i_mode);
8941da177e4SLinus Torvalds 	return error;
8951da177e4SLinus Torvalds }
8961da177e4SLinus Torvalds 
8971f895f75SAl Viro static void shmem_evict_inode(struct inode *inode)
8981da177e4SLinus Torvalds {
8991da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
9001da177e4SLinus Torvalds 
9013889e6e7Snpiggin@suse.de 	if (inode->i_mapping->a_ops == &shmem_aops) {
9021da177e4SLinus Torvalds 		shmem_unacct_size(info->flags, inode->i_size);
9031da177e4SLinus Torvalds 		inode->i_size = 0;
9043889e6e7Snpiggin@suse.de 		shmem_truncate_range(inode, 0, (loff_t)-1);
9051da177e4SLinus Torvalds 		if (!list_empty(&info->swaplist)) {
906cb5f7b9aSHugh Dickins 			mutex_lock(&shmem_swaplist_mutex);
9071da177e4SLinus Torvalds 			list_del_init(&info->swaplist);
908cb5f7b9aSHugh Dickins 			mutex_unlock(&shmem_swaplist_mutex);
9091da177e4SLinus Torvalds 		}
9103ed47db3SAl Viro 	}
911b09e0fa4SEric Paris 
91238f38657SAristeu Rozanski 	simple_xattrs_free(&info->xattrs);
9130f3c42f5SHugh Dickins 	WARN_ON(inode->i_blocks);
9145b04c689SPavel Emelyanov 	shmem_free_inode(inode->i_sb);
915dbd5768fSJan Kara 	clear_inode(inode);
9161da177e4SLinus Torvalds }
9171da177e4SLinus Torvalds 
91846f65ec1SHugh Dickins /*
91946f65ec1SHugh Dickins  * If swap found in inode, free it and move page from swapcache to filecache.
92046f65ec1SHugh Dickins  */
92141ffe5d5SHugh Dickins static int shmem_unuse_inode(struct shmem_inode_info *info,
922bde05d1cSHugh Dickins 			     swp_entry_t swap, struct page **pagep)
9231da177e4SLinus Torvalds {
924285b2c4fSHugh Dickins 	struct address_space *mapping = info->vfs_inode.i_mapping;
92546f65ec1SHugh Dickins 	void *radswap;
92641ffe5d5SHugh Dickins 	pgoff_t index;
927bde05d1cSHugh Dickins 	gfp_t gfp;
928bde05d1cSHugh Dickins 	int error = 0;
9291da177e4SLinus Torvalds 
93046f65ec1SHugh Dickins 	radswap = swp_to_radix_entry(swap);
931e504f3fdSHugh Dickins 	index = radix_tree_locate_item(&mapping->page_tree, radswap);
93246f65ec1SHugh Dickins 	if (index == -1)
93300501b53SJohannes Weiner 		return -EAGAIN;	/* tell shmem_unuse we found nothing */
9342e0e26c7SHugh Dickins 
9351b1b32f2SHugh Dickins 	/*
9361b1b32f2SHugh Dickins 	 * Move _head_ to start search for next from here.
9371f895f75SAl Viro 	 * But be careful: shmem_evict_inode checks list_empty without taking
9381b1b32f2SHugh Dickins 	 * mutex, and there's an instant in list_move_tail when info->swaplist
939285b2c4fSHugh Dickins 	 * would appear empty, if it were the only one on shmem_swaplist.
9401b1b32f2SHugh Dickins 	 */
9411b1b32f2SHugh Dickins 	if (shmem_swaplist.next != &info->swaplist)
9422e0e26c7SHugh Dickins 		list_move_tail(&shmem_swaplist, &info->swaplist);
9432e0e26c7SHugh Dickins 
944bde05d1cSHugh Dickins 	gfp = mapping_gfp_mask(mapping);
945bde05d1cSHugh Dickins 	if (shmem_should_replace_page(*pagep, gfp)) {
946bde05d1cSHugh Dickins 		mutex_unlock(&shmem_swaplist_mutex);
947bde05d1cSHugh Dickins 		error = shmem_replace_page(pagep, gfp, info, index);
948bde05d1cSHugh Dickins 		mutex_lock(&shmem_swaplist_mutex);
949bde05d1cSHugh Dickins 		/*
950bde05d1cSHugh Dickins 		 * We needed to drop mutex to make that restrictive page
9510142ef6cSHugh Dickins 		 * allocation, but the inode might have been freed while we
9520142ef6cSHugh Dickins 		 * dropped it: although a racing shmem_evict_inode() cannot
9530142ef6cSHugh Dickins 		 * complete without emptying the radix_tree, our page lock
9540142ef6cSHugh Dickins 		 * on this swapcache page is not enough to prevent that -
9550142ef6cSHugh Dickins 		 * free_swap_and_cache() of our swap entry will only
9560142ef6cSHugh Dickins 		 * trylock_page(), removing swap from radix_tree whatever.
9570142ef6cSHugh Dickins 		 *
9580142ef6cSHugh Dickins 		 * We must not proceed to shmem_add_to_page_cache() if the
9590142ef6cSHugh Dickins 		 * inode has been freed, but of course we cannot rely on
9600142ef6cSHugh Dickins 		 * inode or mapping or info to check that.  However, we can
9610142ef6cSHugh Dickins 		 * safely check if our swap entry is still in use (and here
9620142ef6cSHugh Dickins 		 * it can't have got reused for another page): if it's still
9630142ef6cSHugh Dickins 		 * in use, then the inode cannot have been freed yet, and we
9640142ef6cSHugh Dickins 		 * can safely proceed (if it's no longer in use, that tells
9650142ef6cSHugh Dickins 		 * nothing about the inode, but we don't need to unuse swap).
966bde05d1cSHugh Dickins 		 */
967bde05d1cSHugh Dickins 		if (!page_swapcount(*pagep))
968bde05d1cSHugh Dickins 			error = -ENOENT;
969bde05d1cSHugh Dickins 	}
970bde05d1cSHugh Dickins 
971d13d1443SKAMEZAWA Hiroyuki 	/*
972778dd893SHugh Dickins 	 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
973778dd893SHugh Dickins 	 * but also to hold up shmem_evict_inode(): so inode cannot be freed
974778dd893SHugh Dickins 	 * beneath us (pagelock doesn't help until the page is in pagecache).
975d13d1443SKAMEZAWA Hiroyuki 	 */
976bde05d1cSHugh Dickins 	if (!error)
977bde05d1cSHugh Dickins 		error = shmem_add_to_page_cache(*pagep, mapping, index,
978fed400a1SWang Sheng-Hui 						radswap);
97948f170fbSHugh Dickins 	if (error != -ENOMEM) {
98046f65ec1SHugh Dickins 		/*
98146f65ec1SHugh Dickins 		 * Truncation and eviction use free_swap_and_cache(), which
98246f65ec1SHugh Dickins 		 * only does trylock page: if we raced, best clean up here.
98346f65ec1SHugh Dickins 		 */
984bde05d1cSHugh Dickins 		delete_from_swap_cache(*pagep);
985bde05d1cSHugh Dickins 		set_page_dirty(*pagep);
98646f65ec1SHugh Dickins 		if (!error) {
98746f65ec1SHugh Dickins 			spin_lock(&info->lock);
988285b2c4fSHugh Dickins 			info->swapped--;
98946f65ec1SHugh Dickins 			spin_unlock(&info->lock);
99041ffe5d5SHugh Dickins 			swap_free(swap);
99146f65ec1SHugh Dickins 		}
9921da177e4SLinus Torvalds 	}
9932e0e26c7SHugh Dickins 	return error;
9941da177e4SLinus Torvalds }
9951da177e4SLinus Torvalds 
9961da177e4SLinus Torvalds /*
99746f65ec1SHugh Dickins  * Search through swapped inodes to find and replace swap by page.
9981da177e4SLinus Torvalds  */
99941ffe5d5SHugh Dickins int shmem_unuse(swp_entry_t swap, struct page *page)
10001da177e4SLinus Torvalds {
100141ffe5d5SHugh Dickins 	struct list_head *this, *next;
10021da177e4SLinus Torvalds 	struct shmem_inode_info *info;
100300501b53SJohannes Weiner 	struct mem_cgroup *memcg;
1004bde05d1cSHugh Dickins 	int error = 0;
1005bde05d1cSHugh Dickins 
1006bde05d1cSHugh Dickins 	/*
1007bde05d1cSHugh Dickins 	 * There's a faint possibility that swap page was replaced before
10080142ef6cSHugh Dickins 	 * caller locked it: caller will come back later with the right page.
1009bde05d1cSHugh Dickins 	 */
10100142ef6cSHugh Dickins 	if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
1011bde05d1cSHugh Dickins 		goto out;
1012778dd893SHugh Dickins 
1013778dd893SHugh Dickins 	/*
1014778dd893SHugh Dickins 	 * Charge page using GFP_KERNEL while we can wait, before taking
1015778dd893SHugh Dickins 	 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1016778dd893SHugh Dickins 	 * Charged back to the user (not to caller) when swap account is used.
1017778dd893SHugh Dickins 	 */
1018f627c2f5SKirill A. Shutemov 	error = mem_cgroup_try_charge(page, current->mm, GFP_KERNEL, &memcg,
1019f627c2f5SKirill A. Shutemov 			false);
1020778dd893SHugh Dickins 	if (error)
1021778dd893SHugh Dickins 		goto out;
102246f65ec1SHugh Dickins 	/* No radix_tree_preload: swap entry keeps a place for page in tree */
102300501b53SJohannes Weiner 	error = -EAGAIN;
10241da177e4SLinus Torvalds 
1025cb5f7b9aSHugh Dickins 	mutex_lock(&shmem_swaplist_mutex);
102641ffe5d5SHugh Dickins 	list_for_each_safe(this, next, &shmem_swaplist) {
102741ffe5d5SHugh Dickins 		info = list_entry(this, struct shmem_inode_info, swaplist);
1028285b2c4fSHugh Dickins 		if (info->swapped)
102900501b53SJohannes Weiner 			error = shmem_unuse_inode(info, swap, &page);
10306922c0c7SHugh Dickins 		else
10316922c0c7SHugh Dickins 			list_del_init(&info->swaplist);
1032cb5f7b9aSHugh Dickins 		cond_resched();
103300501b53SJohannes Weiner 		if (error != -EAGAIN)
1034778dd893SHugh Dickins 			break;
103500501b53SJohannes Weiner 		/* found nothing in this: move on to search the next */
10361da177e4SLinus Torvalds 	}
1037cb5f7b9aSHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
1038778dd893SHugh Dickins 
103900501b53SJohannes Weiner 	if (error) {
104000501b53SJohannes Weiner 		if (error != -ENOMEM)
104100501b53SJohannes Weiner 			error = 0;
1042f627c2f5SKirill A. Shutemov 		mem_cgroup_cancel_charge(page, memcg, false);
104300501b53SJohannes Weiner 	} else
1044f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, true, false);
1045778dd893SHugh Dickins out:
1046aaa46865SHugh Dickins 	unlock_page(page);
104709cbfeafSKirill A. Shutemov 	put_page(page);
1048778dd893SHugh Dickins 	return error;
10491da177e4SLinus Torvalds }
10501da177e4SLinus Torvalds 
10511da177e4SLinus Torvalds /*
10521da177e4SLinus Torvalds  * Move the page from the page cache to the swap cache.
10531da177e4SLinus Torvalds  */
10541da177e4SLinus Torvalds static int shmem_writepage(struct page *page, struct writeback_control *wbc)
10551da177e4SLinus Torvalds {
10561da177e4SLinus Torvalds 	struct shmem_inode_info *info;
10571da177e4SLinus Torvalds 	struct address_space *mapping;
10581da177e4SLinus Torvalds 	struct inode *inode;
10596922c0c7SHugh Dickins 	swp_entry_t swap;
10606922c0c7SHugh Dickins 	pgoff_t index;
10611da177e4SLinus Torvalds 
1062800d8c63SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageCompound(page), page);
10631da177e4SLinus Torvalds 	BUG_ON(!PageLocked(page));
10641da177e4SLinus Torvalds 	mapping = page->mapping;
10651da177e4SLinus Torvalds 	index = page->index;
10661da177e4SLinus Torvalds 	inode = mapping->host;
10671da177e4SLinus Torvalds 	info = SHMEM_I(inode);
10681da177e4SLinus Torvalds 	if (info->flags & VM_LOCKED)
10691da177e4SLinus Torvalds 		goto redirty;
1070d9fe526aSHugh Dickins 	if (!total_swap_pages)
10711da177e4SLinus Torvalds 		goto redirty;
10721da177e4SLinus Torvalds 
1073d9fe526aSHugh Dickins 	/*
107497b713baSChristoph Hellwig 	 * Our capabilities prevent regular writeback or sync from ever calling
107597b713baSChristoph Hellwig 	 * shmem_writepage; but a stacking filesystem might use ->writepage of
107697b713baSChristoph Hellwig 	 * its underlying filesystem, in which case tmpfs should write out to
107797b713baSChristoph Hellwig 	 * swap only in response to memory pressure, and not for the writeback
107897b713baSChristoph Hellwig 	 * threads or sync.
1079d9fe526aSHugh Dickins 	 */
108048f170fbSHugh Dickins 	if (!wbc->for_reclaim) {
108148f170fbSHugh Dickins 		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
108248f170fbSHugh Dickins 		goto redirty;
108348f170fbSHugh Dickins 	}
10841635f6a7SHugh Dickins 
10851635f6a7SHugh Dickins 	/*
10861635f6a7SHugh Dickins 	 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
10871635f6a7SHugh Dickins 	 * value into swapfile.c, the only way we can correctly account for a
10881635f6a7SHugh Dickins 	 * fallocated page arriving here is now to initialize it and write it.
10891aac1400SHugh Dickins 	 *
10901aac1400SHugh Dickins 	 * That's okay for a page already fallocated earlier, but if we have
10911aac1400SHugh Dickins 	 * not yet completed the fallocation, then (a) we want to keep track
10921aac1400SHugh Dickins 	 * of this page in case we have to undo it, and (b) it may not be a
10931aac1400SHugh Dickins 	 * good idea to continue anyway, once we're pushing into swap.  So
10941aac1400SHugh Dickins 	 * reactivate the page, and let shmem_fallocate() quit when too many.
10951635f6a7SHugh Dickins 	 */
10961635f6a7SHugh Dickins 	if (!PageUptodate(page)) {
10971aac1400SHugh Dickins 		if (inode->i_private) {
10981aac1400SHugh Dickins 			struct shmem_falloc *shmem_falloc;
10991aac1400SHugh Dickins 			spin_lock(&inode->i_lock);
11001aac1400SHugh Dickins 			shmem_falloc = inode->i_private;
11011aac1400SHugh Dickins 			if (shmem_falloc &&
11028e205f77SHugh Dickins 			    !shmem_falloc->waitq &&
11031aac1400SHugh Dickins 			    index >= shmem_falloc->start &&
11041aac1400SHugh Dickins 			    index < shmem_falloc->next)
11051aac1400SHugh Dickins 				shmem_falloc->nr_unswapped++;
11061aac1400SHugh Dickins 			else
11071aac1400SHugh Dickins 				shmem_falloc = NULL;
11081aac1400SHugh Dickins 			spin_unlock(&inode->i_lock);
11091aac1400SHugh Dickins 			if (shmem_falloc)
11101aac1400SHugh Dickins 				goto redirty;
11111aac1400SHugh Dickins 		}
11121635f6a7SHugh Dickins 		clear_highpage(page);
11131635f6a7SHugh Dickins 		flush_dcache_page(page);
11141635f6a7SHugh Dickins 		SetPageUptodate(page);
11151635f6a7SHugh Dickins 	}
11161635f6a7SHugh Dickins 
1117d9fe526aSHugh Dickins 	swap = get_swap_page();
111848f170fbSHugh Dickins 	if (!swap.val)
111948f170fbSHugh Dickins 		goto redirty;
1120d9fe526aSHugh Dickins 
112137e84351SVladimir Davydov 	if (mem_cgroup_try_charge_swap(page, swap))
112237e84351SVladimir Davydov 		goto free_swap;
112337e84351SVladimir Davydov 
1124b1dea800SHugh Dickins 	/*
1125b1dea800SHugh Dickins 	 * Add inode to shmem_unuse()'s list of swapped-out inodes,
11266922c0c7SHugh Dickins 	 * if it's not already there.  Do it now before the page is
11276922c0c7SHugh Dickins 	 * moved to swap cache, when its pagelock no longer protects
1128b1dea800SHugh Dickins 	 * the inode from eviction.  But don't unlock the mutex until
11296922c0c7SHugh Dickins 	 * we've incremented swapped, because shmem_unuse_inode() will
11306922c0c7SHugh Dickins 	 * prune a !swapped inode from the swaplist under this mutex.
1131b1dea800SHugh Dickins 	 */
1132b1dea800SHugh Dickins 	mutex_lock(&shmem_swaplist_mutex);
113305bf86b4SHugh Dickins 	if (list_empty(&info->swaplist))
113405bf86b4SHugh Dickins 		list_add_tail(&info->swaplist, &shmem_swaplist);
1135b1dea800SHugh Dickins 
113648f170fbSHugh Dickins 	if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1137267a4c76SHugh Dickins 		spin_lock(&info->lock);
1138267a4c76SHugh Dickins 		shmem_recalc_inode(inode);
1139267a4c76SHugh Dickins 		info->swapped++;
1140267a4c76SHugh Dickins 		spin_unlock(&info->lock);
1141267a4c76SHugh Dickins 
1142aaa46865SHugh Dickins 		swap_shmem_alloc(swap);
11436922c0c7SHugh Dickins 		shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
11446922c0c7SHugh Dickins 
11456922c0c7SHugh Dickins 		mutex_unlock(&shmem_swaplist_mutex);
1146d9fe526aSHugh Dickins 		BUG_ON(page_mapped(page));
11479fab5619SHugh Dickins 		swap_writepage(page, wbc);
11481da177e4SLinus Torvalds 		return 0;
11491da177e4SLinus Torvalds 	}
11501da177e4SLinus Torvalds 
11516922c0c7SHugh Dickins 	mutex_unlock(&shmem_swaplist_mutex);
115237e84351SVladimir Davydov free_swap:
11530a31bc97SJohannes Weiner 	swapcache_free(swap);
11541da177e4SLinus Torvalds redirty:
11551da177e4SLinus Torvalds 	set_page_dirty(page);
1156d9fe526aSHugh Dickins 	if (wbc->for_reclaim)
1157d9fe526aSHugh Dickins 		return AOP_WRITEPAGE_ACTIVATE;	/* Return with page locked */
1158d9fe526aSHugh Dickins 	unlock_page(page);
1159d9fe526aSHugh Dickins 	return 0;
11601da177e4SLinus Torvalds }
11611da177e4SLinus Torvalds 
116275edd345SHugh Dickins #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
116371fe804bSLee Schermerhorn static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1164680d794bSakpm@linux-foundation.org {
1165680d794bSakpm@linux-foundation.org 	char buffer[64];
1166680d794bSakpm@linux-foundation.org 
116771fe804bSLee Schermerhorn 	if (!mpol || mpol->mode == MPOL_DEFAULT)
1168095f1fc4SLee Schermerhorn 		return;		/* show nothing */
1169095f1fc4SLee Schermerhorn 
1170a7a88b23SHugh Dickins 	mpol_to_str(buffer, sizeof(buffer), mpol);
1171095f1fc4SLee Schermerhorn 
1172095f1fc4SLee Schermerhorn 	seq_printf(seq, ",mpol=%s", buffer);
1173680d794bSakpm@linux-foundation.org }
117471fe804bSLee Schermerhorn 
117571fe804bSLee Schermerhorn static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
117671fe804bSLee Schermerhorn {
117771fe804bSLee Schermerhorn 	struct mempolicy *mpol = NULL;
117871fe804bSLee Schermerhorn 	if (sbinfo->mpol) {
117971fe804bSLee Schermerhorn 		spin_lock(&sbinfo->stat_lock);	/* prevent replace/use races */
118071fe804bSLee Schermerhorn 		mpol = sbinfo->mpol;
118171fe804bSLee Schermerhorn 		mpol_get(mpol);
118271fe804bSLee Schermerhorn 		spin_unlock(&sbinfo->stat_lock);
118371fe804bSLee Schermerhorn 	}
118471fe804bSLee Schermerhorn 	return mpol;
118571fe804bSLee Schermerhorn }
118675edd345SHugh Dickins #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
118775edd345SHugh Dickins static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
118875edd345SHugh Dickins {
118975edd345SHugh Dickins }
119075edd345SHugh Dickins static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
119175edd345SHugh Dickins {
119275edd345SHugh Dickins 	return NULL;
119375edd345SHugh Dickins }
119475edd345SHugh Dickins #endif /* CONFIG_NUMA && CONFIG_TMPFS */
119575edd345SHugh Dickins #ifndef CONFIG_NUMA
119675edd345SHugh Dickins #define vm_policy vm_private_data
119775edd345SHugh Dickins #endif
1198680d794bSakpm@linux-foundation.org 
1199800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1200800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1201800d8c63SKirill A. Shutemov {
1202800d8c63SKirill A. Shutemov 	/* Create a pseudo vma that just contains the policy */
1203800d8c63SKirill A. Shutemov 	vma->vm_start = 0;
1204800d8c63SKirill A. Shutemov 	/* Bias interleave by inode number to distribute better across nodes */
1205800d8c63SKirill A. Shutemov 	vma->vm_pgoff = index + info->vfs_inode.i_ino;
1206800d8c63SKirill A. Shutemov 	vma->vm_ops = NULL;
1207800d8c63SKirill A. Shutemov 	vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1208800d8c63SKirill A. Shutemov }
1209800d8c63SKirill A. Shutemov 
1210800d8c63SKirill A. Shutemov static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1211800d8c63SKirill A. Shutemov {
1212800d8c63SKirill A. Shutemov 	/* Drop reference taken by mpol_shared_policy_lookup() */
1213800d8c63SKirill A. Shutemov 	mpol_cond_put(vma->vm_policy);
1214800d8c63SKirill A. Shutemov }
1215800d8c63SKirill A. Shutemov 
121641ffe5d5SHugh Dickins static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
121741ffe5d5SHugh Dickins 			struct shmem_inode_info *info, pgoff_t index)
12181da177e4SLinus Torvalds {
12191da177e4SLinus Torvalds 	struct vm_area_struct pvma;
122018a2f371SMel Gorman 	struct page *page;
12211da177e4SLinus Torvalds 
1222800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
122318a2f371SMel Gorman 	page = swapin_readahead(swap, gfp, &pvma, 0);
1224800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
122518a2f371SMel Gorman 
1226800d8c63SKirill A. Shutemov 	return page;
1227800d8c63SKirill A. Shutemov }
122818a2f371SMel Gorman 
1229800d8c63SKirill A. Shutemov static struct page *shmem_alloc_hugepage(gfp_t gfp,
1230800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, pgoff_t index)
1231800d8c63SKirill A. Shutemov {
1232800d8c63SKirill A. Shutemov 	struct vm_area_struct pvma;
1233800d8c63SKirill A. Shutemov 	struct inode *inode = &info->vfs_inode;
1234800d8c63SKirill A. Shutemov 	struct address_space *mapping = inode->i_mapping;
1235800d8c63SKirill A. Shutemov 	pgoff_t idx, hindex = round_down(index, HPAGE_PMD_NR);
1236800d8c63SKirill A. Shutemov 	void __rcu **results;
1237800d8c63SKirill A. Shutemov 	struct page *page;
1238800d8c63SKirill A. Shutemov 
1239800d8c63SKirill A. Shutemov 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1240800d8c63SKirill A. Shutemov 		return NULL;
1241800d8c63SKirill A. Shutemov 
1242800d8c63SKirill A. Shutemov 	rcu_read_lock();
1243800d8c63SKirill A. Shutemov 	if (radix_tree_gang_lookup_slot(&mapping->page_tree, &results, &idx,
1244800d8c63SKirill A. Shutemov 				hindex, 1) && idx < hindex + HPAGE_PMD_NR) {
1245800d8c63SKirill A. Shutemov 		rcu_read_unlock();
1246800d8c63SKirill A. Shutemov 		return NULL;
1247800d8c63SKirill A. Shutemov 	}
1248800d8c63SKirill A. Shutemov 	rcu_read_unlock();
1249800d8c63SKirill A. Shutemov 
1250800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, hindex);
1251800d8c63SKirill A. Shutemov 	page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1252800d8c63SKirill A. Shutemov 			HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
1253800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
1254800d8c63SKirill A. Shutemov 	if (page)
1255800d8c63SKirill A. Shutemov 		prep_transhuge_page(page);
125618a2f371SMel Gorman 	return page;
125718a2f371SMel Gorman }
125818a2f371SMel Gorman 
125918a2f371SMel Gorman static struct page *shmem_alloc_page(gfp_t gfp,
126018a2f371SMel Gorman 			struct shmem_inode_info *info, pgoff_t index)
126118a2f371SMel Gorman {
126218a2f371SMel Gorman 	struct vm_area_struct pvma;
126318a2f371SMel Gorman 	struct page *page;
126418a2f371SMel Gorman 
1265800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_init(&pvma, info, index);
1266800d8c63SKirill A. Shutemov 	page = alloc_page_vma(gfp, &pvma, 0);
1267800d8c63SKirill A. Shutemov 	shmem_pseudo_vma_destroy(&pvma);
126818a2f371SMel Gorman 
1269800d8c63SKirill A. Shutemov 	return page;
1270800d8c63SKirill A. Shutemov }
1271800d8c63SKirill A. Shutemov 
1272800d8c63SKirill A. Shutemov static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1273800d8c63SKirill A. Shutemov 		struct shmem_inode_info *info, struct shmem_sb_info *sbinfo,
1274800d8c63SKirill A. Shutemov 		pgoff_t index, bool huge)
1275800d8c63SKirill A. Shutemov {
1276800d8c63SKirill A. Shutemov 	struct page *page;
1277800d8c63SKirill A. Shutemov 	int nr;
1278800d8c63SKirill A. Shutemov 	int err = -ENOSPC;
1279800d8c63SKirill A. Shutemov 
1280800d8c63SKirill A. Shutemov 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1281800d8c63SKirill A. Shutemov 		huge = false;
1282800d8c63SKirill A. Shutemov 	nr = huge ? HPAGE_PMD_NR : 1;
1283800d8c63SKirill A. Shutemov 
1284800d8c63SKirill A. Shutemov 	if (shmem_acct_block(info->flags, nr))
1285800d8c63SKirill A. Shutemov 		goto failed;
1286800d8c63SKirill A. Shutemov 	if (sbinfo->max_blocks) {
1287800d8c63SKirill A. Shutemov 		if (percpu_counter_compare(&sbinfo->used_blocks,
1288800d8c63SKirill A. Shutemov 					sbinfo->max_blocks - nr) > 0)
1289800d8c63SKirill A. Shutemov 			goto unacct;
1290800d8c63SKirill A. Shutemov 		percpu_counter_add(&sbinfo->used_blocks, nr);
1291800d8c63SKirill A. Shutemov 	}
1292800d8c63SKirill A. Shutemov 
1293800d8c63SKirill A. Shutemov 	if (huge)
1294800d8c63SKirill A. Shutemov 		page = shmem_alloc_hugepage(gfp, info, index);
1295800d8c63SKirill A. Shutemov 	else
1296800d8c63SKirill A. Shutemov 		page = shmem_alloc_page(gfp, info, index);
129775edd345SHugh Dickins 	if (page) {
129875edd345SHugh Dickins 		__SetPageLocked(page);
129975edd345SHugh Dickins 		__SetPageSwapBacked(page);
1300800d8c63SKirill A. Shutemov 		return page;
130175edd345SHugh Dickins 	}
130218a2f371SMel Gorman 
1303800d8c63SKirill A. Shutemov 	err = -ENOMEM;
1304800d8c63SKirill A. Shutemov 	if (sbinfo->max_blocks)
1305800d8c63SKirill A. Shutemov 		percpu_counter_add(&sbinfo->used_blocks, -nr);
1306800d8c63SKirill A. Shutemov unacct:
1307800d8c63SKirill A. Shutemov 	shmem_unacct_blocks(info->flags, nr);
1308800d8c63SKirill A. Shutemov failed:
1309800d8c63SKirill A. Shutemov 	return ERR_PTR(err);
13101da177e4SLinus Torvalds }
131171fe804bSLee Schermerhorn 
13121da177e4SLinus Torvalds /*
1313bde05d1cSHugh Dickins  * When a page is moved from swapcache to shmem filecache (either by the
1314bde05d1cSHugh Dickins  * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1315bde05d1cSHugh Dickins  * shmem_unuse_inode()), it may have been read in earlier from swap, in
1316bde05d1cSHugh Dickins  * ignorance of the mapping it belongs to.  If that mapping has special
1317bde05d1cSHugh Dickins  * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1318bde05d1cSHugh Dickins  * we may need to copy to a suitable page before moving to filecache.
1319bde05d1cSHugh Dickins  *
1320bde05d1cSHugh Dickins  * In a future release, this may well be extended to respect cpuset and
1321bde05d1cSHugh Dickins  * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1322bde05d1cSHugh Dickins  * but for now it is a simple matter of zone.
1323bde05d1cSHugh Dickins  */
1324bde05d1cSHugh Dickins static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1325bde05d1cSHugh Dickins {
1326bde05d1cSHugh Dickins 	return page_zonenum(page) > gfp_zone(gfp);
1327bde05d1cSHugh Dickins }
1328bde05d1cSHugh Dickins 
1329bde05d1cSHugh Dickins static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1330bde05d1cSHugh Dickins 				struct shmem_inode_info *info, pgoff_t index)
1331bde05d1cSHugh Dickins {
1332bde05d1cSHugh Dickins 	struct page *oldpage, *newpage;
1333bde05d1cSHugh Dickins 	struct address_space *swap_mapping;
1334bde05d1cSHugh Dickins 	pgoff_t swap_index;
1335bde05d1cSHugh Dickins 	int error;
1336bde05d1cSHugh Dickins 
1337bde05d1cSHugh Dickins 	oldpage = *pagep;
1338bde05d1cSHugh Dickins 	swap_index = page_private(oldpage);
1339bde05d1cSHugh Dickins 	swap_mapping = page_mapping(oldpage);
1340bde05d1cSHugh Dickins 
1341bde05d1cSHugh Dickins 	/*
1342bde05d1cSHugh Dickins 	 * We have arrived here because our zones are constrained, so don't
1343bde05d1cSHugh Dickins 	 * limit chance of success by further cpuset and node constraints.
1344bde05d1cSHugh Dickins 	 */
1345bde05d1cSHugh Dickins 	gfp &= ~GFP_CONSTRAINT_MASK;
1346bde05d1cSHugh Dickins 	newpage = shmem_alloc_page(gfp, info, index);
1347bde05d1cSHugh Dickins 	if (!newpage)
1348bde05d1cSHugh Dickins 		return -ENOMEM;
1349bde05d1cSHugh Dickins 
135009cbfeafSKirill A. Shutemov 	get_page(newpage);
1351bde05d1cSHugh Dickins 	copy_highpage(newpage, oldpage);
13520142ef6cSHugh Dickins 	flush_dcache_page(newpage);
1353bde05d1cSHugh Dickins 
1354bde05d1cSHugh Dickins 	SetPageUptodate(newpage);
1355bde05d1cSHugh Dickins 	set_page_private(newpage, swap_index);
1356bde05d1cSHugh Dickins 	SetPageSwapCache(newpage);
1357bde05d1cSHugh Dickins 
1358bde05d1cSHugh Dickins 	/*
1359bde05d1cSHugh Dickins 	 * Our caller will very soon move newpage out of swapcache, but it's
1360bde05d1cSHugh Dickins 	 * a nice clean interface for us to replace oldpage by newpage there.
1361bde05d1cSHugh Dickins 	 */
1362bde05d1cSHugh Dickins 	spin_lock_irq(&swap_mapping->tree_lock);
1363bde05d1cSHugh Dickins 	error = shmem_radix_tree_replace(swap_mapping, swap_index, oldpage,
1364bde05d1cSHugh Dickins 								   newpage);
13650142ef6cSHugh Dickins 	if (!error) {
1366bde05d1cSHugh Dickins 		__inc_zone_page_state(newpage, NR_FILE_PAGES);
1367bde05d1cSHugh Dickins 		__dec_zone_page_state(oldpage, NR_FILE_PAGES);
13680142ef6cSHugh Dickins 	}
1369bde05d1cSHugh Dickins 	spin_unlock_irq(&swap_mapping->tree_lock);
1370bde05d1cSHugh Dickins 
13710142ef6cSHugh Dickins 	if (unlikely(error)) {
13720142ef6cSHugh Dickins 		/*
13730142ef6cSHugh Dickins 		 * Is this possible?  I think not, now that our callers check
13740142ef6cSHugh Dickins 		 * both PageSwapCache and page_private after getting page lock;
13750142ef6cSHugh Dickins 		 * but be defensive.  Reverse old to newpage for clear and free.
13760142ef6cSHugh Dickins 		 */
13770142ef6cSHugh Dickins 		oldpage = newpage;
13780142ef6cSHugh Dickins 	} else {
13796a93ca8fSJohannes Weiner 		mem_cgroup_migrate(oldpage, newpage);
1380bde05d1cSHugh Dickins 		lru_cache_add_anon(newpage);
13810142ef6cSHugh Dickins 		*pagep = newpage;
13820142ef6cSHugh Dickins 	}
1383bde05d1cSHugh Dickins 
1384bde05d1cSHugh Dickins 	ClearPageSwapCache(oldpage);
1385bde05d1cSHugh Dickins 	set_page_private(oldpage, 0);
1386bde05d1cSHugh Dickins 
1387bde05d1cSHugh Dickins 	unlock_page(oldpage);
138809cbfeafSKirill A. Shutemov 	put_page(oldpage);
138909cbfeafSKirill A. Shutemov 	put_page(oldpage);
13900142ef6cSHugh Dickins 	return error;
1391bde05d1cSHugh Dickins }
1392bde05d1cSHugh Dickins 
1393bde05d1cSHugh Dickins /*
139468da9f05SHugh Dickins  * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
13951da177e4SLinus Torvalds  *
13961da177e4SLinus Torvalds  * If we allocate a new one we do not mark it dirty. That's up to the
13971da177e4SLinus Torvalds  * vm. If we swap it in we mark it dirty since we also free the swap
13989e18eb29SAndres Lagar-Cavilla  * entry since a page cannot live in both the swap and page cache.
13999e18eb29SAndres Lagar-Cavilla  *
14009e18eb29SAndres Lagar-Cavilla  * fault_mm and fault_type are only supplied by shmem_fault:
14019e18eb29SAndres Lagar-Cavilla  * otherwise they are NULL.
14021da177e4SLinus Torvalds  */
140341ffe5d5SHugh Dickins static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
14049e18eb29SAndres Lagar-Cavilla 	struct page **pagep, enum sgp_type sgp, gfp_t gfp,
14059e18eb29SAndres Lagar-Cavilla 	struct mm_struct *fault_mm, int *fault_type)
14061da177e4SLinus Torvalds {
14071da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
140854af6042SHugh Dickins 	struct shmem_inode_info *info;
14091da177e4SLinus Torvalds 	struct shmem_sb_info *sbinfo;
14109e18eb29SAndres Lagar-Cavilla 	struct mm_struct *charge_mm;
141100501b53SJohannes Weiner 	struct mem_cgroup *memcg;
141227ab7006SHugh Dickins 	struct page *page;
14131da177e4SLinus Torvalds 	swp_entry_t swap;
1414*657e3038SKirill A. Shutemov 	enum sgp_type sgp_huge = sgp;
1415800d8c63SKirill A. Shutemov 	pgoff_t hindex = index;
14161da177e4SLinus Torvalds 	int error;
141754af6042SHugh Dickins 	int once = 0;
14181635f6a7SHugh Dickins 	int alloced = 0;
14191da177e4SLinus Torvalds 
142009cbfeafSKirill A. Shutemov 	if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
14211da177e4SLinus Torvalds 		return -EFBIG;
1422*657e3038SKirill A. Shutemov 	if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1423*657e3038SKirill A. Shutemov 		sgp = SGP_CACHE;
14241da177e4SLinus Torvalds repeat:
142554af6042SHugh Dickins 	swap.val = 0;
14260cd6144aSJohannes Weiner 	page = find_lock_entry(mapping, index);
142754af6042SHugh Dickins 	if (radix_tree_exceptional_entry(page)) {
142854af6042SHugh Dickins 		swap = radix_to_swp_entry(page);
142954af6042SHugh Dickins 		page = NULL;
143054af6042SHugh Dickins 	}
143154af6042SHugh Dickins 
143275edd345SHugh Dickins 	if (sgp <= SGP_CACHE &&
143309cbfeafSKirill A. Shutemov 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
143454af6042SHugh Dickins 		error = -EINVAL;
1435267a4c76SHugh Dickins 		goto unlock;
143654af6042SHugh Dickins 	}
143754af6042SHugh Dickins 
143866d2f4d2SHugh Dickins 	if (page && sgp == SGP_WRITE)
143966d2f4d2SHugh Dickins 		mark_page_accessed(page);
144066d2f4d2SHugh Dickins 
14411635f6a7SHugh Dickins 	/* fallocated page? */
14421635f6a7SHugh Dickins 	if (page && !PageUptodate(page)) {
14431635f6a7SHugh Dickins 		if (sgp != SGP_READ)
14441635f6a7SHugh Dickins 			goto clear;
14451635f6a7SHugh Dickins 		unlock_page(page);
144609cbfeafSKirill A. Shutemov 		put_page(page);
14471635f6a7SHugh Dickins 		page = NULL;
14481635f6a7SHugh Dickins 	}
144954af6042SHugh Dickins 	if (page || (sgp == SGP_READ && !swap.val)) {
145054af6042SHugh Dickins 		*pagep = page;
145154af6042SHugh Dickins 		return 0;
145227ab7006SHugh Dickins 	}
145327ab7006SHugh Dickins 
1454b409f9fcSHugh Dickins 	/*
145554af6042SHugh Dickins 	 * Fast cache lookup did not find it:
145654af6042SHugh Dickins 	 * bring it back from swap or allocate.
1457b409f9fcSHugh Dickins 	 */
145854af6042SHugh Dickins 	info = SHMEM_I(inode);
145954af6042SHugh Dickins 	sbinfo = SHMEM_SB(inode->i_sb);
14609e18eb29SAndres Lagar-Cavilla 	charge_mm = fault_mm ? : current->mm;
146127ab7006SHugh Dickins 
14621da177e4SLinus Torvalds 	if (swap.val) {
14631da177e4SLinus Torvalds 		/* Look it up and read it in.. */
146427ab7006SHugh Dickins 		page = lookup_swap_cache(swap);
146527ab7006SHugh Dickins 		if (!page) {
14669e18eb29SAndres Lagar-Cavilla 			/* Or update major stats only when swapin succeeds?? */
14679e18eb29SAndres Lagar-Cavilla 			if (fault_type) {
146868da9f05SHugh Dickins 				*fault_type |= VM_FAULT_MAJOR;
14699e18eb29SAndres Lagar-Cavilla 				count_vm_event(PGMAJFAULT);
14709e18eb29SAndres Lagar-Cavilla 				mem_cgroup_count_vm_event(fault_mm, PGMAJFAULT);
14719e18eb29SAndres Lagar-Cavilla 			}
14729e18eb29SAndres Lagar-Cavilla 			/* Here we actually start the io */
147341ffe5d5SHugh Dickins 			page = shmem_swapin(swap, gfp, info, index);
147427ab7006SHugh Dickins 			if (!page) {
14751da177e4SLinus Torvalds 				error = -ENOMEM;
147654af6042SHugh Dickins 				goto failed;
1477285b2c4fSHugh Dickins 			}
14781da177e4SLinus Torvalds 		}
14791da177e4SLinus Torvalds 
14801da177e4SLinus Torvalds 		/* We have to do this with page locked to prevent races */
148154af6042SHugh Dickins 		lock_page(page);
14820142ef6cSHugh Dickins 		if (!PageSwapCache(page) || page_private(page) != swap.val ||
1483d1899228SHugh Dickins 		    !shmem_confirm_swap(mapping, index, swap)) {
1484bde05d1cSHugh Dickins 			error = -EEXIST;	/* try again */
1485d1899228SHugh Dickins 			goto unlock;
1486bde05d1cSHugh Dickins 		}
148727ab7006SHugh Dickins 		if (!PageUptodate(page)) {
14881da177e4SLinus Torvalds 			error = -EIO;
148954af6042SHugh Dickins 			goto failed;
149054af6042SHugh Dickins 		}
149154af6042SHugh Dickins 		wait_on_page_writeback(page);
149254af6042SHugh Dickins 
1493bde05d1cSHugh Dickins 		if (shmem_should_replace_page(page, gfp)) {
1494bde05d1cSHugh Dickins 			error = shmem_replace_page(&page, gfp, info, index);
1495bde05d1cSHugh Dickins 			if (error)
149654af6042SHugh Dickins 				goto failed;
14971da177e4SLinus Torvalds 		}
14981da177e4SLinus Torvalds 
14999e18eb29SAndres Lagar-Cavilla 		error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
1500f627c2f5SKirill A. Shutemov 				false);
1501d1899228SHugh Dickins 		if (!error) {
150254af6042SHugh Dickins 			error = shmem_add_to_page_cache(page, mapping, index,
1503fed400a1SWang Sheng-Hui 						swp_to_radix_entry(swap));
1504215c02bcSHugh Dickins 			/*
1505215c02bcSHugh Dickins 			 * We already confirmed swap under page lock, and make
1506215c02bcSHugh Dickins 			 * no memory allocation here, so usually no possibility
1507215c02bcSHugh Dickins 			 * of error; but free_swap_and_cache() only trylocks a
1508215c02bcSHugh Dickins 			 * page, so it is just possible that the entry has been
1509215c02bcSHugh Dickins 			 * truncated or holepunched since swap was confirmed.
1510215c02bcSHugh Dickins 			 * shmem_undo_range() will have done some of the
1511215c02bcSHugh Dickins 			 * unaccounting, now delete_from_swap_cache() will do
151293aa7d95SVladimir Davydov 			 * the rest.
1513215c02bcSHugh Dickins 			 * Reset swap.val? No, leave it so "failed" goes back to
1514215c02bcSHugh Dickins 			 * "repeat": reading a hole and writing should succeed.
1515215c02bcSHugh Dickins 			 */
151600501b53SJohannes Weiner 			if (error) {
1517f627c2f5SKirill A. Shutemov 				mem_cgroup_cancel_charge(page, memcg, false);
1518215c02bcSHugh Dickins 				delete_from_swap_cache(page);
1519d1899228SHugh Dickins 			}
152000501b53SJohannes Weiner 		}
152154af6042SHugh Dickins 		if (error)
152254af6042SHugh Dickins 			goto failed;
152354af6042SHugh Dickins 
1524f627c2f5SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, true, false);
152500501b53SJohannes Weiner 
152654af6042SHugh Dickins 		spin_lock(&info->lock);
152754af6042SHugh Dickins 		info->swapped--;
152854af6042SHugh Dickins 		shmem_recalc_inode(inode);
15291da177e4SLinus Torvalds 		spin_unlock(&info->lock);
153027ab7006SHugh Dickins 
153166d2f4d2SHugh Dickins 		if (sgp == SGP_WRITE)
153266d2f4d2SHugh Dickins 			mark_page_accessed(page);
153366d2f4d2SHugh Dickins 
153427ab7006SHugh Dickins 		delete_from_swap_cache(page);
153527ab7006SHugh Dickins 		set_page_dirty(page);
153627ab7006SHugh Dickins 		swap_free(swap);
153727ab7006SHugh Dickins 
153854af6042SHugh Dickins 	} else {
1539800d8c63SKirill A. Shutemov 		/* shmem_symlink() */
1540800d8c63SKirill A. Shutemov 		if (mapping->a_ops != &shmem_aops)
1541800d8c63SKirill A. Shutemov 			goto alloc_nohuge;
1542*657e3038SKirill A. Shutemov 		if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1543800d8c63SKirill A. Shutemov 			goto alloc_nohuge;
1544800d8c63SKirill A. Shutemov 		if (shmem_huge == SHMEM_HUGE_FORCE)
1545800d8c63SKirill A. Shutemov 			goto alloc_huge;
1546800d8c63SKirill A. Shutemov 		switch (sbinfo->huge) {
1547800d8c63SKirill A. Shutemov 			loff_t i_size;
1548800d8c63SKirill A. Shutemov 			pgoff_t off;
1549800d8c63SKirill A. Shutemov 		case SHMEM_HUGE_NEVER:
1550800d8c63SKirill A. Shutemov 			goto alloc_nohuge;
1551800d8c63SKirill A. Shutemov 		case SHMEM_HUGE_WITHIN_SIZE:
1552800d8c63SKirill A. Shutemov 			off = round_up(index, HPAGE_PMD_NR);
1553800d8c63SKirill A. Shutemov 			i_size = round_up(i_size_read(inode), PAGE_SIZE);
1554800d8c63SKirill A. Shutemov 			if (i_size >= HPAGE_PMD_SIZE &&
1555800d8c63SKirill A. Shutemov 					i_size >> PAGE_SHIFT >= off)
1556800d8c63SKirill A. Shutemov 				goto alloc_huge;
1557800d8c63SKirill A. Shutemov 			/* fallthrough */
1558800d8c63SKirill A. Shutemov 		case SHMEM_HUGE_ADVISE:
1559*657e3038SKirill A. Shutemov 			if (sgp_huge == SGP_HUGE)
1560*657e3038SKirill A. Shutemov 				goto alloc_huge;
1561*657e3038SKirill A. Shutemov 			/* TODO: implement fadvise() hints */
1562800d8c63SKirill A. Shutemov 			goto alloc_nohuge;
156359a16eadSHugh Dickins 		}
15641da177e4SLinus Torvalds 
1565800d8c63SKirill A. Shutemov alloc_huge:
1566800d8c63SKirill A. Shutemov 		page = shmem_alloc_and_acct_page(gfp, info, sbinfo,
1567800d8c63SKirill A. Shutemov 				index, true);
1568800d8c63SKirill A. Shutemov 		if (IS_ERR(page)) {
1569800d8c63SKirill A. Shutemov alloc_nohuge:		page = shmem_alloc_and_acct_page(gfp, info, sbinfo,
1570800d8c63SKirill A. Shutemov 					index, false);
157154af6042SHugh Dickins 		}
1572800d8c63SKirill A. Shutemov 		if (IS_ERR(page)) {
1573800d8c63SKirill A. Shutemov 			error = PTR_ERR(page);
1574800d8c63SKirill A. Shutemov 			page = NULL;
1575800d8c63SKirill A. Shutemov 			goto failed;
1576800d8c63SKirill A. Shutemov 		}
1577800d8c63SKirill A. Shutemov 
1578800d8c63SKirill A. Shutemov 		if (PageTransHuge(page))
1579800d8c63SKirill A. Shutemov 			hindex = round_down(index, HPAGE_PMD_NR);
1580800d8c63SKirill A. Shutemov 		else
1581800d8c63SKirill A. Shutemov 			hindex = index;
1582800d8c63SKirill A. Shutemov 
158366d2f4d2SHugh Dickins 		if (sgp == SGP_WRITE)
1584eb39d618SHugh Dickins 			__SetPageReferenced(page);
158566d2f4d2SHugh Dickins 
15869e18eb29SAndres Lagar-Cavilla 		error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
1587800d8c63SKirill A. Shutemov 				PageTransHuge(page));
158854af6042SHugh Dickins 		if (error)
1589800d8c63SKirill A. Shutemov 			goto unacct;
1590800d8c63SKirill A. Shutemov 		error = radix_tree_maybe_preload_order(gfp & GFP_RECLAIM_MASK,
1591800d8c63SKirill A. Shutemov 				compound_order(page));
1592b065b432SHugh Dickins 		if (!error) {
1593800d8c63SKirill A. Shutemov 			error = shmem_add_to_page_cache(page, mapping, hindex,
1594fed400a1SWang Sheng-Hui 							NULL);
1595b065b432SHugh Dickins 			radix_tree_preload_end();
1596b065b432SHugh Dickins 		}
1597b065b432SHugh Dickins 		if (error) {
1598800d8c63SKirill A. Shutemov 			mem_cgroup_cancel_charge(page, memcg,
1599800d8c63SKirill A. Shutemov 					PageTransHuge(page));
1600800d8c63SKirill A. Shutemov 			goto unacct;
1601b065b432SHugh Dickins 		}
1602800d8c63SKirill A. Shutemov 		mem_cgroup_commit_charge(page, memcg, false,
1603800d8c63SKirill A. Shutemov 				PageTransHuge(page));
160454af6042SHugh Dickins 		lru_cache_add_anon(page);
160554af6042SHugh Dickins 
160654af6042SHugh Dickins 		spin_lock(&info->lock);
1607800d8c63SKirill A. Shutemov 		info->alloced += 1 << compound_order(page);
1608800d8c63SKirill A. Shutemov 		inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
160954af6042SHugh Dickins 		shmem_recalc_inode(inode);
161059a16eadSHugh Dickins 		spin_unlock(&info->lock);
16111635f6a7SHugh Dickins 		alloced = true;
161254af6042SHugh Dickins 
1613ec9516fbSHugh Dickins 		/*
16141635f6a7SHugh Dickins 		 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
16151635f6a7SHugh Dickins 		 */
16161635f6a7SHugh Dickins 		if (sgp == SGP_FALLOC)
16171635f6a7SHugh Dickins 			sgp = SGP_WRITE;
16181635f6a7SHugh Dickins clear:
16191635f6a7SHugh Dickins 		/*
16201635f6a7SHugh Dickins 		 * Let SGP_WRITE caller clear ends if write does not fill page;
16211635f6a7SHugh Dickins 		 * but SGP_FALLOC on a page fallocated earlier must initialize
16221635f6a7SHugh Dickins 		 * it now, lest undo on failure cancel our earlier guarantee.
1623ec9516fbSHugh Dickins 		 */
1624800d8c63SKirill A. Shutemov 		if (sgp != SGP_WRITE && !PageUptodate(page)) {
1625800d8c63SKirill A. Shutemov 			struct page *head = compound_head(page);
1626800d8c63SKirill A. Shutemov 			int i;
1627800d8c63SKirill A. Shutemov 
1628800d8c63SKirill A. Shutemov 			for (i = 0; i < (1 << compound_order(head)); i++) {
1629800d8c63SKirill A. Shutemov 				clear_highpage(head + i);
1630800d8c63SKirill A. Shutemov 				flush_dcache_page(head + i);
1631800d8c63SKirill A. Shutemov 			}
1632800d8c63SKirill A. Shutemov 			SetPageUptodate(head);
1633ec9516fbSHugh Dickins 		}
16341da177e4SLinus Torvalds 	}
1635bde05d1cSHugh Dickins 
163654af6042SHugh Dickins 	/* Perhaps the file has been truncated since we checked */
163775edd345SHugh Dickins 	if (sgp <= SGP_CACHE &&
163809cbfeafSKirill A. Shutemov 	    ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1639267a4c76SHugh Dickins 		if (alloced) {
1640267a4c76SHugh Dickins 			ClearPageDirty(page);
1641267a4c76SHugh Dickins 			delete_from_page_cache(page);
1642267a4c76SHugh Dickins 			spin_lock(&info->lock);
1643267a4c76SHugh Dickins 			shmem_recalc_inode(inode);
1644267a4c76SHugh Dickins 			spin_unlock(&info->lock);
1645267a4c76SHugh Dickins 		}
164654af6042SHugh Dickins 		error = -EINVAL;
1647267a4c76SHugh Dickins 		goto unlock;
1648ff36b801SShaohua Li 	}
1649800d8c63SKirill A. Shutemov 	*pagep = page + index - hindex;
165054af6042SHugh Dickins 	return 0;
1651d00806b1SNick Piggin 
1652d0217ac0SNick Piggin 	/*
165354af6042SHugh Dickins 	 * Error recovery.
16541da177e4SLinus Torvalds 	 */
165554af6042SHugh Dickins unacct:
1656800d8c63SKirill A. Shutemov 	if (sbinfo->max_blocks)
1657800d8c63SKirill A. Shutemov 		percpu_counter_sub(&sbinfo->used_blocks,
1658800d8c63SKirill A. Shutemov 				1 << compound_order(page));
1659800d8c63SKirill A. Shutemov 	shmem_unacct_blocks(info->flags, 1 << compound_order(page));
1660800d8c63SKirill A. Shutemov 
1661800d8c63SKirill A. Shutemov 	if (PageTransHuge(page)) {
1662800d8c63SKirill A. Shutemov 		unlock_page(page);
1663800d8c63SKirill A. Shutemov 		put_page(page);
1664800d8c63SKirill A. Shutemov 		goto alloc_nohuge;
1665800d8c63SKirill A. Shutemov 	}
166654af6042SHugh Dickins failed:
1667267a4c76SHugh Dickins 	if (swap.val && !shmem_confirm_swap(mapping, index, swap))
166854af6042SHugh Dickins 		error = -EEXIST;
1669d1899228SHugh Dickins unlock:
167027ab7006SHugh Dickins 	if (page) {
167154af6042SHugh Dickins 		unlock_page(page);
167209cbfeafSKirill A. Shutemov 		put_page(page);
167354af6042SHugh Dickins 	}
167454af6042SHugh Dickins 	if (error == -ENOSPC && !once++) {
167554af6042SHugh Dickins 		info = SHMEM_I(inode);
167654af6042SHugh Dickins 		spin_lock(&info->lock);
167754af6042SHugh Dickins 		shmem_recalc_inode(inode);
167854af6042SHugh Dickins 		spin_unlock(&info->lock);
16791da177e4SLinus Torvalds 		goto repeat;
1680d8dc74f2SAdrian Bunk 	}
1681d1899228SHugh Dickins 	if (error == -EEXIST)	/* from above or from radix_tree_insert */
168254af6042SHugh Dickins 		goto repeat;
168354af6042SHugh Dickins 	return error;
16841da177e4SLinus Torvalds }
16851da177e4SLinus Torvalds 
16861da177e4SLinus Torvalds static int shmem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
16871da177e4SLinus Torvalds {
1688496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
16899e18eb29SAndres Lagar-Cavilla 	gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1690*657e3038SKirill A. Shutemov 	enum sgp_type sgp;
16911da177e4SLinus Torvalds 	int error;
169268da9f05SHugh Dickins 	int ret = VM_FAULT_LOCKED;
16931da177e4SLinus Torvalds 
1694f00cdc6dSHugh Dickins 	/*
1695f00cdc6dSHugh Dickins 	 * Trinity finds that probing a hole which tmpfs is punching can
1696f00cdc6dSHugh Dickins 	 * prevent the hole-punch from ever completing: which in turn
1697f00cdc6dSHugh Dickins 	 * locks writers out with its hold on i_mutex.  So refrain from
16988e205f77SHugh Dickins 	 * faulting pages into the hole while it's being punched.  Although
16998e205f77SHugh Dickins 	 * shmem_undo_range() does remove the additions, it may be unable to
17008e205f77SHugh Dickins 	 * keep up, as each new page needs its own unmap_mapping_range() call,
17018e205f77SHugh Dickins 	 * and the i_mmap tree grows ever slower to scan if new vmas are added.
17028e205f77SHugh Dickins 	 *
17038e205f77SHugh Dickins 	 * It does not matter if we sometimes reach this check just before the
17048e205f77SHugh Dickins 	 * hole-punch begins, so that one fault then races with the punch:
17058e205f77SHugh Dickins 	 * we just need to make racing faults a rare case.
17068e205f77SHugh Dickins 	 *
17078e205f77SHugh Dickins 	 * The implementation below would be much simpler if we just used a
17088e205f77SHugh Dickins 	 * standard mutex or completion: but we cannot take i_mutex in fault,
17098e205f77SHugh Dickins 	 * and bloating every shmem inode for this unlikely case would be sad.
1710f00cdc6dSHugh Dickins 	 */
1711f00cdc6dSHugh Dickins 	if (unlikely(inode->i_private)) {
1712f00cdc6dSHugh Dickins 		struct shmem_falloc *shmem_falloc;
1713f00cdc6dSHugh Dickins 
1714f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
1715f00cdc6dSHugh Dickins 		shmem_falloc = inode->i_private;
17168e205f77SHugh Dickins 		if (shmem_falloc &&
17178e205f77SHugh Dickins 		    shmem_falloc->waitq &&
17188e205f77SHugh Dickins 		    vmf->pgoff >= shmem_falloc->start &&
17198e205f77SHugh Dickins 		    vmf->pgoff < shmem_falloc->next) {
17208e205f77SHugh Dickins 			wait_queue_head_t *shmem_falloc_waitq;
17218e205f77SHugh Dickins 			DEFINE_WAIT(shmem_fault_wait);
17228e205f77SHugh Dickins 
17238e205f77SHugh Dickins 			ret = VM_FAULT_NOPAGE;
1724f00cdc6dSHugh Dickins 			if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
1725f00cdc6dSHugh Dickins 			   !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
17268e205f77SHugh Dickins 				/* It's polite to up mmap_sem if we can */
1727f00cdc6dSHugh Dickins 				up_read(&vma->vm_mm->mmap_sem);
17288e205f77SHugh Dickins 				ret = VM_FAULT_RETRY;
1729f00cdc6dSHugh Dickins 			}
17308e205f77SHugh Dickins 
17318e205f77SHugh Dickins 			shmem_falloc_waitq = shmem_falloc->waitq;
17328e205f77SHugh Dickins 			prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
17338e205f77SHugh Dickins 					TASK_UNINTERRUPTIBLE);
17348e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
17358e205f77SHugh Dickins 			schedule();
17368e205f77SHugh Dickins 
17378e205f77SHugh Dickins 			/*
17388e205f77SHugh Dickins 			 * shmem_falloc_waitq points into the shmem_fallocate()
17398e205f77SHugh Dickins 			 * stack of the hole-punching task: shmem_falloc_waitq
17408e205f77SHugh Dickins 			 * is usually invalid by the time we reach here, but
17418e205f77SHugh Dickins 			 * finish_wait() does not dereference it in that case;
17428e205f77SHugh Dickins 			 * though i_lock needed lest racing with wake_up_all().
17438e205f77SHugh Dickins 			 */
17448e205f77SHugh Dickins 			spin_lock(&inode->i_lock);
17458e205f77SHugh Dickins 			finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
17468e205f77SHugh Dickins 			spin_unlock(&inode->i_lock);
17478e205f77SHugh Dickins 			return ret;
1748f00cdc6dSHugh Dickins 		}
17498e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
1750f00cdc6dSHugh Dickins 	}
1751f00cdc6dSHugh Dickins 
1752*657e3038SKirill A. Shutemov 	sgp = SGP_CACHE;
1753*657e3038SKirill A. Shutemov 	if (vma->vm_flags & VM_HUGEPAGE)
1754*657e3038SKirill A. Shutemov 		sgp = SGP_HUGE;
1755*657e3038SKirill A. Shutemov 	else if (vma->vm_flags & VM_NOHUGEPAGE)
1756*657e3038SKirill A. Shutemov 		sgp = SGP_NOHUGE;
1757*657e3038SKirill A. Shutemov 
1758*657e3038SKirill A. Shutemov 	error = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
17599e18eb29SAndres Lagar-Cavilla 				  gfp, vma->vm_mm, &ret);
17601da177e4SLinus Torvalds 	if (error)
17611da177e4SLinus Torvalds 		return ((error == -ENOMEM) ? VM_FAULT_OOM : VM_FAULT_SIGBUS);
176268da9f05SHugh Dickins 	return ret;
17631da177e4SLinus Torvalds }
17641da177e4SLinus Torvalds 
1765c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
1766c01d5b30SHugh Dickins 				      unsigned long uaddr, unsigned long len,
1767c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
1768c01d5b30SHugh Dickins {
1769c01d5b30SHugh Dickins 	unsigned long (*get_area)(struct file *,
1770c01d5b30SHugh Dickins 		unsigned long, unsigned long, unsigned long, unsigned long);
1771c01d5b30SHugh Dickins 	unsigned long addr;
1772c01d5b30SHugh Dickins 	unsigned long offset;
1773c01d5b30SHugh Dickins 	unsigned long inflated_len;
1774c01d5b30SHugh Dickins 	unsigned long inflated_addr;
1775c01d5b30SHugh Dickins 	unsigned long inflated_offset;
1776c01d5b30SHugh Dickins 
1777c01d5b30SHugh Dickins 	if (len > TASK_SIZE)
1778c01d5b30SHugh Dickins 		return -ENOMEM;
1779c01d5b30SHugh Dickins 
1780c01d5b30SHugh Dickins 	get_area = current->mm->get_unmapped_area;
1781c01d5b30SHugh Dickins 	addr = get_area(file, uaddr, len, pgoff, flags);
1782c01d5b30SHugh Dickins 
1783c01d5b30SHugh Dickins 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1784c01d5b30SHugh Dickins 		return addr;
1785c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(addr))
1786c01d5b30SHugh Dickins 		return addr;
1787c01d5b30SHugh Dickins 	if (addr & ~PAGE_MASK)
1788c01d5b30SHugh Dickins 		return addr;
1789c01d5b30SHugh Dickins 	if (addr > TASK_SIZE - len)
1790c01d5b30SHugh Dickins 		return addr;
1791c01d5b30SHugh Dickins 
1792c01d5b30SHugh Dickins 	if (shmem_huge == SHMEM_HUGE_DENY)
1793c01d5b30SHugh Dickins 		return addr;
1794c01d5b30SHugh Dickins 	if (len < HPAGE_PMD_SIZE)
1795c01d5b30SHugh Dickins 		return addr;
1796c01d5b30SHugh Dickins 	if (flags & MAP_FIXED)
1797c01d5b30SHugh Dickins 		return addr;
1798c01d5b30SHugh Dickins 	/*
1799c01d5b30SHugh Dickins 	 * Our priority is to support MAP_SHARED mapped hugely;
1800c01d5b30SHugh Dickins 	 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
1801c01d5b30SHugh Dickins 	 * But if caller specified an address hint, respect that as before.
1802c01d5b30SHugh Dickins 	 */
1803c01d5b30SHugh Dickins 	if (uaddr)
1804c01d5b30SHugh Dickins 		return addr;
1805c01d5b30SHugh Dickins 
1806c01d5b30SHugh Dickins 	if (shmem_huge != SHMEM_HUGE_FORCE) {
1807c01d5b30SHugh Dickins 		struct super_block *sb;
1808c01d5b30SHugh Dickins 
1809c01d5b30SHugh Dickins 		if (file) {
1810c01d5b30SHugh Dickins 			VM_BUG_ON(file->f_op != &shmem_file_operations);
1811c01d5b30SHugh Dickins 			sb = file_inode(file)->i_sb;
1812c01d5b30SHugh Dickins 		} else {
1813c01d5b30SHugh Dickins 			/*
1814c01d5b30SHugh Dickins 			 * Called directly from mm/mmap.c, or drivers/char/mem.c
1815c01d5b30SHugh Dickins 			 * for "/dev/zero", to create a shared anonymous object.
1816c01d5b30SHugh Dickins 			 */
1817c01d5b30SHugh Dickins 			if (IS_ERR(shm_mnt))
1818c01d5b30SHugh Dickins 				return addr;
1819c01d5b30SHugh Dickins 			sb = shm_mnt->mnt_sb;
1820c01d5b30SHugh Dickins 		}
1821c01d5b30SHugh Dickins 		if (SHMEM_SB(sb)->huge != SHMEM_HUGE_NEVER)
1822c01d5b30SHugh Dickins 			return addr;
1823c01d5b30SHugh Dickins 	}
1824c01d5b30SHugh Dickins 
1825c01d5b30SHugh Dickins 	offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
1826c01d5b30SHugh Dickins 	if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
1827c01d5b30SHugh Dickins 		return addr;
1828c01d5b30SHugh Dickins 	if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
1829c01d5b30SHugh Dickins 		return addr;
1830c01d5b30SHugh Dickins 
1831c01d5b30SHugh Dickins 	inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
1832c01d5b30SHugh Dickins 	if (inflated_len > TASK_SIZE)
1833c01d5b30SHugh Dickins 		return addr;
1834c01d5b30SHugh Dickins 	if (inflated_len < len)
1835c01d5b30SHugh Dickins 		return addr;
1836c01d5b30SHugh Dickins 
1837c01d5b30SHugh Dickins 	inflated_addr = get_area(NULL, 0, inflated_len, 0, flags);
1838c01d5b30SHugh Dickins 	if (IS_ERR_VALUE(inflated_addr))
1839c01d5b30SHugh Dickins 		return addr;
1840c01d5b30SHugh Dickins 	if (inflated_addr & ~PAGE_MASK)
1841c01d5b30SHugh Dickins 		return addr;
1842c01d5b30SHugh Dickins 
1843c01d5b30SHugh Dickins 	inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
1844c01d5b30SHugh Dickins 	inflated_addr += offset - inflated_offset;
1845c01d5b30SHugh Dickins 	if (inflated_offset > offset)
1846c01d5b30SHugh Dickins 		inflated_addr += HPAGE_PMD_SIZE;
1847c01d5b30SHugh Dickins 
1848c01d5b30SHugh Dickins 	if (inflated_addr > TASK_SIZE - len)
1849c01d5b30SHugh Dickins 		return addr;
1850c01d5b30SHugh Dickins 	return inflated_addr;
1851c01d5b30SHugh Dickins }
1852c01d5b30SHugh Dickins 
18531da177e4SLinus Torvalds #ifdef CONFIG_NUMA
185441ffe5d5SHugh Dickins static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
18551da177e4SLinus Torvalds {
1856496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
185741ffe5d5SHugh Dickins 	return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
18581da177e4SLinus Torvalds }
18591da177e4SLinus Torvalds 
1860d8dc74f2SAdrian Bunk static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
1861d8dc74f2SAdrian Bunk 					  unsigned long addr)
18621da177e4SLinus Torvalds {
1863496ad9aaSAl Viro 	struct inode *inode = file_inode(vma->vm_file);
186441ffe5d5SHugh Dickins 	pgoff_t index;
18651da177e4SLinus Torvalds 
186641ffe5d5SHugh Dickins 	index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
186741ffe5d5SHugh Dickins 	return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
18681da177e4SLinus Torvalds }
18691da177e4SLinus Torvalds #endif
18701da177e4SLinus Torvalds 
18711da177e4SLinus Torvalds int shmem_lock(struct file *file, int lock, struct user_struct *user)
18721da177e4SLinus Torvalds {
1873496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
18741da177e4SLinus Torvalds 	struct shmem_inode_info *info = SHMEM_I(inode);
18751da177e4SLinus Torvalds 	int retval = -ENOMEM;
18761da177e4SLinus Torvalds 
18771da177e4SLinus Torvalds 	spin_lock(&info->lock);
18781da177e4SLinus Torvalds 	if (lock && !(info->flags & VM_LOCKED)) {
18791da177e4SLinus Torvalds 		if (!user_shm_lock(inode->i_size, user))
18801da177e4SLinus Torvalds 			goto out_nomem;
18811da177e4SLinus Torvalds 		info->flags |= VM_LOCKED;
188289e004eaSLee Schermerhorn 		mapping_set_unevictable(file->f_mapping);
18831da177e4SLinus Torvalds 	}
18841da177e4SLinus Torvalds 	if (!lock && (info->flags & VM_LOCKED) && user) {
18851da177e4SLinus Torvalds 		user_shm_unlock(inode->i_size, user);
18861da177e4SLinus Torvalds 		info->flags &= ~VM_LOCKED;
188789e004eaSLee Schermerhorn 		mapping_clear_unevictable(file->f_mapping);
18881da177e4SLinus Torvalds 	}
18891da177e4SLinus Torvalds 	retval = 0;
189089e004eaSLee Schermerhorn 
18911da177e4SLinus Torvalds out_nomem:
18921da177e4SLinus Torvalds 	spin_unlock(&info->lock);
18931da177e4SLinus Torvalds 	return retval;
18941da177e4SLinus Torvalds }
18951da177e4SLinus Torvalds 
18969b83a6a8SAdrian Bunk static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
18971da177e4SLinus Torvalds {
18981da177e4SLinus Torvalds 	file_accessed(file);
18991da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
19001da177e4SLinus Torvalds 	return 0;
19011da177e4SLinus Torvalds }
19021da177e4SLinus Torvalds 
1903454abafeSDmitry Monakhov static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
190409208d15SAl Viro 				     umode_t mode, dev_t dev, unsigned long flags)
19051da177e4SLinus Torvalds {
19061da177e4SLinus Torvalds 	struct inode *inode;
19071da177e4SLinus Torvalds 	struct shmem_inode_info *info;
19081da177e4SLinus Torvalds 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
19091da177e4SLinus Torvalds 
19105b04c689SPavel Emelyanov 	if (shmem_reserve_inode(sb))
19111da177e4SLinus Torvalds 		return NULL;
19121da177e4SLinus Torvalds 
19131da177e4SLinus Torvalds 	inode = new_inode(sb);
19141da177e4SLinus Torvalds 	if (inode) {
191585fe4025SChristoph Hellwig 		inode->i_ino = get_next_ino();
1916454abafeSDmitry Monakhov 		inode_init_owner(inode, dir, mode);
19171da177e4SLinus Torvalds 		inode->i_blocks = 0;
19181da177e4SLinus Torvalds 		inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
191991828a40SDavid M. Grimes 		inode->i_generation = get_seconds();
19201da177e4SLinus Torvalds 		info = SHMEM_I(inode);
19211da177e4SLinus Torvalds 		memset(info, 0, (char *)inode - (char *)info);
19221da177e4SLinus Torvalds 		spin_lock_init(&info->lock);
192340e041a2SDavid Herrmann 		info->seals = F_SEAL_SEAL;
19240b0a0806SHugh Dickins 		info->flags = flags & VM_NORESERVE;
19251da177e4SLinus Torvalds 		INIT_LIST_HEAD(&info->swaplist);
192638f38657SAristeu Rozanski 		simple_xattrs_init(&info->xattrs);
192772c04902SAl Viro 		cache_no_acl(inode);
19281da177e4SLinus Torvalds 
19291da177e4SLinus Torvalds 		switch (mode & S_IFMT) {
19301da177e4SLinus Torvalds 		default:
193139f0247dSAndreas Gruenbacher 			inode->i_op = &shmem_special_inode_operations;
19321da177e4SLinus Torvalds 			init_special_inode(inode, mode, dev);
19331da177e4SLinus Torvalds 			break;
19341da177e4SLinus Torvalds 		case S_IFREG:
193514fcc23fSHugh Dickins 			inode->i_mapping->a_ops = &shmem_aops;
19361da177e4SLinus Torvalds 			inode->i_op = &shmem_inode_operations;
19371da177e4SLinus Torvalds 			inode->i_fop = &shmem_file_operations;
193871fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy,
193971fe804bSLee Schermerhorn 						 shmem_get_sbmpol(sbinfo));
19401da177e4SLinus Torvalds 			break;
19411da177e4SLinus Torvalds 		case S_IFDIR:
1942d8c76e6fSDave Hansen 			inc_nlink(inode);
19431da177e4SLinus Torvalds 			/* Some things misbehave if size == 0 on a directory */
19441da177e4SLinus Torvalds 			inode->i_size = 2 * BOGO_DIRENT_SIZE;
19451da177e4SLinus Torvalds 			inode->i_op = &shmem_dir_inode_operations;
19461da177e4SLinus Torvalds 			inode->i_fop = &simple_dir_operations;
19471da177e4SLinus Torvalds 			break;
19481da177e4SLinus Torvalds 		case S_IFLNK:
19491da177e4SLinus Torvalds 			/*
19501da177e4SLinus Torvalds 			 * Must not load anything in the rbtree,
19511da177e4SLinus Torvalds 			 * mpol_free_shared_policy will not be called.
19521da177e4SLinus Torvalds 			 */
195371fe804bSLee Schermerhorn 			mpol_shared_policy_init(&info->policy, NULL);
19541da177e4SLinus Torvalds 			break;
19551da177e4SLinus Torvalds 		}
19565b04c689SPavel Emelyanov 	} else
19575b04c689SPavel Emelyanov 		shmem_free_inode(sb);
19581da177e4SLinus Torvalds 	return inode;
19591da177e4SLinus Torvalds }
19601da177e4SLinus Torvalds 
19610cd6144aSJohannes Weiner bool shmem_mapping(struct address_space *mapping)
19620cd6144aSJohannes Weiner {
1963f0774d88SSasha Levin 	if (!mapping->host)
1964f0774d88SSasha Levin 		return false;
1965f0774d88SSasha Levin 
196697b713baSChristoph Hellwig 	return mapping->host->i_sb->s_op == &shmem_ops;
19670cd6144aSJohannes Weiner }
19680cd6144aSJohannes Weiner 
19691da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
197092e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations;
197169f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations;
19721da177e4SLinus Torvalds 
19736d9d88d0SJarkko Sakkinen #ifdef CONFIG_TMPFS_XATTR
19746d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
19756d9d88d0SJarkko Sakkinen #else
19766d9d88d0SJarkko Sakkinen #define shmem_initxattrs NULL
19776d9d88d0SJarkko Sakkinen #endif
19786d9d88d0SJarkko Sakkinen 
19791da177e4SLinus Torvalds static int
1980800d15a5SNick Piggin shmem_write_begin(struct file *file, struct address_space *mapping,
1981800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned flags,
1982800d15a5SNick Piggin 			struct page **pagep, void **fsdata)
19831da177e4SLinus Torvalds {
1984800d15a5SNick Piggin 	struct inode *inode = mapping->host;
198540e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
198609cbfeafSKirill A. Shutemov 	pgoff_t index = pos >> PAGE_SHIFT;
198740e041a2SDavid Herrmann 
198840e041a2SDavid Herrmann 	/* i_mutex is held by caller */
198940e041a2SDavid Herrmann 	if (unlikely(info->seals)) {
199040e041a2SDavid Herrmann 		if (info->seals & F_SEAL_WRITE)
199140e041a2SDavid Herrmann 			return -EPERM;
199240e041a2SDavid Herrmann 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
199340e041a2SDavid Herrmann 			return -EPERM;
199440e041a2SDavid Herrmann 	}
199540e041a2SDavid Herrmann 
19969e18eb29SAndres Lagar-Cavilla 	return shmem_getpage(inode, index, pagep, SGP_WRITE);
1997800d15a5SNick Piggin }
1998800d15a5SNick Piggin 
1999800d15a5SNick Piggin static int
2000800d15a5SNick Piggin shmem_write_end(struct file *file, struct address_space *mapping,
2001800d15a5SNick Piggin 			loff_t pos, unsigned len, unsigned copied,
2002800d15a5SNick Piggin 			struct page *page, void *fsdata)
2003800d15a5SNick Piggin {
2004800d15a5SNick Piggin 	struct inode *inode = mapping->host;
2005800d15a5SNick Piggin 
2006800d15a5SNick Piggin 	if (pos + copied > inode->i_size)
2007800d15a5SNick Piggin 		i_size_write(inode, pos + copied);
2008800d15a5SNick Piggin 
2009ec9516fbSHugh Dickins 	if (!PageUptodate(page)) {
2010800d8c63SKirill A. Shutemov 		struct page *head = compound_head(page);
2011800d8c63SKirill A. Shutemov 		if (PageTransCompound(page)) {
2012800d8c63SKirill A. Shutemov 			int i;
2013800d8c63SKirill A. Shutemov 
2014800d8c63SKirill A. Shutemov 			for (i = 0; i < HPAGE_PMD_NR; i++) {
2015800d8c63SKirill A. Shutemov 				if (head + i == page)
2016800d8c63SKirill A. Shutemov 					continue;
2017800d8c63SKirill A. Shutemov 				clear_highpage(head + i);
2018800d8c63SKirill A. Shutemov 				flush_dcache_page(head + i);
2019800d8c63SKirill A. Shutemov 			}
2020800d8c63SKirill A. Shutemov 		}
202109cbfeafSKirill A. Shutemov 		if (copied < PAGE_SIZE) {
202209cbfeafSKirill A. Shutemov 			unsigned from = pos & (PAGE_SIZE - 1);
2023ec9516fbSHugh Dickins 			zero_user_segments(page, 0, from,
202409cbfeafSKirill A. Shutemov 					from + copied, PAGE_SIZE);
2025ec9516fbSHugh Dickins 		}
2026800d8c63SKirill A. Shutemov 		SetPageUptodate(head);
2027ec9516fbSHugh Dickins 	}
2028d3602444SHugh Dickins 	set_page_dirty(page);
20296746aff7SWu Fengguang 	unlock_page(page);
203009cbfeafSKirill A. Shutemov 	put_page(page);
2031d3602444SHugh Dickins 
2032800d15a5SNick Piggin 	return copied;
20331da177e4SLinus Torvalds }
20341da177e4SLinus Torvalds 
20352ba5bbedSAl Viro static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
20361da177e4SLinus Torvalds {
20376e58e79dSAl Viro 	struct file *file = iocb->ki_filp;
20386e58e79dSAl Viro 	struct inode *inode = file_inode(file);
20391da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
204041ffe5d5SHugh Dickins 	pgoff_t index;
204141ffe5d5SHugh Dickins 	unsigned long offset;
2042a0ee5ec5SHugh Dickins 	enum sgp_type sgp = SGP_READ;
2043f7c1d074SGeert Uytterhoeven 	int error = 0;
2044cb66a7a1SAl Viro 	ssize_t retval = 0;
20456e58e79dSAl Viro 	loff_t *ppos = &iocb->ki_pos;
2046a0ee5ec5SHugh Dickins 
2047a0ee5ec5SHugh Dickins 	/*
2048a0ee5ec5SHugh Dickins 	 * Might this read be for a stacking filesystem?  Then when reading
2049a0ee5ec5SHugh Dickins 	 * holes of a sparse file, we actually need to allocate those pages,
2050a0ee5ec5SHugh Dickins 	 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2051a0ee5ec5SHugh Dickins 	 */
2052777eda2cSAl Viro 	if (!iter_is_iovec(to))
205375edd345SHugh Dickins 		sgp = SGP_CACHE;
20541da177e4SLinus Torvalds 
205509cbfeafSKirill A. Shutemov 	index = *ppos >> PAGE_SHIFT;
205609cbfeafSKirill A. Shutemov 	offset = *ppos & ~PAGE_MASK;
20571da177e4SLinus Torvalds 
20581da177e4SLinus Torvalds 	for (;;) {
20591da177e4SLinus Torvalds 		struct page *page = NULL;
206041ffe5d5SHugh Dickins 		pgoff_t end_index;
206141ffe5d5SHugh Dickins 		unsigned long nr, ret;
20621da177e4SLinus Torvalds 		loff_t i_size = i_size_read(inode);
20631da177e4SLinus Torvalds 
206409cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
20651da177e4SLinus Torvalds 		if (index > end_index)
20661da177e4SLinus Torvalds 			break;
20671da177e4SLinus Torvalds 		if (index == end_index) {
206809cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
20691da177e4SLinus Torvalds 			if (nr <= offset)
20701da177e4SLinus Torvalds 				break;
20711da177e4SLinus Torvalds 		}
20721da177e4SLinus Torvalds 
20739e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, index, &page, sgp);
20746e58e79dSAl Viro 		if (error) {
20756e58e79dSAl Viro 			if (error == -EINVAL)
20766e58e79dSAl Viro 				error = 0;
20771da177e4SLinus Torvalds 			break;
20781da177e4SLinus Torvalds 		}
207975edd345SHugh Dickins 		if (page) {
208075edd345SHugh Dickins 			if (sgp == SGP_CACHE)
208175edd345SHugh Dickins 				set_page_dirty(page);
2082d3602444SHugh Dickins 			unlock_page(page);
208375edd345SHugh Dickins 		}
20841da177e4SLinus Torvalds 
20851da177e4SLinus Torvalds 		/*
20861da177e4SLinus Torvalds 		 * We must evaluate after, since reads (unlike writes)
20871b1dcc1bSJes Sorensen 		 * are called without i_mutex protection against truncate
20881da177e4SLinus Torvalds 		 */
208909cbfeafSKirill A. Shutemov 		nr = PAGE_SIZE;
20901da177e4SLinus Torvalds 		i_size = i_size_read(inode);
209109cbfeafSKirill A. Shutemov 		end_index = i_size >> PAGE_SHIFT;
20921da177e4SLinus Torvalds 		if (index == end_index) {
209309cbfeafSKirill A. Shutemov 			nr = i_size & ~PAGE_MASK;
20941da177e4SLinus Torvalds 			if (nr <= offset) {
20951da177e4SLinus Torvalds 				if (page)
209609cbfeafSKirill A. Shutemov 					put_page(page);
20971da177e4SLinus Torvalds 				break;
20981da177e4SLinus Torvalds 			}
20991da177e4SLinus Torvalds 		}
21001da177e4SLinus Torvalds 		nr -= offset;
21011da177e4SLinus Torvalds 
21021da177e4SLinus Torvalds 		if (page) {
21031da177e4SLinus Torvalds 			/*
21041da177e4SLinus Torvalds 			 * If users can be writing to this page using arbitrary
21051da177e4SLinus Torvalds 			 * virtual addresses, take care about potential aliasing
21061da177e4SLinus Torvalds 			 * before reading the page on the kernel side.
21071da177e4SLinus Torvalds 			 */
21081da177e4SLinus Torvalds 			if (mapping_writably_mapped(mapping))
21091da177e4SLinus Torvalds 				flush_dcache_page(page);
21101da177e4SLinus Torvalds 			/*
21111da177e4SLinus Torvalds 			 * Mark the page accessed if we read the beginning.
21121da177e4SLinus Torvalds 			 */
21131da177e4SLinus Torvalds 			if (!offset)
21141da177e4SLinus Torvalds 				mark_page_accessed(page);
2115b5810039SNick Piggin 		} else {
21161da177e4SLinus Torvalds 			page = ZERO_PAGE(0);
211709cbfeafSKirill A. Shutemov 			get_page(page);
2118b5810039SNick Piggin 		}
21191da177e4SLinus Torvalds 
21201da177e4SLinus Torvalds 		/*
21211da177e4SLinus Torvalds 		 * Ok, we have the page, and it's up-to-date, so
21221da177e4SLinus Torvalds 		 * now we can copy it to user space...
21231da177e4SLinus Torvalds 		 */
21242ba5bbedSAl Viro 		ret = copy_page_to_iter(page, offset, nr, to);
21256e58e79dSAl Viro 		retval += ret;
21261da177e4SLinus Torvalds 		offset += ret;
212709cbfeafSKirill A. Shutemov 		index += offset >> PAGE_SHIFT;
212809cbfeafSKirill A. Shutemov 		offset &= ~PAGE_MASK;
21291da177e4SLinus Torvalds 
213009cbfeafSKirill A. Shutemov 		put_page(page);
21312ba5bbedSAl Viro 		if (!iov_iter_count(to))
21321da177e4SLinus Torvalds 			break;
21336e58e79dSAl Viro 		if (ret < nr) {
21346e58e79dSAl Viro 			error = -EFAULT;
21356e58e79dSAl Viro 			break;
21366e58e79dSAl Viro 		}
21371da177e4SLinus Torvalds 		cond_resched();
21381da177e4SLinus Torvalds 	}
21391da177e4SLinus Torvalds 
214009cbfeafSKirill A. Shutemov 	*ppos = ((loff_t) index << PAGE_SHIFT) + offset;
21416e58e79dSAl Viro 	file_accessed(file);
21426e58e79dSAl Viro 	return retval ? retval : error;
21431da177e4SLinus Torvalds }
21441da177e4SLinus Torvalds 
2145708e3508SHugh Dickins static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
2146708e3508SHugh Dickins 				struct pipe_inode_info *pipe, size_t len,
2147708e3508SHugh Dickins 				unsigned int flags)
2148708e3508SHugh Dickins {
2149708e3508SHugh Dickins 	struct address_space *mapping = in->f_mapping;
215071f0e07aSHugh Dickins 	struct inode *inode = mapping->host;
2151708e3508SHugh Dickins 	unsigned int loff, nr_pages, req_pages;
2152708e3508SHugh Dickins 	struct page *pages[PIPE_DEF_BUFFERS];
2153708e3508SHugh Dickins 	struct partial_page partial[PIPE_DEF_BUFFERS];
2154708e3508SHugh Dickins 	struct page *page;
2155708e3508SHugh Dickins 	pgoff_t index, end_index;
2156708e3508SHugh Dickins 	loff_t isize, left;
2157708e3508SHugh Dickins 	int error, page_nr;
2158708e3508SHugh Dickins 	struct splice_pipe_desc spd = {
2159708e3508SHugh Dickins 		.pages = pages,
2160708e3508SHugh Dickins 		.partial = partial,
2161047fe360SEric Dumazet 		.nr_pages_max = PIPE_DEF_BUFFERS,
2162708e3508SHugh Dickins 		.flags = flags,
2163708e3508SHugh Dickins 		.ops = &page_cache_pipe_buf_ops,
2164708e3508SHugh Dickins 		.spd_release = spd_release_page,
2165708e3508SHugh Dickins 	};
2166708e3508SHugh Dickins 
216771f0e07aSHugh Dickins 	isize = i_size_read(inode);
2168708e3508SHugh Dickins 	if (unlikely(*ppos >= isize))
2169708e3508SHugh Dickins 		return 0;
2170708e3508SHugh Dickins 
2171708e3508SHugh Dickins 	left = isize - *ppos;
2172708e3508SHugh Dickins 	if (unlikely(left < len))
2173708e3508SHugh Dickins 		len = left;
2174708e3508SHugh Dickins 
2175708e3508SHugh Dickins 	if (splice_grow_spd(pipe, &spd))
2176708e3508SHugh Dickins 		return -ENOMEM;
2177708e3508SHugh Dickins 
217809cbfeafSKirill A. Shutemov 	index = *ppos >> PAGE_SHIFT;
217909cbfeafSKirill A. Shutemov 	loff = *ppos & ~PAGE_MASK;
218009cbfeafSKirill A. Shutemov 	req_pages = (len + loff + PAGE_SIZE - 1) >> PAGE_SHIFT;
2181a786c06dSAl Viro 	nr_pages = min(req_pages, spd.nr_pages_max);
2182708e3508SHugh Dickins 
2183708e3508SHugh Dickins 	spd.nr_pages = find_get_pages_contig(mapping, index,
2184708e3508SHugh Dickins 						nr_pages, spd.pages);
2185708e3508SHugh Dickins 	index += spd.nr_pages;
2186708e3508SHugh Dickins 	error = 0;
218771f0e07aSHugh Dickins 
2188708e3508SHugh Dickins 	while (spd.nr_pages < nr_pages) {
21899e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, index, &page, SGP_CACHE);
219071f0e07aSHugh Dickins 		if (error)
2191708e3508SHugh Dickins 			break;
2192708e3508SHugh Dickins 		unlock_page(page);
2193708e3508SHugh Dickins 		spd.pages[spd.nr_pages++] = page;
2194708e3508SHugh Dickins 		index++;
2195708e3508SHugh Dickins 	}
2196708e3508SHugh Dickins 
219709cbfeafSKirill A. Shutemov 	index = *ppos >> PAGE_SHIFT;
2198708e3508SHugh Dickins 	nr_pages = spd.nr_pages;
2199708e3508SHugh Dickins 	spd.nr_pages = 0;
220071f0e07aSHugh Dickins 
2201708e3508SHugh Dickins 	for (page_nr = 0; page_nr < nr_pages; page_nr++) {
2202708e3508SHugh Dickins 		unsigned int this_len;
2203708e3508SHugh Dickins 
2204708e3508SHugh Dickins 		if (!len)
2205708e3508SHugh Dickins 			break;
2206708e3508SHugh Dickins 
220709cbfeafSKirill A. Shutemov 		this_len = min_t(unsigned long, len, PAGE_SIZE - loff);
2208708e3508SHugh Dickins 		page = spd.pages[page_nr];
2209708e3508SHugh Dickins 
221071f0e07aSHugh Dickins 		if (!PageUptodate(page) || page->mapping != mapping) {
22119e18eb29SAndres Lagar-Cavilla 			error = shmem_getpage(inode, index, &page, SGP_CACHE);
221271f0e07aSHugh Dickins 			if (error)
2213708e3508SHugh Dickins 				break;
221471f0e07aSHugh Dickins 			unlock_page(page);
221509cbfeafSKirill A. Shutemov 			put_page(spd.pages[page_nr]);
2216708e3508SHugh Dickins 			spd.pages[page_nr] = page;
2217708e3508SHugh Dickins 		}
2218708e3508SHugh Dickins 
221971f0e07aSHugh Dickins 		isize = i_size_read(inode);
222009cbfeafSKirill A. Shutemov 		end_index = (isize - 1) >> PAGE_SHIFT;
2221708e3508SHugh Dickins 		if (unlikely(!isize || index > end_index))
2222708e3508SHugh Dickins 			break;
2223708e3508SHugh Dickins 
2224708e3508SHugh Dickins 		if (end_index == index) {
2225708e3508SHugh Dickins 			unsigned int plen;
2226708e3508SHugh Dickins 
222709cbfeafSKirill A. Shutemov 			plen = ((isize - 1) & ~PAGE_MASK) + 1;
2228708e3508SHugh Dickins 			if (plen <= loff)
2229708e3508SHugh Dickins 				break;
2230708e3508SHugh Dickins 
2231708e3508SHugh Dickins 			this_len = min(this_len, plen - loff);
2232708e3508SHugh Dickins 			len = this_len;
2233708e3508SHugh Dickins 		}
2234708e3508SHugh Dickins 
2235708e3508SHugh Dickins 		spd.partial[page_nr].offset = loff;
2236708e3508SHugh Dickins 		spd.partial[page_nr].len = this_len;
2237708e3508SHugh Dickins 		len -= this_len;
2238708e3508SHugh Dickins 		loff = 0;
2239708e3508SHugh Dickins 		spd.nr_pages++;
2240708e3508SHugh Dickins 		index++;
2241708e3508SHugh Dickins 	}
2242708e3508SHugh Dickins 
2243708e3508SHugh Dickins 	while (page_nr < nr_pages)
224409cbfeafSKirill A. Shutemov 		put_page(spd.pages[page_nr++]);
2245708e3508SHugh Dickins 
2246708e3508SHugh Dickins 	if (spd.nr_pages)
2247708e3508SHugh Dickins 		error = splice_to_pipe(pipe, &spd);
2248708e3508SHugh Dickins 
2249047fe360SEric Dumazet 	splice_shrink_spd(&spd);
2250708e3508SHugh Dickins 
2251708e3508SHugh Dickins 	if (error > 0) {
2252708e3508SHugh Dickins 		*ppos += error;
2253708e3508SHugh Dickins 		file_accessed(in);
2254708e3508SHugh Dickins 	}
2255708e3508SHugh Dickins 	return error;
2256708e3508SHugh Dickins }
2257708e3508SHugh Dickins 
2258220f2ac9SHugh Dickins /*
2259220f2ac9SHugh Dickins  * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
2260220f2ac9SHugh Dickins  */
2261220f2ac9SHugh Dickins static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2262965c8e59SAndrew Morton 				    pgoff_t index, pgoff_t end, int whence)
2263220f2ac9SHugh Dickins {
2264220f2ac9SHugh Dickins 	struct page *page;
2265220f2ac9SHugh Dickins 	struct pagevec pvec;
2266220f2ac9SHugh Dickins 	pgoff_t indices[PAGEVEC_SIZE];
2267220f2ac9SHugh Dickins 	bool done = false;
2268220f2ac9SHugh Dickins 	int i;
2269220f2ac9SHugh Dickins 
2270220f2ac9SHugh Dickins 	pagevec_init(&pvec, 0);
2271220f2ac9SHugh Dickins 	pvec.nr = 1;		/* start small: we may be there already */
2272220f2ac9SHugh Dickins 	while (!done) {
22730cd6144aSJohannes Weiner 		pvec.nr = find_get_entries(mapping, index,
2274220f2ac9SHugh Dickins 					pvec.nr, pvec.pages, indices);
2275220f2ac9SHugh Dickins 		if (!pvec.nr) {
2276965c8e59SAndrew Morton 			if (whence == SEEK_DATA)
2277220f2ac9SHugh Dickins 				index = end;
2278220f2ac9SHugh Dickins 			break;
2279220f2ac9SHugh Dickins 		}
2280220f2ac9SHugh Dickins 		for (i = 0; i < pvec.nr; i++, index++) {
2281220f2ac9SHugh Dickins 			if (index < indices[i]) {
2282965c8e59SAndrew Morton 				if (whence == SEEK_HOLE) {
2283220f2ac9SHugh Dickins 					done = true;
2284220f2ac9SHugh Dickins 					break;
2285220f2ac9SHugh Dickins 				}
2286220f2ac9SHugh Dickins 				index = indices[i];
2287220f2ac9SHugh Dickins 			}
2288220f2ac9SHugh Dickins 			page = pvec.pages[i];
2289220f2ac9SHugh Dickins 			if (page && !radix_tree_exceptional_entry(page)) {
2290220f2ac9SHugh Dickins 				if (!PageUptodate(page))
2291220f2ac9SHugh Dickins 					page = NULL;
2292220f2ac9SHugh Dickins 			}
2293220f2ac9SHugh Dickins 			if (index >= end ||
2294965c8e59SAndrew Morton 			    (page && whence == SEEK_DATA) ||
2295965c8e59SAndrew Morton 			    (!page && whence == SEEK_HOLE)) {
2296220f2ac9SHugh Dickins 				done = true;
2297220f2ac9SHugh Dickins 				break;
2298220f2ac9SHugh Dickins 			}
2299220f2ac9SHugh Dickins 		}
23000cd6144aSJohannes Weiner 		pagevec_remove_exceptionals(&pvec);
2301220f2ac9SHugh Dickins 		pagevec_release(&pvec);
2302220f2ac9SHugh Dickins 		pvec.nr = PAGEVEC_SIZE;
2303220f2ac9SHugh Dickins 		cond_resched();
2304220f2ac9SHugh Dickins 	}
2305220f2ac9SHugh Dickins 	return index;
2306220f2ac9SHugh Dickins }
2307220f2ac9SHugh Dickins 
2308965c8e59SAndrew Morton static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2309220f2ac9SHugh Dickins {
2310220f2ac9SHugh Dickins 	struct address_space *mapping = file->f_mapping;
2311220f2ac9SHugh Dickins 	struct inode *inode = mapping->host;
2312220f2ac9SHugh Dickins 	pgoff_t start, end;
2313220f2ac9SHugh Dickins 	loff_t new_offset;
2314220f2ac9SHugh Dickins 
2315965c8e59SAndrew Morton 	if (whence != SEEK_DATA && whence != SEEK_HOLE)
2316965c8e59SAndrew Morton 		return generic_file_llseek_size(file, offset, whence,
2317220f2ac9SHugh Dickins 					MAX_LFS_FILESIZE, i_size_read(inode));
23185955102cSAl Viro 	inode_lock(inode);
2319220f2ac9SHugh Dickins 	/* We're holding i_mutex so we can access i_size directly */
2320220f2ac9SHugh Dickins 
2321220f2ac9SHugh Dickins 	if (offset < 0)
2322220f2ac9SHugh Dickins 		offset = -EINVAL;
2323220f2ac9SHugh Dickins 	else if (offset >= inode->i_size)
2324220f2ac9SHugh Dickins 		offset = -ENXIO;
2325220f2ac9SHugh Dickins 	else {
232609cbfeafSKirill A. Shutemov 		start = offset >> PAGE_SHIFT;
232709cbfeafSKirill A. Shutemov 		end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2328965c8e59SAndrew Morton 		new_offset = shmem_seek_hole_data(mapping, start, end, whence);
232909cbfeafSKirill A. Shutemov 		new_offset <<= PAGE_SHIFT;
2330220f2ac9SHugh Dickins 		if (new_offset > offset) {
2331220f2ac9SHugh Dickins 			if (new_offset < inode->i_size)
2332220f2ac9SHugh Dickins 				offset = new_offset;
2333965c8e59SAndrew Morton 			else if (whence == SEEK_DATA)
2334220f2ac9SHugh Dickins 				offset = -ENXIO;
2335220f2ac9SHugh Dickins 			else
2336220f2ac9SHugh Dickins 				offset = inode->i_size;
2337220f2ac9SHugh Dickins 		}
2338220f2ac9SHugh Dickins 	}
2339220f2ac9SHugh Dickins 
2340387aae6fSHugh Dickins 	if (offset >= 0)
234146a1c2c7SJie Liu 		offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
23425955102cSAl Viro 	inode_unlock(inode);
2343220f2ac9SHugh Dickins 	return offset;
2344220f2ac9SHugh Dickins }
2345220f2ac9SHugh Dickins 
234605f65b5cSDavid Herrmann /*
234705f65b5cSDavid Herrmann  * We need a tag: a new tag would expand every radix_tree_node by 8 bytes,
234805f65b5cSDavid Herrmann  * so reuse a tag which we firmly believe is never set or cleared on shmem.
234905f65b5cSDavid Herrmann  */
235005f65b5cSDavid Herrmann #define SHMEM_TAG_PINNED        PAGECACHE_TAG_TOWRITE
235105f65b5cSDavid Herrmann #define LAST_SCAN               4       /* about 150ms max */
235205f65b5cSDavid Herrmann 
235305f65b5cSDavid Herrmann static void shmem_tag_pins(struct address_space *mapping)
235405f65b5cSDavid Herrmann {
235505f65b5cSDavid Herrmann 	struct radix_tree_iter iter;
235605f65b5cSDavid Herrmann 	void **slot;
235705f65b5cSDavid Herrmann 	pgoff_t start;
235805f65b5cSDavid Herrmann 	struct page *page;
235905f65b5cSDavid Herrmann 
236005f65b5cSDavid Herrmann 	lru_add_drain();
236105f65b5cSDavid Herrmann 	start = 0;
236205f65b5cSDavid Herrmann 	rcu_read_lock();
236305f65b5cSDavid Herrmann 
236405f65b5cSDavid Herrmann 	radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
236505f65b5cSDavid Herrmann 		page = radix_tree_deref_slot(slot);
236605f65b5cSDavid Herrmann 		if (!page || radix_tree_exception(page)) {
23672cf938aaSMatthew Wilcox 			if (radix_tree_deref_retry(page)) {
23682cf938aaSMatthew Wilcox 				slot = radix_tree_iter_retry(&iter);
23692cf938aaSMatthew Wilcox 				continue;
23702cf938aaSMatthew Wilcox 			}
237105f65b5cSDavid Herrmann 		} else if (page_count(page) - page_mapcount(page) > 1) {
237205f65b5cSDavid Herrmann 			spin_lock_irq(&mapping->tree_lock);
237305f65b5cSDavid Herrmann 			radix_tree_tag_set(&mapping->page_tree, iter.index,
237405f65b5cSDavid Herrmann 					   SHMEM_TAG_PINNED);
237505f65b5cSDavid Herrmann 			spin_unlock_irq(&mapping->tree_lock);
237605f65b5cSDavid Herrmann 		}
237705f65b5cSDavid Herrmann 
237805f65b5cSDavid Herrmann 		if (need_resched()) {
237905f65b5cSDavid Herrmann 			cond_resched_rcu();
23807165092fSMatthew Wilcox 			slot = radix_tree_iter_next(&iter);
238105f65b5cSDavid Herrmann 		}
238205f65b5cSDavid Herrmann 	}
238305f65b5cSDavid Herrmann 	rcu_read_unlock();
238405f65b5cSDavid Herrmann }
238505f65b5cSDavid Herrmann 
238605f65b5cSDavid Herrmann /*
238705f65b5cSDavid Herrmann  * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
238805f65b5cSDavid Herrmann  * via get_user_pages(), drivers might have some pending I/O without any active
238905f65b5cSDavid Herrmann  * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
239005f65b5cSDavid Herrmann  * and see whether it has an elevated ref-count. If so, we tag them and wait for
239105f65b5cSDavid Herrmann  * them to be dropped.
239205f65b5cSDavid Herrmann  * The caller must guarantee that no new user will acquire writable references
239305f65b5cSDavid Herrmann  * to those pages to avoid races.
239405f65b5cSDavid Herrmann  */
239540e041a2SDavid Herrmann static int shmem_wait_for_pins(struct address_space *mapping)
239640e041a2SDavid Herrmann {
239705f65b5cSDavid Herrmann 	struct radix_tree_iter iter;
239805f65b5cSDavid Herrmann 	void **slot;
239905f65b5cSDavid Herrmann 	pgoff_t start;
240005f65b5cSDavid Herrmann 	struct page *page;
240105f65b5cSDavid Herrmann 	int error, scan;
240205f65b5cSDavid Herrmann 
240305f65b5cSDavid Herrmann 	shmem_tag_pins(mapping);
240405f65b5cSDavid Herrmann 
240505f65b5cSDavid Herrmann 	error = 0;
240605f65b5cSDavid Herrmann 	for (scan = 0; scan <= LAST_SCAN; scan++) {
240705f65b5cSDavid Herrmann 		if (!radix_tree_tagged(&mapping->page_tree, SHMEM_TAG_PINNED))
240805f65b5cSDavid Herrmann 			break;
240905f65b5cSDavid Herrmann 
241005f65b5cSDavid Herrmann 		if (!scan)
241105f65b5cSDavid Herrmann 			lru_add_drain_all();
241205f65b5cSDavid Herrmann 		else if (schedule_timeout_killable((HZ << scan) / 200))
241305f65b5cSDavid Herrmann 			scan = LAST_SCAN;
241405f65b5cSDavid Herrmann 
241505f65b5cSDavid Herrmann 		start = 0;
241605f65b5cSDavid Herrmann 		rcu_read_lock();
241705f65b5cSDavid Herrmann 		radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter,
241805f65b5cSDavid Herrmann 					   start, SHMEM_TAG_PINNED) {
241905f65b5cSDavid Herrmann 
242005f65b5cSDavid Herrmann 			page = radix_tree_deref_slot(slot);
242105f65b5cSDavid Herrmann 			if (radix_tree_exception(page)) {
24222cf938aaSMatthew Wilcox 				if (radix_tree_deref_retry(page)) {
24232cf938aaSMatthew Wilcox 					slot = radix_tree_iter_retry(&iter);
24242cf938aaSMatthew Wilcox 					continue;
24252cf938aaSMatthew Wilcox 				}
242605f65b5cSDavid Herrmann 
242705f65b5cSDavid Herrmann 				page = NULL;
242805f65b5cSDavid Herrmann 			}
242905f65b5cSDavid Herrmann 
243005f65b5cSDavid Herrmann 			if (page &&
243105f65b5cSDavid Herrmann 			    page_count(page) - page_mapcount(page) != 1) {
243205f65b5cSDavid Herrmann 				if (scan < LAST_SCAN)
243305f65b5cSDavid Herrmann 					goto continue_resched;
243405f65b5cSDavid Herrmann 
243505f65b5cSDavid Herrmann 				/*
243605f65b5cSDavid Herrmann 				 * On the last scan, we clean up all those tags
243705f65b5cSDavid Herrmann 				 * we inserted; but make a note that we still
243805f65b5cSDavid Herrmann 				 * found pages pinned.
243905f65b5cSDavid Herrmann 				 */
244005f65b5cSDavid Herrmann 				error = -EBUSY;
244105f65b5cSDavid Herrmann 			}
244205f65b5cSDavid Herrmann 
244305f65b5cSDavid Herrmann 			spin_lock_irq(&mapping->tree_lock);
244405f65b5cSDavid Herrmann 			radix_tree_tag_clear(&mapping->page_tree,
244505f65b5cSDavid Herrmann 					     iter.index, SHMEM_TAG_PINNED);
244605f65b5cSDavid Herrmann 			spin_unlock_irq(&mapping->tree_lock);
244705f65b5cSDavid Herrmann continue_resched:
244805f65b5cSDavid Herrmann 			if (need_resched()) {
244905f65b5cSDavid Herrmann 				cond_resched_rcu();
24507165092fSMatthew Wilcox 				slot = radix_tree_iter_next(&iter);
245105f65b5cSDavid Herrmann 			}
245205f65b5cSDavid Herrmann 		}
245305f65b5cSDavid Herrmann 		rcu_read_unlock();
245405f65b5cSDavid Herrmann 	}
245505f65b5cSDavid Herrmann 
245605f65b5cSDavid Herrmann 	return error;
245740e041a2SDavid Herrmann }
245840e041a2SDavid Herrmann 
245940e041a2SDavid Herrmann #define F_ALL_SEALS (F_SEAL_SEAL | \
246040e041a2SDavid Herrmann 		     F_SEAL_SHRINK | \
246140e041a2SDavid Herrmann 		     F_SEAL_GROW | \
246240e041a2SDavid Herrmann 		     F_SEAL_WRITE)
246340e041a2SDavid Herrmann 
246440e041a2SDavid Herrmann int shmem_add_seals(struct file *file, unsigned int seals)
246540e041a2SDavid Herrmann {
246640e041a2SDavid Herrmann 	struct inode *inode = file_inode(file);
246740e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
246840e041a2SDavid Herrmann 	int error;
246940e041a2SDavid Herrmann 
247040e041a2SDavid Herrmann 	/*
247140e041a2SDavid Herrmann 	 * SEALING
247240e041a2SDavid Herrmann 	 * Sealing allows multiple parties to share a shmem-file but restrict
247340e041a2SDavid Herrmann 	 * access to a specific subset of file operations. Seals can only be
247440e041a2SDavid Herrmann 	 * added, but never removed. This way, mutually untrusted parties can
247540e041a2SDavid Herrmann 	 * share common memory regions with a well-defined policy. A malicious
247640e041a2SDavid Herrmann 	 * peer can thus never perform unwanted operations on a shared object.
247740e041a2SDavid Herrmann 	 *
247840e041a2SDavid Herrmann 	 * Seals are only supported on special shmem-files and always affect
247940e041a2SDavid Herrmann 	 * the whole underlying inode. Once a seal is set, it may prevent some
248040e041a2SDavid Herrmann 	 * kinds of access to the file. Currently, the following seals are
248140e041a2SDavid Herrmann 	 * defined:
248240e041a2SDavid Herrmann 	 *   SEAL_SEAL: Prevent further seals from being set on this file
248340e041a2SDavid Herrmann 	 *   SEAL_SHRINK: Prevent the file from shrinking
248440e041a2SDavid Herrmann 	 *   SEAL_GROW: Prevent the file from growing
248540e041a2SDavid Herrmann 	 *   SEAL_WRITE: Prevent write access to the file
248640e041a2SDavid Herrmann 	 *
248740e041a2SDavid Herrmann 	 * As we don't require any trust relationship between two parties, we
248840e041a2SDavid Herrmann 	 * must prevent seals from being removed. Therefore, sealing a file
248940e041a2SDavid Herrmann 	 * only adds a given set of seals to the file, it never touches
249040e041a2SDavid Herrmann 	 * existing seals. Furthermore, the "setting seals"-operation can be
249140e041a2SDavid Herrmann 	 * sealed itself, which basically prevents any further seal from being
249240e041a2SDavid Herrmann 	 * added.
249340e041a2SDavid Herrmann 	 *
249440e041a2SDavid Herrmann 	 * Semantics of sealing are only defined on volatile files. Only
249540e041a2SDavid Herrmann 	 * anonymous shmem files support sealing. More importantly, seals are
249640e041a2SDavid Herrmann 	 * never written to disk. Therefore, there's no plan to support it on
249740e041a2SDavid Herrmann 	 * other file types.
249840e041a2SDavid Herrmann 	 */
249940e041a2SDavid Herrmann 
250040e041a2SDavid Herrmann 	if (file->f_op != &shmem_file_operations)
250140e041a2SDavid Herrmann 		return -EINVAL;
250240e041a2SDavid Herrmann 	if (!(file->f_mode & FMODE_WRITE))
250340e041a2SDavid Herrmann 		return -EPERM;
250440e041a2SDavid Herrmann 	if (seals & ~(unsigned int)F_ALL_SEALS)
250540e041a2SDavid Herrmann 		return -EINVAL;
250640e041a2SDavid Herrmann 
25075955102cSAl Viro 	inode_lock(inode);
250840e041a2SDavid Herrmann 
250940e041a2SDavid Herrmann 	if (info->seals & F_SEAL_SEAL) {
251040e041a2SDavid Herrmann 		error = -EPERM;
251140e041a2SDavid Herrmann 		goto unlock;
251240e041a2SDavid Herrmann 	}
251340e041a2SDavid Herrmann 
251440e041a2SDavid Herrmann 	if ((seals & F_SEAL_WRITE) && !(info->seals & F_SEAL_WRITE)) {
251540e041a2SDavid Herrmann 		error = mapping_deny_writable(file->f_mapping);
251640e041a2SDavid Herrmann 		if (error)
251740e041a2SDavid Herrmann 			goto unlock;
251840e041a2SDavid Herrmann 
251940e041a2SDavid Herrmann 		error = shmem_wait_for_pins(file->f_mapping);
252040e041a2SDavid Herrmann 		if (error) {
252140e041a2SDavid Herrmann 			mapping_allow_writable(file->f_mapping);
252240e041a2SDavid Herrmann 			goto unlock;
252340e041a2SDavid Herrmann 		}
252440e041a2SDavid Herrmann 	}
252540e041a2SDavid Herrmann 
252640e041a2SDavid Herrmann 	info->seals |= seals;
252740e041a2SDavid Herrmann 	error = 0;
252840e041a2SDavid Herrmann 
252940e041a2SDavid Herrmann unlock:
25305955102cSAl Viro 	inode_unlock(inode);
253140e041a2SDavid Herrmann 	return error;
253240e041a2SDavid Herrmann }
253340e041a2SDavid Herrmann EXPORT_SYMBOL_GPL(shmem_add_seals);
253440e041a2SDavid Herrmann 
253540e041a2SDavid Herrmann int shmem_get_seals(struct file *file)
253640e041a2SDavid Herrmann {
253740e041a2SDavid Herrmann 	if (file->f_op != &shmem_file_operations)
253840e041a2SDavid Herrmann 		return -EINVAL;
253940e041a2SDavid Herrmann 
254040e041a2SDavid Herrmann 	return SHMEM_I(file_inode(file))->seals;
254140e041a2SDavid Herrmann }
254240e041a2SDavid Herrmann EXPORT_SYMBOL_GPL(shmem_get_seals);
254340e041a2SDavid Herrmann 
254440e041a2SDavid Herrmann long shmem_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
254540e041a2SDavid Herrmann {
254640e041a2SDavid Herrmann 	long error;
254740e041a2SDavid Herrmann 
254840e041a2SDavid Herrmann 	switch (cmd) {
254940e041a2SDavid Herrmann 	case F_ADD_SEALS:
255040e041a2SDavid Herrmann 		/* disallow upper 32bit */
255140e041a2SDavid Herrmann 		if (arg > UINT_MAX)
255240e041a2SDavid Herrmann 			return -EINVAL;
255340e041a2SDavid Herrmann 
255440e041a2SDavid Herrmann 		error = shmem_add_seals(file, arg);
255540e041a2SDavid Herrmann 		break;
255640e041a2SDavid Herrmann 	case F_GET_SEALS:
255740e041a2SDavid Herrmann 		error = shmem_get_seals(file);
255840e041a2SDavid Herrmann 		break;
255940e041a2SDavid Herrmann 	default:
256040e041a2SDavid Herrmann 		error = -EINVAL;
256140e041a2SDavid Herrmann 		break;
256240e041a2SDavid Herrmann 	}
256340e041a2SDavid Herrmann 
256440e041a2SDavid Herrmann 	return error;
256540e041a2SDavid Herrmann }
256640e041a2SDavid Herrmann 
256783e4fa9cSHugh Dickins static long shmem_fallocate(struct file *file, int mode, loff_t offset,
256883e4fa9cSHugh Dickins 							 loff_t len)
256983e4fa9cSHugh Dickins {
2570496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
2571e2d12e22SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
257240e041a2SDavid Herrmann 	struct shmem_inode_info *info = SHMEM_I(inode);
25731aac1400SHugh Dickins 	struct shmem_falloc shmem_falloc;
2574e2d12e22SHugh Dickins 	pgoff_t start, index, end;
2575e2d12e22SHugh Dickins 	int error;
257683e4fa9cSHugh Dickins 
257713ace4d0SHugh Dickins 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
257813ace4d0SHugh Dickins 		return -EOPNOTSUPP;
257913ace4d0SHugh Dickins 
25805955102cSAl Viro 	inode_lock(inode);
258183e4fa9cSHugh Dickins 
258283e4fa9cSHugh Dickins 	if (mode & FALLOC_FL_PUNCH_HOLE) {
258383e4fa9cSHugh Dickins 		struct address_space *mapping = file->f_mapping;
258483e4fa9cSHugh Dickins 		loff_t unmap_start = round_up(offset, PAGE_SIZE);
258583e4fa9cSHugh Dickins 		loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
25868e205f77SHugh Dickins 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
258783e4fa9cSHugh Dickins 
258840e041a2SDavid Herrmann 		/* protected by i_mutex */
258940e041a2SDavid Herrmann 		if (info->seals & F_SEAL_WRITE) {
259040e041a2SDavid Herrmann 			error = -EPERM;
259140e041a2SDavid Herrmann 			goto out;
259240e041a2SDavid Herrmann 		}
259340e041a2SDavid Herrmann 
25948e205f77SHugh Dickins 		shmem_falloc.waitq = &shmem_falloc_waitq;
2595f00cdc6dSHugh Dickins 		shmem_falloc.start = unmap_start >> PAGE_SHIFT;
2596f00cdc6dSHugh Dickins 		shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2597f00cdc6dSHugh Dickins 		spin_lock(&inode->i_lock);
2598f00cdc6dSHugh Dickins 		inode->i_private = &shmem_falloc;
2599f00cdc6dSHugh Dickins 		spin_unlock(&inode->i_lock);
2600f00cdc6dSHugh Dickins 
260183e4fa9cSHugh Dickins 		if ((u64)unmap_end > (u64)unmap_start)
260283e4fa9cSHugh Dickins 			unmap_mapping_range(mapping, unmap_start,
260383e4fa9cSHugh Dickins 					    1 + unmap_end - unmap_start, 0);
260483e4fa9cSHugh Dickins 		shmem_truncate_range(inode, offset, offset + len - 1);
260583e4fa9cSHugh Dickins 		/* No need to unmap again: hole-punching leaves COWed pages */
26068e205f77SHugh Dickins 
26078e205f77SHugh Dickins 		spin_lock(&inode->i_lock);
26088e205f77SHugh Dickins 		inode->i_private = NULL;
26098e205f77SHugh Dickins 		wake_up_all(&shmem_falloc_waitq);
26108e205f77SHugh Dickins 		spin_unlock(&inode->i_lock);
261183e4fa9cSHugh Dickins 		error = 0;
26128e205f77SHugh Dickins 		goto out;
261383e4fa9cSHugh Dickins 	}
261483e4fa9cSHugh Dickins 
2615e2d12e22SHugh Dickins 	/* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2616e2d12e22SHugh Dickins 	error = inode_newsize_ok(inode, offset + len);
2617e2d12e22SHugh Dickins 	if (error)
2618e2d12e22SHugh Dickins 		goto out;
2619e2d12e22SHugh Dickins 
262040e041a2SDavid Herrmann 	if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
262140e041a2SDavid Herrmann 		error = -EPERM;
262240e041a2SDavid Herrmann 		goto out;
262340e041a2SDavid Herrmann 	}
262440e041a2SDavid Herrmann 
262509cbfeafSKirill A. Shutemov 	start = offset >> PAGE_SHIFT;
262609cbfeafSKirill A. Shutemov 	end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2627e2d12e22SHugh Dickins 	/* Try to avoid a swapstorm if len is impossible to satisfy */
2628e2d12e22SHugh Dickins 	if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2629e2d12e22SHugh Dickins 		error = -ENOSPC;
2630e2d12e22SHugh Dickins 		goto out;
2631e2d12e22SHugh Dickins 	}
2632e2d12e22SHugh Dickins 
26338e205f77SHugh Dickins 	shmem_falloc.waitq = NULL;
26341aac1400SHugh Dickins 	shmem_falloc.start = start;
26351aac1400SHugh Dickins 	shmem_falloc.next  = start;
26361aac1400SHugh Dickins 	shmem_falloc.nr_falloced = 0;
26371aac1400SHugh Dickins 	shmem_falloc.nr_unswapped = 0;
26381aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
26391aac1400SHugh Dickins 	inode->i_private = &shmem_falloc;
26401aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
26411aac1400SHugh Dickins 
2642e2d12e22SHugh Dickins 	for (index = start; index < end; index++) {
2643e2d12e22SHugh Dickins 		struct page *page;
2644e2d12e22SHugh Dickins 
2645e2d12e22SHugh Dickins 		/*
2646e2d12e22SHugh Dickins 		 * Good, the fallocate(2) manpage permits EINTR: we may have
2647e2d12e22SHugh Dickins 		 * been interrupted because we are using up too much memory.
2648e2d12e22SHugh Dickins 		 */
2649e2d12e22SHugh Dickins 		if (signal_pending(current))
2650e2d12e22SHugh Dickins 			error = -EINTR;
26511aac1400SHugh Dickins 		else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
26521aac1400SHugh Dickins 			error = -ENOMEM;
2653e2d12e22SHugh Dickins 		else
26549e18eb29SAndres Lagar-Cavilla 			error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2655e2d12e22SHugh Dickins 		if (error) {
26561635f6a7SHugh Dickins 			/* Remove the !PageUptodate pages we added */
26577f556567SHugh Dickins 			if (index > start) {
26581635f6a7SHugh Dickins 				shmem_undo_range(inode,
265909cbfeafSKirill A. Shutemov 				    (loff_t)start << PAGE_SHIFT,
2660b9b4bb26SAnthony Romano 				    ((loff_t)index << PAGE_SHIFT) - 1, true);
26617f556567SHugh Dickins 			}
26621aac1400SHugh Dickins 			goto undone;
2663e2d12e22SHugh Dickins 		}
2664e2d12e22SHugh Dickins 
2665e2d12e22SHugh Dickins 		/*
26661aac1400SHugh Dickins 		 * Inform shmem_writepage() how far we have reached.
26671aac1400SHugh Dickins 		 * No need for lock or barrier: we have the page lock.
26681aac1400SHugh Dickins 		 */
26691aac1400SHugh Dickins 		shmem_falloc.next++;
26701aac1400SHugh Dickins 		if (!PageUptodate(page))
26711aac1400SHugh Dickins 			shmem_falloc.nr_falloced++;
26721aac1400SHugh Dickins 
26731aac1400SHugh Dickins 		/*
26741635f6a7SHugh Dickins 		 * If !PageUptodate, leave it that way so that freeable pages
26751635f6a7SHugh Dickins 		 * can be recognized if we need to rollback on error later.
26761635f6a7SHugh Dickins 		 * But set_page_dirty so that memory pressure will swap rather
2677e2d12e22SHugh Dickins 		 * than free the pages we are allocating (and SGP_CACHE pages
2678e2d12e22SHugh Dickins 		 * might still be clean: we now need to mark those dirty too).
2679e2d12e22SHugh Dickins 		 */
2680e2d12e22SHugh Dickins 		set_page_dirty(page);
2681e2d12e22SHugh Dickins 		unlock_page(page);
268209cbfeafSKirill A. Shutemov 		put_page(page);
2683e2d12e22SHugh Dickins 		cond_resched();
2684e2d12e22SHugh Dickins 	}
2685e2d12e22SHugh Dickins 
2686e2d12e22SHugh Dickins 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2687e2d12e22SHugh Dickins 		i_size_write(inode, offset + len);
2688e2d12e22SHugh Dickins 	inode->i_ctime = CURRENT_TIME;
26891aac1400SHugh Dickins undone:
26901aac1400SHugh Dickins 	spin_lock(&inode->i_lock);
26911aac1400SHugh Dickins 	inode->i_private = NULL;
26921aac1400SHugh Dickins 	spin_unlock(&inode->i_lock);
2693e2d12e22SHugh Dickins out:
26945955102cSAl Viro 	inode_unlock(inode);
269583e4fa9cSHugh Dickins 	return error;
269683e4fa9cSHugh Dickins }
269783e4fa9cSHugh Dickins 
2698726c3342SDavid Howells static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
26991da177e4SLinus Torvalds {
2700726c3342SDavid Howells 	struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
27011da177e4SLinus Torvalds 
27021da177e4SLinus Torvalds 	buf->f_type = TMPFS_MAGIC;
270309cbfeafSKirill A. Shutemov 	buf->f_bsize = PAGE_SIZE;
27041da177e4SLinus Torvalds 	buf->f_namelen = NAME_MAX;
27050edd73b3SHugh Dickins 	if (sbinfo->max_blocks) {
27061da177e4SLinus Torvalds 		buf->f_blocks = sbinfo->max_blocks;
270741ffe5d5SHugh Dickins 		buf->f_bavail =
270841ffe5d5SHugh Dickins 		buf->f_bfree  = sbinfo->max_blocks -
270941ffe5d5SHugh Dickins 				percpu_counter_sum(&sbinfo->used_blocks);
27100edd73b3SHugh Dickins 	}
27110edd73b3SHugh Dickins 	if (sbinfo->max_inodes) {
27121da177e4SLinus Torvalds 		buf->f_files = sbinfo->max_inodes;
27131da177e4SLinus Torvalds 		buf->f_ffree = sbinfo->free_inodes;
27141da177e4SLinus Torvalds 	}
27151da177e4SLinus Torvalds 	/* else leave those fields 0 like simple_statfs */
27161da177e4SLinus Torvalds 	return 0;
27171da177e4SLinus Torvalds }
27181da177e4SLinus Torvalds 
27191da177e4SLinus Torvalds /*
27201da177e4SLinus Torvalds  * File creation. Allocate an inode, and we're done..
27211da177e4SLinus Torvalds  */
27221da177e4SLinus Torvalds static int
27231a67aafbSAl Viro shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
27241da177e4SLinus Torvalds {
27250b0a0806SHugh Dickins 	struct inode *inode;
27261da177e4SLinus Torvalds 	int error = -ENOSPC;
27271da177e4SLinus Torvalds 
2728454abafeSDmitry Monakhov 	inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
27291da177e4SLinus Torvalds 	if (inode) {
2730feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2731feda821eSChristoph Hellwig 		if (error)
2732feda821eSChristoph Hellwig 			goto out_iput;
27332a7dba39SEric Paris 		error = security_inode_init_security(inode, dir,
27349d8f13baSMimi Zohar 						     &dentry->d_name,
27356d9d88d0SJarkko Sakkinen 						     shmem_initxattrs, NULL);
2736feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2737feda821eSChristoph Hellwig 			goto out_iput;
273837ec43cdSMimi Zohar 
2739718deb6bSAl Viro 		error = 0;
27401da177e4SLinus Torvalds 		dir->i_size += BOGO_DIRENT_SIZE;
27411da177e4SLinus Torvalds 		dir->i_ctime = dir->i_mtime = CURRENT_TIME;
27421da177e4SLinus Torvalds 		d_instantiate(dentry, inode);
27431da177e4SLinus Torvalds 		dget(dentry); /* Extra count - pin the dentry in core */
27441da177e4SLinus Torvalds 	}
27451da177e4SLinus Torvalds 	return error;
2746feda821eSChristoph Hellwig out_iput:
2747feda821eSChristoph Hellwig 	iput(inode);
2748feda821eSChristoph Hellwig 	return error;
27491da177e4SLinus Torvalds }
27501da177e4SLinus Torvalds 
275160545d0dSAl Viro static int
275260545d0dSAl Viro shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
275360545d0dSAl Viro {
275460545d0dSAl Viro 	struct inode *inode;
275560545d0dSAl Viro 	int error = -ENOSPC;
275660545d0dSAl Viro 
275760545d0dSAl Viro 	inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
275860545d0dSAl Viro 	if (inode) {
275960545d0dSAl Viro 		error = security_inode_init_security(inode, dir,
276060545d0dSAl Viro 						     NULL,
276160545d0dSAl Viro 						     shmem_initxattrs, NULL);
2762feda821eSChristoph Hellwig 		if (error && error != -EOPNOTSUPP)
2763feda821eSChristoph Hellwig 			goto out_iput;
2764feda821eSChristoph Hellwig 		error = simple_acl_create(dir, inode);
2765feda821eSChristoph Hellwig 		if (error)
2766feda821eSChristoph Hellwig 			goto out_iput;
276760545d0dSAl Viro 		d_tmpfile(dentry, inode);
276860545d0dSAl Viro 	}
276960545d0dSAl Viro 	return error;
2770feda821eSChristoph Hellwig out_iput:
2771feda821eSChristoph Hellwig 	iput(inode);
2772feda821eSChristoph Hellwig 	return error;
277360545d0dSAl Viro }
277460545d0dSAl Viro 
277518bb1db3SAl Viro static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
27761da177e4SLinus Torvalds {
27771da177e4SLinus Torvalds 	int error;
27781da177e4SLinus Torvalds 
27791da177e4SLinus Torvalds 	if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
27801da177e4SLinus Torvalds 		return error;
2781d8c76e6fSDave Hansen 	inc_nlink(dir);
27821da177e4SLinus Torvalds 	return 0;
27831da177e4SLinus Torvalds }
27841da177e4SLinus Torvalds 
27854acdaf27SAl Viro static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2786ebfc3b49SAl Viro 		bool excl)
27871da177e4SLinus Torvalds {
27881da177e4SLinus Torvalds 	return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
27891da177e4SLinus Torvalds }
27901da177e4SLinus Torvalds 
27911da177e4SLinus Torvalds /*
27921da177e4SLinus Torvalds  * Link a file..
27931da177e4SLinus Torvalds  */
27941da177e4SLinus Torvalds static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
27951da177e4SLinus Torvalds {
279675c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
27975b04c689SPavel Emelyanov 	int ret;
27981da177e4SLinus Torvalds 
27991da177e4SLinus Torvalds 	/*
28001da177e4SLinus Torvalds 	 * No ordinary (disk based) filesystem counts links as inodes;
28011da177e4SLinus Torvalds 	 * but each new link needs a new dentry, pinning lowmem, and
28021da177e4SLinus Torvalds 	 * tmpfs dentries cannot be pruned until they are unlinked.
28031da177e4SLinus Torvalds 	 */
28045b04c689SPavel Emelyanov 	ret = shmem_reserve_inode(inode->i_sb);
28055b04c689SPavel Emelyanov 	if (ret)
28065b04c689SPavel Emelyanov 		goto out;
28071da177e4SLinus Torvalds 
28081da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
28091da177e4SLinus Torvalds 	inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2810d8c76e6fSDave Hansen 	inc_nlink(inode);
28117de9c6eeSAl Viro 	ihold(inode);	/* New dentry reference */
28121da177e4SLinus Torvalds 	dget(dentry);		/* Extra pinning count for the created dentry */
28131da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
28145b04c689SPavel Emelyanov out:
28155b04c689SPavel Emelyanov 	return ret;
28161da177e4SLinus Torvalds }
28171da177e4SLinus Torvalds 
28181da177e4SLinus Torvalds static int shmem_unlink(struct inode *dir, struct dentry *dentry)
28191da177e4SLinus Torvalds {
282075c3cfa8SDavid Howells 	struct inode *inode = d_inode(dentry);
28211da177e4SLinus Torvalds 
28225b04c689SPavel Emelyanov 	if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
28235b04c689SPavel Emelyanov 		shmem_free_inode(inode->i_sb);
28241da177e4SLinus Torvalds 
28251da177e4SLinus Torvalds 	dir->i_size -= BOGO_DIRENT_SIZE;
28261da177e4SLinus Torvalds 	inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
28279a53c3a7SDave Hansen 	drop_nlink(inode);
28281da177e4SLinus Torvalds 	dput(dentry);	/* Undo the count from "create" - this does all the work */
28291da177e4SLinus Torvalds 	return 0;
28301da177e4SLinus Torvalds }
28311da177e4SLinus Torvalds 
28321da177e4SLinus Torvalds static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
28331da177e4SLinus Torvalds {
28341da177e4SLinus Torvalds 	if (!simple_empty(dentry))
28351da177e4SLinus Torvalds 		return -ENOTEMPTY;
28361da177e4SLinus Torvalds 
283775c3cfa8SDavid Howells 	drop_nlink(d_inode(dentry));
28389a53c3a7SDave Hansen 	drop_nlink(dir);
28391da177e4SLinus Torvalds 	return shmem_unlink(dir, dentry);
28401da177e4SLinus Torvalds }
28411da177e4SLinus Torvalds 
284237456771SMiklos Szeredi static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
284337456771SMiklos Szeredi {
2844e36cb0b8SDavid Howells 	bool old_is_dir = d_is_dir(old_dentry);
2845e36cb0b8SDavid Howells 	bool new_is_dir = d_is_dir(new_dentry);
284637456771SMiklos Szeredi 
284737456771SMiklos Szeredi 	if (old_dir != new_dir && old_is_dir != new_is_dir) {
284837456771SMiklos Szeredi 		if (old_is_dir) {
284937456771SMiklos Szeredi 			drop_nlink(old_dir);
285037456771SMiklos Szeredi 			inc_nlink(new_dir);
285137456771SMiklos Szeredi 		} else {
285237456771SMiklos Szeredi 			drop_nlink(new_dir);
285337456771SMiklos Szeredi 			inc_nlink(old_dir);
285437456771SMiklos Szeredi 		}
285537456771SMiklos Szeredi 	}
285637456771SMiklos Szeredi 	old_dir->i_ctime = old_dir->i_mtime =
285737456771SMiklos Szeredi 	new_dir->i_ctime = new_dir->i_mtime =
285875c3cfa8SDavid Howells 	d_inode(old_dentry)->i_ctime =
285975c3cfa8SDavid Howells 	d_inode(new_dentry)->i_ctime = CURRENT_TIME;
286037456771SMiklos Szeredi 
286137456771SMiklos Szeredi 	return 0;
286237456771SMiklos Szeredi }
286337456771SMiklos Szeredi 
286446fdb794SMiklos Szeredi static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
286546fdb794SMiklos Szeredi {
286646fdb794SMiklos Szeredi 	struct dentry *whiteout;
286746fdb794SMiklos Szeredi 	int error;
286846fdb794SMiklos Szeredi 
286946fdb794SMiklos Szeredi 	whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
287046fdb794SMiklos Szeredi 	if (!whiteout)
287146fdb794SMiklos Szeredi 		return -ENOMEM;
287246fdb794SMiklos Szeredi 
287346fdb794SMiklos Szeredi 	error = shmem_mknod(old_dir, whiteout,
287446fdb794SMiklos Szeredi 			    S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
287546fdb794SMiklos Szeredi 	dput(whiteout);
287646fdb794SMiklos Szeredi 	if (error)
287746fdb794SMiklos Szeredi 		return error;
287846fdb794SMiklos Szeredi 
287946fdb794SMiklos Szeredi 	/*
288046fdb794SMiklos Szeredi 	 * Cheat and hash the whiteout while the old dentry is still in
288146fdb794SMiklos Szeredi 	 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
288246fdb794SMiklos Szeredi 	 *
288346fdb794SMiklos Szeredi 	 * d_lookup() will consistently find one of them at this point,
288446fdb794SMiklos Szeredi 	 * not sure which one, but that isn't even important.
288546fdb794SMiklos Szeredi 	 */
288646fdb794SMiklos Szeredi 	d_rehash(whiteout);
288746fdb794SMiklos Szeredi 	return 0;
288846fdb794SMiklos Szeredi }
288946fdb794SMiklos Szeredi 
28901da177e4SLinus Torvalds /*
28911da177e4SLinus Torvalds  * The VFS layer already does all the dentry stuff for rename,
28921da177e4SLinus Torvalds  * we just have to decrement the usage count for the target if
28931da177e4SLinus Torvalds  * it exists so that the VFS layer correctly free's it when it
28941da177e4SLinus Torvalds  * gets overwritten.
28951da177e4SLinus Torvalds  */
28963b69ff51SMiklos Szeredi static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
28971da177e4SLinus Torvalds {
289875c3cfa8SDavid Howells 	struct inode *inode = d_inode(old_dentry);
28991da177e4SLinus Torvalds 	int they_are_dirs = S_ISDIR(inode->i_mode);
29001da177e4SLinus Torvalds 
290146fdb794SMiklos Szeredi 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
29023b69ff51SMiklos Szeredi 		return -EINVAL;
29033b69ff51SMiklos Szeredi 
290437456771SMiklos Szeredi 	if (flags & RENAME_EXCHANGE)
290537456771SMiklos Szeredi 		return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
290637456771SMiklos Szeredi 
29071da177e4SLinus Torvalds 	if (!simple_empty(new_dentry))
29081da177e4SLinus Torvalds 		return -ENOTEMPTY;
29091da177e4SLinus Torvalds 
291046fdb794SMiklos Szeredi 	if (flags & RENAME_WHITEOUT) {
291146fdb794SMiklos Szeredi 		int error;
291246fdb794SMiklos Szeredi 
291346fdb794SMiklos Szeredi 		error = shmem_whiteout(old_dir, old_dentry);
291446fdb794SMiklos Szeredi 		if (error)
291546fdb794SMiklos Szeredi 			return error;
291646fdb794SMiklos Szeredi 	}
291746fdb794SMiklos Szeredi 
291875c3cfa8SDavid Howells 	if (d_really_is_positive(new_dentry)) {
29191da177e4SLinus Torvalds 		(void) shmem_unlink(new_dir, new_dentry);
2920b928095bSMiklos Szeredi 		if (they_are_dirs) {
292175c3cfa8SDavid Howells 			drop_nlink(d_inode(new_dentry));
29229a53c3a7SDave Hansen 			drop_nlink(old_dir);
2923b928095bSMiklos Szeredi 		}
29241da177e4SLinus Torvalds 	} else if (they_are_dirs) {
29259a53c3a7SDave Hansen 		drop_nlink(old_dir);
2926d8c76e6fSDave Hansen 		inc_nlink(new_dir);
29271da177e4SLinus Torvalds 	}
29281da177e4SLinus Torvalds 
29291da177e4SLinus Torvalds 	old_dir->i_size -= BOGO_DIRENT_SIZE;
29301da177e4SLinus Torvalds 	new_dir->i_size += BOGO_DIRENT_SIZE;
29311da177e4SLinus Torvalds 	old_dir->i_ctime = old_dir->i_mtime =
29321da177e4SLinus Torvalds 	new_dir->i_ctime = new_dir->i_mtime =
29331da177e4SLinus Torvalds 	inode->i_ctime = CURRENT_TIME;
29341da177e4SLinus Torvalds 	return 0;
29351da177e4SLinus Torvalds }
29361da177e4SLinus Torvalds 
29371da177e4SLinus Torvalds static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
29381da177e4SLinus Torvalds {
29391da177e4SLinus Torvalds 	int error;
29401da177e4SLinus Torvalds 	int len;
29411da177e4SLinus Torvalds 	struct inode *inode;
29429276aad6SHugh Dickins 	struct page *page;
29431da177e4SLinus Torvalds 	struct shmem_inode_info *info;
29441da177e4SLinus Torvalds 
29451da177e4SLinus Torvalds 	len = strlen(symname) + 1;
294609cbfeafSKirill A. Shutemov 	if (len > PAGE_SIZE)
29471da177e4SLinus Torvalds 		return -ENAMETOOLONG;
29481da177e4SLinus Torvalds 
2949454abafeSDmitry Monakhov 	inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
29501da177e4SLinus Torvalds 	if (!inode)
29511da177e4SLinus Torvalds 		return -ENOSPC;
29521da177e4SLinus Torvalds 
29539d8f13baSMimi Zohar 	error = security_inode_init_security(inode, dir, &dentry->d_name,
29546d9d88d0SJarkko Sakkinen 					     shmem_initxattrs, NULL);
2955570bc1c2SStephen Smalley 	if (error) {
2956570bc1c2SStephen Smalley 		if (error != -EOPNOTSUPP) {
2957570bc1c2SStephen Smalley 			iput(inode);
2958570bc1c2SStephen Smalley 			return error;
2959570bc1c2SStephen Smalley 		}
2960570bc1c2SStephen Smalley 		error = 0;
2961570bc1c2SStephen Smalley 	}
2962570bc1c2SStephen Smalley 
29631da177e4SLinus Torvalds 	info = SHMEM_I(inode);
29641da177e4SLinus Torvalds 	inode->i_size = len-1;
296569f07ec9SHugh Dickins 	if (len <= SHORT_SYMLINK_LEN) {
29663ed47db3SAl Viro 		inode->i_link = kmemdup(symname, len, GFP_KERNEL);
29673ed47db3SAl Viro 		if (!inode->i_link) {
296869f07ec9SHugh Dickins 			iput(inode);
296969f07ec9SHugh Dickins 			return -ENOMEM;
297069f07ec9SHugh Dickins 		}
297169f07ec9SHugh Dickins 		inode->i_op = &shmem_short_symlink_operations;
29721da177e4SLinus Torvalds 	} else {
2973e8ecde25SAl Viro 		inode_nohighmem(inode);
29749e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_WRITE);
29751da177e4SLinus Torvalds 		if (error) {
29761da177e4SLinus Torvalds 			iput(inode);
29771da177e4SLinus Torvalds 			return error;
29781da177e4SLinus Torvalds 		}
297914fcc23fSHugh Dickins 		inode->i_mapping->a_ops = &shmem_aops;
29801da177e4SLinus Torvalds 		inode->i_op = &shmem_symlink_inode_operations;
298121fc61c7SAl Viro 		memcpy(page_address(page), symname, len);
2982ec9516fbSHugh Dickins 		SetPageUptodate(page);
29831da177e4SLinus Torvalds 		set_page_dirty(page);
29846746aff7SWu Fengguang 		unlock_page(page);
298509cbfeafSKirill A. Shutemov 		put_page(page);
29861da177e4SLinus Torvalds 	}
29871da177e4SLinus Torvalds 	dir->i_size += BOGO_DIRENT_SIZE;
29881da177e4SLinus Torvalds 	dir->i_ctime = dir->i_mtime = CURRENT_TIME;
29891da177e4SLinus Torvalds 	d_instantiate(dentry, inode);
29901da177e4SLinus Torvalds 	dget(dentry);
29911da177e4SLinus Torvalds 	return 0;
29921da177e4SLinus Torvalds }
29931da177e4SLinus Torvalds 
2994fceef393SAl Viro static void shmem_put_link(void *arg)
2995fceef393SAl Viro {
2996fceef393SAl Viro 	mark_page_accessed(arg);
2997fceef393SAl Viro 	put_page(arg);
2998fceef393SAl Viro }
2999fceef393SAl Viro 
30006b255391SAl Viro static const char *shmem_get_link(struct dentry *dentry,
3001fceef393SAl Viro 				  struct inode *inode,
3002fceef393SAl Viro 				  struct delayed_call *done)
30031da177e4SLinus Torvalds {
30041da177e4SLinus Torvalds 	struct page *page = NULL;
30056b255391SAl Viro 	int error;
30066a6c9904SAl Viro 	if (!dentry) {
30076a6c9904SAl Viro 		page = find_get_page(inode->i_mapping, 0);
30086a6c9904SAl Viro 		if (!page)
30096b255391SAl Viro 			return ERR_PTR(-ECHILD);
30106a6c9904SAl Viro 		if (!PageUptodate(page)) {
30116a6c9904SAl Viro 			put_page(page);
30126a6c9904SAl Viro 			return ERR_PTR(-ECHILD);
30136a6c9904SAl Viro 		}
30146a6c9904SAl Viro 	} else {
30159e18eb29SAndres Lagar-Cavilla 		error = shmem_getpage(inode, 0, &page, SGP_READ);
3016680baacbSAl Viro 		if (error)
3017680baacbSAl Viro 			return ERR_PTR(error);
3018d3602444SHugh Dickins 		unlock_page(page);
30191da177e4SLinus Torvalds 	}
3020fceef393SAl Viro 	set_delayed_call(done, shmem_put_link, page);
302121fc61c7SAl Viro 	return page_address(page);
30221da177e4SLinus Torvalds }
30231da177e4SLinus Torvalds 
3024b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3025b09e0fa4SEric Paris /*
3026b09e0fa4SEric Paris  * Superblocks without xattr inode operations may get some security.* xattr
3027b09e0fa4SEric Paris  * support from the LSM "for free". As soon as we have any other xattrs
3028b09e0fa4SEric Paris  * like ACLs, we also need to implement the security.* handlers at
3029b09e0fa4SEric Paris  * filesystem level, though.
3030b09e0fa4SEric Paris  */
3031b09e0fa4SEric Paris 
30326d9d88d0SJarkko Sakkinen /*
30336d9d88d0SJarkko Sakkinen  * Callback for security_inode_init_security() for acquiring xattrs.
30346d9d88d0SJarkko Sakkinen  */
30356d9d88d0SJarkko Sakkinen static int shmem_initxattrs(struct inode *inode,
30366d9d88d0SJarkko Sakkinen 			    const struct xattr *xattr_array,
30376d9d88d0SJarkko Sakkinen 			    void *fs_info)
30386d9d88d0SJarkko Sakkinen {
30396d9d88d0SJarkko Sakkinen 	struct shmem_inode_info *info = SHMEM_I(inode);
30406d9d88d0SJarkko Sakkinen 	const struct xattr *xattr;
304138f38657SAristeu Rozanski 	struct simple_xattr *new_xattr;
30426d9d88d0SJarkko Sakkinen 	size_t len;
30436d9d88d0SJarkko Sakkinen 
30446d9d88d0SJarkko Sakkinen 	for (xattr = xattr_array; xattr->name != NULL; xattr++) {
304538f38657SAristeu Rozanski 		new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
30466d9d88d0SJarkko Sakkinen 		if (!new_xattr)
30476d9d88d0SJarkko Sakkinen 			return -ENOMEM;
30486d9d88d0SJarkko Sakkinen 
30496d9d88d0SJarkko Sakkinen 		len = strlen(xattr->name) + 1;
30506d9d88d0SJarkko Sakkinen 		new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
30516d9d88d0SJarkko Sakkinen 					  GFP_KERNEL);
30526d9d88d0SJarkko Sakkinen 		if (!new_xattr->name) {
30536d9d88d0SJarkko Sakkinen 			kfree(new_xattr);
30546d9d88d0SJarkko Sakkinen 			return -ENOMEM;
30556d9d88d0SJarkko Sakkinen 		}
30566d9d88d0SJarkko Sakkinen 
30576d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
30586d9d88d0SJarkko Sakkinen 		       XATTR_SECURITY_PREFIX_LEN);
30596d9d88d0SJarkko Sakkinen 		memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
30606d9d88d0SJarkko Sakkinen 		       xattr->name, len);
30616d9d88d0SJarkko Sakkinen 
306238f38657SAristeu Rozanski 		simple_xattr_list_add(&info->xattrs, new_xattr);
30636d9d88d0SJarkko Sakkinen 	}
30646d9d88d0SJarkko Sakkinen 
30656d9d88d0SJarkko Sakkinen 	return 0;
30666d9d88d0SJarkko Sakkinen }
30676d9d88d0SJarkko Sakkinen 
3068aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3069b296821aSAl Viro 				   struct dentry *unused, struct inode *inode,
3070b296821aSAl Viro 				   const char *name, void *buffer, size_t size)
3071aa7c5241SAndreas Gruenbacher {
3072b296821aSAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3073aa7c5241SAndreas Gruenbacher 
3074aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3075aa7c5241SAndreas Gruenbacher 	return simple_xattr_get(&info->xattrs, name, buffer, size);
3076aa7c5241SAndreas Gruenbacher }
3077aa7c5241SAndreas Gruenbacher 
3078aa7c5241SAndreas Gruenbacher static int shmem_xattr_handler_set(const struct xattr_handler *handler,
307959301226SAl Viro 				   struct dentry *unused, struct inode *inode,
308059301226SAl Viro 				   const char *name, const void *value,
308159301226SAl Viro 				   size_t size, int flags)
3082aa7c5241SAndreas Gruenbacher {
308359301226SAl Viro 	struct shmem_inode_info *info = SHMEM_I(inode);
3084aa7c5241SAndreas Gruenbacher 
3085aa7c5241SAndreas Gruenbacher 	name = xattr_full_name(handler, name);
3086aa7c5241SAndreas Gruenbacher 	return simple_xattr_set(&info->xattrs, name, value, size, flags);
3087aa7c5241SAndreas Gruenbacher }
3088aa7c5241SAndreas Gruenbacher 
3089aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_security_xattr_handler = {
3090aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_SECURITY_PREFIX,
3091aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3092aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3093aa7c5241SAndreas Gruenbacher };
3094aa7c5241SAndreas Gruenbacher 
3095aa7c5241SAndreas Gruenbacher static const struct xattr_handler shmem_trusted_xattr_handler = {
3096aa7c5241SAndreas Gruenbacher 	.prefix = XATTR_TRUSTED_PREFIX,
3097aa7c5241SAndreas Gruenbacher 	.get = shmem_xattr_handler_get,
3098aa7c5241SAndreas Gruenbacher 	.set = shmem_xattr_handler_set,
3099aa7c5241SAndreas Gruenbacher };
3100aa7c5241SAndreas Gruenbacher 
3101b09e0fa4SEric Paris static const struct xattr_handler *shmem_xattr_handlers[] = {
3102b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
3103feda821eSChristoph Hellwig 	&posix_acl_access_xattr_handler,
3104feda821eSChristoph Hellwig 	&posix_acl_default_xattr_handler,
3105b09e0fa4SEric Paris #endif
3106aa7c5241SAndreas Gruenbacher 	&shmem_security_xattr_handler,
3107aa7c5241SAndreas Gruenbacher 	&shmem_trusted_xattr_handler,
3108b09e0fa4SEric Paris 	NULL
3109b09e0fa4SEric Paris };
3110b09e0fa4SEric Paris 
3111b09e0fa4SEric Paris static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3112b09e0fa4SEric Paris {
311375c3cfa8SDavid Howells 	struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3114786534b9SAndreas Gruenbacher 	return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3115b09e0fa4SEric Paris }
3116b09e0fa4SEric Paris #endif /* CONFIG_TMPFS_XATTR */
3117b09e0fa4SEric Paris 
311869f07ec9SHugh Dickins static const struct inode_operations shmem_short_symlink_operations = {
31191da177e4SLinus Torvalds 	.readlink	= generic_readlink,
31206b255391SAl Viro 	.get_link	= simple_get_link,
3121b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3122aa7c5241SAndreas Gruenbacher 	.setxattr	= generic_setxattr,
3123aa7c5241SAndreas Gruenbacher 	.getxattr	= generic_getxattr,
3124b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3125aa7c5241SAndreas Gruenbacher 	.removexattr	= generic_removexattr,
3126b09e0fa4SEric Paris #endif
31271da177e4SLinus Torvalds };
31281da177e4SLinus Torvalds 
312992e1d5beSArjan van de Ven static const struct inode_operations shmem_symlink_inode_operations = {
31301da177e4SLinus Torvalds 	.readlink	= generic_readlink,
31316b255391SAl Viro 	.get_link	= shmem_get_link,
3132b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3133aa7c5241SAndreas Gruenbacher 	.setxattr	= generic_setxattr,
3134aa7c5241SAndreas Gruenbacher 	.getxattr	= generic_getxattr,
3135b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3136aa7c5241SAndreas Gruenbacher 	.removexattr	= generic_removexattr,
313739f0247dSAndreas Gruenbacher #endif
3138b09e0fa4SEric Paris };
313939f0247dSAndreas Gruenbacher 
314091828a40SDavid M. Grimes static struct dentry *shmem_get_parent(struct dentry *child)
314191828a40SDavid M. Grimes {
314291828a40SDavid M. Grimes 	return ERR_PTR(-ESTALE);
314391828a40SDavid M. Grimes }
314491828a40SDavid M. Grimes 
314591828a40SDavid M. Grimes static int shmem_match(struct inode *ino, void *vfh)
314691828a40SDavid M. Grimes {
314791828a40SDavid M. Grimes 	__u32 *fh = vfh;
314891828a40SDavid M. Grimes 	__u64 inum = fh[2];
314991828a40SDavid M. Grimes 	inum = (inum << 32) | fh[1];
315091828a40SDavid M. Grimes 	return ino->i_ino == inum && fh[0] == ino->i_generation;
315191828a40SDavid M. Grimes }
315291828a40SDavid M. Grimes 
3153480b116cSChristoph Hellwig static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3154480b116cSChristoph Hellwig 		struct fid *fid, int fh_len, int fh_type)
315591828a40SDavid M. Grimes {
315691828a40SDavid M. Grimes 	struct inode *inode;
3157480b116cSChristoph Hellwig 	struct dentry *dentry = NULL;
315835c2a7f4SHugh Dickins 	u64 inum;
315991828a40SDavid M. Grimes 
3160480b116cSChristoph Hellwig 	if (fh_len < 3)
3161480b116cSChristoph Hellwig 		return NULL;
3162480b116cSChristoph Hellwig 
316335c2a7f4SHugh Dickins 	inum = fid->raw[2];
316435c2a7f4SHugh Dickins 	inum = (inum << 32) | fid->raw[1];
316535c2a7f4SHugh Dickins 
3166480b116cSChristoph Hellwig 	inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3167480b116cSChristoph Hellwig 			shmem_match, fid->raw);
316891828a40SDavid M. Grimes 	if (inode) {
3169480b116cSChristoph Hellwig 		dentry = d_find_alias(inode);
317091828a40SDavid M. Grimes 		iput(inode);
317191828a40SDavid M. Grimes 	}
317291828a40SDavid M. Grimes 
3173480b116cSChristoph Hellwig 	return dentry;
317491828a40SDavid M. Grimes }
317591828a40SDavid M. Grimes 
3176b0b0382bSAl Viro static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3177b0b0382bSAl Viro 				struct inode *parent)
317891828a40SDavid M. Grimes {
31795fe0c237SAneesh Kumar K.V 	if (*len < 3) {
31805fe0c237SAneesh Kumar K.V 		*len = 3;
318194e07a75SNamjae Jeon 		return FILEID_INVALID;
31825fe0c237SAneesh Kumar K.V 	}
318391828a40SDavid M. Grimes 
31841d3382cbSAl Viro 	if (inode_unhashed(inode)) {
318591828a40SDavid M. Grimes 		/* Unfortunately insert_inode_hash is not idempotent,
318691828a40SDavid M. Grimes 		 * so as we hash inodes here rather than at creation
318791828a40SDavid M. Grimes 		 * time, we need a lock to ensure we only try
318891828a40SDavid M. Grimes 		 * to do it once
318991828a40SDavid M. Grimes 		 */
319091828a40SDavid M. Grimes 		static DEFINE_SPINLOCK(lock);
319191828a40SDavid M. Grimes 		spin_lock(&lock);
31921d3382cbSAl Viro 		if (inode_unhashed(inode))
319391828a40SDavid M. Grimes 			__insert_inode_hash(inode,
319491828a40SDavid M. Grimes 					    inode->i_ino + inode->i_generation);
319591828a40SDavid M. Grimes 		spin_unlock(&lock);
319691828a40SDavid M. Grimes 	}
319791828a40SDavid M. Grimes 
319891828a40SDavid M. Grimes 	fh[0] = inode->i_generation;
319991828a40SDavid M. Grimes 	fh[1] = inode->i_ino;
320091828a40SDavid M. Grimes 	fh[2] = ((__u64)inode->i_ino) >> 32;
320191828a40SDavid M. Grimes 
320291828a40SDavid M. Grimes 	*len = 3;
320391828a40SDavid M. Grimes 	return 1;
320491828a40SDavid M. Grimes }
320591828a40SDavid M. Grimes 
320639655164SChristoph Hellwig static const struct export_operations shmem_export_ops = {
320791828a40SDavid M. Grimes 	.get_parent     = shmem_get_parent,
320891828a40SDavid M. Grimes 	.encode_fh      = shmem_encode_fh,
3209480b116cSChristoph Hellwig 	.fh_to_dentry	= shmem_fh_to_dentry,
321091828a40SDavid M. Grimes };
321191828a40SDavid M. Grimes 
3212680d794bSakpm@linux-foundation.org static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
3213680d794bSakpm@linux-foundation.org 			       bool remount)
32141da177e4SLinus Torvalds {
32151da177e4SLinus Torvalds 	char *this_char, *value, *rest;
321649cd0a5cSGreg Thelen 	struct mempolicy *mpol = NULL;
32178751e039SEric W. Biederman 	uid_t uid;
32188751e039SEric W. Biederman 	gid_t gid;
32191da177e4SLinus Torvalds 
3220b00dc3adSHugh Dickins 	while (options != NULL) {
3221b00dc3adSHugh Dickins 		this_char = options;
3222b00dc3adSHugh Dickins 		for (;;) {
3223b00dc3adSHugh Dickins 			/*
3224b00dc3adSHugh Dickins 			 * NUL-terminate this option: unfortunately,
3225b00dc3adSHugh Dickins 			 * mount options form a comma-separated list,
3226b00dc3adSHugh Dickins 			 * but mpol's nodelist may also contain commas.
3227b00dc3adSHugh Dickins 			 */
3228b00dc3adSHugh Dickins 			options = strchr(options, ',');
3229b00dc3adSHugh Dickins 			if (options == NULL)
3230b00dc3adSHugh Dickins 				break;
3231b00dc3adSHugh Dickins 			options++;
3232b00dc3adSHugh Dickins 			if (!isdigit(*options)) {
3233b00dc3adSHugh Dickins 				options[-1] = '\0';
3234b00dc3adSHugh Dickins 				break;
3235b00dc3adSHugh Dickins 			}
3236b00dc3adSHugh Dickins 		}
32371da177e4SLinus Torvalds 		if (!*this_char)
32381da177e4SLinus Torvalds 			continue;
32391da177e4SLinus Torvalds 		if ((value = strchr(this_char,'=')) != NULL) {
32401da177e4SLinus Torvalds 			*value++ = 0;
32411da177e4SLinus Torvalds 		} else {
32421170532bSJoe Perches 			pr_err("tmpfs: No value for mount option '%s'\n",
32431da177e4SLinus Torvalds 			       this_char);
324449cd0a5cSGreg Thelen 			goto error;
32451da177e4SLinus Torvalds 		}
32461da177e4SLinus Torvalds 
32471da177e4SLinus Torvalds 		if (!strcmp(this_char,"size")) {
32481da177e4SLinus Torvalds 			unsigned long long size;
32491da177e4SLinus Torvalds 			size = memparse(value,&rest);
32501da177e4SLinus Torvalds 			if (*rest == '%') {
32511da177e4SLinus Torvalds 				size <<= PAGE_SHIFT;
32521da177e4SLinus Torvalds 				size *= totalram_pages;
32531da177e4SLinus Torvalds 				do_div(size, 100);
32541da177e4SLinus Torvalds 				rest++;
32551da177e4SLinus Torvalds 			}
32561da177e4SLinus Torvalds 			if (*rest)
32571da177e4SLinus Torvalds 				goto bad_val;
3258680d794bSakpm@linux-foundation.org 			sbinfo->max_blocks =
325909cbfeafSKirill A. Shutemov 				DIV_ROUND_UP(size, PAGE_SIZE);
32601da177e4SLinus Torvalds 		} else if (!strcmp(this_char,"nr_blocks")) {
3261680d794bSakpm@linux-foundation.org 			sbinfo->max_blocks = memparse(value, &rest);
32621da177e4SLinus Torvalds 			if (*rest)
32631da177e4SLinus Torvalds 				goto bad_val;
32641da177e4SLinus Torvalds 		} else if (!strcmp(this_char,"nr_inodes")) {
3265680d794bSakpm@linux-foundation.org 			sbinfo->max_inodes = memparse(value, &rest);
32661da177e4SLinus Torvalds 			if (*rest)
32671da177e4SLinus Torvalds 				goto bad_val;
32681da177e4SLinus Torvalds 		} else if (!strcmp(this_char,"mode")) {
3269680d794bSakpm@linux-foundation.org 			if (remount)
32701da177e4SLinus Torvalds 				continue;
3271680d794bSakpm@linux-foundation.org 			sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
32721da177e4SLinus Torvalds 			if (*rest)
32731da177e4SLinus Torvalds 				goto bad_val;
32741da177e4SLinus Torvalds 		} else if (!strcmp(this_char,"uid")) {
3275680d794bSakpm@linux-foundation.org 			if (remount)
32761da177e4SLinus Torvalds 				continue;
32778751e039SEric W. Biederman 			uid = simple_strtoul(value, &rest, 0);
32781da177e4SLinus Torvalds 			if (*rest)
32791da177e4SLinus Torvalds 				goto bad_val;
32808751e039SEric W. Biederman 			sbinfo->uid = make_kuid(current_user_ns(), uid);
32818751e039SEric W. Biederman 			if (!uid_valid(sbinfo->uid))
32828751e039SEric W. Biederman 				goto bad_val;
32831da177e4SLinus Torvalds 		} else if (!strcmp(this_char,"gid")) {
3284680d794bSakpm@linux-foundation.org 			if (remount)
32851da177e4SLinus Torvalds 				continue;
32868751e039SEric W. Biederman 			gid = simple_strtoul(value, &rest, 0);
32871da177e4SLinus Torvalds 			if (*rest)
32881da177e4SLinus Torvalds 				goto bad_val;
32898751e039SEric W. Biederman 			sbinfo->gid = make_kgid(current_user_ns(), gid);
32908751e039SEric W. Biederman 			if (!gid_valid(sbinfo->gid))
32918751e039SEric W. Biederman 				goto bad_val;
32925a6e75f8SKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGEPAGE
32935a6e75f8SKirill A. Shutemov 		} else if (!strcmp(this_char, "huge")) {
32945a6e75f8SKirill A. Shutemov 			int huge;
32955a6e75f8SKirill A. Shutemov 			huge = shmem_parse_huge(value);
32965a6e75f8SKirill A. Shutemov 			if (huge < 0)
32975a6e75f8SKirill A. Shutemov 				goto bad_val;
32985a6e75f8SKirill A. Shutemov 			if (!has_transparent_hugepage() &&
32995a6e75f8SKirill A. Shutemov 					huge != SHMEM_HUGE_NEVER)
33005a6e75f8SKirill A. Shutemov 				goto bad_val;
33015a6e75f8SKirill A. Shutemov 			sbinfo->huge = huge;
33025a6e75f8SKirill A. Shutemov #endif
33035a6e75f8SKirill A. Shutemov #ifdef CONFIG_NUMA
33047339ff83SRobin Holt 		} else if (!strcmp(this_char,"mpol")) {
330549cd0a5cSGreg Thelen 			mpol_put(mpol);
330649cd0a5cSGreg Thelen 			mpol = NULL;
330749cd0a5cSGreg Thelen 			if (mpol_parse_str(value, &mpol))
33087339ff83SRobin Holt 				goto bad_val;
33095a6e75f8SKirill A. Shutemov #endif
33101da177e4SLinus Torvalds 		} else {
33111170532bSJoe Perches 			pr_err("tmpfs: Bad mount option %s\n", this_char);
331249cd0a5cSGreg Thelen 			goto error;
33131da177e4SLinus Torvalds 		}
33141da177e4SLinus Torvalds 	}
331549cd0a5cSGreg Thelen 	sbinfo->mpol = mpol;
33161da177e4SLinus Torvalds 	return 0;
33171da177e4SLinus Torvalds 
33181da177e4SLinus Torvalds bad_val:
33191170532bSJoe Perches 	pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
33201da177e4SLinus Torvalds 	       value, this_char);
332149cd0a5cSGreg Thelen error:
332249cd0a5cSGreg Thelen 	mpol_put(mpol);
33231da177e4SLinus Torvalds 	return 1;
33241da177e4SLinus Torvalds 
33251da177e4SLinus Torvalds }
33261da177e4SLinus Torvalds 
33271da177e4SLinus Torvalds static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
33281da177e4SLinus Torvalds {
33291da177e4SLinus Torvalds 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3330680d794bSakpm@linux-foundation.org 	struct shmem_sb_info config = *sbinfo;
33310edd73b3SHugh Dickins 	unsigned long inodes;
33320edd73b3SHugh Dickins 	int error = -EINVAL;
33331da177e4SLinus Torvalds 
33345f00110fSGreg Thelen 	config.mpol = NULL;
3335680d794bSakpm@linux-foundation.org 	if (shmem_parse_options(data, &config, true))
33360edd73b3SHugh Dickins 		return error;
33370edd73b3SHugh Dickins 
33380edd73b3SHugh Dickins 	spin_lock(&sbinfo->stat_lock);
33390edd73b3SHugh Dickins 	inodes = sbinfo->max_inodes - sbinfo->free_inodes;
33407e496299STim Chen 	if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
33410edd73b3SHugh Dickins 		goto out;
3342680d794bSakpm@linux-foundation.org 	if (config.max_inodes < inodes)
33430edd73b3SHugh Dickins 		goto out;
33440edd73b3SHugh Dickins 	/*
334554af6042SHugh Dickins 	 * Those tests disallow limited->unlimited while any are in use;
33460edd73b3SHugh Dickins 	 * but we must separately disallow unlimited->limited, because
33470edd73b3SHugh Dickins 	 * in that case we have no record of how much is already in use.
33480edd73b3SHugh Dickins 	 */
3349680d794bSakpm@linux-foundation.org 	if (config.max_blocks && !sbinfo->max_blocks)
33500edd73b3SHugh Dickins 		goto out;
3351680d794bSakpm@linux-foundation.org 	if (config.max_inodes && !sbinfo->max_inodes)
33520edd73b3SHugh Dickins 		goto out;
33530edd73b3SHugh Dickins 
33540edd73b3SHugh Dickins 	error = 0;
33555a6e75f8SKirill A. Shutemov 	sbinfo->huge = config.huge;
3356680d794bSakpm@linux-foundation.org 	sbinfo->max_blocks  = config.max_blocks;
3357680d794bSakpm@linux-foundation.org 	sbinfo->max_inodes  = config.max_inodes;
3358680d794bSakpm@linux-foundation.org 	sbinfo->free_inodes = config.max_inodes - inodes;
335971fe804bSLee Schermerhorn 
33605f00110fSGreg Thelen 	/*
33615f00110fSGreg Thelen 	 * Preserve previous mempolicy unless mpol remount option was specified.
33625f00110fSGreg Thelen 	 */
33635f00110fSGreg Thelen 	if (config.mpol) {
336471fe804bSLee Schermerhorn 		mpol_put(sbinfo->mpol);
336571fe804bSLee Schermerhorn 		sbinfo->mpol = config.mpol;	/* transfers initial ref */
33665f00110fSGreg Thelen 	}
33670edd73b3SHugh Dickins out:
33680edd73b3SHugh Dickins 	spin_unlock(&sbinfo->stat_lock);
33690edd73b3SHugh Dickins 	return error;
33701da177e4SLinus Torvalds }
3371680d794bSakpm@linux-foundation.org 
337234c80b1dSAl Viro static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3373680d794bSakpm@linux-foundation.org {
337434c80b1dSAl Viro 	struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3375680d794bSakpm@linux-foundation.org 
3376680d794bSakpm@linux-foundation.org 	if (sbinfo->max_blocks != shmem_default_max_blocks())
3377680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",size=%luk",
337809cbfeafSKirill A. Shutemov 			sbinfo->max_blocks << (PAGE_SHIFT - 10));
3379680d794bSakpm@linux-foundation.org 	if (sbinfo->max_inodes != shmem_default_max_inodes())
3380680d794bSakpm@linux-foundation.org 		seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3381680d794bSakpm@linux-foundation.org 	if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
338209208d15SAl Viro 		seq_printf(seq, ",mode=%03ho", sbinfo->mode);
33838751e039SEric W. Biederman 	if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
33848751e039SEric W. Biederman 		seq_printf(seq, ",uid=%u",
33858751e039SEric W. Biederman 				from_kuid_munged(&init_user_ns, sbinfo->uid));
33868751e039SEric W. Biederman 	if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
33878751e039SEric W. Biederman 		seq_printf(seq, ",gid=%u",
33888751e039SEric W. Biederman 				from_kgid_munged(&init_user_ns, sbinfo->gid));
33895a6e75f8SKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGEPAGE
33905a6e75f8SKirill A. Shutemov 	/* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
33915a6e75f8SKirill A. Shutemov 	if (sbinfo->huge)
33925a6e75f8SKirill A. Shutemov 		seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
33935a6e75f8SKirill A. Shutemov #endif
339471fe804bSLee Schermerhorn 	shmem_show_mpol(seq, sbinfo->mpol);
3395680d794bSakpm@linux-foundation.org 	return 0;
3396680d794bSakpm@linux-foundation.org }
33979183df25SDavid Herrmann 
33989183df25SDavid Herrmann #define MFD_NAME_PREFIX "memfd:"
33999183df25SDavid Herrmann #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
34009183df25SDavid Herrmann #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
34019183df25SDavid Herrmann 
34029183df25SDavid Herrmann #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING)
34039183df25SDavid Herrmann 
34049183df25SDavid Herrmann SYSCALL_DEFINE2(memfd_create,
34059183df25SDavid Herrmann 		const char __user *, uname,
34069183df25SDavid Herrmann 		unsigned int, flags)
34079183df25SDavid Herrmann {
34089183df25SDavid Herrmann 	struct shmem_inode_info *info;
34099183df25SDavid Herrmann 	struct file *file;
34109183df25SDavid Herrmann 	int fd, error;
34119183df25SDavid Herrmann 	char *name;
34129183df25SDavid Herrmann 	long len;
34139183df25SDavid Herrmann 
34149183df25SDavid Herrmann 	if (flags & ~(unsigned int)MFD_ALL_FLAGS)
34159183df25SDavid Herrmann 		return -EINVAL;
34169183df25SDavid Herrmann 
34179183df25SDavid Herrmann 	/* length includes terminating zero */
34189183df25SDavid Herrmann 	len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
34199183df25SDavid Herrmann 	if (len <= 0)
34209183df25SDavid Herrmann 		return -EFAULT;
34219183df25SDavid Herrmann 	if (len > MFD_NAME_MAX_LEN + 1)
34229183df25SDavid Herrmann 		return -EINVAL;
34239183df25SDavid Herrmann 
34249183df25SDavid Herrmann 	name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_TEMPORARY);
34259183df25SDavid Herrmann 	if (!name)
34269183df25SDavid Herrmann 		return -ENOMEM;
34279183df25SDavid Herrmann 
34289183df25SDavid Herrmann 	strcpy(name, MFD_NAME_PREFIX);
34299183df25SDavid Herrmann 	if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
34309183df25SDavid Herrmann 		error = -EFAULT;
34319183df25SDavid Herrmann 		goto err_name;
34329183df25SDavid Herrmann 	}
34339183df25SDavid Herrmann 
34349183df25SDavid Herrmann 	/* terminating-zero may have changed after strnlen_user() returned */
34359183df25SDavid Herrmann 	if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
34369183df25SDavid Herrmann 		error = -EFAULT;
34379183df25SDavid Herrmann 		goto err_name;
34389183df25SDavid Herrmann 	}
34399183df25SDavid Herrmann 
34409183df25SDavid Herrmann 	fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
34419183df25SDavid Herrmann 	if (fd < 0) {
34429183df25SDavid Herrmann 		error = fd;
34439183df25SDavid Herrmann 		goto err_name;
34449183df25SDavid Herrmann 	}
34459183df25SDavid Herrmann 
34469183df25SDavid Herrmann 	file = shmem_file_setup(name, 0, VM_NORESERVE);
34479183df25SDavid Herrmann 	if (IS_ERR(file)) {
34489183df25SDavid Herrmann 		error = PTR_ERR(file);
34499183df25SDavid Herrmann 		goto err_fd;
34509183df25SDavid Herrmann 	}
34519183df25SDavid Herrmann 	info = SHMEM_I(file_inode(file));
34529183df25SDavid Herrmann 	file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
34539183df25SDavid Herrmann 	file->f_flags |= O_RDWR | O_LARGEFILE;
34549183df25SDavid Herrmann 	if (flags & MFD_ALLOW_SEALING)
34559183df25SDavid Herrmann 		info->seals &= ~F_SEAL_SEAL;
34569183df25SDavid Herrmann 
34579183df25SDavid Herrmann 	fd_install(fd, file);
34589183df25SDavid Herrmann 	kfree(name);
34599183df25SDavid Herrmann 	return fd;
34609183df25SDavid Herrmann 
34619183df25SDavid Herrmann err_fd:
34629183df25SDavid Herrmann 	put_unused_fd(fd);
34639183df25SDavid Herrmann err_name:
34649183df25SDavid Herrmann 	kfree(name);
34659183df25SDavid Herrmann 	return error;
34669183df25SDavid Herrmann }
34679183df25SDavid Herrmann 
3468680d794bSakpm@linux-foundation.org #endif /* CONFIG_TMPFS */
34691da177e4SLinus Torvalds 
34701da177e4SLinus Torvalds static void shmem_put_super(struct super_block *sb)
34711da177e4SLinus Torvalds {
3472602586a8SHugh Dickins 	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3473602586a8SHugh Dickins 
3474602586a8SHugh Dickins 	percpu_counter_destroy(&sbinfo->used_blocks);
347549cd0a5cSGreg Thelen 	mpol_put(sbinfo->mpol);
3476602586a8SHugh Dickins 	kfree(sbinfo);
34771da177e4SLinus Torvalds 	sb->s_fs_info = NULL;
34781da177e4SLinus Torvalds }
34791da177e4SLinus Torvalds 
34802b2af54aSKay Sievers int shmem_fill_super(struct super_block *sb, void *data, int silent)
34811da177e4SLinus Torvalds {
34821da177e4SLinus Torvalds 	struct inode *inode;
34830edd73b3SHugh Dickins 	struct shmem_sb_info *sbinfo;
3484680d794bSakpm@linux-foundation.org 	int err = -ENOMEM;
3485680d794bSakpm@linux-foundation.org 
3486680d794bSakpm@linux-foundation.org 	/* Round up to L1_CACHE_BYTES to resist false sharing */
3487425fbf04SPekka Enberg 	sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3488680d794bSakpm@linux-foundation.org 				L1_CACHE_BYTES), GFP_KERNEL);
3489680d794bSakpm@linux-foundation.org 	if (!sbinfo)
3490680d794bSakpm@linux-foundation.org 		return -ENOMEM;
3491680d794bSakpm@linux-foundation.org 
3492680d794bSakpm@linux-foundation.org 	sbinfo->mode = S_IRWXUGO | S_ISVTX;
349376aac0e9SDavid Howells 	sbinfo->uid = current_fsuid();
349476aac0e9SDavid Howells 	sbinfo->gid = current_fsgid();
3495680d794bSakpm@linux-foundation.org 	sb->s_fs_info = sbinfo;
34961da177e4SLinus Torvalds 
34970edd73b3SHugh Dickins #ifdef CONFIG_TMPFS
34981da177e4SLinus Torvalds 	/*
34991da177e4SLinus Torvalds 	 * Per default we only allow half of the physical ram per
35001da177e4SLinus Torvalds 	 * tmpfs instance, limiting inodes to one per page of lowmem;
35011da177e4SLinus Torvalds 	 * but the internal instance is left unlimited.
35021da177e4SLinus Torvalds 	 */
3503ca4e0519SAl Viro 	if (!(sb->s_flags & MS_KERNMOUNT)) {
3504680d794bSakpm@linux-foundation.org 		sbinfo->max_blocks = shmem_default_max_blocks();
3505680d794bSakpm@linux-foundation.org 		sbinfo->max_inodes = shmem_default_max_inodes();
3506680d794bSakpm@linux-foundation.org 		if (shmem_parse_options(data, sbinfo, false)) {
3507680d794bSakpm@linux-foundation.org 			err = -EINVAL;
3508680d794bSakpm@linux-foundation.org 			goto failed;
3509680d794bSakpm@linux-foundation.org 		}
3510ca4e0519SAl Viro 	} else {
3511ca4e0519SAl Viro 		sb->s_flags |= MS_NOUSER;
35121da177e4SLinus Torvalds 	}
351391828a40SDavid M. Grimes 	sb->s_export_op = &shmem_export_ops;
35142f6e38f3SHugh Dickins 	sb->s_flags |= MS_NOSEC;
35150edd73b3SHugh Dickins #else
35160edd73b3SHugh Dickins 	sb->s_flags |= MS_NOUSER;
35170edd73b3SHugh Dickins #endif
35181da177e4SLinus Torvalds 
35191da177e4SLinus Torvalds 	spin_lock_init(&sbinfo->stat_lock);
3520908c7f19STejun Heo 	if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3521602586a8SHugh Dickins 		goto failed;
3522680d794bSakpm@linux-foundation.org 	sbinfo->free_inodes = sbinfo->max_inodes;
35231da177e4SLinus Torvalds 
3524285b2c4fSHugh Dickins 	sb->s_maxbytes = MAX_LFS_FILESIZE;
352509cbfeafSKirill A. Shutemov 	sb->s_blocksize = PAGE_SIZE;
352609cbfeafSKirill A. Shutemov 	sb->s_blocksize_bits = PAGE_SHIFT;
35271da177e4SLinus Torvalds 	sb->s_magic = TMPFS_MAGIC;
35281da177e4SLinus Torvalds 	sb->s_op = &shmem_ops;
3529cfd95a9cSRobin H. Johnson 	sb->s_time_gran = 1;
3530b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
353139f0247dSAndreas Gruenbacher 	sb->s_xattr = shmem_xattr_handlers;
3532b09e0fa4SEric Paris #endif
3533b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_POSIX_ACL
353439f0247dSAndreas Gruenbacher 	sb->s_flags |= MS_POSIXACL;
353539f0247dSAndreas Gruenbacher #endif
35360edd73b3SHugh Dickins 
3537454abafeSDmitry Monakhov 	inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
35381da177e4SLinus Torvalds 	if (!inode)
35391da177e4SLinus Torvalds 		goto failed;
3540680d794bSakpm@linux-foundation.org 	inode->i_uid = sbinfo->uid;
3541680d794bSakpm@linux-foundation.org 	inode->i_gid = sbinfo->gid;
3542318ceed0SAl Viro 	sb->s_root = d_make_root(inode);
3543318ceed0SAl Viro 	if (!sb->s_root)
354448fde701SAl Viro 		goto failed;
35451da177e4SLinus Torvalds 	return 0;
35461da177e4SLinus Torvalds 
35471da177e4SLinus Torvalds failed:
35481da177e4SLinus Torvalds 	shmem_put_super(sb);
35491da177e4SLinus Torvalds 	return err;
35501da177e4SLinus Torvalds }
35511da177e4SLinus Torvalds 
3552fcc234f8SPekka Enberg static struct kmem_cache *shmem_inode_cachep;
35531da177e4SLinus Torvalds 
35541da177e4SLinus Torvalds static struct inode *shmem_alloc_inode(struct super_block *sb)
35551da177e4SLinus Torvalds {
355641ffe5d5SHugh Dickins 	struct shmem_inode_info *info;
355741ffe5d5SHugh Dickins 	info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
355841ffe5d5SHugh Dickins 	if (!info)
35591da177e4SLinus Torvalds 		return NULL;
356041ffe5d5SHugh Dickins 	return &info->vfs_inode;
35611da177e4SLinus Torvalds }
35621da177e4SLinus Torvalds 
356341ffe5d5SHugh Dickins static void shmem_destroy_callback(struct rcu_head *head)
3564fa0d7e3dSNick Piggin {
3565fa0d7e3dSNick Piggin 	struct inode *inode = container_of(head, struct inode, i_rcu);
356684e710daSAl Viro 	if (S_ISLNK(inode->i_mode))
35673ed47db3SAl Viro 		kfree(inode->i_link);
3568fa0d7e3dSNick Piggin 	kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3569fa0d7e3dSNick Piggin }
3570fa0d7e3dSNick Piggin 
35711da177e4SLinus Torvalds static void shmem_destroy_inode(struct inode *inode)
35721da177e4SLinus Torvalds {
357309208d15SAl Viro 	if (S_ISREG(inode->i_mode))
35741da177e4SLinus Torvalds 		mpol_free_shared_policy(&SHMEM_I(inode)->policy);
357541ffe5d5SHugh Dickins 	call_rcu(&inode->i_rcu, shmem_destroy_callback);
35761da177e4SLinus Torvalds }
35771da177e4SLinus Torvalds 
357841ffe5d5SHugh Dickins static void shmem_init_inode(void *foo)
35791da177e4SLinus Torvalds {
358041ffe5d5SHugh Dickins 	struct shmem_inode_info *info = foo;
358141ffe5d5SHugh Dickins 	inode_init_once(&info->vfs_inode);
35821da177e4SLinus Torvalds }
35831da177e4SLinus Torvalds 
358441ffe5d5SHugh Dickins static int shmem_init_inodecache(void)
35851da177e4SLinus Torvalds {
35861da177e4SLinus Torvalds 	shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
35871da177e4SLinus Torvalds 				sizeof(struct shmem_inode_info),
35885d097056SVladimir Davydov 				0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
35891da177e4SLinus Torvalds 	return 0;
35901da177e4SLinus Torvalds }
35911da177e4SLinus Torvalds 
359241ffe5d5SHugh Dickins static void shmem_destroy_inodecache(void)
35931da177e4SLinus Torvalds {
35941a1d92c1SAlexey Dobriyan 	kmem_cache_destroy(shmem_inode_cachep);
35951da177e4SLinus Torvalds }
35961da177e4SLinus Torvalds 
3597f5e54d6eSChristoph Hellwig static const struct address_space_operations shmem_aops = {
35981da177e4SLinus Torvalds 	.writepage	= shmem_writepage,
359976719325SKen Chen 	.set_page_dirty	= __set_page_dirty_no_writeback,
36001da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3601800d15a5SNick Piggin 	.write_begin	= shmem_write_begin,
3602800d15a5SNick Piggin 	.write_end	= shmem_write_end,
36031da177e4SLinus Torvalds #endif
36041c93923cSAndrew Morton #ifdef CONFIG_MIGRATION
3605304dbdb7SLee Schermerhorn 	.migratepage	= migrate_page,
36061c93923cSAndrew Morton #endif
3607aa261f54SAndi Kleen 	.error_remove_page = generic_error_remove_page,
36081da177e4SLinus Torvalds };
36091da177e4SLinus Torvalds 
361015ad7cdcSHelge Deller static const struct file_operations shmem_file_operations = {
36111da177e4SLinus Torvalds 	.mmap		= shmem_mmap,
3612c01d5b30SHugh Dickins 	.get_unmapped_area = shmem_get_unmapped_area,
36131da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
3614220f2ac9SHugh Dickins 	.llseek		= shmem_file_llseek,
36152ba5bbedSAl Viro 	.read_iter	= shmem_file_read_iter,
36168174202bSAl Viro 	.write_iter	= generic_file_write_iter,
36171b061d92SChristoph Hellwig 	.fsync		= noop_fsync,
3618708e3508SHugh Dickins 	.splice_read	= shmem_file_splice_read,
3619f6cb85d0SAl Viro 	.splice_write	= iter_file_splice_write,
362083e4fa9cSHugh Dickins 	.fallocate	= shmem_fallocate,
36211da177e4SLinus Torvalds #endif
36221da177e4SLinus Torvalds };
36231da177e4SLinus Torvalds 
362492e1d5beSArjan van de Ven static const struct inode_operations shmem_inode_operations = {
362544a30220SYu Zhao 	.getattr	= shmem_getattr,
362694c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3627b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3628aa7c5241SAndreas Gruenbacher 	.setxattr	= generic_setxattr,
3629aa7c5241SAndreas Gruenbacher 	.getxattr	= generic_getxattr,
3630b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3631aa7c5241SAndreas Gruenbacher 	.removexattr	= generic_removexattr,
3632feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
3633b09e0fa4SEric Paris #endif
36341da177e4SLinus Torvalds };
36351da177e4SLinus Torvalds 
363692e1d5beSArjan van de Ven static const struct inode_operations shmem_dir_inode_operations = {
36371da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
36381da177e4SLinus Torvalds 	.create		= shmem_create,
36391da177e4SLinus Torvalds 	.lookup		= simple_lookup,
36401da177e4SLinus Torvalds 	.link		= shmem_link,
36411da177e4SLinus Torvalds 	.unlink		= shmem_unlink,
36421da177e4SLinus Torvalds 	.symlink	= shmem_symlink,
36431da177e4SLinus Torvalds 	.mkdir		= shmem_mkdir,
36441da177e4SLinus Torvalds 	.rmdir		= shmem_rmdir,
36451da177e4SLinus Torvalds 	.mknod		= shmem_mknod,
36463b69ff51SMiklos Szeredi 	.rename2	= shmem_rename2,
364760545d0dSAl Viro 	.tmpfile	= shmem_tmpfile,
36481da177e4SLinus Torvalds #endif
3649b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3650aa7c5241SAndreas Gruenbacher 	.setxattr	= generic_setxattr,
3651aa7c5241SAndreas Gruenbacher 	.getxattr	= generic_getxattr,
3652b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3653aa7c5241SAndreas Gruenbacher 	.removexattr	= generic_removexattr,
3654b09e0fa4SEric Paris #endif
365539f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
365694c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3657feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
365839f0247dSAndreas Gruenbacher #endif
365939f0247dSAndreas Gruenbacher };
366039f0247dSAndreas Gruenbacher 
366192e1d5beSArjan van de Ven static const struct inode_operations shmem_special_inode_operations = {
3662b09e0fa4SEric Paris #ifdef CONFIG_TMPFS_XATTR
3663aa7c5241SAndreas Gruenbacher 	.setxattr	= generic_setxattr,
3664aa7c5241SAndreas Gruenbacher 	.getxattr	= generic_getxattr,
3665b09e0fa4SEric Paris 	.listxattr	= shmem_listxattr,
3666aa7c5241SAndreas Gruenbacher 	.removexattr	= generic_removexattr,
3667b09e0fa4SEric Paris #endif
366839f0247dSAndreas Gruenbacher #ifdef CONFIG_TMPFS_POSIX_ACL
366994c1e62dSHugh Dickins 	.setattr	= shmem_setattr,
3670feda821eSChristoph Hellwig 	.set_acl	= simple_set_acl,
367139f0247dSAndreas Gruenbacher #endif
36721da177e4SLinus Torvalds };
36731da177e4SLinus Torvalds 
3674759b9775SHugh Dickins static const struct super_operations shmem_ops = {
36751da177e4SLinus Torvalds 	.alloc_inode	= shmem_alloc_inode,
36761da177e4SLinus Torvalds 	.destroy_inode	= shmem_destroy_inode,
36771da177e4SLinus Torvalds #ifdef CONFIG_TMPFS
36781da177e4SLinus Torvalds 	.statfs		= shmem_statfs,
36791da177e4SLinus Torvalds 	.remount_fs	= shmem_remount_fs,
3680680d794bSakpm@linux-foundation.org 	.show_options	= shmem_show_options,
36811da177e4SLinus Torvalds #endif
36821f895f75SAl Viro 	.evict_inode	= shmem_evict_inode,
36831da177e4SLinus Torvalds 	.drop_inode	= generic_delete_inode,
36841da177e4SLinus Torvalds 	.put_super	= shmem_put_super,
36851da177e4SLinus Torvalds };
36861da177e4SLinus Torvalds 
3687f0f37e2fSAlexey Dobriyan static const struct vm_operations_struct shmem_vm_ops = {
368854cb8821SNick Piggin 	.fault		= shmem_fault,
3689d7c17551SNing Qu 	.map_pages	= filemap_map_pages,
36901da177e4SLinus Torvalds #ifdef CONFIG_NUMA
36911da177e4SLinus Torvalds 	.set_policy     = shmem_set_policy,
36921da177e4SLinus Torvalds 	.get_policy     = shmem_get_policy,
36931da177e4SLinus Torvalds #endif
36941da177e4SLinus Torvalds };
36951da177e4SLinus Torvalds 
36963c26ff6eSAl Viro static struct dentry *shmem_mount(struct file_system_type *fs_type,
36973c26ff6eSAl Viro 	int flags, const char *dev_name, void *data)
36981da177e4SLinus Torvalds {
36993c26ff6eSAl Viro 	return mount_nodev(fs_type, flags, data, shmem_fill_super);
37001da177e4SLinus Torvalds }
37011da177e4SLinus Torvalds 
370241ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
37031da177e4SLinus Torvalds 	.owner		= THIS_MODULE,
37041da177e4SLinus Torvalds 	.name		= "tmpfs",
37053c26ff6eSAl Viro 	.mount		= shmem_mount,
37061da177e4SLinus Torvalds 	.kill_sb	= kill_litter_super,
37072b8576cbSEric W. Biederman 	.fs_flags	= FS_USERNS_MOUNT,
37081da177e4SLinus Torvalds };
37091da177e4SLinus Torvalds 
371041ffe5d5SHugh Dickins int __init shmem_init(void)
37111da177e4SLinus Torvalds {
37121da177e4SLinus Torvalds 	int error;
37131da177e4SLinus Torvalds 
371416203a7aSRob Landley 	/* If rootfs called this, don't re-init */
371516203a7aSRob Landley 	if (shmem_inode_cachep)
371616203a7aSRob Landley 		return 0;
371716203a7aSRob Landley 
371841ffe5d5SHugh Dickins 	error = shmem_init_inodecache();
37191da177e4SLinus Torvalds 	if (error)
37201da177e4SLinus Torvalds 		goto out3;
37211da177e4SLinus Torvalds 
372241ffe5d5SHugh Dickins 	error = register_filesystem(&shmem_fs_type);
37231da177e4SLinus Torvalds 	if (error) {
37241170532bSJoe Perches 		pr_err("Could not register tmpfs\n");
37251da177e4SLinus Torvalds 		goto out2;
37261da177e4SLinus Torvalds 	}
372795dc112aSGreg Kroah-Hartman 
3728ca4e0519SAl Viro 	shm_mnt = kern_mount(&shmem_fs_type);
37291da177e4SLinus Torvalds 	if (IS_ERR(shm_mnt)) {
37301da177e4SLinus Torvalds 		error = PTR_ERR(shm_mnt);
37311170532bSJoe Perches 		pr_err("Could not kern_mount tmpfs\n");
37321da177e4SLinus Torvalds 		goto out1;
37331da177e4SLinus Torvalds 	}
37345a6e75f8SKirill A. Shutemov 
37355a6e75f8SKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGEPAGE
37365a6e75f8SKirill A. Shutemov 	if (has_transparent_hugepage() && shmem_huge < SHMEM_HUGE_DENY)
37375a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
37385a6e75f8SKirill A. Shutemov 	else
37395a6e75f8SKirill A. Shutemov 		shmem_huge = 0; /* just in case it was patched */
37405a6e75f8SKirill A. Shutemov #endif
37411da177e4SLinus Torvalds 	return 0;
37421da177e4SLinus Torvalds 
37431da177e4SLinus Torvalds out1:
374441ffe5d5SHugh Dickins 	unregister_filesystem(&shmem_fs_type);
37451da177e4SLinus Torvalds out2:
374641ffe5d5SHugh Dickins 	shmem_destroy_inodecache();
37471da177e4SLinus Torvalds out3:
37481da177e4SLinus Torvalds 	shm_mnt = ERR_PTR(error);
37491da177e4SLinus Torvalds 	return error;
37501da177e4SLinus Torvalds }
3751853ac43aSMatt Mackall 
37525a6e75f8SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
37535a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_show(struct kobject *kobj,
37545a6e75f8SKirill A. Shutemov 		struct kobj_attribute *attr, char *buf)
37555a6e75f8SKirill A. Shutemov {
37565a6e75f8SKirill A. Shutemov 	int values[] = {
37575a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ALWAYS,
37585a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_WITHIN_SIZE,
37595a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_ADVISE,
37605a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_NEVER,
37615a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_DENY,
37625a6e75f8SKirill A. Shutemov 		SHMEM_HUGE_FORCE,
37635a6e75f8SKirill A. Shutemov 	};
37645a6e75f8SKirill A. Shutemov 	int i, count;
37655a6e75f8SKirill A. Shutemov 
37665a6e75f8SKirill A. Shutemov 	for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
37675a6e75f8SKirill A. Shutemov 		const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
37685a6e75f8SKirill A. Shutemov 
37695a6e75f8SKirill A. Shutemov 		count += sprintf(buf + count, fmt,
37705a6e75f8SKirill A. Shutemov 				shmem_format_huge(values[i]));
37715a6e75f8SKirill A. Shutemov 	}
37725a6e75f8SKirill A. Shutemov 	buf[count - 1] = '\n';
37735a6e75f8SKirill A. Shutemov 	return count;
37745a6e75f8SKirill A. Shutemov }
37755a6e75f8SKirill A. Shutemov 
37765a6e75f8SKirill A. Shutemov static ssize_t shmem_enabled_store(struct kobject *kobj,
37775a6e75f8SKirill A. Shutemov 		struct kobj_attribute *attr, const char *buf, size_t count)
37785a6e75f8SKirill A. Shutemov {
37795a6e75f8SKirill A. Shutemov 	char tmp[16];
37805a6e75f8SKirill A. Shutemov 	int huge;
37815a6e75f8SKirill A. Shutemov 
37825a6e75f8SKirill A. Shutemov 	if (count + 1 > sizeof(tmp))
37835a6e75f8SKirill A. Shutemov 		return -EINVAL;
37845a6e75f8SKirill A. Shutemov 	memcpy(tmp, buf, count);
37855a6e75f8SKirill A. Shutemov 	tmp[count] = '\0';
37865a6e75f8SKirill A. Shutemov 	if (count && tmp[count - 1] == '\n')
37875a6e75f8SKirill A. Shutemov 		tmp[count - 1] = '\0';
37885a6e75f8SKirill A. Shutemov 
37895a6e75f8SKirill A. Shutemov 	huge = shmem_parse_huge(tmp);
37905a6e75f8SKirill A. Shutemov 	if (huge == -EINVAL)
37915a6e75f8SKirill A. Shutemov 		return -EINVAL;
37925a6e75f8SKirill A. Shutemov 	if (!has_transparent_hugepage() &&
37935a6e75f8SKirill A. Shutemov 			huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
37945a6e75f8SKirill A. Shutemov 		return -EINVAL;
37955a6e75f8SKirill A. Shutemov 
37965a6e75f8SKirill A. Shutemov 	shmem_huge = huge;
37975a6e75f8SKirill A. Shutemov 	if (shmem_huge < SHMEM_HUGE_DENY)
37985a6e75f8SKirill A. Shutemov 		SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
37995a6e75f8SKirill A. Shutemov 	return count;
38005a6e75f8SKirill A. Shutemov }
38015a6e75f8SKirill A. Shutemov 
38025a6e75f8SKirill A. Shutemov struct kobj_attribute shmem_enabled_attr =
38035a6e75f8SKirill A. Shutemov 	__ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
38045a6e75f8SKirill A. Shutemov #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
38055a6e75f8SKirill A. Shutemov 
3806853ac43aSMatt Mackall #else /* !CONFIG_SHMEM */
3807853ac43aSMatt Mackall 
3808853ac43aSMatt Mackall /*
3809853ac43aSMatt Mackall  * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3810853ac43aSMatt Mackall  *
3811853ac43aSMatt Mackall  * This is intended for small system where the benefits of the full
3812853ac43aSMatt Mackall  * shmem code (swap-backed and resource-limited) are outweighed by
3813853ac43aSMatt Mackall  * their complexity. On systems without swap this code should be
3814853ac43aSMatt Mackall  * effectively equivalent, but much lighter weight.
3815853ac43aSMatt Mackall  */
3816853ac43aSMatt Mackall 
381741ffe5d5SHugh Dickins static struct file_system_type shmem_fs_type = {
3818853ac43aSMatt Mackall 	.name		= "tmpfs",
38193c26ff6eSAl Viro 	.mount		= ramfs_mount,
3820853ac43aSMatt Mackall 	.kill_sb	= kill_litter_super,
38212b8576cbSEric W. Biederman 	.fs_flags	= FS_USERNS_MOUNT,
3822853ac43aSMatt Mackall };
3823853ac43aSMatt Mackall 
382441ffe5d5SHugh Dickins int __init shmem_init(void)
3825853ac43aSMatt Mackall {
382641ffe5d5SHugh Dickins 	BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3827853ac43aSMatt Mackall 
382841ffe5d5SHugh Dickins 	shm_mnt = kern_mount(&shmem_fs_type);
3829853ac43aSMatt Mackall 	BUG_ON(IS_ERR(shm_mnt));
3830853ac43aSMatt Mackall 
3831853ac43aSMatt Mackall 	return 0;
3832853ac43aSMatt Mackall }
3833853ac43aSMatt Mackall 
383441ffe5d5SHugh Dickins int shmem_unuse(swp_entry_t swap, struct page *page)
3835853ac43aSMatt Mackall {
3836853ac43aSMatt Mackall 	return 0;
3837853ac43aSMatt Mackall }
3838853ac43aSMatt Mackall 
38393f96b79aSHugh Dickins int shmem_lock(struct file *file, int lock, struct user_struct *user)
38403f96b79aSHugh Dickins {
38413f96b79aSHugh Dickins 	return 0;
38423f96b79aSHugh Dickins }
38433f96b79aSHugh Dickins 
384424513264SHugh Dickins void shmem_unlock_mapping(struct address_space *mapping)
384524513264SHugh Dickins {
384624513264SHugh Dickins }
384724513264SHugh Dickins 
3848c01d5b30SHugh Dickins #ifdef CONFIG_MMU
3849c01d5b30SHugh Dickins unsigned long shmem_get_unmapped_area(struct file *file,
3850c01d5b30SHugh Dickins 				      unsigned long addr, unsigned long len,
3851c01d5b30SHugh Dickins 				      unsigned long pgoff, unsigned long flags)
3852c01d5b30SHugh Dickins {
3853c01d5b30SHugh Dickins 	return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
3854c01d5b30SHugh Dickins }
3855c01d5b30SHugh Dickins #endif
3856c01d5b30SHugh Dickins 
385741ffe5d5SHugh Dickins void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
385894c1e62dSHugh Dickins {
385941ffe5d5SHugh Dickins 	truncate_inode_pages_range(inode->i_mapping, lstart, lend);
386094c1e62dSHugh Dickins }
386194c1e62dSHugh Dickins EXPORT_SYMBOL_GPL(shmem_truncate_range);
386294c1e62dSHugh Dickins 
3863853ac43aSMatt Mackall #define shmem_vm_ops				generic_file_vm_ops
38640b0a0806SHugh Dickins #define shmem_file_operations			ramfs_file_operations
3865454abafeSDmitry Monakhov #define shmem_get_inode(sb, dir, mode, dev, flags)	ramfs_get_inode(sb, dir, mode, dev)
38660b0a0806SHugh Dickins #define shmem_acct_size(flags, size)		0
38670b0a0806SHugh Dickins #define shmem_unacct_size(flags, size)		do {} while (0)
3868853ac43aSMatt Mackall 
3869853ac43aSMatt Mackall #endif /* CONFIG_SHMEM */
3870853ac43aSMatt Mackall 
3871853ac43aSMatt Mackall /* common code */
38721da177e4SLinus Torvalds 
38733451538aSAl Viro static struct dentry_operations anon_ops = {
3874118b2302SAl Viro 	.d_dname = simple_dname
38753451538aSAl Viro };
38763451538aSAl Viro 
3877c7277090SEric Paris static struct file *__shmem_file_setup(const char *name, loff_t size,
3878c7277090SEric Paris 				       unsigned long flags, unsigned int i_flags)
38791da177e4SLinus Torvalds {
38806b4d0b27SAl Viro 	struct file *res;
38811da177e4SLinus Torvalds 	struct inode *inode;
38822c48b9c4SAl Viro 	struct path path;
38833451538aSAl Viro 	struct super_block *sb;
38841da177e4SLinus Torvalds 	struct qstr this;
38851da177e4SLinus Torvalds 
38861da177e4SLinus Torvalds 	if (IS_ERR(shm_mnt))
38876b4d0b27SAl Viro 		return ERR_CAST(shm_mnt);
38881da177e4SLinus Torvalds 
3889285b2c4fSHugh Dickins 	if (size < 0 || size > MAX_LFS_FILESIZE)
38901da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
38911da177e4SLinus Torvalds 
38921da177e4SLinus Torvalds 	if (shmem_acct_size(flags, size))
38931da177e4SLinus Torvalds 		return ERR_PTR(-ENOMEM);
38941da177e4SLinus Torvalds 
38956b4d0b27SAl Viro 	res = ERR_PTR(-ENOMEM);
38961da177e4SLinus Torvalds 	this.name = name;
38971da177e4SLinus Torvalds 	this.len = strlen(name);
38981da177e4SLinus Torvalds 	this.hash = 0; /* will go */
38993451538aSAl Viro 	sb = shm_mnt->mnt_sb;
390066ee4b88SKonstantin Khlebnikov 	path.mnt = mntget(shm_mnt);
39013451538aSAl Viro 	path.dentry = d_alloc_pseudo(sb, &this);
39022c48b9c4SAl Viro 	if (!path.dentry)
39031da177e4SLinus Torvalds 		goto put_memory;
39043451538aSAl Viro 	d_set_d_op(path.dentry, &anon_ops);
39051da177e4SLinus Torvalds 
39066b4d0b27SAl Viro 	res = ERR_PTR(-ENOSPC);
39073451538aSAl Viro 	inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
39081da177e4SLinus Torvalds 	if (!inode)
390966ee4b88SKonstantin Khlebnikov 		goto put_memory;
39101da177e4SLinus Torvalds 
3911c7277090SEric Paris 	inode->i_flags |= i_flags;
39122c48b9c4SAl Viro 	d_instantiate(path.dentry, inode);
39131da177e4SLinus Torvalds 	inode->i_size = size;
39146d6b77f1SMiklos Szeredi 	clear_nlink(inode);	/* It is unlinked */
391526567cdbSAl Viro 	res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
391626567cdbSAl Viro 	if (IS_ERR(res))
391766ee4b88SKonstantin Khlebnikov 		goto put_path;
39184b42af81SAl Viro 
39196b4d0b27SAl Viro 	res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
39204b42af81SAl Viro 		  &shmem_file_operations);
39216b4d0b27SAl Viro 	if (IS_ERR(res))
392266ee4b88SKonstantin Khlebnikov 		goto put_path;
39234b42af81SAl Viro 
39246b4d0b27SAl Viro 	return res;
39251da177e4SLinus Torvalds 
39261da177e4SLinus Torvalds put_memory:
39271da177e4SLinus Torvalds 	shmem_unacct_size(flags, size);
392866ee4b88SKonstantin Khlebnikov put_path:
392966ee4b88SKonstantin Khlebnikov 	path_put(&path);
39306b4d0b27SAl Viro 	return res;
39311da177e4SLinus Torvalds }
3932c7277090SEric Paris 
3933c7277090SEric Paris /**
3934c7277090SEric Paris  * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
3935c7277090SEric Paris  * 	kernel internal.  There will be NO LSM permission checks against the
3936c7277090SEric Paris  * 	underlying inode.  So users of this interface must do LSM checks at a
3937e1832f29SStephen Smalley  *	higher layer.  The users are the big_key and shm implementations.  LSM
3938e1832f29SStephen Smalley  *	checks are provided at the key or shm level rather than the inode.
3939c7277090SEric Paris  * @name: name for dentry (to be seen in /proc/<pid>/maps
3940c7277090SEric Paris  * @size: size to be set for the file
3941c7277090SEric Paris  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3942c7277090SEric Paris  */
3943c7277090SEric Paris struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
3944c7277090SEric Paris {
3945c7277090SEric Paris 	return __shmem_file_setup(name, size, flags, S_PRIVATE);
3946c7277090SEric Paris }
3947c7277090SEric Paris 
3948c7277090SEric Paris /**
3949c7277090SEric Paris  * shmem_file_setup - get an unlinked file living in tmpfs
3950c7277090SEric Paris  * @name: name for dentry (to be seen in /proc/<pid>/maps
3951c7277090SEric Paris  * @size: size to be set for the file
3952c7277090SEric Paris  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3953c7277090SEric Paris  */
3954c7277090SEric Paris struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
3955c7277090SEric Paris {
3956c7277090SEric Paris 	return __shmem_file_setup(name, size, flags, 0);
3957c7277090SEric Paris }
3958395e0ddcSKeith Packard EXPORT_SYMBOL_GPL(shmem_file_setup);
39591da177e4SLinus Torvalds 
396046711810SRandy Dunlap /**
39611da177e4SLinus Torvalds  * shmem_zero_setup - setup a shared anonymous mapping
39621da177e4SLinus Torvalds  * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
39631da177e4SLinus Torvalds  */
39641da177e4SLinus Torvalds int shmem_zero_setup(struct vm_area_struct *vma)
39651da177e4SLinus Torvalds {
39661da177e4SLinus Torvalds 	struct file *file;
39671da177e4SLinus Torvalds 	loff_t size = vma->vm_end - vma->vm_start;
39681da177e4SLinus Torvalds 
396966fc1303SHugh Dickins 	/*
397066fc1303SHugh Dickins 	 * Cloning a new file under mmap_sem leads to a lock ordering conflict
397166fc1303SHugh Dickins 	 * between XFS directory reading and selinux: since this file is only
397266fc1303SHugh Dickins 	 * accessible to the user through its mapping, use S_PRIVATE flag to
397366fc1303SHugh Dickins 	 * bypass file security, in the same way as shmem_kernel_file_setup().
397466fc1303SHugh Dickins 	 */
397566fc1303SHugh Dickins 	file = __shmem_file_setup("dev/zero", size, vma->vm_flags, S_PRIVATE);
39761da177e4SLinus Torvalds 	if (IS_ERR(file))
39771da177e4SLinus Torvalds 		return PTR_ERR(file);
39781da177e4SLinus Torvalds 
39791da177e4SLinus Torvalds 	if (vma->vm_file)
39801da177e4SLinus Torvalds 		fput(vma->vm_file);
39811da177e4SLinus Torvalds 	vma->vm_file = file;
39821da177e4SLinus Torvalds 	vma->vm_ops = &shmem_vm_ops;
39831da177e4SLinus Torvalds 	return 0;
39841da177e4SLinus Torvalds }
3985d9d90e5eSHugh Dickins 
3986d9d90e5eSHugh Dickins /**
3987d9d90e5eSHugh Dickins  * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
3988d9d90e5eSHugh Dickins  * @mapping:	the page's address_space
3989d9d90e5eSHugh Dickins  * @index:	the page index
3990d9d90e5eSHugh Dickins  * @gfp:	the page allocator flags to use if allocating
3991d9d90e5eSHugh Dickins  *
3992d9d90e5eSHugh Dickins  * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
3993d9d90e5eSHugh Dickins  * with any new page allocations done using the specified allocation flags.
3994d9d90e5eSHugh Dickins  * But read_cache_page_gfp() uses the ->readpage() method: which does not
3995d9d90e5eSHugh Dickins  * suit tmpfs, since it may have pages in swapcache, and needs to find those
3996d9d90e5eSHugh Dickins  * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
3997d9d90e5eSHugh Dickins  *
399868da9f05SHugh Dickins  * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
399968da9f05SHugh Dickins  * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4000d9d90e5eSHugh Dickins  */
4001d9d90e5eSHugh Dickins struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4002d9d90e5eSHugh Dickins 					 pgoff_t index, gfp_t gfp)
4003d9d90e5eSHugh Dickins {
400468da9f05SHugh Dickins #ifdef CONFIG_SHMEM
400568da9f05SHugh Dickins 	struct inode *inode = mapping->host;
40069276aad6SHugh Dickins 	struct page *page;
400768da9f05SHugh Dickins 	int error;
400868da9f05SHugh Dickins 
400968da9f05SHugh Dickins 	BUG_ON(mapping->a_ops != &shmem_aops);
40109e18eb29SAndres Lagar-Cavilla 	error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
40119e18eb29SAndres Lagar-Cavilla 				  gfp, NULL, NULL);
401268da9f05SHugh Dickins 	if (error)
401368da9f05SHugh Dickins 		page = ERR_PTR(error);
401468da9f05SHugh Dickins 	else
401568da9f05SHugh Dickins 		unlock_page(page);
401668da9f05SHugh Dickins 	return page;
401768da9f05SHugh Dickins #else
401868da9f05SHugh Dickins 	/*
401968da9f05SHugh Dickins 	 * The tiny !SHMEM case uses ramfs without swap
402068da9f05SHugh Dickins 	 */
4021d9d90e5eSHugh Dickins 	return read_cache_page_gfp(mapping, index, gfp);
402268da9f05SHugh Dickins #endif
4023d9d90e5eSHugh Dickins }
4024d9d90e5eSHugh Dickins EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
4025