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