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