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