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