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