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