]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - mm/shmem.c
UBUNTU: SAUCE: Import aufs driver
[mirror_ubuntu-hirsute-kernel.git] / mm / shmem.c
CommitLineData
1da177e4
LT
1/*
2 * Resizable virtual memory filesystem for Linux.
3 *
4 * Copyright (C) 2000 Linus Torvalds.
5 * 2000 Transmeta Corp.
6 * 2000-2001 Christoph Rohland
7 * 2000-2001 SAP AG
8 * 2002 Red Hat Inc.
6922c0c7
HD
9 * Copyright (C) 2002-2011 Hugh Dickins.
10 * Copyright (C) 2011 Google Inc.
0edd73b3 11 * Copyright (C) 2002-2005 VERITAS Software Corporation.
1da177e4
LT
12 * Copyright (C) 2004 Andi Kleen, SuSE Labs
13 *
14 * Extended attribute support for tmpfs:
15 * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
16 * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
17 *
853ac43a
MM
18 * tiny-shmem:
19 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
20 *
1da177e4
LT
21 * This file is released under the GPL.
22 */
23
853ac43a
MM
24#include <linux/fs.h>
25#include <linux/init.h>
26#include <linux/vfs.h>
27#include <linux/mount.h>
250297ed 28#include <linux/ramfs.h>
caefba17 29#include <linux/pagemap.h>
853ac43a
MM
30#include <linux/file.h>
31#include <linux/mm.h>
46c9a946 32#include <linux/random.h>
174cd4b1 33#include <linux/sched/signal.h>
b95f1b31 34#include <linux/export.h>
853ac43a 35#include <linux/swap.h>
e2e40f2c 36#include <linux/uio.h>
f3f0e1d2 37#include <linux/khugepaged.h>
749df87b 38#include <linux/hugetlb.h>
b56a2d8a 39#include <linux/frontswap.h>
626c3920 40#include <linux/fs_parser.h>
853ac43a 41
95cc09d6
AA
42#include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
43
853ac43a
MM
44static struct vfsmount *shm_mnt;
45
46#ifdef CONFIG_SHMEM
1da177e4
LT
47/*
48 * This virtual memory filesystem is heavily based on the ramfs. It
49 * extends ramfs by the ability to use swap and honor resource limits
50 * which makes it a completely usable filesystem.
51 */
52
39f0247d 53#include <linux/xattr.h>
a5694255 54#include <linux/exportfs.h>
1c7c474c 55#include <linux/posix_acl.h>
feda821e 56#include <linux/posix_acl_xattr.h>
1da177e4 57#include <linux/mman.h>
1da177e4
LT
58#include <linux/string.h>
59#include <linux/slab.h>
60#include <linux/backing-dev.h>
61#include <linux/shmem_fs.h>
1da177e4 62#include <linux/writeback.h>
1da177e4 63#include <linux/blkdev.h>
bda97eab 64#include <linux/pagevec.h>
41ffe5d5 65#include <linux/percpu_counter.h>
83e4fa9c 66#include <linux/falloc.h>
708e3508 67#include <linux/splice.h>
1da177e4
LT
68#include <linux/security.h>
69#include <linux/swapops.h>
70#include <linux/mempolicy.h>
71#include <linux/namei.h>
b00dc3ad 72#include <linux/ctype.h>
304dbdb7 73#include <linux/migrate.h>
c1f60a5a 74#include <linux/highmem.h>
680d794b 75#include <linux/seq_file.h>
92562927 76#include <linux/magic.h>
9183df25 77#include <linux/syscalls.h>
40e041a2 78#include <linux/fcntl.h>
9183df25 79#include <uapi/linux/memfd.h>
cfda0526 80#include <linux/userfaultfd_k.h>
4c27fe4c 81#include <linux/rmap.h>
2b4db796 82#include <linux/uuid.h>
304dbdb7 83
7c0f6ba6 84#include <linux/uaccess.h>
1da177e4 85
dd56b046
MG
86#include "internal.h"
87
09cbfeaf
KS
88#define BLOCKS_PER_PAGE (PAGE_SIZE/512)
89#define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
1da177e4 90
1da177e4
LT
91/* Pretend that each entry is of this size in directory's i_size */
92#define BOGO_DIRENT_SIZE 20
93
69f07ec9
HD
94/* Symlink up to this size is kmalloc'ed instead of using a swappable page */
95#define SHORT_SYMLINK_LEN 128
96
1aac1400 97/*
f00cdc6d
HD
98 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
99 * inode->i_private (with i_mutex making sure that it has only one user at
100 * a time): we would prefer not to enlarge the shmem inode just for that.
1aac1400
HD
101 */
102struct shmem_falloc {
8e205f77 103 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
1aac1400
HD
104 pgoff_t start; /* start of range currently being fallocated */
105 pgoff_t next; /* the next page offset to be fallocated */
106 pgoff_t nr_falloced; /* how many new pages have been fallocated */
107 pgoff_t nr_unswapped; /* how often writepage refused to swap out */
108};
109
0b5071dd
AV
110struct shmem_options {
111 unsigned long long blocks;
a3853725 112 int inodes;
0b5071dd
AV
113 struct mempolicy *mpol;
114 kuid_t uid;
115 kgid_t gid;
116 umode_t mode;
ea3271f7 117 bool full_inums;
0b5071dd
AV
118 int huge;
119 int seen;
120#define SHMEM_SEEN_BLOCKS 1
121#define SHMEM_SEEN_INODES 2
122#define SHMEM_SEEN_HUGE 4
ea3271f7 123#define SHMEM_SEEN_INUMS 8
0b5071dd
AV
124};
125
b76db735 126#ifdef CONFIG_TMPFS
680d794b
AM
127static unsigned long shmem_default_max_blocks(void)
128{
ca79b0c2 129 return totalram_pages() / 2;
680d794b
AM
130}
131
a3853725 132static int shmem_default_max_inodes(void)
680d794b 133{
ca79b0c2 134 unsigned long nr_pages = totalram_pages();
a3853725 135 unsigned long ul;
ca79b0c2 136
a3853725
PP
137 ul = INT_MAX;
138 ul = min3(ul, nr_pages - totalhigh_pages(), nr_pages / 2);
139 return ul;
680d794b 140}
b76db735 141#endif
680d794b 142
bde05d1c
HD
143static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
144static int shmem_replace_page(struct page **pagep, gfp_t gfp,
145 struct shmem_inode_info *info, pgoff_t index);
c5bf121e
VRP
146static int shmem_swapin_page(struct inode *inode, pgoff_t index,
147 struct page **pagep, enum sgp_type sgp,
148 gfp_t gfp, struct vm_area_struct *vma,
149 vm_fault_t *fault_type);
68da9f05 150static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
9e18eb29 151 struct page **pagep, enum sgp_type sgp,
cfda0526 152 gfp_t gfp, struct vm_area_struct *vma,
2b740303 153 struct vm_fault *vmf, vm_fault_t *fault_type);
68da9f05 154
f3f0e1d2 155int shmem_getpage(struct inode *inode, pgoff_t index,
9e18eb29 156 struct page **pagep, enum sgp_type sgp)
68da9f05
HD
157{
158 return shmem_getpage_gfp(inode, index, pagep, sgp,
cfda0526 159 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
68da9f05 160}
1da177e4 161
1da177e4
LT
162static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
163{
164 return sb->s_fs_info;
165}
166
167/*
168 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
169 * for shared memory and for shared anonymous (/dev/zero) mappings
170 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
171 * consistent with the pre-accounting of private mappings ...
172 */
173static inline int shmem_acct_size(unsigned long flags, loff_t size)
174{
0b0a0806 175 return (flags & VM_NORESERVE) ?
191c5424 176 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
1da177e4
LT
177}
178
179static inline void shmem_unacct_size(unsigned long flags, loff_t size)
180{
0b0a0806 181 if (!(flags & VM_NORESERVE))
1da177e4
LT
182 vm_unacct_memory(VM_ACCT(size));
183}
184
77142517
KK
185static inline int shmem_reacct_size(unsigned long flags,
186 loff_t oldsize, loff_t newsize)
187{
188 if (!(flags & VM_NORESERVE)) {
189 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
190 return security_vm_enough_memory_mm(current->mm,
191 VM_ACCT(newsize) - VM_ACCT(oldsize));
192 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
193 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
194 }
195 return 0;
196}
197
1da177e4
LT
198/*
199 * ... whereas tmpfs objects are accounted incrementally as
75edd345 200 * pages are allocated, in order to allow large sparse files.
1da177e4
LT
201 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
202 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
203 */
800d8c63 204static inline int shmem_acct_block(unsigned long flags, long pages)
1da177e4 205{
800d8c63
KS
206 if (!(flags & VM_NORESERVE))
207 return 0;
208
209 return security_vm_enough_memory_mm(current->mm,
210 pages * VM_ACCT(PAGE_SIZE));
1da177e4
LT
211}
212
213static inline void shmem_unacct_blocks(unsigned long flags, long pages)
214{
0b0a0806 215 if (flags & VM_NORESERVE)
09cbfeaf 216 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
1da177e4
LT
217}
218
0f079694
MR
219static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
220{
221 struct shmem_inode_info *info = SHMEM_I(inode);
222 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
223
224 if (shmem_acct_block(info->flags, pages))
225 return false;
226
227 if (sbinfo->max_blocks) {
228 if (percpu_counter_compare(&sbinfo->used_blocks,
229 sbinfo->max_blocks - pages) > 0)
230 goto unacct;
231 percpu_counter_add(&sbinfo->used_blocks, pages);
232 }
233
234 return true;
235
236unacct:
237 shmem_unacct_blocks(info->flags, pages);
238 return false;
239}
240
241static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
242{
243 struct shmem_inode_info *info = SHMEM_I(inode);
244 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
245
246 if (sbinfo->max_blocks)
247 percpu_counter_sub(&sbinfo->used_blocks, pages);
248 shmem_unacct_blocks(info->flags, pages);
249}
250
759b9775 251static const struct super_operations shmem_ops;
f5e54d6e 252static const struct address_space_operations shmem_aops;
15ad7cdc 253static const struct file_operations shmem_file_operations;
92e1d5be
AV
254static const struct inode_operations shmem_inode_operations;
255static const struct inode_operations shmem_dir_inode_operations;
256static const struct inode_operations shmem_special_inode_operations;
f0f37e2f 257static const struct vm_operations_struct shmem_vm_ops;
779750d2 258static struct file_system_type shmem_fs_type;
1da177e4 259
b0506e48
MR
260bool vma_is_shmem(struct vm_area_struct *vma)
261{
262 return vma->vm_ops == &shmem_vm_ops;
263}
264
1da177e4 265static LIST_HEAD(shmem_swaplist);
cb5f7b9a 266static DEFINE_MUTEX(shmem_swaplist_mutex);
1da177e4 267
e809d5f0
CD
268/*
269 * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
270 * produces a novel ino for the newly allocated inode.
271 *
272 * It may also be called when making a hard link to permit the space needed by
273 * each dentry. However, in that case, no new inode number is needed since that
274 * internally draws from another pool of inode numbers (currently global
275 * get_next_ino()). This case is indicated by passing NULL as inop.
276 */
277#define SHMEM_INO_BATCH 1024
278static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
5b04c689
PE
279{
280 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
e809d5f0
CD
281 ino_t ino;
282
283 if (!(sb->s_flags & SB_KERNMOUNT)) {
5b04c689 284 spin_lock(&sbinfo->stat_lock);
bb3e96d6
BS
285 if (sbinfo->max_inodes) {
286 if (!sbinfo->free_inodes) {
287 spin_unlock(&sbinfo->stat_lock);
288 return -ENOSPC;
289 }
290 sbinfo->free_inodes--;
5b04c689 291 }
e809d5f0
CD
292 if (inop) {
293 ino = sbinfo->next_ino++;
294 if (unlikely(is_zero_ino(ino)))
295 ino = sbinfo->next_ino++;
ea3271f7
CD
296 if (unlikely(!sbinfo->full_inums &&
297 ino > UINT_MAX)) {
e809d5f0
CD
298 /*
299 * Emulate get_next_ino uint wraparound for
300 * compatibility
301 */
ea3271f7
CD
302 if (IS_ENABLED(CONFIG_64BIT))
303 pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
304 __func__, MINOR(sb->s_dev));
305 sbinfo->next_ino = 1;
306 ino = sbinfo->next_ino++;
e809d5f0
CD
307 }
308 *inop = ino;
309 }
5b04c689 310 spin_unlock(&sbinfo->stat_lock);
e809d5f0
CD
311 } else if (inop) {
312 /*
313 * __shmem_file_setup, one of our callers, is lock-free: it
314 * doesn't hold stat_lock in shmem_reserve_inode since
315 * max_inodes is always 0, and is called from potentially
316 * unknown contexts. As such, use a per-cpu batched allocator
317 * which doesn't require the per-sb stat_lock unless we are at
318 * the batch boundary.
ea3271f7
CD
319 *
320 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
321 * shmem mounts are not exposed to userspace, so we don't need
322 * to worry about things like glibc compatibility.
e809d5f0
CD
323 */
324 ino_t *next_ino;
325 next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
326 ino = *next_ino;
327 if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
328 spin_lock(&sbinfo->stat_lock);
329 ino = sbinfo->next_ino;
330 sbinfo->next_ino += SHMEM_INO_BATCH;
331 spin_unlock(&sbinfo->stat_lock);
332 if (unlikely(is_zero_ino(ino)))
333 ino++;
334 }
335 *inop = ino;
336 *next_ino = ++ino;
337 put_cpu();
5b04c689 338 }
e809d5f0 339
5b04c689
PE
340 return 0;
341}
342
343static void shmem_free_inode(struct super_block *sb)
344{
345 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
346 if (sbinfo->max_inodes) {
347 spin_lock(&sbinfo->stat_lock);
348 sbinfo->free_inodes++;
349 spin_unlock(&sbinfo->stat_lock);
350 }
351}
352
46711810 353/**
41ffe5d5 354 * shmem_recalc_inode - recalculate the block usage of an inode
1da177e4
LT
355 * @inode: inode to recalc
356 *
357 * We have to calculate the free blocks since the mm can drop
358 * undirtied hole pages behind our back.
359 *
360 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
361 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
362 *
363 * It has to be called with the spinlock held.
364 */
365static void shmem_recalc_inode(struct inode *inode)
366{
367 struct shmem_inode_info *info = SHMEM_I(inode);
368 long freed;
369
370 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
371 if (freed > 0) {
372 info->alloced -= freed;
54af6042 373 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
0f079694 374 shmem_inode_unacct_blocks(inode, freed);
1da177e4
LT
375 }
376}
377
800d8c63
KS
378bool shmem_charge(struct inode *inode, long pages)
379{
380 struct shmem_inode_info *info = SHMEM_I(inode);
4595ef88 381 unsigned long flags;
800d8c63 382
0f079694 383 if (!shmem_inode_acct_block(inode, pages))
800d8c63 384 return false;
b1cc94ab 385
aaa52e34
HD
386 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
387 inode->i_mapping->nrpages += pages;
388
4595ef88 389 spin_lock_irqsave(&info->lock, flags);
800d8c63
KS
390 info->alloced += pages;
391 inode->i_blocks += pages * BLOCKS_PER_PAGE;
392 shmem_recalc_inode(inode);
4595ef88 393 spin_unlock_irqrestore(&info->lock, flags);
800d8c63 394
800d8c63
KS
395 return true;
396}
397
398void shmem_uncharge(struct inode *inode, long pages)
399{
400 struct shmem_inode_info *info = SHMEM_I(inode);
4595ef88 401 unsigned long flags;
800d8c63 402
aaa52e34
HD
403 /* nrpages adjustment done by __delete_from_page_cache() or caller */
404
4595ef88 405 spin_lock_irqsave(&info->lock, flags);
800d8c63
KS
406 info->alloced -= pages;
407 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
408 shmem_recalc_inode(inode);
4595ef88 409 spin_unlock_irqrestore(&info->lock, flags);
800d8c63 410
0f079694 411 shmem_inode_unacct_blocks(inode, pages);
800d8c63
KS
412}
413
7a5d0fbb 414/*
62f945b6 415 * Replace item expected in xarray by a new item, while holding xa_lock.
7a5d0fbb 416 */
62f945b6 417static int shmem_replace_entry(struct address_space *mapping,
7a5d0fbb
HD
418 pgoff_t index, void *expected, void *replacement)
419{
62f945b6 420 XA_STATE(xas, &mapping->i_pages, index);
6dbaf22c 421 void *item;
7a5d0fbb
HD
422
423 VM_BUG_ON(!expected);
6dbaf22c 424 VM_BUG_ON(!replacement);
62f945b6 425 item = xas_load(&xas);
7a5d0fbb
HD
426 if (item != expected)
427 return -ENOENT;
62f945b6 428 xas_store(&xas, replacement);
7a5d0fbb
HD
429 return 0;
430}
431
d1899228
HD
432/*
433 * Sometimes, before we decide whether to proceed or to fail, we must check
434 * that an entry was not already brought back from swap by a racing thread.
435 *
436 * Checking page is not enough: by the time a SwapCache page is locked, it
437 * might be reused, and again be SwapCache, using the same swap as before.
438 */
439static bool shmem_confirm_swap(struct address_space *mapping,
440 pgoff_t index, swp_entry_t swap)
441{
a12831bf 442 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
d1899228
HD
443}
444
5a6e75f8
KS
445/*
446 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
447 *
448 * SHMEM_HUGE_NEVER:
449 * disables huge pages for the mount;
450 * SHMEM_HUGE_ALWAYS:
451 * enables huge pages for the mount;
452 * SHMEM_HUGE_WITHIN_SIZE:
453 * only allocate huge pages if the page will be fully within i_size,
454 * also respect fadvise()/madvise() hints;
455 * SHMEM_HUGE_ADVISE:
456 * only allocate huge pages if requested with fadvise()/madvise();
457 */
458
459#define SHMEM_HUGE_NEVER 0
460#define SHMEM_HUGE_ALWAYS 1
461#define SHMEM_HUGE_WITHIN_SIZE 2
462#define SHMEM_HUGE_ADVISE 3
463
464/*
465 * Special values.
466 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
467 *
468 * SHMEM_HUGE_DENY:
469 * disables huge on shm_mnt and all mounts, for emergency use;
470 * SHMEM_HUGE_FORCE:
471 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
472 *
473 */
474#define SHMEM_HUGE_DENY (-1)
475#define SHMEM_HUGE_FORCE (-2)
476
396bcc52 477#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5a6e75f8
KS
478/* ifdef here to avoid bloating shmem.o when not necessary */
479
5b9c98f3 480static int shmem_huge __read_mostly;
5a6e75f8 481
e5f2249a 482#if defined(CONFIG_SYSFS)
5a6e75f8
KS
483static int shmem_parse_huge(const char *str)
484{
485 if (!strcmp(str, "never"))
486 return SHMEM_HUGE_NEVER;
487 if (!strcmp(str, "always"))
488 return SHMEM_HUGE_ALWAYS;
489 if (!strcmp(str, "within_size"))
490 return SHMEM_HUGE_WITHIN_SIZE;
491 if (!strcmp(str, "advise"))
492 return SHMEM_HUGE_ADVISE;
493 if (!strcmp(str, "deny"))
494 return SHMEM_HUGE_DENY;
495 if (!strcmp(str, "force"))
496 return SHMEM_HUGE_FORCE;
497 return -EINVAL;
498}
e5f2249a 499#endif
5a6e75f8 500
e5f2249a 501#if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
5a6e75f8
KS
502static const char *shmem_format_huge(int huge)
503{
504 switch (huge) {
505 case SHMEM_HUGE_NEVER:
506 return "never";
507 case SHMEM_HUGE_ALWAYS:
508 return "always";
509 case SHMEM_HUGE_WITHIN_SIZE:
510 return "within_size";
511 case SHMEM_HUGE_ADVISE:
512 return "advise";
513 case SHMEM_HUGE_DENY:
514 return "deny";
515 case SHMEM_HUGE_FORCE:
516 return "force";
517 default:
518 VM_BUG_ON(1);
519 return "bad_val";
520 }
521}
f1f5929c 522#endif
5a6e75f8 523
779750d2
KS
524static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
525 struct shrink_control *sc, unsigned long nr_to_split)
526{
527 LIST_HEAD(list), *pos, *next;
253fd0f0 528 LIST_HEAD(to_remove);
779750d2
KS
529 struct inode *inode;
530 struct shmem_inode_info *info;
531 struct page *page;
532 unsigned long batch = sc ? sc->nr_to_scan : 128;
533 int removed = 0, split = 0;
534
535 if (list_empty(&sbinfo->shrinklist))
536 return SHRINK_STOP;
537
538 spin_lock(&sbinfo->shrinklist_lock);
539 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
540 info = list_entry(pos, struct shmem_inode_info, shrinklist);
541
542 /* pin the inode */
543 inode = igrab(&info->vfs_inode);
544
545 /* inode is about to be evicted */
546 if (!inode) {
547 list_del_init(&info->shrinklist);
548 removed++;
549 goto next;
550 }
551
552 /* Check if there's anything to gain */
553 if (round_up(inode->i_size, PAGE_SIZE) ==
554 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
253fd0f0 555 list_move(&info->shrinklist, &to_remove);
779750d2 556 removed++;
779750d2
KS
557 goto next;
558 }
559
560 list_move(&info->shrinklist, &list);
561next:
562 if (!--batch)
563 break;
564 }
565 spin_unlock(&sbinfo->shrinklist_lock);
566
253fd0f0
KS
567 list_for_each_safe(pos, next, &to_remove) {
568 info = list_entry(pos, struct shmem_inode_info, shrinklist);
569 inode = &info->vfs_inode;
570 list_del_init(&info->shrinklist);
571 iput(inode);
572 }
573
779750d2
KS
574 list_for_each_safe(pos, next, &list) {
575 int ret;
576
577 info = list_entry(pos, struct shmem_inode_info, shrinklist);
578 inode = &info->vfs_inode;
579
b3cd54b2
KS
580 if (nr_to_split && split >= nr_to_split)
581 goto leave;
779750d2 582
b3cd54b2 583 page = find_get_page(inode->i_mapping,
779750d2
KS
584 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
585 if (!page)
586 goto drop;
587
b3cd54b2 588 /* No huge page at the end of the file: nothing to split */
779750d2 589 if (!PageTransHuge(page)) {
779750d2
KS
590 put_page(page);
591 goto drop;
592 }
593
b3cd54b2
KS
594 /*
595 * Leave the inode on the list if we failed to lock
596 * the page at this time.
597 *
598 * Waiting for the lock may lead to deadlock in the
599 * reclaim path.
600 */
601 if (!trylock_page(page)) {
602 put_page(page);
603 goto leave;
604 }
605
779750d2
KS
606 ret = split_huge_page(page);
607 unlock_page(page);
608 put_page(page);
609
b3cd54b2
KS
610 /* If split failed leave the inode on the list */
611 if (ret)
612 goto leave;
779750d2
KS
613
614 split++;
615drop:
616 list_del_init(&info->shrinklist);
617 removed++;
b3cd54b2 618leave:
779750d2
KS
619 iput(inode);
620 }
621
622 spin_lock(&sbinfo->shrinklist_lock);
623 list_splice_tail(&list, &sbinfo->shrinklist);
624 sbinfo->shrinklist_len -= removed;
625 spin_unlock(&sbinfo->shrinklist_lock);
626
627 return split;
628}
629
630static long shmem_unused_huge_scan(struct super_block *sb,
631 struct shrink_control *sc)
632{
633 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
634
635 if (!READ_ONCE(sbinfo->shrinklist_len))
636 return SHRINK_STOP;
637
638 return shmem_unused_huge_shrink(sbinfo, sc, 0);
639}
640
641static long shmem_unused_huge_count(struct super_block *sb,
642 struct shrink_control *sc)
643{
644 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
645 return READ_ONCE(sbinfo->shrinklist_len);
646}
396bcc52 647#else /* !CONFIG_TRANSPARENT_HUGEPAGE */
5a6e75f8
KS
648
649#define shmem_huge SHMEM_HUGE_DENY
650
779750d2
KS
651static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
652 struct shrink_control *sc, unsigned long nr_to_split)
653{
654 return 0;
655}
396bcc52 656#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5a6e75f8 657
89fdcd26
YS
658static inline bool is_huge_enabled(struct shmem_sb_info *sbinfo)
659{
396bcc52 660 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
89fdcd26
YS
661 (shmem_huge == SHMEM_HUGE_FORCE || sbinfo->huge) &&
662 shmem_huge != SHMEM_HUGE_DENY)
663 return true;
664 return false;
665}
666
46f65ec1
HD
667/*
668 * Like add_to_page_cache_locked, but error if expected item has gone.
669 */
670static int shmem_add_to_page_cache(struct page *page,
671 struct address_space *mapping,
3fea5a49
JW
672 pgoff_t index, void *expected, gfp_t gfp,
673 struct mm_struct *charge_mm)
46f65ec1 674{
552446a4
MW
675 XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
676 unsigned long i = 0;
d8c6546b 677 unsigned long nr = compound_nr(page);
3fea5a49 678 int error;
46f65ec1 679
800d8c63
KS
680 VM_BUG_ON_PAGE(PageTail(page), page);
681 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
309381fe
SL
682 VM_BUG_ON_PAGE(!PageLocked(page), page);
683 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
800d8c63 684 VM_BUG_ON(expected && PageTransHuge(page));
46f65ec1 685
800d8c63 686 page_ref_add(page, nr);
b065b432
HD
687 page->mapping = mapping;
688 page->index = index;
689
4c6355b2 690 if (!PageSwapCache(page)) {
d9eb1ea2 691 error = mem_cgroup_charge(page, charge_mm, gfp);
4c6355b2
JW
692 if (error) {
693 if (PageTransHuge(page)) {
694 count_vm_event(THP_FILE_FALLBACK);
695 count_vm_event(THP_FILE_FALLBACK_CHARGE);
696 }
697 goto error;
3fea5a49 698 }
3fea5a49
JW
699 }
700 cgroup_throttle_swaprate(page, gfp);
701
552446a4
MW
702 do {
703 void *entry;
704 xas_lock_irq(&xas);
705 entry = xas_find_conflict(&xas);
706 if (entry != expected)
707 xas_set_err(&xas, -EEXIST);
708 xas_create_range(&xas);
709 if (xas_error(&xas))
710 goto unlock;
711next:
4101196b 712 xas_store(&xas, page);
552446a4
MW
713 if (++i < nr) {
714 xas_next(&xas);
715 goto next;
800d8c63 716 }
552446a4 717 if (PageTransHuge(page)) {
800d8c63 718 count_vm_event(THP_FILE_ALLOC);
552446a4 719 __inc_node_page_state(page, NR_SHMEM_THPS);
800d8c63 720 }
800d8c63 721 mapping->nrpages += nr;
0d1c2072
JW
722 __mod_lruvec_page_state(page, NR_FILE_PAGES, nr);
723 __mod_lruvec_page_state(page, NR_SHMEM, nr);
552446a4
MW
724unlock:
725 xas_unlock_irq(&xas);
726 } while (xas_nomem(&xas, gfp));
727
728 if (xas_error(&xas)) {
3fea5a49
JW
729 error = xas_error(&xas);
730 goto error;
46f65ec1 731 }
552446a4
MW
732
733 return 0;
3fea5a49
JW
734error:
735 page->mapping = NULL;
736 page_ref_sub(page, nr);
737 return error;
46f65ec1
HD
738}
739
6922c0c7
HD
740/*
741 * Like delete_from_page_cache, but substitutes swap for page.
742 */
743static void shmem_delete_from_page_cache(struct page *page, void *radswap)
744{
745 struct address_space *mapping = page->mapping;
746 int error;
747
800d8c63
KS
748 VM_BUG_ON_PAGE(PageCompound(page), page);
749
b93b0163 750 xa_lock_irq(&mapping->i_pages);
62f945b6 751 error = shmem_replace_entry(mapping, page->index, page, radswap);
6922c0c7
HD
752 page->mapping = NULL;
753 mapping->nrpages--;
0d1c2072
JW
754 __dec_lruvec_page_state(page, NR_FILE_PAGES);
755 __dec_lruvec_page_state(page, NR_SHMEM);
b93b0163 756 xa_unlock_irq(&mapping->i_pages);
09cbfeaf 757 put_page(page);
6922c0c7
HD
758 BUG_ON(error);
759}
760
7a5d0fbb 761/*
c121d3bb 762 * Remove swap entry from page cache, free the swap and its page cache.
7a5d0fbb
HD
763 */
764static int shmem_free_swap(struct address_space *mapping,
765 pgoff_t index, void *radswap)
766{
6dbaf22c 767 void *old;
7a5d0fbb 768
55f3f7ea 769 old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
6dbaf22c
JW
770 if (old != radswap)
771 return -ENOENT;
772 free_swap_and_cache(radix_to_swp_entry(radswap));
773 return 0;
7a5d0fbb
HD
774}
775
6a15a370
VB
776/*
777 * Determine (in bytes) how many of the shmem object's pages mapped by the
48131e03 778 * given offsets are swapped out.
6a15a370 779 *
b93b0163 780 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
6a15a370
VB
781 * as long as the inode doesn't go away and racy results are not a problem.
782 */
48131e03
VB
783unsigned long shmem_partial_swap_usage(struct address_space *mapping,
784 pgoff_t start, pgoff_t end)
6a15a370 785{
7ae3424f 786 XA_STATE(xas, &mapping->i_pages, start);
6a15a370 787 struct page *page;
48131e03 788 unsigned long swapped = 0;
6a15a370
VB
789
790 rcu_read_lock();
7ae3424f
MW
791 xas_for_each(&xas, page, end - 1) {
792 if (xas_retry(&xas, page))
2cf938aa 793 continue;
3159f943 794 if (xa_is_value(page))
6a15a370
VB
795 swapped++;
796
797 if (need_resched()) {
7ae3424f 798 xas_pause(&xas);
6a15a370 799 cond_resched_rcu();
6a15a370
VB
800 }
801 }
802
803 rcu_read_unlock();
804
805 return swapped << PAGE_SHIFT;
806}
807
48131e03
VB
808/*
809 * Determine (in bytes) how many of the shmem object's pages mapped by the
810 * given vma is swapped out.
811 *
b93b0163 812 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
48131e03
VB
813 * as long as the inode doesn't go away and racy results are not a problem.
814 */
815unsigned long shmem_swap_usage(struct vm_area_struct *vma)
816{
817 struct inode *inode = file_inode(vma->vm_file);
818 struct shmem_inode_info *info = SHMEM_I(inode);
819 struct address_space *mapping = inode->i_mapping;
820 unsigned long swapped;
821
822 /* Be careful as we don't hold info->lock */
823 swapped = READ_ONCE(info->swapped);
824
825 /*
826 * The easier cases are when the shmem object has nothing in swap, or
827 * the vma maps it whole. Then we can simply use the stats that we
828 * already track.
829 */
830 if (!swapped)
831 return 0;
832
833 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
834 return swapped << PAGE_SHIFT;
835
836 /* Here comes the more involved part */
837 return shmem_partial_swap_usage(mapping,
838 linear_page_index(vma, vma->vm_start),
839 linear_page_index(vma, vma->vm_end));
840}
841
24513264
HD
842/*
843 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
844 */
845void shmem_unlock_mapping(struct address_space *mapping)
846{
847 struct pagevec pvec;
848 pgoff_t indices[PAGEVEC_SIZE];
849 pgoff_t index = 0;
850
86679820 851 pagevec_init(&pvec);
24513264
HD
852 /*
853 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
854 */
855 while (!mapping_unevictable(mapping)) {
856 /*
857 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
858 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
859 */
0cd6144a
JW
860 pvec.nr = find_get_entries(mapping, index,
861 PAGEVEC_SIZE, pvec.pages, indices);
24513264
HD
862 if (!pvec.nr)
863 break;
864 index = indices[pvec.nr - 1] + 1;
0cd6144a 865 pagevec_remove_exceptionals(&pvec);
64e3d12f 866 check_move_unevictable_pages(&pvec);
24513264
HD
867 pagevec_release(&pvec);
868 cond_resched();
869 }
7a5d0fbb
HD
870}
871
71725ed1
HD
872/*
873 * Check whether a hole-punch or truncation needs to split a huge page,
874 * returning true if no split was required, or the split has been successful.
875 *
876 * Eviction (or truncation to 0 size) should never need to split a huge page;
877 * but in rare cases might do so, if shmem_undo_range() failed to trylock on
878 * head, and then succeeded to trylock on tail.
879 *
880 * A split can only succeed when there are no additional references on the
881 * huge page: so the split below relies upon find_get_entries() having stopped
882 * when it found a subpage of the huge page, without getting further references.
883 */
884static bool shmem_punch_compound(struct page *page, pgoff_t start, pgoff_t end)
885{
886 if (!PageTransCompound(page))
887 return true;
888
889 /* Just proceed to delete a huge page wholly within the range punched */
890 if (PageHead(page) &&
891 page->index >= start && page->index + HPAGE_PMD_NR <= end)
892 return true;
893
894 /* Try to split huge page, so we can truly punch the hole or truncate */
895 return split_huge_page(page) >= 0;
896}
897
7a5d0fbb 898/*
7f4446ee 899 * Remove range of pages and swap entries from page cache, and free them.
1635f6a7 900 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
7a5d0fbb 901 */
1635f6a7
HD
902static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
903 bool unfalloc)
1da177e4 904{
285b2c4f 905 struct address_space *mapping = inode->i_mapping;
1da177e4 906 struct shmem_inode_info *info = SHMEM_I(inode);
09cbfeaf
KS
907 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
908 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
909 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
910 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
bda97eab 911 struct pagevec pvec;
7a5d0fbb
HD
912 pgoff_t indices[PAGEVEC_SIZE];
913 long nr_swaps_freed = 0;
285b2c4f 914 pgoff_t index;
bda97eab
HD
915 int i;
916
83e4fa9c
HD
917 if (lend == -1)
918 end = -1; /* unsigned, so actually very big */
bda97eab 919
86679820 920 pagevec_init(&pvec);
bda97eab 921 index = start;
83e4fa9c 922 while (index < end) {
0cd6144a
JW
923 pvec.nr = find_get_entries(mapping, index,
924 min(end - index, (pgoff_t)PAGEVEC_SIZE),
925 pvec.pages, indices);
7a5d0fbb
HD
926 if (!pvec.nr)
927 break;
bda97eab
HD
928 for (i = 0; i < pagevec_count(&pvec); i++) {
929 struct page *page = pvec.pages[i];
930
7a5d0fbb 931 index = indices[i];
83e4fa9c 932 if (index >= end)
bda97eab
HD
933 break;
934
3159f943 935 if (xa_is_value(page)) {
1635f6a7
HD
936 if (unfalloc)
937 continue;
7a5d0fbb
HD
938 nr_swaps_freed += !shmem_free_swap(mapping,
939 index, page);
bda97eab 940 continue;
7a5d0fbb
HD
941 }
942
800d8c63
KS
943 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
944
7a5d0fbb 945 if (!trylock_page(page))
bda97eab 946 continue;
800d8c63 947
71725ed1
HD
948 if ((!unfalloc || !PageUptodate(page)) &&
949 page_mapping(page) == mapping) {
950 VM_BUG_ON_PAGE(PageWriteback(page), page);
951 if (shmem_punch_compound(page, start, end))
1635f6a7 952 truncate_inode_page(mapping, page);
bda97eab 953 }
bda97eab
HD
954 unlock_page(page);
955 }
0cd6144a 956 pagevec_remove_exceptionals(&pvec);
24513264 957 pagevec_release(&pvec);
bda97eab
HD
958 cond_resched();
959 index++;
960 }
1da177e4 961
83e4fa9c 962 if (partial_start) {
bda97eab 963 struct page *page = NULL;
9e18eb29 964 shmem_getpage(inode, start - 1, &page, SGP_READ);
bda97eab 965 if (page) {
09cbfeaf 966 unsigned int top = PAGE_SIZE;
83e4fa9c
HD
967 if (start > end) {
968 top = partial_end;
969 partial_end = 0;
970 }
971 zero_user_segment(page, partial_start, top);
972 set_page_dirty(page);
973 unlock_page(page);
09cbfeaf 974 put_page(page);
83e4fa9c
HD
975 }
976 }
977 if (partial_end) {
978 struct page *page = NULL;
9e18eb29 979 shmem_getpage(inode, end, &page, SGP_READ);
83e4fa9c
HD
980 if (page) {
981 zero_user_segment(page, 0, partial_end);
bda97eab
HD
982 set_page_dirty(page);
983 unlock_page(page);
09cbfeaf 984 put_page(page);
bda97eab
HD
985 }
986 }
83e4fa9c
HD
987 if (start >= end)
988 return;
bda97eab
HD
989
990 index = start;
b1a36650 991 while (index < end) {
bda97eab 992 cond_resched();
0cd6144a
JW
993
994 pvec.nr = find_get_entries(mapping, index,
83e4fa9c 995 min(end - index, (pgoff_t)PAGEVEC_SIZE),
0cd6144a 996 pvec.pages, indices);
7a5d0fbb 997 if (!pvec.nr) {
b1a36650
HD
998 /* If all gone or hole-punch or unfalloc, we're done */
999 if (index == start || end != -1)
bda97eab 1000 break;
b1a36650 1001 /* But if truncating, restart to make sure all gone */
bda97eab
HD
1002 index = start;
1003 continue;
1004 }
bda97eab
HD
1005 for (i = 0; i < pagevec_count(&pvec); i++) {
1006 struct page *page = pvec.pages[i];
1007
7a5d0fbb 1008 index = indices[i];
83e4fa9c 1009 if (index >= end)
bda97eab
HD
1010 break;
1011
3159f943 1012 if (xa_is_value(page)) {
1635f6a7
HD
1013 if (unfalloc)
1014 continue;
b1a36650
HD
1015 if (shmem_free_swap(mapping, index, page)) {
1016 /* Swap was replaced by page: retry */
1017 index--;
1018 break;
1019 }
1020 nr_swaps_freed++;
7a5d0fbb
HD
1021 continue;
1022 }
1023
bda97eab 1024 lock_page(page);
800d8c63 1025
1635f6a7 1026 if (!unfalloc || !PageUptodate(page)) {
71725ed1 1027 if (page_mapping(page) != mapping) {
b1a36650
HD
1028 /* Page was replaced by swap: retry */
1029 unlock_page(page);
1030 index--;
1031 break;
1635f6a7 1032 }
71725ed1
HD
1033 VM_BUG_ON_PAGE(PageWriteback(page), page);
1034 if (shmem_punch_compound(page, start, end))
1035 truncate_inode_page(mapping, page);
0783ac95 1036 else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
71725ed1
HD
1037 /* Wipe the page and don't get stuck */
1038 clear_highpage(page);
1039 flush_dcache_page(page);
1040 set_page_dirty(page);
1041 if (index <
1042 round_up(start, HPAGE_PMD_NR))
1043 start = index + 1;
1044 }
7a5d0fbb 1045 }
bda97eab
HD
1046 unlock_page(page);
1047 }
0cd6144a 1048 pagevec_remove_exceptionals(&pvec);
24513264 1049 pagevec_release(&pvec);
bda97eab
HD
1050 index++;
1051 }
94c1e62d 1052
4595ef88 1053 spin_lock_irq(&info->lock);
7a5d0fbb 1054 info->swapped -= nr_swaps_freed;
1da177e4 1055 shmem_recalc_inode(inode);
4595ef88 1056 spin_unlock_irq(&info->lock);
1635f6a7 1057}
1da177e4 1058
1635f6a7
HD
1059void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
1060{
1061 shmem_undo_range(inode, lstart, lend, false);
078cd827 1062 inode->i_ctime = inode->i_mtime = current_time(inode);
1da177e4 1063}
94c1e62d 1064EXPORT_SYMBOL_GPL(shmem_truncate_range);
1da177e4 1065
a528d35e
DH
1066static int shmem_getattr(const struct path *path, struct kstat *stat,
1067 u32 request_mask, unsigned int query_flags)
44a30220 1068{
a528d35e 1069 struct inode *inode = path->dentry->d_inode;
44a30220 1070 struct shmem_inode_info *info = SHMEM_I(inode);
89fdcd26 1071 struct shmem_sb_info *sb_info = SHMEM_SB(inode->i_sb);
44a30220 1072
d0424c42 1073 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
4595ef88 1074 spin_lock_irq(&info->lock);
d0424c42 1075 shmem_recalc_inode(inode);
4595ef88 1076 spin_unlock_irq(&info->lock);
d0424c42 1077 }
44a30220 1078 generic_fillattr(inode, stat);
89fdcd26
YS
1079
1080 if (is_huge_enabled(sb_info))
1081 stat->blksize = HPAGE_PMD_SIZE;
1082
44a30220
YZ
1083 return 0;
1084}
1085
94c1e62d 1086static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
1da177e4 1087{
75c3cfa8 1088 struct inode *inode = d_inode(dentry);
40e041a2 1089 struct shmem_inode_info *info = SHMEM_I(inode);
779750d2 1090 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1da177e4
LT
1091 int error;
1092
31051c85 1093 error = setattr_prepare(dentry, attr);
db78b877
CH
1094 if (error)
1095 return error;
1096
94c1e62d
HD
1097 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1098 loff_t oldsize = inode->i_size;
1099 loff_t newsize = attr->ia_size;
3889e6e7 1100
40e041a2
DH
1101 /* protected by i_mutex */
1102 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1103 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1104 return -EPERM;
1105
94c1e62d 1106 if (newsize != oldsize) {
77142517
KK
1107 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1108 oldsize, newsize);
1109 if (error)
1110 return error;
94c1e62d 1111 i_size_write(inode, newsize);
078cd827 1112 inode->i_ctime = inode->i_mtime = current_time(inode);
94c1e62d 1113 }
afa2db2f 1114 if (newsize <= oldsize) {
94c1e62d 1115 loff_t holebegin = round_up(newsize, PAGE_SIZE);
d0424c42
HD
1116 if (oldsize > holebegin)
1117 unmap_mapping_range(inode->i_mapping,
1118 holebegin, 0, 1);
1119 if (info->alloced)
1120 shmem_truncate_range(inode,
1121 newsize, (loff_t)-1);
94c1e62d 1122 /* unmap again to remove racily COWed private pages */
d0424c42
HD
1123 if (oldsize > holebegin)
1124 unmap_mapping_range(inode->i_mapping,
1125 holebegin, 0, 1);
779750d2
KS
1126
1127 /*
1128 * Part of the huge page can be beyond i_size: subject
1129 * to shrink under memory pressure.
1130 */
396bcc52 1131 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
779750d2 1132 spin_lock(&sbinfo->shrinklist_lock);
d041353d
CW
1133 /*
1134 * _careful to defend against unlocked access to
1135 * ->shrink_list in shmem_unused_huge_shrink()
1136 */
1137 if (list_empty_careful(&info->shrinklist)) {
779750d2
KS
1138 list_add_tail(&info->shrinklist,
1139 &sbinfo->shrinklist);
1140 sbinfo->shrinklist_len++;
1141 }
1142 spin_unlock(&sbinfo->shrinklist_lock);
1143 }
94c1e62d 1144 }
1da177e4
LT
1145 }
1146
db78b877 1147 setattr_copy(inode, attr);
db78b877 1148 if (attr->ia_valid & ATTR_MODE)
feda821e 1149 error = posix_acl_chmod(inode, inode->i_mode);
1da177e4
LT
1150 return error;
1151}
1152
1f895f75 1153static void shmem_evict_inode(struct inode *inode)
1da177e4 1154{
1da177e4 1155 struct shmem_inode_info *info = SHMEM_I(inode);
779750d2 1156 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1da177e4 1157
3889e6e7 1158 if (inode->i_mapping->a_ops == &shmem_aops) {
1da177e4
LT
1159 shmem_unacct_size(info->flags, inode->i_size);
1160 inode->i_size = 0;
3889e6e7 1161 shmem_truncate_range(inode, 0, (loff_t)-1);
779750d2
KS
1162 if (!list_empty(&info->shrinklist)) {
1163 spin_lock(&sbinfo->shrinklist_lock);
1164 if (!list_empty(&info->shrinklist)) {
1165 list_del_init(&info->shrinklist);
1166 sbinfo->shrinklist_len--;
1167 }
1168 spin_unlock(&sbinfo->shrinklist_lock);
1169 }
af53d3e9
HD
1170 while (!list_empty(&info->swaplist)) {
1171 /* Wait while shmem_unuse() is scanning this inode... */
1172 wait_var_event(&info->stop_eviction,
1173 !atomic_read(&info->stop_eviction));
cb5f7b9a 1174 mutex_lock(&shmem_swaplist_mutex);
af53d3e9
HD
1175 /* ...but beware of the race if we peeked too early */
1176 if (!atomic_read(&info->stop_eviction))
1177 list_del_init(&info->swaplist);
cb5f7b9a 1178 mutex_unlock(&shmem_swaplist_mutex);
1da177e4 1179 }
3ed47db3 1180 }
b09e0fa4 1181
38f38657 1182 simple_xattrs_free(&info->xattrs);
0f3c42f5 1183 WARN_ON(inode->i_blocks);
a3853725
PP
1184 if (!sbinfo->idr_nouse && inode->i_ino) {
1185 mutex_lock(&sbinfo->idr_lock);
1186 idr_remove(&sbinfo->idr, inode->i_ino);
1187 mutex_unlock(&sbinfo->idr_lock);
1188 }
5b04c689 1189 shmem_free_inode(inode->i_sb);
dbd5768f 1190 clear_inode(inode);
1da177e4
LT
1191}
1192
b56a2d8a
VRP
1193extern struct swap_info_struct *swap_info[];
1194
1195static int shmem_find_swap_entries(struct address_space *mapping,
1196 pgoff_t start, unsigned int nr_entries,
1197 struct page **entries, pgoff_t *indices,
87039546 1198 unsigned int type, bool frontswap)
478922e2 1199{
b56a2d8a
VRP
1200 XA_STATE(xas, &mapping->i_pages, start);
1201 struct page *page;
87039546 1202 swp_entry_t entry;
b56a2d8a
VRP
1203 unsigned int ret = 0;
1204
1205 if (!nr_entries)
1206 return 0;
478922e2
MW
1207
1208 rcu_read_lock();
b56a2d8a
VRP
1209 xas_for_each(&xas, page, ULONG_MAX) {
1210 if (xas_retry(&xas, page))
5b9c98f3 1211 continue;
b56a2d8a
VRP
1212
1213 if (!xa_is_value(page))
478922e2 1214 continue;
b56a2d8a 1215
87039546
HD
1216 entry = radix_to_swp_entry(page);
1217 if (swp_type(entry) != type)
1218 continue;
1219 if (frontswap &&
1220 !frontswap_test(swap_info[type], swp_offset(entry)))
1221 continue;
b56a2d8a
VRP
1222
1223 indices[ret] = xas.xa_index;
1224 entries[ret] = page;
1225
1226 if (need_resched()) {
1227 xas_pause(&xas);
1228 cond_resched_rcu();
1229 }
1230 if (++ret == nr_entries)
1231 break;
478922e2 1232 }
478922e2 1233 rcu_read_unlock();
e21a2955 1234
b56a2d8a 1235 return ret;
478922e2
MW
1236}
1237
46f65ec1 1238/*
b56a2d8a
VRP
1239 * Move the swapped pages for an inode to page cache. Returns the count
1240 * of pages swapped in, or the error in case of failure.
46f65ec1 1241 */
b56a2d8a
VRP
1242static int shmem_unuse_swap_entries(struct inode *inode, struct pagevec pvec,
1243 pgoff_t *indices)
1da177e4 1244{
b56a2d8a
VRP
1245 int i = 0;
1246 int ret = 0;
bde05d1c 1247 int error = 0;
b56a2d8a 1248 struct address_space *mapping = inode->i_mapping;
1da177e4 1249
b56a2d8a
VRP
1250 for (i = 0; i < pvec.nr; i++) {
1251 struct page *page = pvec.pages[i];
2e0e26c7 1252
b56a2d8a
VRP
1253 if (!xa_is_value(page))
1254 continue;
1255 error = shmem_swapin_page(inode, indices[i],
1256 &page, SGP_CACHE,
1257 mapping_gfp_mask(mapping),
1258 NULL, NULL);
1259 if (error == 0) {
1260 unlock_page(page);
1261 put_page(page);
1262 ret++;
1263 }
1264 if (error == -ENOMEM)
1265 break;
1266 error = 0;
bde05d1c 1267 }
b56a2d8a
VRP
1268 return error ? error : ret;
1269}
bde05d1c 1270
b56a2d8a
VRP
1271/*
1272 * If swap found in inode, free it and move page from swapcache to filecache.
1273 */
1274static int shmem_unuse_inode(struct inode *inode, unsigned int type,
1275 bool frontswap, unsigned long *fs_pages_to_unuse)
1276{
1277 struct address_space *mapping = inode->i_mapping;
1278 pgoff_t start = 0;
1279 struct pagevec pvec;
1280 pgoff_t indices[PAGEVEC_SIZE];
1281 bool frontswap_partial = (frontswap && *fs_pages_to_unuse > 0);
1282 int ret = 0;
1283
1284 pagevec_init(&pvec);
1285 do {
1286 unsigned int nr_entries = PAGEVEC_SIZE;
1287
1288 if (frontswap_partial && *fs_pages_to_unuse < PAGEVEC_SIZE)
1289 nr_entries = *fs_pages_to_unuse;
1290
1291 pvec.nr = shmem_find_swap_entries(mapping, start, nr_entries,
1292 pvec.pages, indices,
87039546 1293 type, frontswap);
b56a2d8a
VRP
1294 if (pvec.nr == 0) {
1295 ret = 0;
1296 break;
46f65ec1 1297 }
b56a2d8a
VRP
1298
1299 ret = shmem_unuse_swap_entries(inode, pvec, indices);
1300 if (ret < 0)
1301 break;
1302
1303 if (frontswap_partial) {
1304 *fs_pages_to_unuse -= ret;
1305 if (*fs_pages_to_unuse == 0) {
1306 ret = FRONTSWAP_PAGES_UNUSED;
1307 break;
1308 }
1309 }
1310
1311 start = indices[pvec.nr - 1];
1312 } while (true);
1313
1314 return ret;
1da177e4
LT
1315}
1316
1317/*
b56a2d8a
VRP
1318 * Read all the shared memory data that resides in the swap
1319 * device 'type' back into memory, so the swap device can be
1320 * unused.
1da177e4 1321 */
b56a2d8a
VRP
1322int shmem_unuse(unsigned int type, bool frontswap,
1323 unsigned long *fs_pages_to_unuse)
1da177e4 1324{
b56a2d8a 1325 struct shmem_inode_info *info, *next;
bde05d1c
HD
1326 int error = 0;
1327
b56a2d8a
VRP
1328 if (list_empty(&shmem_swaplist))
1329 return 0;
1330
1331 mutex_lock(&shmem_swaplist_mutex);
b56a2d8a
VRP
1332 list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1333 if (!info->swapped) {
6922c0c7 1334 list_del_init(&info->swaplist);
b56a2d8a
VRP
1335 continue;
1336 }
af53d3e9
HD
1337 /*
1338 * Drop the swaplist mutex while searching the inode for swap;
1339 * but before doing so, make sure shmem_evict_inode() will not
1340 * remove placeholder inode from swaplist, nor let it be freed
1341 * (igrab() would protect from unlink, but not from unmount).
1342 */
1343 atomic_inc(&info->stop_eviction);
b56a2d8a 1344 mutex_unlock(&shmem_swaplist_mutex);
b56a2d8a 1345
af53d3e9 1346 error = shmem_unuse_inode(&info->vfs_inode, type, frontswap,
b56a2d8a 1347 fs_pages_to_unuse);
cb5f7b9a 1348 cond_resched();
b56a2d8a
VRP
1349
1350 mutex_lock(&shmem_swaplist_mutex);
1351 next = list_next_entry(info, swaplist);
1352 if (!info->swapped)
1353 list_del_init(&info->swaplist);
af53d3e9
HD
1354 if (atomic_dec_and_test(&info->stop_eviction))
1355 wake_up_var(&info->stop_eviction);
b56a2d8a 1356 if (error)
778dd893 1357 break;
1da177e4 1358 }
cb5f7b9a 1359 mutex_unlock(&shmem_swaplist_mutex);
778dd893 1360
778dd893 1361 return error;
1da177e4
LT
1362}
1363
1364/*
1365 * Move the page from the page cache to the swap cache.
1366 */
1367static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1368{
1369 struct shmem_inode_info *info;
1da177e4 1370 struct address_space *mapping;
1da177e4 1371 struct inode *inode;
6922c0c7
HD
1372 swp_entry_t swap;
1373 pgoff_t index;
1da177e4 1374
800d8c63 1375 VM_BUG_ON_PAGE(PageCompound(page), page);
1da177e4 1376 BUG_ON(!PageLocked(page));
1da177e4
LT
1377 mapping = page->mapping;
1378 index = page->index;
1379 inode = mapping->host;
1380 info = SHMEM_I(inode);
1381 if (info->flags & VM_LOCKED)
1382 goto redirty;
d9fe526a 1383 if (!total_swap_pages)
1da177e4
LT
1384 goto redirty;
1385
d9fe526a 1386 /*
97b713ba
CH
1387 * Our capabilities prevent regular writeback or sync from ever calling
1388 * shmem_writepage; but a stacking filesystem might use ->writepage of
1389 * its underlying filesystem, in which case tmpfs should write out to
1390 * swap only in response to memory pressure, and not for the writeback
1391 * threads or sync.
d9fe526a 1392 */
48f170fb
HD
1393 if (!wbc->for_reclaim) {
1394 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1395 goto redirty;
1396 }
1635f6a7
HD
1397
1398 /*
1399 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1400 * value into swapfile.c, the only way we can correctly account for a
1401 * fallocated page arriving here is now to initialize it and write it.
1aac1400
HD
1402 *
1403 * That's okay for a page already fallocated earlier, but if we have
1404 * not yet completed the fallocation, then (a) we want to keep track
1405 * of this page in case we have to undo it, and (b) it may not be a
1406 * good idea to continue anyway, once we're pushing into swap. So
1407 * reactivate the page, and let shmem_fallocate() quit when too many.
1635f6a7
HD
1408 */
1409 if (!PageUptodate(page)) {
1aac1400
HD
1410 if (inode->i_private) {
1411 struct shmem_falloc *shmem_falloc;
1412 spin_lock(&inode->i_lock);
1413 shmem_falloc = inode->i_private;
1414 if (shmem_falloc &&
8e205f77 1415 !shmem_falloc->waitq &&
1aac1400
HD
1416 index >= shmem_falloc->start &&
1417 index < shmem_falloc->next)
1418 shmem_falloc->nr_unswapped++;
1419 else
1420 shmem_falloc = NULL;
1421 spin_unlock(&inode->i_lock);
1422 if (shmem_falloc)
1423 goto redirty;
1424 }
1635f6a7
HD
1425 clear_highpage(page);
1426 flush_dcache_page(page);
1427 SetPageUptodate(page);
1428 }
1429
38d8b4e6 1430 swap = get_swap_page(page);
48f170fb
HD
1431 if (!swap.val)
1432 goto redirty;
d9fe526a 1433
b1dea800
HD
1434 /*
1435 * Add inode to shmem_unuse()'s list of swapped-out inodes,
6922c0c7
HD
1436 * if it's not already there. Do it now before the page is
1437 * moved to swap cache, when its pagelock no longer protects
b1dea800 1438 * the inode from eviction. But don't unlock the mutex until
6922c0c7
HD
1439 * we've incremented swapped, because shmem_unuse_inode() will
1440 * prune a !swapped inode from the swaplist under this mutex.
b1dea800 1441 */
48f170fb
HD
1442 mutex_lock(&shmem_swaplist_mutex);
1443 if (list_empty(&info->swaplist))
b56a2d8a 1444 list_add(&info->swaplist, &shmem_swaplist);
b1dea800 1445
4afab1cd 1446 if (add_to_swap_cache(page, swap,
3852f676
JK
1447 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN,
1448 NULL) == 0) {
4595ef88 1449 spin_lock_irq(&info->lock);
6922c0c7 1450 shmem_recalc_inode(inode);
267a4c76 1451 info->swapped++;
4595ef88 1452 spin_unlock_irq(&info->lock);
6922c0c7 1453
267a4c76
HD
1454 swap_shmem_alloc(swap);
1455 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1456
6922c0c7 1457 mutex_unlock(&shmem_swaplist_mutex);
d9fe526a 1458 BUG_ON(page_mapped(page));
9fab5619 1459 swap_writepage(page, wbc);
1da177e4
LT
1460 return 0;
1461 }
1462
6922c0c7 1463 mutex_unlock(&shmem_swaplist_mutex);
75f6d6d2 1464 put_swap_page(page, swap);
1da177e4
LT
1465redirty:
1466 set_page_dirty(page);
d9fe526a
HD
1467 if (wbc->for_reclaim)
1468 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1469 unlock_page(page);
1470 return 0;
1da177e4
LT
1471}
1472
75edd345 1473#if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
71fe804b 1474static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
680d794b 1475{
095f1fc4 1476 char buffer[64];
680d794b 1477
71fe804b 1478 if (!mpol || mpol->mode == MPOL_DEFAULT)
095f1fc4 1479 return; /* show nothing */
680d794b 1480
a7a88b23 1481 mpol_to_str(buffer, sizeof(buffer), mpol);
095f1fc4
LS
1482
1483 seq_printf(seq, ",mpol=%s", buffer);
680d794b 1484}
71fe804b
LS
1485
1486static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1487{
1488 struct mempolicy *mpol = NULL;
1489 if (sbinfo->mpol) {
1490 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1491 mpol = sbinfo->mpol;
1492 mpol_get(mpol);
1493 spin_unlock(&sbinfo->stat_lock);
1494 }
1495 return mpol;
1496}
75edd345
HD
1497#else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1498static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1499{
1500}
1501static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1502{
1503 return NULL;
1504}
1505#endif /* CONFIG_NUMA && CONFIG_TMPFS */
1506#ifndef CONFIG_NUMA
1507#define vm_policy vm_private_data
1508#endif
680d794b 1509
800d8c63
KS
1510static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1511 struct shmem_inode_info *info, pgoff_t index)
1512{
1513 /* Create a pseudo vma that just contains the policy */
2c4541e2 1514 vma_init(vma, NULL);
800d8c63
KS
1515 /* Bias interleave by inode number to distribute better across nodes */
1516 vma->vm_pgoff = index + info->vfs_inode.i_ino;
800d8c63
KS
1517 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1518}
1519
1520static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1521{
1522 /* Drop reference taken by mpol_shared_policy_lookup() */
1523 mpol_cond_put(vma->vm_policy);
1524}
1525
41ffe5d5
HD
1526static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1527 struct shmem_inode_info *info, pgoff_t index)
1da177e4 1528{
1da177e4 1529 struct vm_area_struct pvma;
18a2f371 1530 struct page *page;
e9e9b7ec 1531 struct vm_fault vmf;
52cd3b07 1532
800d8c63 1533 shmem_pseudo_vma_init(&pvma, info, index);
e9e9b7ec
MK
1534 vmf.vma = &pvma;
1535 vmf.address = 0;
1536 page = swap_cluster_readahead(swap, gfp, &vmf);
800d8c63 1537 shmem_pseudo_vma_destroy(&pvma);
18a2f371 1538
800d8c63
KS
1539 return page;
1540}
1541
1542static struct page *shmem_alloc_hugepage(gfp_t gfp,
1543 struct shmem_inode_info *info, pgoff_t index)
1544{
1545 struct vm_area_struct pvma;
7b8d046f
MW
1546 struct address_space *mapping = info->vfs_inode.i_mapping;
1547 pgoff_t hindex;
800d8c63
KS
1548 struct page *page;
1549
4620a06e 1550 hindex = round_down(index, HPAGE_PMD_NR);
7b8d046f
MW
1551 if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
1552 XA_PRESENT))
800d8c63 1553 return NULL;
18a2f371 1554
800d8c63
KS
1555 shmem_pseudo_vma_init(&pvma, info, hindex);
1556 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
19deb769 1557 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
800d8c63
KS
1558 shmem_pseudo_vma_destroy(&pvma);
1559 if (page)
1560 prep_transhuge_page(page);
dcdf11ee
DR
1561 else
1562 count_vm_event(THP_FILE_FALLBACK);
18a2f371 1563 return page;
1da177e4
LT
1564}
1565
02098fea 1566static struct page *shmem_alloc_page(gfp_t gfp,
41ffe5d5 1567 struct shmem_inode_info *info, pgoff_t index)
1da177e4
LT
1568{
1569 struct vm_area_struct pvma;
18a2f371 1570 struct page *page;
1da177e4 1571
800d8c63
KS
1572 shmem_pseudo_vma_init(&pvma, info, index);
1573 page = alloc_page_vma(gfp, &pvma, 0);
1574 shmem_pseudo_vma_destroy(&pvma);
1575
1576 return page;
1577}
1578
1579static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
0f079694 1580 struct inode *inode,
800d8c63
KS
1581 pgoff_t index, bool huge)
1582{
0f079694 1583 struct shmem_inode_info *info = SHMEM_I(inode);
800d8c63
KS
1584 struct page *page;
1585 int nr;
1586 int err = -ENOSPC;
52cd3b07 1587
396bcc52 1588 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
800d8c63
KS
1589 huge = false;
1590 nr = huge ? HPAGE_PMD_NR : 1;
1591
0f079694 1592 if (!shmem_inode_acct_block(inode, nr))
800d8c63 1593 goto failed;
800d8c63
KS
1594
1595 if (huge)
1596 page = shmem_alloc_hugepage(gfp, info, index);
1597 else
1598 page = shmem_alloc_page(gfp, info, index);
75edd345
HD
1599 if (page) {
1600 __SetPageLocked(page);
1601 __SetPageSwapBacked(page);
800d8c63 1602 return page;
75edd345 1603 }
18a2f371 1604
800d8c63 1605 err = -ENOMEM;
0f079694 1606 shmem_inode_unacct_blocks(inode, nr);
800d8c63
KS
1607failed:
1608 return ERR_PTR(err);
1da177e4 1609}
71fe804b 1610
bde05d1c
HD
1611/*
1612 * When a page is moved from swapcache to shmem filecache (either by the
1613 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1614 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1615 * ignorance of the mapping it belongs to. If that mapping has special
1616 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1617 * we may need to copy to a suitable page before moving to filecache.
1618 *
1619 * In a future release, this may well be extended to respect cpuset and
1620 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1621 * but for now it is a simple matter of zone.
1622 */
1623static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1624{
1625 return page_zonenum(page) > gfp_zone(gfp);
1626}
1627
1628static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1629 struct shmem_inode_info *info, pgoff_t index)
1630{
1631 struct page *oldpage, *newpage;
1632 struct address_space *swap_mapping;
c1cb20d4 1633 swp_entry_t entry;
bde05d1c
HD
1634 pgoff_t swap_index;
1635 int error;
1636
1637 oldpage = *pagep;
c1cb20d4
YZ
1638 entry.val = page_private(oldpage);
1639 swap_index = swp_offset(entry);
bde05d1c
HD
1640 swap_mapping = page_mapping(oldpage);
1641
1642 /*
1643 * We have arrived here because our zones are constrained, so don't
1644 * limit chance of success by further cpuset and node constraints.
1645 */
1646 gfp &= ~GFP_CONSTRAINT_MASK;
1647 newpage = shmem_alloc_page(gfp, info, index);
1648 if (!newpage)
1649 return -ENOMEM;
bde05d1c 1650
09cbfeaf 1651 get_page(newpage);
bde05d1c 1652 copy_highpage(newpage, oldpage);
0142ef6c 1653 flush_dcache_page(newpage);
bde05d1c 1654
9956edf3
HD
1655 __SetPageLocked(newpage);
1656 __SetPageSwapBacked(newpage);
bde05d1c 1657 SetPageUptodate(newpage);
c1cb20d4 1658 set_page_private(newpage, entry.val);
bde05d1c
HD
1659 SetPageSwapCache(newpage);
1660
1661 /*
1662 * Our caller will very soon move newpage out of swapcache, but it's
1663 * a nice clean interface for us to replace oldpage by newpage there.
1664 */
b93b0163 1665 xa_lock_irq(&swap_mapping->i_pages);
62f945b6 1666 error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
0142ef6c 1667 if (!error) {
0d1c2072
JW
1668 mem_cgroup_migrate(oldpage, newpage);
1669 __inc_lruvec_page_state(newpage, NR_FILE_PAGES);
1670 __dec_lruvec_page_state(oldpage, NR_FILE_PAGES);
0142ef6c 1671 }
b93b0163 1672 xa_unlock_irq(&swap_mapping->i_pages);
bde05d1c 1673
0142ef6c
HD
1674 if (unlikely(error)) {
1675 /*
1676 * Is this possible? I think not, now that our callers check
1677 * both PageSwapCache and page_private after getting page lock;
1678 * but be defensive. Reverse old to newpage for clear and free.
1679 */
1680 oldpage = newpage;
1681 } else {
6058eaec 1682 lru_cache_add(newpage);
0142ef6c
HD
1683 *pagep = newpage;
1684 }
bde05d1c
HD
1685
1686 ClearPageSwapCache(oldpage);
1687 set_page_private(oldpage, 0);
1688
1689 unlock_page(oldpage);
09cbfeaf
KS
1690 put_page(oldpage);
1691 put_page(oldpage);
0142ef6c 1692 return error;
bde05d1c
HD
1693}
1694
c5bf121e
VRP
1695/*
1696 * Swap in the page pointed to by *pagep.
1697 * Caller has to make sure that *pagep contains a valid swapped page.
1698 * Returns 0 and the page in pagep if success. On failure, returns the
af44c12f 1699 * error code and NULL in *pagep.
c5bf121e
VRP
1700 */
1701static int shmem_swapin_page(struct inode *inode, pgoff_t index,
1702 struct page **pagep, enum sgp_type sgp,
1703 gfp_t gfp, struct vm_area_struct *vma,
1704 vm_fault_t *fault_type)
1705{
1706 struct address_space *mapping = inode->i_mapping;
1707 struct shmem_inode_info *info = SHMEM_I(inode);
1708 struct mm_struct *charge_mm = vma ? vma->vm_mm : current->mm;
c5bf121e
VRP
1709 struct page *page;
1710 swp_entry_t swap;
1711 int error;
1712
1713 VM_BUG_ON(!*pagep || !xa_is_value(*pagep));
1714 swap = radix_to_swp_entry(*pagep);
1715 *pagep = NULL;
1716
1717 /* Look it up and read it in.. */
1718 page = lookup_swap_cache(swap, NULL, 0);
1719 if (!page) {
1720 /* Or update major stats only when swapin succeeds?? */
1721 if (fault_type) {
1722 *fault_type |= VM_FAULT_MAJOR;
1723 count_vm_event(PGMAJFAULT);
1724 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1725 }
1726 /* Here we actually start the io */
1727 page = shmem_swapin(swap, gfp, info, index);
1728 if (!page) {
1729 error = -ENOMEM;
1730 goto failed;
1731 }
1732 }
1733
1734 /* We have to do this with page locked to prevent races */
1735 lock_page(page);
1736 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1737 !shmem_confirm_swap(mapping, index, swap)) {
1738 error = -EEXIST;
1739 goto unlock;
1740 }
1741 if (!PageUptodate(page)) {
1742 error = -EIO;
1743 goto failed;
1744 }
1745 wait_on_page_writeback(page);
1746
8a84802e
SP
1747 /*
1748 * Some architectures may have to restore extra metadata to the
1749 * physical page after reading from swap.
1750 */
1751 arch_swap_restore(swap, page);
1752
c5bf121e
VRP
1753 if (shmem_should_replace_page(page, gfp)) {
1754 error = shmem_replace_page(&page, gfp, info, index);
1755 if (error)
1756 goto failed;
1757 }
1758
14235ab3 1759 error = shmem_add_to_page_cache(page, mapping, index,
3fea5a49
JW
1760 swp_to_radix_entry(swap), gfp,
1761 charge_mm);
1762 if (error)
14235ab3 1763 goto failed;
c5bf121e
VRP
1764
1765 spin_lock_irq(&info->lock);
1766 info->swapped--;
1767 shmem_recalc_inode(inode);
1768 spin_unlock_irq(&info->lock);
1769
1770 if (sgp == SGP_WRITE)
1771 mark_page_accessed(page);
1772
1773 delete_from_swap_cache(page);
1774 set_page_dirty(page);
1775 swap_free(swap);
1776
1777 *pagep = page;
1778 return 0;
1779failed:
1780 if (!shmem_confirm_swap(mapping, index, swap))
1781 error = -EEXIST;
1782unlock:
1783 if (page) {
1784 unlock_page(page);
1785 put_page(page);
1786 }
1787
1788 return error;
1789}
1790
1da177e4 1791/*
68da9f05 1792 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1da177e4
LT
1793 *
1794 * If we allocate a new one we do not mark it dirty. That's up to the
1795 * vm. If we swap it in we mark it dirty since we also free the swap
9e18eb29
ALC
1796 * entry since a page cannot live in both the swap and page cache.
1797 *
28eb3c80 1798 * vmf and fault_type are only supplied by shmem_fault:
9e18eb29 1799 * otherwise they are NULL.
1da177e4 1800 */
41ffe5d5 1801static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
9e18eb29 1802 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
2b740303
SJ
1803 struct vm_area_struct *vma, struct vm_fault *vmf,
1804 vm_fault_t *fault_type)
1da177e4
LT
1805{
1806 struct address_space *mapping = inode->i_mapping;
23f919d4 1807 struct shmem_inode_info *info = SHMEM_I(inode);
1da177e4 1808 struct shmem_sb_info *sbinfo;
9e18eb29 1809 struct mm_struct *charge_mm;
27ab7006 1810 struct page *page;
657e3038 1811 enum sgp_type sgp_huge = sgp;
800d8c63 1812 pgoff_t hindex = index;
1da177e4 1813 int error;
54af6042 1814 int once = 0;
1635f6a7 1815 int alloced = 0;
1da177e4 1816
09cbfeaf 1817 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1da177e4 1818 return -EFBIG;
657e3038
KS
1819 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1820 sgp = SGP_CACHE;
1da177e4 1821repeat:
c5bf121e
VRP
1822 if (sgp <= SGP_CACHE &&
1823 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1824 return -EINVAL;
1825 }
1826
1827 sbinfo = SHMEM_SB(inode->i_sb);
1828 charge_mm = vma ? vma->vm_mm : current->mm;
1829
0cd6144a 1830 page = find_lock_entry(mapping, index);
3159f943 1831 if (xa_is_value(page)) {
c5bf121e
VRP
1832 error = shmem_swapin_page(inode, index, &page,
1833 sgp, gfp, vma, fault_type);
1834 if (error == -EEXIST)
1835 goto repeat;
54af6042 1836
c5bf121e
VRP
1837 *pagep = page;
1838 return error;
54af6042
HD
1839 }
1840
63ec1973
MWO
1841 if (page)
1842 hindex = page->index;
66d2f4d2
HD
1843 if (page && sgp == SGP_WRITE)
1844 mark_page_accessed(page);
1845
1635f6a7
HD
1846 /* fallocated page? */
1847 if (page && !PageUptodate(page)) {
1848 if (sgp != SGP_READ)
1849 goto clear;
1850 unlock_page(page);
09cbfeaf 1851 put_page(page);
1635f6a7 1852 page = NULL;
63ec1973 1853 hindex = index;
1635f6a7 1854 }
63ec1973
MWO
1855 if (page || sgp == SGP_READ)
1856 goto out;
27ab7006
HD
1857
1858 /*
54af6042
HD
1859 * Fast cache lookup did not find it:
1860 * bring it back from swap or allocate.
27ab7006 1861 */
54af6042 1862
c5bf121e
VRP
1863 if (vma && userfaultfd_missing(vma)) {
1864 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1865 return 0;
1866 }
cfda0526 1867
c5bf121e
VRP
1868 /* shmem_symlink() */
1869 if (mapping->a_ops != &shmem_aops)
1870 goto alloc_nohuge;
1871 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1872 goto alloc_nohuge;
1873 if (shmem_huge == SHMEM_HUGE_FORCE)
1874 goto alloc_huge;
1875 switch (sbinfo->huge) {
c5bf121e
VRP
1876 case SHMEM_HUGE_NEVER:
1877 goto alloc_nohuge;
27d80fa2
KC
1878 case SHMEM_HUGE_WITHIN_SIZE: {
1879 loff_t i_size;
1880 pgoff_t off;
1881
c5bf121e
VRP
1882 off = round_up(index, HPAGE_PMD_NR);
1883 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1884 if (i_size >= HPAGE_PMD_SIZE &&
1885 i_size >> PAGE_SHIFT >= off)
800d8c63 1886 goto alloc_huge;
27d80fa2
KC
1887
1888 fallthrough;
1889 }
c5bf121e
VRP
1890 case SHMEM_HUGE_ADVISE:
1891 if (sgp_huge == SGP_HUGE)
1892 goto alloc_huge;
1893 /* TODO: implement fadvise() hints */
1894 goto alloc_nohuge;
1895 }
1da177e4 1896
800d8c63 1897alloc_huge:
c5bf121e
VRP
1898 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1899 if (IS_ERR(page)) {
1900alloc_nohuge:
1901 page = shmem_alloc_and_acct_page(gfp, inode,
1902 index, false);
1903 }
1904 if (IS_ERR(page)) {
1905 int retry = 5;
800d8c63 1906
c5bf121e
VRP
1907 error = PTR_ERR(page);
1908 page = NULL;
1909 if (error != -ENOSPC)
1910 goto unlock;
1911 /*
1912 * Try to reclaim some space by splitting a huge page
1913 * beyond i_size on the filesystem.
1914 */
1915 while (retry--) {
1916 int ret;
66d2f4d2 1917
c5bf121e
VRP
1918 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1919 if (ret == SHRINK_STOP)
1920 break;
1921 if (ret)
1922 goto alloc_nohuge;
b065b432 1923 }
c5bf121e
VRP
1924 goto unlock;
1925 }
54af6042 1926
c5bf121e
VRP
1927 if (PageTransHuge(page))
1928 hindex = round_down(index, HPAGE_PMD_NR);
1929 else
1930 hindex = index;
54af6042 1931
c5bf121e
VRP
1932 if (sgp == SGP_WRITE)
1933 __SetPageReferenced(page);
1934
c5bf121e 1935 error = shmem_add_to_page_cache(page, mapping, hindex,
3fea5a49
JW
1936 NULL, gfp & GFP_RECLAIM_MASK,
1937 charge_mm);
1938 if (error)
c5bf121e 1939 goto unacct;
6058eaec 1940 lru_cache_add(page);
779750d2 1941
c5bf121e 1942 spin_lock_irq(&info->lock);
d8c6546b 1943 info->alloced += compound_nr(page);
c5bf121e
VRP
1944 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1945 shmem_recalc_inode(inode);
1946 spin_unlock_irq(&info->lock);
1947 alloced = true;
1948
1949 if (PageTransHuge(page) &&
1950 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1951 hindex + HPAGE_PMD_NR - 1) {
ec9516fb 1952 /*
c5bf121e
VRP
1953 * Part of the huge page is beyond i_size: subject
1954 * to shrink under memory pressure.
1635f6a7 1955 */
c5bf121e 1956 spin_lock(&sbinfo->shrinklist_lock);
1635f6a7 1957 /*
c5bf121e
VRP
1958 * _careful to defend against unlocked access to
1959 * ->shrink_list in shmem_unused_huge_shrink()
ec9516fb 1960 */
c5bf121e
VRP
1961 if (list_empty_careful(&info->shrinklist)) {
1962 list_add_tail(&info->shrinklist,
1963 &sbinfo->shrinklist);
1964 sbinfo->shrinklist_len++;
1965 }
1966 spin_unlock(&sbinfo->shrinklist_lock);
1967 }
800d8c63 1968
c5bf121e
VRP
1969 /*
1970 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1971 */
1972 if (sgp == SGP_FALLOC)
1973 sgp = SGP_WRITE;
1974clear:
1975 /*
1976 * Let SGP_WRITE caller clear ends if write does not fill page;
1977 * but SGP_FALLOC on a page fallocated earlier must initialize
1978 * it now, lest undo on failure cancel our earlier guarantee.
1979 */
1980 if (sgp != SGP_WRITE && !PageUptodate(page)) {
c5bf121e
VRP
1981 int i;
1982
63ec1973
MWO
1983 for (i = 0; i < compound_nr(page); i++) {
1984 clear_highpage(page + i);
1985 flush_dcache_page(page + i);
ec9516fb 1986 }
63ec1973 1987 SetPageUptodate(page);
1da177e4 1988 }
bde05d1c 1989
54af6042 1990 /* Perhaps the file has been truncated since we checked */
75edd345 1991 if (sgp <= SGP_CACHE &&
09cbfeaf 1992 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
267a4c76
HD
1993 if (alloced) {
1994 ClearPageDirty(page);
1995 delete_from_page_cache(page);
4595ef88 1996 spin_lock_irq(&info->lock);
267a4c76 1997 shmem_recalc_inode(inode);
4595ef88 1998 spin_unlock_irq(&info->lock);
267a4c76 1999 }
54af6042 2000 error = -EINVAL;
267a4c76 2001 goto unlock;
e83c32e8 2002 }
63ec1973 2003out:
800d8c63 2004 *pagep = page + index - hindex;
54af6042 2005 return 0;
1da177e4 2006
59a16ead 2007 /*
54af6042 2008 * Error recovery.
59a16ead 2009 */
54af6042 2010unacct:
d8c6546b 2011 shmem_inode_unacct_blocks(inode, compound_nr(page));
800d8c63
KS
2012
2013 if (PageTransHuge(page)) {
2014 unlock_page(page);
2015 put_page(page);
2016 goto alloc_nohuge;
2017 }
d1899228 2018unlock:
27ab7006 2019 if (page) {
54af6042 2020 unlock_page(page);
09cbfeaf 2021 put_page(page);
54af6042
HD
2022 }
2023 if (error == -ENOSPC && !once++) {
4595ef88 2024 spin_lock_irq(&info->lock);
54af6042 2025 shmem_recalc_inode(inode);
4595ef88 2026 spin_unlock_irq(&info->lock);
27ab7006 2027 goto repeat;
ff36b801 2028 }
7f4446ee 2029 if (error == -EEXIST)
54af6042
HD
2030 goto repeat;
2031 return error;
1da177e4
LT
2032}
2033
10d20bd2
LT
2034/*
2035 * This is like autoremove_wake_function, but it removes the wait queue
2036 * entry unconditionally - even if something else had already woken the
2037 * target.
2038 */
ac6424b9 2039static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
10d20bd2
LT
2040{
2041 int ret = default_wake_function(wait, mode, sync, key);
2055da97 2042 list_del_init(&wait->entry);
10d20bd2
LT
2043 return ret;
2044}
2045
20acce67 2046static vm_fault_t shmem_fault(struct vm_fault *vmf)
1da177e4 2047{
11bac800 2048 struct vm_area_struct *vma = vmf->vma;
496ad9aa 2049 struct inode *inode = file_inode(vma->vm_file);
9e18eb29 2050 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
657e3038 2051 enum sgp_type sgp;
20acce67
SJ
2052 int err;
2053 vm_fault_t ret = VM_FAULT_LOCKED;
1da177e4 2054
f00cdc6d
HD
2055 /*
2056 * Trinity finds that probing a hole which tmpfs is punching can
2057 * prevent the hole-punch from ever completing: which in turn
2058 * locks writers out with its hold on i_mutex. So refrain from
8e205f77
HD
2059 * faulting pages into the hole while it's being punched. Although
2060 * shmem_undo_range() does remove the additions, it may be unable to
2061 * keep up, as each new page needs its own unmap_mapping_range() call,
2062 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2063 *
2064 * It does not matter if we sometimes reach this check just before the
2065 * hole-punch begins, so that one fault then races with the punch:
2066 * we just need to make racing faults a rare case.
2067 *
2068 * The implementation below would be much simpler if we just used a
2069 * standard mutex or completion: but we cannot take i_mutex in fault,
2070 * and bloating every shmem inode for this unlikely case would be sad.
f00cdc6d
HD
2071 */
2072 if (unlikely(inode->i_private)) {
2073 struct shmem_falloc *shmem_falloc;
2074
2075 spin_lock(&inode->i_lock);
2076 shmem_falloc = inode->i_private;
8e205f77
HD
2077 if (shmem_falloc &&
2078 shmem_falloc->waitq &&
2079 vmf->pgoff >= shmem_falloc->start &&
2080 vmf->pgoff < shmem_falloc->next) {
8897c1b1 2081 struct file *fpin;
8e205f77 2082 wait_queue_head_t *shmem_falloc_waitq;
10d20bd2 2083 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
8e205f77
HD
2084
2085 ret = VM_FAULT_NOPAGE;
8897c1b1
KS
2086 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2087 if (fpin)
8e205f77 2088 ret = VM_FAULT_RETRY;
8e205f77
HD
2089
2090 shmem_falloc_waitq = shmem_falloc->waitq;
2091 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
2092 TASK_UNINTERRUPTIBLE);
2093 spin_unlock(&inode->i_lock);
2094 schedule();
2095
2096 /*
2097 * shmem_falloc_waitq points into the shmem_fallocate()
2098 * stack of the hole-punching task: shmem_falloc_waitq
2099 * is usually invalid by the time we reach here, but
2100 * finish_wait() does not dereference it in that case;
2101 * though i_lock needed lest racing with wake_up_all().
2102 */
2103 spin_lock(&inode->i_lock);
2104 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2105 spin_unlock(&inode->i_lock);
8897c1b1
KS
2106
2107 if (fpin)
2108 fput(fpin);
8e205f77 2109 return ret;
f00cdc6d 2110 }
8e205f77 2111 spin_unlock(&inode->i_lock);
f00cdc6d
HD
2112 }
2113
657e3038 2114 sgp = SGP_CACHE;
18600332
MH
2115
2116 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
2117 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
657e3038 2118 sgp = SGP_NOHUGE;
18600332
MH
2119 else if (vma->vm_flags & VM_HUGEPAGE)
2120 sgp = SGP_HUGE;
657e3038 2121
20acce67 2122 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
cfda0526 2123 gfp, vma, vmf, &ret);
20acce67
SJ
2124 if (err)
2125 return vmf_error(err);
68da9f05 2126 return ret;
1da177e4
LT
2127}
2128
c01d5b30
HD
2129unsigned long shmem_get_unmapped_area(struct file *file,
2130 unsigned long uaddr, unsigned long len,
2131 unsigned long pgoff, unsigned long flags)
2132{
2133 unsigned long (*get_area)(struct file *,
2134 unsigned long, unsigned long, unsigned long, unsigned long);
2135 unsigned long addr;
2136 unsigned long offset;
2137 unsigned long inflated_len;
2138 unsigned long inflated_addr;
2139 unsigned long inflated_offset;
2140
2141 if (len > TASK_SIZE)
2142 return -ENOMEM;
2143
2144 get_area = current->mm->get_unmapped_area;
2145 addr = get_area(file, uaddr, len, pgoff, flags);
2146
396bcc52 2147 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
c01d5b30
HD
2148 return addr;
2149 if (IS_ERR_VALUE(addr))
2150 return addr;
2151 if (addr & ~PAGE_MASK)
2152 return addr;
2153 if (addr > TASK_SIZE - len)
2154 return addr;
2155
2156 if (shmem_huge == SHMEM_HUGE_DENY)
2157 return addr;
2158 if (len < HPAGE_PMD_SIZE)
2159 return addr;
2160 if (flags & MAP_FIXED)
2161 return addr;
2162 /*
2163 * Our priority is to support MAP_SHARED mapped hugely;
2164 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
99158997
KS
2165 * But if caller specified an address hint and we allocated area there
2166 * successfully, respect that as before.
c01d5b30 2167 */
99158997 2168 if (uaddr == addr)
c01d5b30
HD
2169 return addr;
2170
2171 if (shmem_huge != SHMEM_HUGE_FORCE) {
2172 struct super_block *sb;
2173
2174 if (file) {
2175 VM_BUG_ON(file->f_op != &shmem_file_operations);
2176 sb = file_inode(file)->i_sb;
2177 } else {
2178 /*
2179 * Called directly from mm/mmap.c, or drivers/char/mem.c
2180 * for "/dev/zero", to create a shared anonymous object.
2181 */
2182 if (IS_ERR(shm_mnt))
2183 return addr;
2184 sb = shm_mnt->mnt_sb;
2185 }
3089bf61 2186 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
c01d5b30
HD
2187 return addr;
2188 }
2189
2190 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2191 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2192 return addr;
2193 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2194 return addr;
2195
2196 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2197 if (inflated_len > TASK_SIZE)
2198 return addr;
2199 if (inflated_len < len)
2200 return addr;
2201
99158997 2202 inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
c01d5b30
HD
2203 if (IS_ERR_VALUE(inflated_addr))
2204 return addr;
2205 if (inflated_addr & ~PAGE_MASK)
2206 return addr;
2207
2208 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2209 inflated_addr += offset - inflated_offset;
2210 if (inflated_offset > offset)
2211 inflated_addr += HPAGE_PMD_SIZE;
2212
2213 if (inflated_addr > TASK_SIZE - len)
2214 return addr;
2215 return inflated_addr;
2216}
2217
1da177e4 2218#ifdef CONFIG_NUMA
41ffe5d5 2219static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
1da177e4 2220{
496ad9aa 2221 struct inode *inode = file_inode(vma->vm_file);
41ffe5d5 2222 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
1da177e4
LT
2223}
2224
d8dc74f2
AB
2225static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2226 unsigned long addr)
1da177e4 2227{
496ad9aa 2228 struct inode *inode = file_inode(vma->vm_file);
41ffe5d5 2229 pgoff_t index;
1da177e4 2230
41ffe5d5
HD
2231 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2232 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
1da177e4
LT
2233}
2234#endif
2235
2236int shmem_lock(struct file *file, int lock, struct user_struct *user)
2237{
496ad9aa 2238 struct inode *inode = file_inode(file);
1da177e4
LT
2239 struct shmem_inode_info *info = SHMEM_I(inode);
2240 int retval = -ENOMEM;
2241
ea0dfeb4
HD
2242 /*
2243 * What serializes the accesses to info->flags?
2244 * ipc_lock_object() when called from shmctl_do_lock(),
2245 * no serialization needed when called from shm_destroy().
2246 */
1da177e4
LT
2247 if (lock && !(info->flags & VM_LOCKED)) {
2248 if (!user_shm_lock(inode->i_size, user))
2249 goto out_nomem;
2250 info->flags |= VM_LOCKED;
89e004ea 2251 mapping_set_unevictable(file->f_mapping);
1da177e4
LT
2252 }
2253 if (!lock && (info->flags & VM_LOCKED) && user) {
2254 user_shm_unlock(inode->i_size, user);
2255 info->flags &= ~VM_LOCKED;
89e004ea 2256 mapping_clear_unevictable(file->f_mapping);
1da177e4
LT
2257 }
2258 retval = 0;
89e004ea 2259
1da177e4 2260out_nomem:
1da177e4
LT
2261 return retval;
2262}
2263
9b83a6a8 2264static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
1da177e4 2265{
ab3948f5
JFG
2266 struct shmem_inode_info *info = SHMEM_I(file_inode(file));
2267
2268 if (info->seals & F_SEAL_FUTURE_WRITE) {
2269 /*
2270 * New PROT_WRITE and MAP_SHARED mmaps are not allowed when
2271 * "future write" seal active.
2272 */
2273 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_WRITE))
2274 return -EPERM;
2275
2276 /*
05d35110
NG
2277 * Since an F_SEAL_FUTURE_WRITE sealed memfd can be mapped as
2278 * MAP_SHARED and read-only, take care to not allow mprotect to
2279 * revert protections on such mappings. Do this only for shared
2280 * mappings. For private mappings, don't need to mask
2281 * VM_MAYWRITE as we still want them to be COW-writable.
ab3948f5 2282 */
05d35110
NG
2283 if (vma->vm_flags & VM_SHARED)
2284 vma->vm_flags &= ~(VM_MAYWRITE);
ab3948f5
JFG
2285 }
2286
51b0bff2
CM
2287 /* arm64 - allow memory tagging on RAM-based files */
2288 vma->vm_flags |= VM_MTE_ALLOWED;
2289
1da177e4
LT
2290 file_accessed(file);
2291 vma->vm_ops = &shmem_vm_ops;
396bcc52 2292 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
f3f0e1d2
KS
2293 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2294 (vma->vm_end & HPAGE_PMD_MASK)) {
2295 khugepaged_enter(vma, vma->vm_flags);
2296 }
1da177e4
LT
2297 return 0;
2298}
2299
454abafe 2300static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
09208d15 2301 umode_t mode, dev_t dev, unsigned long flags)
1da177e4
LT
2302{
2303 struct inode *inode;
2304 struct shmem_inode_info *info;
2305 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
e809d5f0 2306 ino_t ino;
1da177e4 2307
e809d5f0 2308 if (shmem_reserve_inode(sb, &ino))
5b04c689 2309 return NULL;
1da177e4
LT
2310
2311 inode = new_inode(sb);
2312 if (inode) {
454abafe 2313 inode_init_owner(inode, dir, mode);
1da177e4 2314 inode->i_blocks = 0;
078cd827 2315 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
46c9a946 2316 inode->i_generation = prandom_u32();
1da177e4
LT
2317 info = SHMEM_I(inode);
2318 memset(info, 0, (char *)inode - (char *)info);
2319 spin_lock_init(&info->lock);
af53d3e9 2320 atomic_set(&info->stop_eviction, 0);
40e041a2 2321 info->seals = F_SEAL_SEAL;
0b0a0806 2322 info->flags = flags & VM_NORESERVE;
779750d2 2323 INIT_LIST_HEAD(&info->shrinklist);
1da177e4 2324 INIT_LIST_HEAD(&info->swaplist);
38f38657 2325 simple_xattrs_init(&info->xattrs);
72c04902 2326 cache_no_acl(inode);
1da177e4
LT
2327
2328 switch (mode & S_IFMT) {
2329 default:
39f0247d 2330 inode->i_op = &shmem_special_inode_operations;
1da177e4
LT
2331 init_special_inode(inode, mode, dev);
2332 break;
2333 case S_IFREG:
14fcc23f 2334 inode->i_mapping->a_ops = &shmem_aops;
1da177e4
LT
2335 inode->i_op = &shmem_inode_operations;
2336 inode->i_fop = &shmem_file_operations;
71fe804b
LS
2337 mpol_shared_policy_init(&info->policy,
2338 shmem_get_sbmpol(sbinfo));
1da177e4
LT
2339 break;
2340 case S_IFDIR:
d8c76e6f 2341 inc_nlink(inode);
1da177e4
LT
2342 /* Some things misbehave if size == 0 on a directory */
2343 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2344 inode->i_op = &shmem_dir_inode_operations;
2345 inode->i_fop = &simple_dir_operations;
2346 break;
2347 case S_IFLNK:
2348 /*
2349 * Must not load anything in the rbtree,
2350 * mpol_free_shared_policy will not be called.
2351 */
71fe804b 2352 mpol_shared_policy_init(&info->policy, NULL);
1da177e4
LT
2353 break;
2354 }
b45d71fb 2355
a3853725
PP
2356 if (!sbinfo->idr_nouse) {
2357 /* inum 0 and 1 are unused */
2358 mutex_lock(&sbinfo->idr_lock);
2359 ino = idr_alloc(&sbinfo->idr, inode, 2, INT_MAX,
2360 GFP_NOFS);
2361 if (ino > 0) {
2362 inode->i_ino = ino;
2363 mutex_unlock(&sbinfo->idr_lock);
2364 __insert_inode_hash(inode, inode->i_ino);
2365 } else {
2366 inode->i_ino = 0;
2367 mutex_unlock(&sbinfo->idr_lock);
2368 iput(inode);
2369 /* shmem_free_inode() will be called */
2370 inode = NULL;
2371 }
2372 } else
2373 inode->i_ino = ino;
2374
b45d71fb 2375 lockdep_annotate_inode_mutex_key(inode);
5b04c689
PE
2376 } else
2377 shmem_free_inode(sb);
1da177e4
LT
2378 return inode;
2379}
2380
0cd6144a
JW
2381bool shmem_mapping(struct address_space *mapping)
2382{
f8005451 2383 return mapping->a_ops == &shmem_aops;
0cd6144a
JW
2384}
2385
8d103963
MR
2386static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2387 pmd_t *dst_pmd,
2388 struct vm_area_struct *dst_vma,
2389 unsigned long dst_addr,
2390 unsigned long src_addr,
2391 bool zeropage,
2392 struct page **pagep)
4c27fe4c
MR
2393{
2394 struct inode *inode = file_inode(dst_vma->vm_file);
2395 struct shmem_inode_info *info = SHMEM_I(inode);
4c27fe4c
MR
2396 struct address_space *mapping = inode->i_mapping;
2397 gfp_t gfp = mapping_gfp_mask(mapping);
2398 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
4c27fe4c
MR
2399 spinlock_t *ptl;
2400 void *page_kaddr;
2401 struct page *page;
2402 pte_t _dst_pte, *dst_pte;
2403 int ret;
e2a50c1f 2404 pgoff_t offset, max_off;
4c27fe4c 2405
cb658a45 2406 ret = -ENOMEM;
0f079694 2407 if (!shmem_inode_acct_block(inode, 1))
cb658a45 2408 goto out;
4c27fe4c 2409
cb658a45 2410 if (!*pagep) {
4c27fe4c
MR
2411 page = shmem_alloc_page(gfp, info, pgoff);
2412 if (!page)
0f079694 2413 goto out_unacct_blocks;
4c27fe4c 2414
8d103963
MR
2415 if (!zeropage) { /* mcopy_atomic */
2416 page_kaddr = kmap_atomic(page);
2417 ret = copy_from_user(page_kaddr,
2418 (const void __user *)src_addr,
2419 PAGE_SIZE);
2420 kunmap_atomic(page_kaddr);
2421
c1e8d7c6 2422 /* fallback to copy_from_user outside mmap_lock */
8d103963
MR
2423 if (unlikely(ret)) {
2424 *pagep = page;
2425 shmem_inode_unacct_blocks(inode, 1);
2426 /* don't free the page */
9e368259 2427 return -ENOENT;
8d103963
MR
2428 }
2429 } else { /* mfill_zeropage_atomic */
2430 clear_highpage(page);
4c27fe4c
MR
2431 }
2432 } else {
2433 page = *pagep;
2434 *pagep = NULL;
2435 }
2436
9cc90c66
AA
2437 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2438 __SetPageLocked(page);
2439 __SetPageSwapBacked(page);
a425d358 2440 __SetPageUptodate(page);
9cc90c66 2441
e2a50c1f
AA
2442 ret = -EFAULT;
2443 offset = linear_page_index(dst_vma, dst_addr);
2444 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2445 if (unlikely(offset >= max_off))
2446 goto out_release;
2447
552446a4 2448 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
3fea5a49 2449 gfp & GFP_RECLAIM_MASK, dst_mm);
4c27fe4c 2450 if (ret)
3fea5a49 2451 goto out_release;
4c27fe4c
MR
2452
2453 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2454 if (dst_vma->vm_flags & VM_WRITE)
2455 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
dcf7fe9d
AA
2456 else {
2457 /*
2458 * We don't set the pte dirty if the vma has no
2459 * VM_WRITE permission, so mark the page dirty or it
2460 * could be freed from under us. We could do it
2461 * unconditionally before unlock_page(), but doing it
2462 * only if VM_WRITE is not set is faster.
2463 */
2464 set_page_dirty(page);
2465 }
4c27fe4c 2466
4c27fe4c 2467 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
e2a50c1f
AA
2468
2469 ret = -EFAULT;
2470 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2471 if (unlikely(offset >= max_off))
3fea5a49 2472 goto out_release_unlock;
e2a50c1f
AA
2473
2474 ret = -EEXIST;
4c27fe4c 2475 if (!pte_none(*dst_pte))
3fea5a49 2476 goto out_release_unlock;
4c27fe4c 2477
6058eaec 2478 lru_cache_add(page);
4c27fe4c 2479
94b7cc01 2480 spin_lock_irq(&info->lock);
4c27fe4c
MR
2481 info->alloced++;
2482 inode->i_blocks += BLOCKS_PER_PAGE;
2483 shmem_recalc_inode(inode);
94b7cc01 2484 spin_unlock_irq(&info->lock);
4c27fe4c
MR
2485
2486 inc_mm_counter(dst_mm, mm_counter_file(page));
2487 page_add_file_rmap(page, false);
2488 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2489
2490 /* No need to invalidate - it was non-present before */
2491 update_mmu_cache(dst_vma, dst_addr, dst_pte);
4c27fe4c 2492 pte_unmap_unlock(dst_pte, ptl);
e2a50c1f 2493 unlock_page(page);
4c27fe4c
MR
2494 ret = 0;
2495out:
2496 return ret;
3fea5a49 2497out_release_unlock:
4c27fe4c 2498 pte_unmap_unlock(dst_pte, ptl);
dcf7fe9d 2499 ClearPageDirty(page);
e2a50c1f 2500 delete_from_page_cache(page);
4c27fe4c 2501out_release:
9cc90c66 2502 unlock_page(page);
4c27fe4c 2503 put_page(page);
4c27fe4c 2504out_unacct_blocks:
0f079694 2505 shmem_inode_unacct_blocks(inode, 1);
4c27fe4c
MR
2506 goto out;
2507}
2508
8d103963
MR
2509int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2510 pmd_t *dst_pmd,
2511 struct vm_area_struct *dst_vma,
2512 unsigned long dst_addr,
2513 unsigned long src_addr,
2514 struct page **pagep)
2515{
2516 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2517 dst_addr, src_addr, false, pagep);
2518}
2519
2520int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2521 pmd_t *dst_pmd,
2522 struct vm_area_struct *dst_vma,
2523 unsigned long dst_addr)
2524{
2525 struct page *page = NULL;
2526
2527 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2528 dst_addr, 0, true, &page);
2529}
2530
1da177e4 2531#ifdef CONFIG_TMPFS
92e1d5be 2532static const struct inode_operations shmem_symlink_inode_operations;
69f07ec9 2533static const struct inode_operations shmem_short_symlink_operations;
1da177e4 2534
6d9d88d0
JS
2535#ifdef CONFIG_TMPFS_XATTR
2536static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2537#else
2538#define shmem_initxattrs NULL
2539#endif
2540
1da177e4 2541static int
800d15a5
NP
2542shmem_write_begin(struct file *file, struct address_space *mapping,
2543 loff_t pos, unsigned len, unsigned flags,
2544 struct page **pagep, void **fsdata)
1da177e4 2545{
800d15a5 2546 struct inode *inode = mapping->host;
40e041a2 2547 struct shmem_inode_info *info = SHMEM_I(inode);
09cbfeaf 2548 pgoff_t index = pos >> PAGE_SHIFT;
40e041a2
DH
2549
2550 /* i_mutex is held by caller */
ab3948f5
JFG
2551 if (unlikely(info->seals & (F_SEAL_GROW |
2552 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
2553 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
40e041a2
DH
2554 return -EPERM;
2555 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2556 return -EPERM;
2557 }
2558
9e18eb29 2559 return shmem_getpage(inode, index, pagep, SGP_WRITE);
800d15a5
NP
2560}
2561
2562static int
2563shmem_write_end(struct file *file, struct address_space *mapping,
2564 loff_t pos, unsigned len, unsigned copied,
2565 struct page *page, void *fsdata)
2566{
2567 struct inode *inode = mapping->host;
2568
d3602444
HD
2569 if (pos + copied > inode->i_size)
2570 i_size_write(inode, pos + copied);
2571
ec9516fb 2572 if (!PageUptodate(page)) {
800d8c63
KS
2573 struct page *head = compound_head(page);
2574 if (PageTransCompound(page)) {
2575 int i;
2576
2577 for (i = 0; i < HPAGE_PMD_NR; i++) {
2578 if (head + i == page)
2579 continue;
2580 clear_highpage(head + i);
2581 flush_dcache_page(head + i);
2582 }
2583 }
09cbfeaf
KS
2584 if (copied < PAGE_SIZE) {
2585 unsigned from = pos & (PAGE_SIZE - 1);
ec9516fb 2586 zero_user_segments(page, 0, from,
09cbfeaf 2587 from + copied, PAGE_SIZE);
ec9516fb 2588 }
800d8c63 2589 SetPageUptodate(head);
ec9516fb 2590 }
800d15a5 2591 set_page_dirty(page);
6746aff7 2592 unlock_page(page);
09cbfeaf 2593 put_page(page);
800d15a5 2594
800d15a5 2595 return copied;
1da177e4
LT
2596}
2597
2ba5bbed 2598static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
1da177e4 2599{
6e58e79d
AV
2600 struct file *file = iocb->ki_filp;
2601 struct inode *inode = file_inode(file);
1da177e4 2602 struct address_space *mapping = inode->i_mapping;
41ffe5d5
HD
2603 pgoff_t index;
2604 unsigned long offset;
a0ee5ec5 2605 enum sgp_type sgp = SGP_READ;
f7c1d074 2606 int error = 0;
cb66a7a1 2607 ssize_t retval = 0;
6e58e79d 2608 loff_t *ppos = &iocb->ki_pos;
a0ee5ec5
HD
2609
2610 /*
2611 * Might this read be for a stacking filesystem? Then when reading
2612 * holes of a sparse file, we actually need to allocate those pages,
2613 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2614 */
777eda2c 2615 if (!iter_is_iovec(to))
75edd345 2616 sgp = SGP_CACHE;
1da177e4 2617
09cbfeaf
KS
2618 index = *ppos >> PAGE_SHIFT;
2619 offset = *ppos & ~PAGE_MASK;
1da177e4
LT
2620
2621 for (;;) {
2622 struct page *page = NULL;
41ffe5d5
HD
2623 pgoff_t end_index;
2624 unsigned long nr, ret;
1da177e4
LT
2625 loff_t i_size = i_size_read(inode);
2626
09cbfeaf 2627 end_index = i_size >> PAGE_SHIFT;
1da177e4
LT
2628 if (index > end_index)
2629 break;
2630 if (index == end_index) {
09cbfeaf 2631 nr = i_size & ~PAGE_MASK;
1da177e4
LT
2632 if (nr <= offset)
2633 break;
2634 }
2635
9e18eb29 2636 error = shmem_getpage(inode, index, &page, sgp);
6e58e79d
AV
2637 if (error) {
2638 if (error == -EINVAL)
2639 error = 0;
1da177e4
LT
2640 break;
2641 }
75edd345
HD
2642 if (page) {
2643 if (sgp == SGP_CACHE)
2644 set_page_dirty(page);
d3602444 2645 unlock_page(page);
75edd345 2646 }
1da177e4
LT
2647
2648 /*
2649 * We must evaluate after, since reads (unlike writes)
1b1dcc1b 2650 * are called without i_mutex protection against truncate
1da177e4 2651 */
09cbfeaf 2652 nr = PAGE_SIZE;
1da177e4 2653 i_size = i_size_read(inode);
09cbfeaf 2654 end_index = i_size >> PAGE_SHIFT;
1da177e4 2655 if (index == end_index) {
09cbfeaf 2656 nr = i_size & ~PAGE_MASK;
1da177e4
LT
2657 if (nr <= offset) {
2658 if (page)
09cbfeaf 2659 put_page(page);
1da177e4
LT
2660 break;
2661 }
2662 }
2663 nr -= offset;
2664
2665 if (page) {
2666 /*
2667 * If users can be writing to this page using arbitrary
2668 * virtual addresses, take care about potential aliasing
2669 * before reading the page on the kernel side.
2670 */
2671 if (mapping_writably_mapped(mapping))
2672 flush_dcache_page(page);
2673 /*
2674 * Mark the page accessed if we read the beginning.
2675 */
2676 if (!offset)
2677 mark_page_accessed(page);
b5810039 2678 } else {
1da177e4 2679 page = ZERO_PAGE(0);
09cbfeaf 2680 get_page(page);
b5810039 2681 }
1da177e4
LT
2682
2683 /*
2684 * Ok, we have the page, and it's up-to-date, so
2685 * now we can copy it to user space...
1da177e4 2686 */
2ba5bbed 2687 ret = copy_page_to_iter(page, offset, nr, to);
6e58e79d 2688 retval += ret;
1da177e4 2689 offset += ret;
09cbfeaf
KS
2690 index += offset >> PAGE_SHIFT;
2691 offset &= ~PAGE_MASK;
1da177e4 2692
09cbfeaf 2693 put_page(page);
2ba5bbed 2694 if (!iov_iter_count(to))
1da177e4 2695 break;
6e58e79d
AV
2696 if (ret < nr) {
2697 error = -EFAULT;
2698 break;
2699 }
1da177e4
LT
2700 cond_resched();
2701 }
2702
09cbfeaf 2703 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
6e58e79d
AV
2704 file_accessed(file);
2705 return retval ? retval : error;
1da177e4
LT
2706}
2707
220f2ac9 2708/*
7f4446ee 2709 * llseek SEEK_DATA or SEEK_HOLE through the page cache.
220f2ac9
HD
2710 */
2711static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
965c8e59 2712 pgoff_t index, pgoff_t end, int whence)
220f2ac9
HD
2713{
2714 struct page *page;
2715 struct pagevec pvec;
2716 pgoff_t indices[PAGEVEC_SIZE];
2717 bool done = false;
2718 int i;
2719
86679820 2720 pagevec_init(&pvec);
220f2ac9
HD
2721 pvec.nr = 1; /* start small: we may be there already */
2722 while (!done) {
0cd6144a 2723 pvec.nr = find_get_entries(mapping, index,
220f2ac9
HD
2724 pvec.nr, pvec.pages, indices);
2725 if (!pvec.nr) {
965c8e59 2726 if (whence == SEEK_DATA)
220f2ac9
HD
2727 index = end;
2728 break;
2729 }
2730 for (i = 0; i < pvec.nr; i++, index++) {
2731 if (index < indices[i]) {
965c8e59 2732 if (whence == SEEK_HOLE) {
220f2ac9
HD
2733 done = true;
2734 break;
2735 }
2736 index = indices[i];
2737 }
2738 page = pvec.pages[i];
3159f943 2739 if (page && !xa_is_value(page)) {
220f2ac9
HD
2740 if (!PageUptodate(page))
2741 page = NULL;
2742 }
2743 if (index >= end ||
965c8e59
AM
2744 (page && whence == SEEK_DATA) ||
2745 (!page && whence == SEEK_HOLE)) {
220f2ac9
HD
2746 done = true;
2747 break;
2748 }
2749 }
0cd6144a 2750 pagevec_remove_exceptionals(&pvec);
220f2ac9
HD
2751 pagevec_release(&pvec);
2752 pvec.nr = PAGEVEC_SIZE;
2753 cond_resched();
2754 }
2755 return index;
2756}
2757
965c8e59 2758static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
220f2ac9
HD
2759{
2760 struct address_space *mapping = file->f_mapping;
2761 struct inode *inode = mapping->host;
2762 pgoff_t start, end;
2763 loff_t new_offset;
2764
965c8e59
AM
2765 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2766 return generic_file_llseek_size(file, offset, whence,
220f2ac9 2767 MAX_LFS_FILESIZE, i_size_read(inode));
5955102c 2768 inode_lock(inode);
220f2ac9
HD
2769 /* We're holding i_mutex so we can access i_size directly */
2770
1a413646 2771 if (offset < 0 || offset >= inode->i_size)
220f2ac9
HD
2772 offset = -ENXIO;
2773 else {
09cbfeaf
KS
2774 start = offset >> PAGE_SHIFT;
2775 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
965c8e59 2776 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
09cbfeaf 2777 new_offset <<= PAGE_SHIFT;
220f2ac9
HD
2778 if (new_offset > offset) {
2779 if (new_offset < inode->i_size)
2780 offset = new_offset;
965c8e59 2781 else if (whence == SEEK_DATA)
220f2ac9
HD
2782 offset = -ENXIO;
2783 else
2784 offset = inode->i_size;
2785 }
2786 }
2787
387aae6f
HD
2788 if (offset >= 0)
2789 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
5955102c 2790 inode_unlock(inode);
220f2ac9
HD
2791 return offset;
2792}
2793
83e4fa9c
HD
2794static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2795 loff_t len)
2796{
496ad9aa 2797 struct inode *inode = file_inode(file);
e2d12e22 2798 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
40e041a2 2799 struct shmem_inode_info *info = SHMEM_I(inode);
1aac1400 2800 struct shmem_falloc shmem_falloc;
e2d12e22
HD
2801 pgoff_t start, index, end;
2802 int error;
83e4fa9c 2803
13ace4d0
HD
2804 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2805 return -EOPNOTSUPP;
2806
5955102c 2807 inode_lock(inode);
83e4fa9c
HD
2808
2809 if (mode & FALLOC_FL_PUNCH_HOLE) {
2810 struct address_space *mapping = file->f_mapping;
2811 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2812 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
8e205f77 2813 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
83e4fa9c 2814
40e041a2 2815 /* protected by i_mutex */
ab3948f5 2816 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
40e041a2
DH
2817 error = -EPERM;
2818 goto out;
2819 }
2820
8e205f77 2821 shmem_falloc.waitq = &shmem_falloc_waitq;
aa71ecd8 2822 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
f00cdc6d
HD
2823 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2824 spin_lock(&inode->i_lock);
2825 inode->i_private = &shmem_falloc;
2826 spin_unlock(&inode->i_lock);
2827
83e4fa9c
HD
2828 if ((u64)unmap_end > (u64)unmap_start)
2829 unmap_mapping_range(mapping, unmap_start,
2830 1 + unmap_end - unmap_start, 0);
2831 shmem_truncate_range(inode, offset, offset + len - 1);
2832 /* No need to unmap again: hole-punching leaves COWed pages */
8e205f77
HD
2833
2834 spin_lock(&inode->i_lock);
2835 inode->i_private = NULL;
2836 wake_up_all(&shmem_falloc_waitq);
2055da97 2837 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
8e205f77 2838 spin_unlock(&inode->i_lock);
83e4fa9c 2839 error = 0;
8e205f77 2840 goto out;
e2d12e22
HD
2841 }
2842
2843 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2844 error = inode_newsize_ok(inode, offset + len);
2845 if (error)
2846 goto out;
2847
40e041a2
DH
2848 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2849 error = -EPERM;
2850 goto out;
2851 }
2852
09cbfeaf
KS
2853 start = offset >> PAGE_SHIFT;
2854 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
e2d12e22
HD
2855 /* Try to avoid a swapstorm if len is impossible to satisfy */
2856 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2857 error = -ENOSPC;
2858 goto out;
83e4fa9c
HD
2859 }
2860
8e205f77 2861 shmem_falloc.waitq = NULL;
1aac1400
HD
2862 shmem_falloc.start = start;
2863 shmem_falloc.next = start;
2864 shmem_falloc.nr_falloced = 0;
2865 shmem_falloc.nr_unswapped = 0;
2866 spin_lock(&inode->i_lock);
2867 inode->i_private = &shmem_falloc;
2868 spin_unlock(&inode->i_lock);
2869
e2d12e22
HD
2870 for (index = start; index < end; index++) {
2871 struct page *page;
2872
2873 /*
2874 * Good, the fallocate(2) manpage permits EINTR: we may have
2875 * been interrupted because we are using up too much memory.
2876 */
2877 if (signal_pending(current))
2878 error = -EINTR;
1aac1400
HD
2879 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2880 error = -ENOMEM;
e2d12e22 2881 else
9e18eb29 2882 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
e2d12e22 2883 if (error) {
1635f6a7 2884 /* Remove the !PageUptodate pages we added */
7f556567
HD
2885 if (index > start) {
2886 shmem_undo_range(inode,
2887 (loff_t)start << PAGE_SHIFT,
2888 ((loff_t)index << PAGE_SHIFT) - 1, true);
2889 }
1aac1400 2890 goto undone;
e2d12e22
HD
2891 }
2892
1aac1400
HD
2893 /*
2894 * Inform shmem_writepage() how far we have reached.
2895 * No need for lock or barrier: we have the page lock.
2896 */
2897 shmem_falloc.next++;
2898 if (!PageUptodate(page))
2899 shmem_falloc.nr_falloced++;
2900
e2d12e22 2901 /*
1635f6a7
HD
2902 * If !PageUptodate, leave it that way so that freeable pages
2903 * can be recognized if we need to rollback on error later.
2904 * But set_page_dirty so that memory pressure will swap rather
e2d12e22
HD
2905 * than free the pages we are allocating (and SGP_CACHE pages
2906 * might still be clean: we now need to mark those dirty too).
2907 */
2908 set_page_dirty(page);
2909 unlock_page(page);
09cbfeaf 2910 put_page(page);
e2d12e22
HD
2911 cond_resched();
2912 }
2913
2914 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2915 i_size_write(inode, offset + len);
078cd827 2916 inode->i_ctime = current_time(inode);
1aac1400
HD
2917undone:
2918 spin_lock(&inode->i_lock);
2919 inode->i_private = NULL;
2920 spin_unlock(&inode->i_lock);
e2d12e22 2921out:
5955102c 2922 inode_unlock(inode);
83e4fa9c
HD
2923 return error;
2924}
2925
726c3342 2926static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
1da177e4 2927{
726c3342 2928 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
1da177e4
LT
2929
2930 buf->f_type = TMPFS_MAGIC;
09cbfeaf 2931 buf->f_bsize = PAGE_SIZE;
1da177e4 2932 buf->f_namelen = NAME_MAX;
0edd73b3 2933 if (sbinfo->max_blocks) {
1da177e4 2934 buf->f_blocks = sbinfo->max_blocks;
41ffe5d5
HD
2935 buf->f_bavail =
2936 buf->f_bfree = sbinfo->max_blocks -
2937 percpu_counter_sum(&sbinfo->used_blocks);
0edd73b3
HD
2938 }
2939 if (sbinfo->max_inodes) {
1da177e4
LT
2940 buf->f_files = sbinfo->max_inodes;
2941 buf->f_ffree = sbinfo->free_inodes;
1da177e4
LT
2942 }
2943 /* else leave those fields 0 like simple_statfs */
2944 return 0;
2945}
2946
2947/*
2948 * File creation. Allocate an inode, and we're done..
2949 */
2950static int
1a67aafb 2951shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
1da177e4 2952{
0b0a0806 2953 struct inode *inode;
1da177e4
LT
2954 int error = -ENOSPC;
2955
454abafe 2956 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
1da177e4 2957 if (inode) {
feda821e
CH
2958 error = simple_acl_create(dir, inode);
2959 if (error)
2960 goto out_iput;
2a7dba39 2961 error = security_inode_init_security(inode, dir,
9d8f13ba 2962 &dentry->d_name,
6d9d88d0 2963 shmem_initxattrs, NULL);
feda821e
CH
2964 if (error && error != -EOPNOTSUPP)
2965 goto out_iput;
37ec43cd 2966
718deb6b 2967 error = 0;
1da177e4 2968 dir->i_size += BOGO_DIRENT_SIZE;
078cd827 2969 dir->i_ctime = dir->i_mtime = current_time(dir);
1da177e4
LT
2970 d_instantiate(dentry, inode);
2971 dget(dentry); /* Extra count - pin the dentry in core */
1da177e4
LT
2972 }
2973 return error;
feda821e
CH
2974out_iput:
2975 iput(inode);
2976 return error;
1da177e4
LT
2977}
2978
60545d0d
AV
2979static int
2980shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2981{
2982 struct inode *inode;
2983 int error = -ENOSPC;
2984
2985 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2986 if (inode) {
2987 error = security_inode_init_security(inode, dir,
2988 NULL,
2989 shmem_initxattrs, NULL);
feda821e
CH
2990 if (error && error != -EOPNOTSUPP)
2991 goto out_iput;
2992 error = simple_acl_create(dir, inode);
2993 if (error)
2994 goto out_iput;
60545d0d
AV
2995 d_tmpfile(dentry, inode);
2996 }
2997 return error;
feda821e
CH
2998out_iput:
2999 iput(inode);
3000 return error;
60545d0d
AV
3001}
3002
18bb1db3 3003static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
1da177e4
LT
3004{
3005 int error;
3006
3007 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
3008 return error;
d8c76e6f 3009 inc_nlink(dir);
1da177e4
LT
3010 return 0;
3011}
3012
4acdaf27 3013static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
ebfc3b49 3014 bool excl)
1da177e4
LT
3015{
3016 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
3017}
3018
3019/*
3020 * Link a file..
3021 */
3022static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
3023{
75c3cfa8 3024 struct inode *inode = d_inode(old_dentry);
29b00e60 3025 int ret = 0;
1da177e4
LT
3026
3027 /*
3028 * No ordinary (disk based) filesystem counts links as inodes;
3029 * but each new link needs a new dentry, pinning lowmem, and
3030 * tmpfs dentries cannot be pruned until they are unlinked.
1062af92
DW
3031 * But if an O_TMPFILE file is linked into the tmpfs, the
3032 * first link must skip that, to get the accounting right.
1da177e4 3033 */
1062af92 3034 if (inode->i_nlink) {
e809d5f0 3035 ret = shmem_reserve_inode(inode->i_sb, NULL);
1062af92
DW
3036 if (ret)
3037 goto out;
3038 }
1da177e4
LT
3039
3040 dir->i_size += BOGO_DIRENT_SIZE;
078cd827 3041 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
d8c76e6f 3042 inc_nlink(inode);
7de9c6ee 3043 ihold(inode); /* New dentry reference */
1da177e4
LT
3044 dget(dentry); /* Extra pinning count for the created dentry */
3045 d_instantiate(dentry, inode);
5b04c689
PE
3046out:
3047 return ret;
1da177e4
LT
3048}
3049
3050static int shmem_unlink(struct inode *dir, struct dentry *dentry)
3051{
75c3cfa8 3052 struct inode *inode = d_inode(dentry);
1da177e4 3053
5b04c689
PE
3054 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
3055 shmem_free_inode(inode->i_sb);
1da177e4
LT
3056
3057 dir->i_size -= BOGO_DIRENT_SIZE;
078cd827 3058 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
9a53c3a7 3059 drop_nlink(inode);
1da177e4
LT
3060 dput(dentry); /* Undo the count from "create" - this does all the work */
3061 return 0;
3062}
3063
3064static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
3065{
3066 if (!simple_empty(dentry))
3067 return -ENOTEMPTY;
3068
75c3cfa8 3069 drop_nlink(d_inode(dentry));
9a53c3a7 3070 drop_nlink(dir);
1da177e4
LT
3071 return shmem_unlink(dir, dentry);
3072}
3073
37456771
MS
3074static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
3075{
e36cb0b8
DH
3076 bool old_is_dir = d_is_dir(old_dentry);
3077 bool new_is_dir = d_is_dir(new_dentry);
37456771
MS
3078
3079 if (old_dir != new_dir && old_is_dir != new_is_dir) {
3080 if (old_is_dir) {
3081 drop_nlink(old_dir);
3082 inc_nlink(new_dir);
3083 } else {
3084 drop_nlink(new_dir);
3085 inc_nlink(old_dir);
3086 }
3087 }
3088 old_dir->i_ctime = old_dir->i_mtime =
3089 new_dir->i_ctime = new_dir->i_mtime =
75c3cfa8 3090 d_inode(old_dentry)->i_ctime =
078cd827 3091 d_inode(new_dentry)->i_ctime = current_time(old_dir);
37456771
MS
3092
3093 return 0;
3094}
3095
46fdb794
MS
3096static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
3097{
3098 struct dentry *whiteout;
3099 int error;
3100
3101 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
3102 if (!whiteout)
3103 return -ENOMEM;
3104
3105 error = shmem_mknod(old_dir, whiteout,
3106 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
3107 dput(whiteout);
3108 if (error)
3109 return error;
3110
3111 /*
3112 * Cheat and hash the whiteout while the old dentry is still in
3113 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3114 *
3115 * d_lookup() will consistently find one of them at this point,
3116 * not sure which one, but that isn't even important.
3117 */
3118 d_rehash(whiteout);
3119 return 0;
3120}
3121
1da177e4
LT
3122/*
3123 * The VFS layer already does all the dentry stuff for rename,
3124 * we just have to decrement the usage count for the target if
3125 * it exists so that the VFS layer correctly free's it when it
3126 * gets overwritten.
3127 */
3b69ff51 3128static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
1da177e4 3129{
75c3cfa8 3130 struct inode *inode = d_inode(old_dentry);
1da177e4
LT
3131 int they_are_dirs = S_ISDIR(inode->i_mode);
3132
46fdb794 3133 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3b69ff51
MS
3134 return -EINVAL;
3135
37456771
MS
3136 if (flags & RENAME_EXCHANGE)
3137 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
3138
1da177e4
LT
3139 if (!simple_empty(new_dentry))
3140 return -ENOTEMPTY;
3141
46fdb794
MS
3142 if (flags & RENAME_WHITEOUT) {
3143 int error;
3144
3145 error = shmem_whiteout(old_dir, old_dentry);
3146 if (error)
3147 return error;
3148 }
3149
75c3cfa8 3150 if (d_really_is_positive(new_dentry)) {
1da177e4 3151 (void) shmem_unlink(new_dir, new_dentry);
b928095b 3152 if (they_are_dirs) {
75c3cfa8 3153 drop_nlink(d_inode(new_dentry));
9a53c3a7 3154 drop_nlink(old_dir);
b928095b 3155 }
1da177e4 3156 } else if (they_are_dirs) {
9a53c3a7 3157 drop_nlink(old_dir);
d8c76e6f 3158 inc_nlink(new_dir);
1da177e4
LT
3159 }
3160
3161 old_dir->i_size -= BOGO_DIRENT_SIZE;
3162 new_dir->i_size += BOGO_DIRENT_SIZE;
3163 old_dir->i_ctime = old_dir->i_mtime =
3164 new_dir->i_ctime = new_dir->i_mtime =
078cd827 3165 inode->i_ctime = current_time(old_dir);
1da177e4
LT
3166 return 0;
3167}
3168
3169static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
3170{
3171 int error;
3172 int len;
3173 struct inode *inode;
9276aad6 3174 struct page *page;
1da177e4
LT
3175
3176 len = strlen(symname) + 1;
09cbfeaf 3177 if (len > PAGE_SIZE)
1da177e4
LT
3178 return -ENAMETOOLONG;
3179
0825a6f9
JP
3180 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
3181 VM_NORESERVE);
1da177e4
LT
3182 if (!inode)
3183 return -ENOSPC;
3184
9d8f13ba 3185 error = security_inode_init_security(inode, dir, &dentry->d_name,
6d9d88d0 3186 shmem_initxattrs, NULL);
343c3d7f
MN
3187 if (error && error != -EOPNOTSUPP) {
3188 iput(inode);
3189 return error;
570bc1c2
SS
3190 }
3191
1da177e4 3192 inode->i_size = len-1;
69f07ec9 3193 if (len <= SHORT_SYMLINK_LEN) {
3ed47db3
AV
3194 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3195 if (!inode->i_link) {
69f07ec9
HD
3196 iput(inode);
3197 return -ENOMEM;
3198 }
3199 inode->i_op = &shmem_short_symlink_operations;
1da177e4 3200 } else {
e8ecde25 3201 inode_nohighmem(inode);
9e18eb29 3202 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
1da177e4
LT
3203 if (error) {
3204 iput(inode);
3205 return error;
3206 }
14fcc23f 3207 inode->i_mapping->a_ops = &shmem_aops;
1da177e4 3208 inode->i_op = &shmem_symlink_inode_operations;
21fc61c7 3209 memcpy(page_address(page), symname, len);
ec9516fb 3210 SetPageUptodate(page);
1da177e4 3211 set_page_dirty(page);
6746aff7 3212 unlock_page(page);
09cbfeaf 3213 put_page(page);
1da177e4 3214 }
1da177e4 3215 dir->i_size += BOGO_DIRENT_SIZE;
078cd827 3216 dir->i_ctime = dir->i_mtime = current_time(dir);
1da177e4
LT
3217 d_instantiate(dentry, inode);
3218 dget(dentry);
3219 return 0;
3220}
3221
fceef393 3222static void shmem_put_link(void *arg)
1da177e4 3223{
fceef393
AV
3224 mark_page_accessed(arg);
3225 put_page(arg);
1da177e4
LT
3226}
3227
6b255391 3228static const char *shmem_get_link(struct dentry *dentry,
fceef393
AV
3229 struct inode *inode,
3230 struct delayed_call *done)
1da177e4 3231{
1da177e4 3232 struct page *page = NULL;
6b255391 3233 int error;
6a6c9904
AV
3234 if (!dentry) {
3235 page = find_get_page(inode->i_mapping, 0);
3236 if (!page)
3237 return ERR_PTR(-ECHILD);
3238 if (!PageUptodate(page)) {
3239 put_page(page);
3240 return ERR_PTR(-ECHILD);
3241 }
3242 } else {
9e18eb29 3243 error = shmem_getpage(inode, 0, &page, SGP_READ);
6a6c9904
AV
3244 if (error)
3245 return ERR_PTR(error);
3246 unlock_page(page);
3247 }
fceef393 3248 set_delayed_call(done, shmem_put_link, page);
21fc61c7 3249 return page_address(page);
1da177e4
LT
3250}
3251
b09e0fa4 3252#ifdef CONFIG_TMPFS_XATTR
46711810 3253/*
b09e0fa4
EP
3254 * Superblocks without xattr inode operations may get some security.* xattr
3255 * support from the LSM "for free". As soon as we have any other xattrs
39f0247d
AG
3256 * like ACLs, we also need to implement the security.* handlers at
3257 * filesystem level, though.
3258 */
3259
6d9d88d0
JS
3260/*
3261 * Callback for security_inode_init_security() for acquiring xattrs.
3262 */
3263static int shmem_initxattrs(struct inode *inode,
3264 const struct xattr *xattr_array,
3265 void *fs_info)
3266{
3267 struct shmem_inode_info *info = SHMEM_I(inode);
3268 const struct xattr *xattr;
38f38657 3269 struct simple_xattr *new_xattr;
6d9d88d0
JS
3270 size_t len;
3271
3272 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
38f38657 3273 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
6d9d88d0
JS
3274 if (!new_xattr)
3275 return -ENOMEM;
3276
3277 len = strlen(xattr->name) + 1;
3278 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3279 GFP_KERNEL);
3280 if (!new_xattr->name) {
3bef735a 3281 kvfree(new_xattr);
6d9d88d0
JS
3282 return -ENOMEM;
3283 }
3284
3285 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3286 XATTR_SECURITY_PREFIX_LEN);
3287 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3288 xattr->name, len);
3289
38f38657 3290 simple_xattr_list_add(&info->xattrs, new_xattr);
6d9d88d0
JS
3291 }
3292
3293 return 0;
3294}
3295
aa7c5241 3296static int shmem_xattr_handler_get(const struct xattr_handler *handler,
b296821a
AV
3297 struct dentry *unused, struct inode *inode,
3298 const char *name, void *buffer, size_t size)
b09e0fa4 3299{
b296821a 3300 struct shmem_inode_info *info = SHMEM_I(inode);
b09e0fa4 3301
aa7c5241 3302 name = xattr_full_name(handler, name);
38f38657 3303 return simple_xattr_get(&info->xattrs, name, buffer, size);
b09e0fa4
EP
3304}
3305
aa7c5241 3306static int shmem_xattr_handler_set(const struct xattr_handler *handler,
59301226
AV
3307 struct dentry *unused, struct inode *inode,
3308 const char *name, const void *value,
3309 size_t size, int flags)
b09e0fa4 3310{
59301226 3311 struct shmem_inode_info *info = SHMEM_I(inode);
b09e0fa4 3312
aa7c5241 3313 name = xattr_full_name(handler, name);
a46a2295 3314 return simple_xattr_set(&info->xattrs, name, value, size, flags, NULL);
b09e0fa4
EP
3315}
3316
aa7c5241
AG
3317static const struct xattr_handler shmem_security_xattr_handler = {
3318 .prefix = XATTR_SECURITY_PREFIX,
3319 .get = shmem_xattr_handler_get,
3320 .set = shmem_xattr_handler_set,
3321};
b09e0fa4 3322
aa7c5241
AG
3323static const struct xattr_handler shmem_trusted_xattr_handler = {
3324 .prefix = XATTR_TRUSTED_PREFIX,
3325 .get = shmem_xattr_handler_get,
3326 .set = shmem_xattr_handler_set,
3327};
b09e0fa4 3328
aa7c5241
AG
3329static const struct xattr_handler *shmem_xattr_handlers[] = {
3330#ifdef CONFIG_TMPFS_POSIX_ACL
3331 &posix_acl_access_xattr_handler,
3332 &posix_acl_default_xattr_handler,
3333#endif
3334 &shmem_security_xattr_handler,
3335 &shmem_trusted_xattr_handler,
3336 NULL
3337};
b09e0fa4
EP
3338
3339static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3340{
75c3cfa8 3341 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
786534b9 3342 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
b09e0fa4
EP
3343}
3344#endif /* CONFIG_TMPFS_XATTR */
3345
69f07ec9 3346static const struct inode_operations shmem_short_symlink_operations = {
6b255391 3347 .get_link = simple_get_link,
b09e0fa4 3348#ifdef CONFIG_TMPFS_XATTR
b09e0fa4 3349 .listxattr = shmem_listxattr,
b09e0fa4
EP
3350#endif
3351};
3352
3353static const struct inode_operations shmem_symlink_inode_operations = {
6b255391 3354 .get_link = shmem_get_link,
b09e0fa4 3355#ifdef CONFIG_TMPFS_XATTR
b09e0fa4 3356 .listxattr = shmem_listxattr,
39f0247d 3357#endif
b09e0fa4 3358};
39f0247d 3359
91828a40
DG
3360static struct dentry *shmem_get_parent(struct dentry *child)
3361{
3362 return ERR_PTR(-ESTALE);
3363}
3364
3365static int shmem_match(struct inode *ino, void *vfh)
3366{
3367 __u32 *fh = vfh;
a3853725 3368 __u64 inum = fh[1];
91828a40
DG
3369 return ino->i_ino == inum && fh[0] == ino->i_generation;
3370}
3371
12ba780d
AG
3372/* Find any alias of inode, but prefer a hashed alias */
3373static struct dentry *shmem_find_alias(struct inode *inode)
3374{
3375 struct dentry *alias = d_find_alias(inode);
3376
3377 return alias ?: d_find_any_alias(inode);
3378}
3379
3380
480b116c
CH
3381static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3382 struct fid *fid, int fh_len, int fh_type)
91828a40 3383{
91828a40 3384 struct inode *inode;
480b116c 3385 struct dentry *dentry = NULL;
35c2a7f4 3386 u64 inum;
480b116c 3387
a3853725 3388 if (fh_len < 2)
480b116c 3389 return NULL;
91828a40 3390
a3853725
PP
3391 inum = fid->raw[1];
3392 inode = ilookup5(sb, inum, shmem_match, fid->raw);
91828a40 3393 if (inode) {
12ba780d 3394 dentry = shmem_find_alias(inode);
91828a40
DG
3395 iput(inode);
3396 }
3397
480b116c 3398 return dentry;
91828a40
DG
3399}
3400
b0b0382b
AV
3401static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3402 struct inode *parent)
91828a40 3403{
a3853725
PP
3404 if (*len < 2) {
3405 *len = 2;
94e07a75 3406 return FILEID_INVALID;
5fe0c237 3407 }
91828a40 3408
91828a40
DG
3409 fh[0] = inode->i_generation;
3410 fh[1] = inode->i_ino;
91828a40 3411
a3853725 3412 *len = 2;
91828a40
DG
3413 return 1;
3414}
3415
39655164 3416static const struct export_operations shmem_export_ops = {
91828a40 3417 .get_parent = shmem_get_parent,
91828a40 3418 .encode_fh = shmem_encode_fh,
480b116c 3419 .fh_to_dentry = shmem_fh_to_dentry,
91828a40
DG
3420};
3421
626c3920
AV
3422enum shmem_param {
3423 Opt_gid,
3424 Opt_huge,
3425 Opt_mode,
3426 Opt_mpol,
3427 Opt_nr_blocks,
3428 Opt_nr_inodes,
3429 Opt_size,
3430 Opt_uid,
ea3271f7
CD
3431 Opt_inode32,
3432 Opt_inode64,
626c3920
AV
3433};
3434
5eede625 3435static const struct constant_table shmem_param_enums_huge[] = {
2710c957
AV
3436 {"never", SHMEM_HUGE_NEVER },
3437 {"always", SHMEM_HUGE_ALWAYS },
3438 {"within_size", SHMEM_HUGE_WITHIN_SIZE },
3439 {"advise", SHMEM_HUGE_ADVISE },
2710c957
AV
3440 {}
3441};
3442
d7167b14 3443const struct fs_parameter_spec shmem_fs_parameters[] = {
626c3920 3444 fsparam_u32 ("gid", Opt_gid),
2710c957 3445 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge),
626c3920
AV
3446 fsparam_u32oct("mode", Opt_mode),
3447 fsparam_string("mpol", Opt_mpol),
3448 fsparam_string("nr_blocks", Opt_nr_blocks),
3449 fsparam_string("nr_inodes", Opt_nr_inodes),
3450 fsparam_string("size", Opt_size),
3451 fsparam_u32 ("uid", Opt_uid),
ea3271f7
CD
3452 fsparam_flag ("inode32", Opt_inode32),
3453 fsparam_flag ("inode64", Opt_inode64),
626c3920
AV
3454 {}
3455};
3456
f3235626 3457static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
1da177e4 3458{
f3235626 3459 struct shmem_options *ctx = fc->fs_private;
626c3920
AV
3460 struct fs_parse_result result;
3461 unsigned long long size;
e04dc423 3462 char *rest;
626c3920
AV
3463 int opt;
3464
d7167b14 3465 opt = fs_parse(fc, shmem_fs_parameters, param, &result);
f3235626 3466 if (opt < 0)
626c3920 3467 return opt;
1da177e4 3468
626c3920
AV
3469 switch (opt) {
3470 case Opt_size:
3471 size = memparse(param->string, &rest);
e04dc423
AV
3472 if (*rest == '%') {
3473 size <<= PAGE_SHIFT;
3474 size *= totalram_pages();
3475 do_div(size, 100);
3476 rest++;
3477 }
3478 if (*rest)
626c3920 3479 goto bad_value;
e04dc423
AV
3480 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
3481 ctx->seen |= SHMEM_SEEN_BLOCKS;
626c3920
AV
3482 break;
3483 case Opt_nr_blocks:
3484 ctx->blocks = memparse(param->string, &rest);
e04dc423 3485 if (*rest)
626c3920 3486 goto bad_value;
e04dc423 3487 ctx->seen |= SHMEM_SEEN_BLOCKS;
626c3920
AV
3488 break;
3489 case Opt_nr_inodes:
3490 ctx->inodes = memparse(param->string, &rest);
a3853725 3491 if (*rest || ctx->inodes < 2)
626c3920 3492 goto bad_value;
e04dc423 3493 ctx->seen |= SHMEM_SEEN_INODES;
626c3920
AV
3494 break;
3495 case Opt_mode:
3496 ctx->mode = result.uint_32 & 07777;
3497 break;
3498 case Opt_uid:
3499 ctx->uid = make_kuid(current_user_ns(), result.uint_32);
e04dc423 3500 if (!uid_valid(ctx->uid))
626c3920
AV
3501 goto bad_value;
3502 break;
3503 case Opt_gid:
3504 ctx->gid = make_kgid(current_user_ns(), result.uint_32);
e04dc423 3505 if (!gid_valid(ctx->gid))
626c3920
AV
3506 goto bad_value;
3507 break;
3508 case Opt_huge:
3509 ctx->huge = result.uint_32;
3510 if (ctx->huge != SHMEM_HUGE_NEVER &&
396bcc52 3511 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
626c3920
AV
3512 has_transparent_hugepage()))
3513 goto unsupported_parameter;
e04dc423 3514 ctx->seen |= SHMEM_SEEN_HUGE;
626c3920
AV
3515 break;
3516 case Opt_mpol:
3517 if (IS_ENABLED(CONFIG_NUMA)) {
3518 mpol_put(ctx->mpol);
3519 ctx->mpol = NULL;
3520 if (mpol_parse_str(param->string, &ctx->mpol))
3521 goto bad_value;
3522 break;
3523 }
3524 goto unsupported_parameter;
ea3271f7
CD
3525 case Opt_inode32:
3526 ctx->full_inums = false;
3527 ctx->seen |= SHMEM_SEEN_INUMS;
3528 break;
3529 case Opt_inode64:
3530 if (sizeof(ino_t) < 8) {
3531 return invalfc(fc,
3532 "Cannot use inode64 with <64bit inums in kernel\n");
3533 }
3534 ctx->full_inums = true;
3535 ctx->seen |= SHMEM_SEEN_INUMS;
3536 break;
e04dc423
AV
3537 }
3538 return 0;
3539
626c3920 3540unsupported_parameter:
f35aa2bc 3541 return invalfc(fc, "Unsupported parameter '%s'", param->key);
626c3920 3542bad_value:
f35aa2bc 3543 return invalfc(fc, "Bad value for '%s'", param->key);
e04dc423
AV
3544}
3545
f3235626 3546static int shmem_parse_options(struct fs_context *fc, void *data)
e04dc423 3547{
f3235626
DH
3548 char *options = data;
3549
33f37c64
AV
3550 if (options) {
3551 int err = security_sb_eat_lsm_opts(options, &fc->security);
3552 if (err)
3553 return err;
3554 }
3555
b00dc3ad 3556 while (options != NULL) {
626c3920 3557 char *this_char = options;
b00dc3ad
HD
3558 for (;;) {
3559 /*
3560 * NUL-terminate this option: unfortunately,
3561 * mount options form a comma-separated list,
3562 * but mpol's nodelist may also contain commas.
3563 */
3564 options = strchr(options, ',');
3565 if (options == NULL)
3566 break;
3567 options++;
3568 if (!isdigit(*options)) {
3569 options[-1] = '\0';
3570 break;
3571 }
3572 }
626c3920
AV
3573 if (*this_char) {
3574 char *value = strchr(this_char,'=');
f3235626 3575 size_t len = 0;
626c3920
AV
3576 int err;
3577
3578 if (value) {
3579 *value++ = '\0';
f3235626 3580 len = strlen(value);
626c3920 3581 }
f3235626
DH
3582 err = vfs_parse_fs_string(fc, this_char, value, len);
3583 if (err < 0)
3584 return err;
1da177e4 3585 }
1da177e4
LT
3586 }
3587 return 0;
1da177e4
LT
3588}
3589
f3235626
DH
3590/*
3591 * Reconfigure a shmem filesystem.
3592 *
3593 * Note that we disallow change from limited->unlimited blocks/inodes while any
3594 * are in use; but we must separately disallow unlimited->limited, because in
3595 * that case we have no record of how much is already in use.
3596 */
3597static int shmem_reconfigure(struct fs_context *fc)
1da177e4 3598{
f3235626
DH
3599 struct shmem_options *ctx = fc->fs_private;
3600 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
a3853725 3601 int inodes;
f3235626 3602 const char *err;
1da177e4 3603
0edd73b3 3604 spin_lock(&sbinfo->stat_lock);
0edd73b3 3605 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
f3235626
DH
3606 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
3607 if (!sbinfo->max_blocks) {
3608 err = "Cannot retroactively limit size";
0b5071dd 3609 goto out;
f3235626 3610 }
0b5071dd 3611 if (percpu_counter_compare(&sbinfo->used_blocks,
f3235626
DH
3612 ctx->blocks) > 0) {
3613 err = "Too small a size for current use";
0b5071dd 3614 goto out;
f3235626 3615 }
0b5071dd 3616 }
f3235626
DH
3617 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
3618 if (!sbinfo->max_inodes) {
3619 err = "Cannot retroactively limit inodes";
0b5071dd 3620 goto out;
f3235626
DH
3621 }
3622 if (ctx->inodes < inodes) {
3623 err = "Too few inodes for current use";
0b5071dd 3624 goto out;
f3235626 3625 }
0b5071dd 3626 }
0edd73b3 3627
ea3271f7
CD
3628 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
3629 sbinfo->next_ino > UINT_MAX) {
3630 err = "Current inum too high to switch to 32-bit inums";
3631 goto out;
3632 }
3633
f3235626
DH
3634 if (ctx->seen & SHMEM_SEEN_HUGE)
3635 sbinfo->huge = ctx->huge;
ea3271f7
CD
3636 if (ctx->seen & SHMEM_SEEN_INUMS)
3637 sbinfo->full_inums = ctx->full_inums;
f3235626
DH
3638 if (ctx->seen & SHMEM_SEEN_BLOCKS)
3639 sbinfo->max_blocks = ctx->blocks;
3640 if (ctx->seen & SHMEM_SEEN_INODES) {
3641 sbinfo->max_inodes = ctx->inodes;
3642 sbinfo->free_inodes = ctx->inodes - inodes;
0b5071dd 3643 }
71fe804b 3644
5f00110f
GT
3645 /*
3646 * Preserve previous mempolicy unless mpol remount option was specified.
3647 */
f3235626 3648 if (ctx->mpol) {
5f00110f 3649 mpol_put(sbinfo->mpol);
f3235626
DH
3650 sbinfo->mpol = ctx->mpol; /* transfers initial ref */
3651 ctx->mpol = NULL;
5f00110f 3652 }
f3235626
DH
3653 spin_unlock(&sbinfo->stat_lock);
3654 return 0;
0edd73b3
HD
3655out:
3656 spin_unlock(&sbinfo->stat_lock);
f35aa2bc 3657 return invalfc(fc, "%s", err);
1da177e4 3658}
680d794b 3659
34c80b1d 3660static int shmem_show_options(struct seq_file *seq, struct dentry *root)
680d794b 3661{
34c80b1d 3662 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
680d794b
AM
3663
3664 if (sbinfo->max_blocks != shmem_default_max_blocks())
3665 seq_printf(seq, ",size=%luk",
09cbfeaf 3666 sbinfo->max_blocks << (PAGE_SHIFT - 10));
680d794b 3667 if (sbinfo->max_inodes != shmem_default_max_inodes())
a3853725 3668 seq_printf(seq, ",nr_inodes=%d", sbinfo->max_inodes);
0825a6f9 3669 if (sbinfo->mode != (0777 | S_ISVTX))
09208d15 3670 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
8751e039
EB
3671 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3672 seq_printf(seq, ",uid=%u",
3673 from_kuid_munged(&init_user_ns, sbinfo->uid));
3674 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3675 seq_printf(seq, ",gid=%u",
3676 from_kgid_munged(&init_user_ns, sbinfo->gid));
ea3271f7
CD
3677
3678 /*
3679 * Showing inode{64,32} might be useful even if it's the system default,
3680 * since then people don't have to resort to checking both here and
3681 * /proc/config.gz to confirm 64-bit inums were successfully applied
3682 * (which may not even exist if IKCONFIG_PROC isn't enabled).
3683 *
3684 * We hide it when inode64 isn't the default and we are using 32-bit
3685 * inodes, since that probably just means the feature isn't even under
3686 * consideration.
3687 *
3688 * As such:
3689 *
3690 * +-----------------+-----------------+
3691 * | TMPFS_INODE64=y | TMPFS_INODE64=n |
3692 * +------------------+-----------------+-----------------+
3693 * | full_inums=true | show | show |
3694 * | full_inums=false | show | hide |
3695 * +------------------+-----------------+-----------------+
3696 *
3697 */
3698 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
3699 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
396bcc52 3700#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5a6e75f8
KS
3701 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3702 if (sbinfo->huge)
3703 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3704#endif
71fe804b 3705 shmem_show_mpol(seq, sbinfo->mpol);
680d794b
AM
3706 return 0;
3707}
9183df25 3708
680d794b 3709#endif /* CONFIG_TMPFS */
1da177e4
LT
3710
3711static void shmem_put_super(struct super_block *sb)
3712{
602586a8
HD
3713 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3714
a3853725
PP
3715 if (!sbinfo->idr_nouse)
3716 idr_destroy(&sbinfo->idr);
e809d5f0 3717 free_percpu(sbinfo->ino_batch);
602586a8 3718 percpu_counter_destroy(&sbinfo->used_blocks);
49cd0a5c 3719 mpol_put(sbinfo->mpol);
602586a8 3720 kfree(sbinfo);
1da177e4
LT
3721 sb->s_fs_info = NULL;
3722}
3723
f3235626 3724static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
1da177e4 3725{
f3235626 3726 struct shmem_options *ctx = fc->fs_private;
1da177e4 3727 struct inode *inode;
0edd73b3 3728 struct shmem_sb_info *sbinfo;
680d794b
AM
3729 int err = -ENOMEM;
3730
3731 /* Round up to L1_CACHE_BYTES to resist false sharing */
425fbf04 3732 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
680d794b
AM
3733 L1_CACHE_BYTES), GFP_KERNEL);
3734 if (!sbinfo)
3735 return -ENOMEM;
3736
680d794b 3737 sb->s_fs_info = sbinfo;
1da177e4 3738
0edd73b3 3739#ifdef CONFIG_TMPFS
1da177e4
LT
3740 /*
3741 * Per default we only allow half of the physical ram per
3742 * tmpfs instance, limiting inodes to one per page of lowmem;
3743 * but the internal instance is left unlimited.
3744 */
1751e8a6 3745 if (!(sb->s_flags & SB_KERNMOUNT)) {
f3235626
DH
3746 if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
3747 ctx->blocks = shmem_default_max_blocks();
3748 if (!(ctx->seen & SHMEM_SEEN_INODES))
3749 ctx->inodes = shmem_default_max_inodes();
ea3271f7
CD
3750 if (!(ctx->seen & SHMEM_SEEN_INUMS))
3751 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
ca4e0519 3752 } else {
1751e8a6 3753 sb->s_flags |= SB_NOUSER;
1da177e4 3754 }
91828a40 3755 sb->s_export_op = &shmem_export_ops;
1751e8a6 3756 sb->s_flags |= SB_NOSEC;
1da177e4 3757#else
1751e8a6 3758 sb->s_flags |= SB_NOUSER;
1da177e4 3759#endif
a3853725
PP
3760 mutex_init(&sbinfo->idr_lock);
3761 idr_init(&sbinfo->idr);
f3235626
DH
3762 sbinfo->max_blocks = ctx->blocks;
3763 sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes;
e809d5f0
CD
3764 if (sb->s_flags & SB_KERNMOUNT) {
3765 sbinfo->ino_batch = alloc_percpu(ino_t);
3766 if (!sbinfo->ino_batch)
3767 goto failed;
3768 }
f3235626
DH
3769 sbinfo->uid = ctx->uid;
3770 sbinfo->gid = ctx->gid;
ea3271f7 3771 sbinfo->full_inums = ctx->full_inums;
f3235626
DH
3772 sbinfo->mode = ctx->mode;
3773 sbinfo->huge = ctx->huge;
3774 sbinfo->mpol = ctx->mpol;
3775 ctx->mpol = NULL;
1da177e4 3776
0edd73b3 3777 spin_lock_init(&sbinfo->stat_lock);
908c7f19 3778 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
602586a8 3779 goto failed;
779750d2
KS
3780 spin_lock_init(&sbinfo->shrinklist_lock);
3781 INIT_LIST_HEAD(&sbinfo->shrinklist);
0edd73b3 3782
285b2c4f 3783 sb->s_maxbytes = MAX_LFS_FILESIZE;
09cbfeaf
KS
3784 sb->s_blocksize = PAGE_SIZE;
3785 sb->s_blocksize_bits = PAGE_SHIFT;
1da177e4
LT
3786 sb->s_magic = TMPFS_MAGIC;
3787 sb->s_op = &shmem_ops;
cfd95a9c 3788 sb->s_time_gran = 1;
b09e0fa4 3789#ifdef CONFIG_TMPFS_XATTR
39f0247d 3790 sb->s_xattr = shmem_xattr_handlers;
b09e0fa4
EP
3791#endif
3792#ifdef CONFIG_TMPFS_POSIX_ACL
1751e8a6 3793 sb->s_flags |= SB_POSIXACL;
39f0247d 3794#endif
2b4db796 3795 uuid_gen(&sb->s_uuid);
0edd73b3 3796
454abafe 3797 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
1da177e4
LT
3798 if (!inode)
3799 goto failed;
680d794b
AM
3800 inode->i_uid = sbinfo->uid;
3801 inode->i_gid = sbinfo->gid;
318ceed0
AV
3802 sb->s_root = d_make_root(inode);
3803 if (!sb->s_root)
48fde701 3804 goto failed;
1da177e4
LT
3805 return 0;
3806
1da177e4
LT
3807failed:
3808 shmem_put_super(sb);
3809 return err;
3810}
3811
f3235626
DH
3812static int shmem_get_tree(struct fs_context *fc)
3813{
3814 return get_tree_nodev(fc, shmem_fill_super);
3815}
3816
3817static void shmem_free_fc(struct fs_context *fc)
3818{
3819 struct shmem_options *ctx = fc->fs_private;
3820
3821 if (ctx) {
3822 mpol_put(ctx->mpol);
3823 kfree(ctx);
3824 }
3825}
3826
3827static const struct fs_context_operations shmem_fs_context_ops = {
3828 .free = shmem_free_fc,
3829 .get_tree = shmem_get_tree,
3830#ifdef CONFIG_TMPFS
3831 .parse_monolithic = shmem_parse_options,
3832 .parse_param = shmem_parse_one,
3833 .reconfigure = shmem_reconfigure,
3834#endif
3835};
3836
fcc234f8 3837static struct kmem_cache *shmem_inode_cachep;
1da177e4
LT
3838
3839static struct inode *shmem_alloc_inode(struct super_block *sb)
3840{
41ffe5d5
HD
3841 struct shmem_inode_info *info;
3842 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3843 if (!info)
1da177e4 3844 return NULL;
41ffe5d5 3845 return &info->vfs_inode;
1da177e4
LT
3846}
3847
74b1da56 3848static void shmem_free_in_core_inode(struct inode *inode)
fa0d7e3d 3849{
84e710da
AV
3850 if (S_ISLNK(inode->i_mode))
3851 kfree(inode->i_link);
fa0d7e3d
NP
3852 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3853}
3854
1da177e4
LT
3855static void shmem_destroy_inode(struct inode *inode)
3856{
09208d15 3857 if (S_ISREG(inode->i_mode))
1da177e4 3858 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
1da177e4
LT
3859}
3860
41ffe5d5 3861static void shmem_init_inode(void *foo)
1da177e4 3862{
41ffe5d5
HD
3863 struct shmem_inode_info *info = foo;
3864 inode_init_once(&info->vfs_inode);
1da177e4
LT
3865}
3866
9a8ec03e 3867static void shmem_init_inodecache(void)
1da177e4
LT
3868{
3869 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3870 sizeof(struct shmem_inode_info),
5d097056 3871 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
1da177e4
LT
3872}
3873
41ffe5d5 3874static void shmem_destroy_inodecache(void)
1da177e4 3875{
1a1d92c1 3876 kmem_cache_destroy(shmem_inode_cachep);
1da177e4
LT
3877}
3878
a3853725
PP
3879static __init void shmem_no_idr(struct super_block *sb)
3880{
3881 struct shmem_sb_info *sbinfo;
3882
3883 sbinfo = SHMEM_SB(sb);
3884 sbinfo->idr_nouse = true;
3885 idr_destroy(&sbinfo->idr);
3886}
3887
f5e54d6e 3888static const struct address_space_operations shmem_aops = {
1da177e4 3889 .writepage = shmem_writepage,
76719325 3890 .set_page_dirty = __set_page_dirty_no_writeback,
1da177e4 3891#ifdef CONFIG_TMPFS
800d15a5
NP
3892 .write_begin = shmem_write_begin,
3893 .write_end = shmem_write_end,
1da177e4 3894#endif
1c93923c 3895#ifdef CONFIG_MIGRATION
304dbdb7 3896 .migratepage = migrate_page,
1c93923c 3897#endif
aa261f54 3898 .error_remove_page = generic_error_remove_page,
1da177e4
LT
3899};
3900
15ad7cdc 3901static const struct file_operations shmem_file_operations = {
1da177e4 3902 .mmap = shmem_mmap,
c01d5b30 3903 .get_unmapped_area = shmem_get_unmapped_area,
1da177e4 3904#ifdef CONFIG_TMPFS
220f2ac9 3905 .llseek = shmem_file_llseek,
2ba5bbed 3906 .read_iter = shmem_file_read_iter,
8174202b 3907 .write_iter = generic_file_write_iter,
1b061d92 3908 .fsync = noop_fsync,
82c156f8 3909 .splice_read = generic_file_splice_read,
f6cb85d0 3910 .splice_write = iter_file_splice_write,
83e4fa9c 3911 .fallocate = shmem_fallocate,
1da177e4
LT
3912#endif
3913};
3914
92e1d5be 3915static const struct inode_operations shmem_inode_operations = {
44a30220 3916 .getattr = shmem_getattr,
94c1e62d 3917 .setattr = shmem_setattr,
b09e0fa4 3918#ifdef CONFIG_TMPFS_XATTR
b09e0fa4 3919 .listxattr = shmem_listxattr,
feda821e 3920 .set_acl = simple_set_acl,
b09e0fa4 3921#endif
1da177e4
LT
3922};
3923
92e1d5be 3924static const struct inode_operations shmem_dir_inode_operations = {
1da177e4
LT
3925#ifdef CONFIG_TMPFS
3926 .create = shmem_create,
3927 .lookup = simple_lookup,
3928 .link = shmem_link,
3929 .unlink = shmem_unlink,
3930 .symlink = shmem_symlink,
3931 .mkdir = shmem_mkdir,
3932 .rmdir = shmem_rmdir,
3933 .mknod = shmem_mknod,
2773bf00 3934 .rename = shmem_rename2,
60545d0d 3935 .tmpfile = shmem_tmpfile,
1da177e4 3936#endif
b09e0fa4 3937#ifdef CONFIG_TMPFS_XATTR
b09e0fa4 3938 .listxattr = shmem_listxattr,
b09e0fa4 3939#endif
39f0247d 3940#ifdef CONFIG_TMPFS_POSIX_ACL
94c1e62d 3941 .setattr = shmem_setattr,
feda821e 3942 .set_acl = simple_set_acl,
39f0247d
AG
3943#endif
3944};
3945
92e1d5be 3946static const struct inode_operations shmem_special_inode_operations = {
b09e0fa4 3947#ifdef CONFIG_TMPFS_XATTR
b09e0fa4 3948 .listxattr = shmem_listxattr,
b09e0fa4 3949#endif
39f0247d 3950#ifdef CONFIG_TMPFS_POSIX_ACL
94c1e62d 3951 .setattr = shmem_setattr,
feda821e 3952 .set_acl = simple_set_acl,
39f0247d 3953#endif
1da177e4
LT
3954};
3955
759b9775 3956static const struct super_operations shmem_ops = {
1da177e4 3957 .alloc_inode = shmem_alloc_inode,
74b1da56 3958 .free_inode = shmem_free_in_core_inode,
1da177e4
LT
3959 .destroy_inode = shmem_destroy_inode,
3960#ifdef CONFIG_TMPFS
3961 .statfs = shmem_statfs,
680d794b 3962 .show_options = shmem_show_options,
1da177e4 3963#endif
1f895f75 3964 .evict_inode = shmem_evict_inode,
1da177e4
LT
3965 .drop_inode = generic_delete_inode,
3966 .put_super = shmem_put_super,
396bcc52 3967#ifdef CONFIG_TRANSPARENT_HUGEPAGE
779750d2
KS
3968 .nr_cached_objects = shmem_unused_huge_count,
3969 .free_cached_objects = shmem_unused_huge_scan,
3970#endif
1da177e4
LT
3971};
3972
f0f37e2f 3973static const struct vm_operations_struct shmem_vm_ops = {
54cb8821 3974 .fault = shmem_fault,
d7c17551 3975 .map_pages = filemap_map_pages,
1da177e4
LT
3976#ifdef CONFIG_NUMA
3977 .set_policy = shmem_set_policy,
3978 .get_policy = shmem_get_policy,
3979#endif
3980};
3981
f3235626 3982int shmem_init_fs_context(struct fs_context *fc)
1da177e4 3983{
f3235626
DH
3984 struct shmem_options *ctx;
3985
3986 ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL);
3987 if (!ctx)
3988 return -ENOMEM;
3989
3990 ctx->mode = 0777 | S_ISVTX;
3991 ctx->uid = current_fsuid();
3992 ctx->gid = current_fsgid();
3993
3994 fc->fs_private = ctx;
3995 fc->ops = &shmem_fs_context_ops;
3996 return 0;
1da177e4
LT
3997}
3998
41ffe5d5 3999static struct file_system_type shmem_fs_type = {
1da177e4
LT
4000 .owner = THIS_MODULE,
4001 .name = "tmpfs",
f3235626
DH
4002 .init_fs_context = shmem_init_fs_context,
4003#ifdef CONFIG_TMPFS
d7167b14 4004 .parameters = shmem_fs_parameters,
f3235626 4005#endif
1da177e4 4006 .kill_sb = kill_litter_super,
01c70267 4007 .fs_flags = FS_USERNS_MOUNT | FS_THP_SUPPORT,
1da177e4 4008};
1da177e4 4009
41ffe5d5 4010int __init shmem_init(void)
1da177e4
LT
4011{
4012 int error;
4013
9a8ec03e 4014 shmem_init_inodecache();
1da177e4 4015
41ffe5d5 4016 error = register_filesystem(&shmem_fs_type);
1da177e4 4017 if (error) {
1170532b 4018 pr_err("Could not register tmpfs\n");
1da177e4
LT
4019 goto out2;
4020 }
95dc112a 4021
ca4e0519 4022 shm_mnt = kern_mount(&shmem_fs_type);
1da177e4
LT
4023 if (IS_ERR(shm_mnt)) {
4024 error = PTR_ERR(shm_mnt);
1170532b 4025 pr_err("Could not kern_mount tmpfs\n");
1da177e4
LT
4026 goto out1;
4027 }
a3853725 4028 shmem_no_idr(shm_mnt->mnt_sb);
5a6e75f8 4029
396bcc52 4030#ifdef CONFIG_TRANSPARENT_HUGEPAGE
435c0b87 4031 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
5a6e75f8
KS
4032 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4033 else
4034 shmem_huge = 0; /* just in case it was patched */
4035#endif
1da177e4
LT
4036 return 0;
4037
4038out1:
41ffe5d5 4039 unregister_filesystem(&shmem_fs_type);
1da177e4 4040out2:
41ffe5d5 4041 shmem_destroy_inodecache();
1da177e4
LT
4042 shm_mnt = ERR_PTR(error);
4043 return error;
4044}
853ac43a 4045
396bcc52 4046#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
5a6e75f8
KS
4047static ssize_t shmem_enabled_show(struct kobject *kobj,
4048 struct kobj_attribute *attr, char *buf)
4049{
26083eb6 4050 static const int values[] = {
5a6e75f8
KS
4051 SHMEM_HUGE_ALWAYS,
4052 SHMEM_HUGE_WITHIN_SIZE,
4053 SHMEM_HUGE_ADVISE,
4054 SHMEM_HUGE_NEVER,
4055 SHMEM_HUGE_DENY,
4056 SHMEM_HUGE_FORCE,
4057 };
4058 int i, count;
4059
4060 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
4061 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
4062
4063 count += sprintf(buf + count, fmt,
4064 shmem_format_huge(values[i]));
4065 }
4066 buf[count - 1] = '\n';
4067 return count;
4068}
4069
4070static ssize_t shmem_enabled_store(struct kobject *kobj,
4071 struct kobj_attribute *attr, const char *buf, size_t count)
4072{
4073 char tmp[16];
4074 int huge;
4075
4076 if (count + 1 > sizeof(tmp))
4077 return -EINVAL;
4078 memcpy(tmp, buf, count);
4079 tmp[count] = '\0';
4080 if (count && tmp[count - 1] == '\n')
4081 tmp[count - 1] = '\0';
4082
4083 huge = shmem_parse_huge(tmp);
4084 if (huge == -EINVAL)
4085 return -EINVAL;
4086 if (!has_transparent_hugepage() &&
4087 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
4088 return -EINVAL;
4089
4090 shmem_huge = huge;
435c0b87 4091 if (shmem_huge > SHMEM_HUGE_DENY)
5a6e75f8
KS
4092 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4093 return count;
4094}
4095
4096struct kobj_attribute shmem_enabled_attr =
4097 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
396bcc52 4098#endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
f3f0e1d2 4099
396bcc52 4100#ifdef CONFIG_TRANSPARENT_HUGEPAGE
f3f0e1d2
KS
4101bool shmem_huge_enabled(struct vm_area_struct *vma)
4102{
4103 struct inode *inode = file_inode(vma->vm_file);
4104 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
4105 loff_t i_size;
4106 pgoff_t off;
4107
c0630669
YS
4108 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
4109 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
4110 return false;
f3f0e1d2
KS
4111 if (shmem_huge == SHMEM_HUGE_FORCE)
4112 return true;
4113 if (shmem_huge == SHMEM_HUGE_DENY)
4114 return false;
4115 switch (sbinfo->huge) {
4116 case SHMEM_HUGE_NEVER:
4117 return false;
4118 case SHMEM_HUGE_ALWAYS:
4119 return true;
4120 case SHMEM_HUGE_WITHIN_SIZE:
4121 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
4122 i_size = round_up(i_size_read(inode), PAGE_SIZE);
4123 if (i_size >= HPAGE_PMD_SIZE &&
4124 i_size >> PAGE_SHIFT >= off)
4125 return true;
e4a9bc58 4126 fallthrough;
f3f0e1d2
KS
4127 case SHMEM_HUGE_ADVISE:
4128 /* TODO: implement fadvise() hints */
4129 return (vma->vm_flags & VM_HUGEPAGE);
4130 default:
4131 VM_BUG_ON(1);
4132 return false;
4133 }
4134}
396bcc52 4135#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5a6e75f8 4136
853ac43a
MM
4137#else /* !CONFIG_SHMEM */
4138
4139/*
4140 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
4141 *
4142 * This is intended for small system where the benefits of the full
4143 * shmem code (swap-backed and resource-limited) are outweighed by
4144 * their complexity. On systems without swap this code should be
4145 * effectively equivalent, but much lighter weight.
4146 */
4147
41ffe5d5 4148static struct file_system_type shmem_fs_type = {
853ac43a 4149 .name = "tmpfs",
f3235626 4150 .init_fs_context = ramfs_init_fs_context,
d7167b14 4151 .parameters = ramfs_fs_parameters,
853ac43a 4152 .kill_sb = kill_litter_super,
2b8576cb 4153 .fs_flags = FS_USERNS_MOUNT,
853ac43a
MM
4154};
4155
41ffe5d5 4156int __init shmem_init(void)
853ac43a 4157{
41ffe5d5 4158 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
853ac43a 4159
41ffe5d5 4160 shm_mnt = kern_mount(&shmem_fs_type);
853ac43a
MM
4161 BUG_ON(IS_ERR(shm_mnt));
4162
4163 return 0;
4164}
4165
b56a2d8a
VRP
4166int shmem_unuse(unsigned int type, bool frontswap,
4167 unsigned long *fs_pages_to_unuse)
853ac43a
MM
4168{
4169 return 0;
4170}
4171
3f96b79a
HD
4172int shmem_lock(struct file *file, int lock, struct user_struct *user)
4173{
4174 return 0;
4175}
4176
24513264
HD
4177void shmem_unlock_mapping(struct address_space *mapping)
4178{
4179}
4180
c01d5b30
HD
4181#ifdef CONFIG_MMU
4182unsigned long shmem_get_unmapped_area(struct file *file,
4183 unsigned long addr, unsigned long len,
4184 unsigned long pgoff, unsigned long flags)
4185{
4186 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
4187}
4188#endif
4189
41ffe5d5 4190void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
94c1e62d 4191{
41ffe5d5 4192 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
94c1e62d
HD
4193}
4194EXPORT_SYMBOL_GPL(shmem_truncate_range);
4195
0b0a0806
HD
4196#define shmem_vm_ops generic_file_vm_ops
4197#define shmem_file_operations ramfs_file_operations
454abafe 4198#define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
0b0a0806
HD
4199#define shmem_acct_size(flags, size) 0
4200#define shmem_unacct_size(flags, size) do {} while (0)
853ac43a
MM
4201
4202#endif /* CONFIG_SHMEM */
4203
4204/* common code */
1da177e4 4205
703321b6 4206static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
c7277090 4207 unsigned long flags, unsigned int i_flags)
1da177e4 4208{
1da177e4 4209 struct inode *inode;
93dec2da 4210 struct file *res;
1da177e4 4211
703321b6
MA
4212 if (IS_ERR(mnt))
4213 return ERR_CAST(mnt);
1da177e4 4214
285b2c4f 4215 if (size < 0 || size > MAX_LFS_FILESIZE)
1da177e4
LT
4216 return ERR_PTR(-EINVAL);
4217
4218 if (shmem_acct_size(flags, size))
4219 return ERR_PTR(-ENOMEM);
4220
93dec2da
AV
4221 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
4222 flags);
dac2d1f6
AV
4223 if (unlikely(!inode)) {
4224 shmem_unacct_size(flags, size);
4225 return ERR_PTR(-ENOSPC);
4226 }
c7277090 4227 inode->i_flags |= i_flags;
1da177e4 4228 inode->i_size = size;
6d6b77f1 4229 clear_nlink(inode); /* It is unlinked */
26567cdb 4230 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
93dec2da
AV
4231 if (!IS_ERR(res))
4232 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
4233 &shmem_file_operations);
26567cdb 4234 if (IS_ERR(res))
93dec2da 4235 iput(inode);
6b4d0b27 4236 return res;
1da177e4 4237}
c7277090
EP
4238
4239/**
4240 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4241 * kernel internal. There will be NO LSM permission checks against the
4242 * underlying inode. So users of this interface must do LSM checks at a
e1832f29
SS
4243 * higher layer. The users are the big_key and shm implementations. LSM
4244 * checks are provided at the key or shm level rather than the inode.
c7277090
EP
4245 * @name: name for dentry (to be seen in /proc/<pid>/maps
4246 * @size: size to be set for the file
4247 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4248 */
4249struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4250{
703321b6 4251 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
c7277090
EP
4252}
4253
4254/**
4255 * shmem_file_setup - get an unlinked file living in tmpfs
4256 * @name: name for dentry (to be seen in /proc/<pid>/maps
4257 * @size: size to be set for the file
4258 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4259 */
4260struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4261{
703321b6 4262 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
c7277090 4263}
395e0ddc 4264EXPORT_SYMBOL_GPL(shmem_file_setup);
1da177e4 4265
703321b6
MA
4266/**
4267 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4268 * @mnt: the tmpfs mount where the file will be created
4269 * @name: name for dentry (to be seen in /proc/<pid>/maps
4270 * @size: size to be set for the file
4271 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4272 */
4273struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4274 loff_t size, unsigned long flags)
4275{
4276 return __shmem_file_setup(mnt, name, size, flags, 0);
4277}
4278EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4279
46711810 4280/**
1da177e4 4281 * shmem_zero_setup - setup a shared anonymous mapping
45e55300 4282 * @vma: the vma to be mmapped is prepared by do_mmap
1da177e4
LT
4283 */
4284int shmem_zero_setup(struct vm_area_struct *vma)
4285{
4286 struct file *file;
4287 loff_t size = vma->vm_end - vma->vm_start;
4288
66fc1303 4289 /*
c1e8d7c6 4290 * Cloning a new file under mmap_lock leads to a lock ordering conflict
66fc1303
HD
4291 * between XFS directory reading and selinux: since this file is only
4292 * accessible to the user through its mapping, use S_PRIVATE flag to
4293 * bypass file security, in the same way as shmem_kernel_file_setup().
4294 */
703321b6 4295 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
1da177e4
LT
4296 if (IS_ERR(file))
4297 return PTR_ERR(file);
4298
4299 if (vma->vm_file)
4300 fput(vma->vm_file);
4301 vma->vm_file = file;
4302 vma->vm_ops = &shmem_vm_ops;
f3f0e1d2 4303
396bcc52 4304 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
f3f0e1d2
KS
4305 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4306 (vma->vm_end & HPAGE_PMD_MASK)) {
4307 khugepaged_enter(vma, vma->vm_flags);
4308 }
4309
1da177e4
LT
4310 return 0;
4311}
13967d29 4312EXPORT_SYMBOL_GPL(shmem_zero_setup);
d9d90e5e
HD
4313
4314/**
4315 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4316 * @mapping: the page's address_space
4317 * @index: the page index
4318 * @gfp: the page allocator flags to use if allocating
4319 *
4320 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4321 * with any new page allocations done using the specified allocation flags.
4322 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4323 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4324 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4325 *
68da9f05
HD
4326 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4327 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
d9d90e5e
HD
4328 */
4329struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4330 pgoff_t index, gfp_t gfp)
4331{
68da9f05
HD
4332#ifdef CONFIG_SHMEM
4333 struct inode *inode = mapping->host;
9276aad6 4334 struct page *page;
68da9f05
HD
4335 int error;
4336
4337 BUG_ON(mapping->a_ops != &shmem_aops);
9e18eb29 4338 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
cfda0526 4339 gfp, NULL, NULL, NULL);
68da9f05
HD
4340 if (error)
4341 page = ERR_PTR(error);
4342 else
4343 unlock_page(page);
4344 return page;
4345#else
4346 /*
4347 * The tiny !SHMEM case uses ramfs without swap
4348 */
d9d90e5e 4349 return read_cache_page_gfp(mapping, index, gfp);
68da9f05 4350#endif
d9d90e5e
HD
4351}
4352EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);