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