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