2 * Resizable virtual memory filesystem for Linux.
4 * Copyright (C) 2000 Linus Torvalds.
6 * 2000-2001 Christoph Rohland
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
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>
19 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
21 * This file is released under the GPL.
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>
32 #include <linux/random.h>
33 #include <linux/sched/signal.h>
34 #include <linux/export.h>
35 #include <linux/swap.h>
36 #include <linux/uio.h>
37 #include <linux/khugepaged.h>
38 #include <linux/hugetlb.h>
39 #include <linux/frontswap.h>
41 #include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
43 static struct vfsmount *shm_mnt;
47 * This virtual memory filesystem is heavily based on the ramfs. It
48 * extends ramfs by the ability to use swap and honor resource limits
49 * which makes it a completely usable filesystem.
52 #include <linux/xattr.h>
53 #include <linux/exportfs.h>
54 #include <linux/posix_acl.h>
55 #include <linux/posix_acl_xattr.h>
56 #include <linux/mman.h>
57 #include <linux/string.h>
58 #include <linux/slab.h>
59 #include <linux/backing-dev.h>
60 #include <linux/shmem_fs.h>
61 #include <linux/writeback.h>
62 #include <linux/blkdev.h>
63 #include <linux/pagevec.h>
64 #include <linux/percpu_counter.h>
65 #include <linux/falloc.h>
66 #include <linux/splice.h>
67 #include <linux/security.h>
68 #include <linux/swapops.h>
69 #include <linux/mempolicy.h>
70 #include <linux/namei.h>
71 #include <linux/ctype.h>
72 #include <linux/migrate.h>
73 #include <linux/highmem.h>
74 #include <linux/seq_file.h>
75 #include <linux/magic.h>
76 #include <linux/syscalls.h>
77 #include <linux/fcntl.h>
78 #include <uapi/linux/memfd.h>
79 #include <linux/userfaultfd_k.h>
80 #include <linux/rmap.h>
81 #include <linux/uuid.h>
83 #include <linux/uaccess.h>
84 #include <asm/pgtable.h>
88 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
89 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
91 /* Pretend that each entry is of this size in directory's i_size */
92 #define BOGO_DIRENT_SIZE 20
94 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
95 #define SHORT_SYMLINK_LEN 128
98 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
99 * inode->i_private (with i_mutex making sure that it has only one user at
100 * a time): we would prefer not to enlarge the shmem inode just for that.
102 struct shmem_falloc {
103 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
104 pgoff_t start; /* start of range currently being fallocated */
105 pgoff_t next; /* the next page offset to be fallocated */
106 pgoff_t nr_falloced; /* how many new pages have been fallocated */
107 pgoff_t nr_unswapped; /* how often writepage refused to swap out */
110 struct shmem_options {
111 unsigned long long blocks;
112 unsigned long long inodes;
113 struct mempolicy *mpol;
119 #define SHMEM_SEEN_BLOCKS 1
120 #define SHMEM_SEEN_INODES 2
121 #define SHMEM_SEEN_HUGE 4
125 static unsigned long shmem_default_max_blocks(void)
127 return totalram_pages() / 2;
130 static unsigned long shmem_default_max_inodes(void)
132 unsigned long nr_pages = totalram_pages();
134 return min(nr_pages - totalhigh_pages(), nr_pages / 2);
138 static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
139 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
140 struct shmem_inode_info *info, pgoff_t index);
141 static int shmem_swapin_page(struct inode *inode, pgoff_t index,
142 struct page **pagep, enum sgp_type sgp,
143 gfp_t gfp, struct vm_area_struct *vma,
144 vm_fault_t *fault_type);
145 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
146 struct page **pagep, enum sgp_type sgp,
147 gfp_t gfp, struct vm_area_struct *vma,
148 struct vm_fault *vmf, vm_fault_t *fault_type);
150 int shmem_getpage(struct inode *inode, pgoff_t index,
151 struct page **pagep, enum sgp_type sgp)
153 return shmem_getpage_gfp(inode, index, pagep, sgp,
154 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
157 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
159 return sb->s_fs_info;
163 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
164 * for shared memory and for shared anonymous (/dev/zero) mappings
165 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
166 * consistent with the pre-accounting of private mappings ...
168 static inline int shmem_acct_size(unsigned long flags, loff_t size)
170 return (flags & VM_NORESERVE) ?
171 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
174 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
176 if (!(flags & VM_NORESERVE))
177 vm_unacct_memory(VM_ACCT(size));
180 static inline int shmem_reacct_size(unsigned long flags,
181 loff_t oldsize, loff_t newsize)
183 if (!(flags & VM_NORESERVE)) {
184 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
185 return security_vm_enough_memory_mm(current->mm,
186 VM_ACCT(newsize) - VM_ACCT(oldsize));
187 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
188 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
194 * ... whereas tmpfs objects are accounted incrementally as
195 * pages are allocated, in order to allow large sparse files.
196 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
197 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
199 static inline int shmem_acct_block(unsigned long flags, long pages)
201 if (!(flags & VM_NORESERVE))
204 return security_vm_enough_memory_mm(current->mm,
205 pages * VM_ACCT(PAGE_SIZE));
208 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
210 if (flags & VM_NORESERVE)
211 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
214 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
216 struct shmem_inode_info *info = SHMEM_I(inode);
217 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
219 if (shmem_acct_block(info->flags, pages))
222 if (sbinfo->max_blocks) {
223 if (percpu_counter_compare(&sbinfo->used_blocks,
224 sbinfo->max_blocks - pages) > 0)
226 percpu_counter_add(&sbinfo->used_blocks, pages);
232 shmem_unacct_blocks(info->flags, pages);
236 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
238 struct shmem_inode_info *info = SHMEM_I(inode);
239 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
241 if (sbinfo->max_blocks)
242 percpu_counter_sub(&sbinfo->used_blocks, pages);
243 shmem_unacct_blocks(info->flags, pages);
246 static const struct super_operations shmem_ops;
247 static const struct address_space_operations shmem_aops;
248 static const struct file_operations shmem_file_operations;
249 static const struct inode_operations shmem_inode_operations;
250 static const struct inode_operations shmem_dir_inode_operations;
251 static const struct inode_operations shmem_special_inode_operations;
252 static const struct vm_operations_struct shmem_vm_ops;
253 static struct file_system_type shmem_fs_type;
255 bool vma_is_shmem(struct vm_area_struct *vma)
257 return vma->vm_ops == &shmem_vm_ops;
260 static LIST_HEAD(shmem_swaplist);
261 static DEFINE_MUTEX(shmem_swaplist_mutex);
263 static int shmem_reserve_inode(struct super_block *sb)
265 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
266 if (sbinfo->max_inodes) {
267 spin_lock(&sbinfo->stat_lock);
268 if (!sbinfo->free_inodes) {
269 spin_unlock(&sbinfo->stat_lock);
272 sbinfo->free_inodes--;
273 spin_unlock(&sbinfo->stat_lock);
278 static void shmem_free_inode(struct super_block *sb)
280 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
281 if (sbinfo->max_inodes) {
282 spin_lock(&sbinfo->stat_lock);
283 sbinfo->free_inodes++;
284 spin_unlock(&sbinfo->stat_lock);
289 * shmem_recalc_inode - recalculate the block usage of an inode
290 * @inode: inode to recalc
292 * We have to calculate the free blocks since the mm can drop
293 * undirtied hole pages behind our back.
295 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
296 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
298 * It has to be called with the spinlock held.
300 static void shmem_recalc_inode(struct inode *inode)
302 struct shmem_inode_info *info = SHMEM_I(inode);
305 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
307 info->alloced -= freed;
308 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
309 shmem_inode_unacct_blocks(inode, freed);
313 bool shmem_charge(struct inode *inode, long pages)
315 struct shmem_inode_info *info = SHMEM_I(inode);
318 if (!shmem_inode_acct_block(inode, pages))
321 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
322 inode->i_mapping->nrpages += pages;
324 spin_lock_irqsave(&info->lock, flags);
325 info->alloced += pages;
326 inode->i_blocks += pages * BLOCKS_PER_PAGE;
327 shmem_recalc_inode(inode);
328 spin_unlock_irqrestore(&info->lock, flags);
333 void shmem_uncharge(struct inode *inode, long pages)
335 struct shmem_inode_info *info = SHMEM_I(inode);
338 /* nrpages adjustment done by __delete_from_page_cache() or caller */
340 spin_lock_irqsave(&info->lock, flags);
341 info->alloced -= pages;
342 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
343 shmem_recalc_inode(inode);
344 spin_unlock_irqrestore(&info->lock, flags);
346 shmem_inode_unacct_blocks(inode, pages);
350 * Replace item expected in xarray by a new item, while holding xa_lock.
352 static int shmem_replace_entry(struct address_space *mapping,
353 pgoff_t index, void *expected, void *replacement)
355 XA_STATE(xas, &mapping->i_pages, index);
358 VM_BUG_ON(!expected);
359 VM_BUG_ON(!replacement);
360 item = xas_load(&xas);
361 if (item != expected)
363 xas_store(&xas, replacement);
368 * Sometimes, before we decide whether to proceed or to fail, we must check
369 * that an entry was not already brought back from swap by a racing thread.
371 * Checking page is not enough: by the time a SwapCache page is locked, it
372 * might be reused, and again be SwapCache, using the same swap as before.
374 static bool shmem_confirm_swap(struct address_space *mapping,
375 pgoff_t index, swp_entry_t swap)
377 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
381 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
384 * disables huge pages for the mount;
386 * enables huge pages for the mount;
387 * SHMEM_HUGE_WITHIN_SIZE:
388 * only allocate huge pages if the page will be fully within i_size,
389 * also respect fadvise()/madvise() hints;
391 * only allocate huge pages if requested with fadvise()/madvise();
394 #define SHMEM_HUGE_NEVER 0
395 #define SHMEM_HUGE_ALWAYS 1
396 #define SHMEM_HUGE_WITHIN_SIZE 2
397 #define SHMEM_HUGE_ADVISE 3
401 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
404 * disables huge on shm_mnt and all mounts, for emergency use;
406 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
409 #define SHMEM_HUGE_DENY (-1)
410 #define SHMEM_HUGE_FORCE (-2)
412 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
413 /* ifdef here to avoid bloating shmem.o when not necessary */
415 static int shmem_huge __read_mostly;
417 #if defined(CONFIG_SYSFS)
418 static int shmem_parse_huge(const char *str)
420 if (!strcmp(str, "never"))
421 return SHMEM_HUGE_NEVER;
422 if (!strcmp(str, "always"))
423 return SHMEM_HUGE_ALWAYS;
424 if (!strcmp(str, "within_size"))
425 return SHMEM_HUGE_WITHIN_SIZE;
426 if (!strcmp(str, "advise"))
427 return SHMEM_HUGE_ADVISE;
428 if (!strcmp(str, "deny"))
429 return SHMEM_HUGE_DENY;
430 if (!strcmp(str, "force"))
431 return SHMEM_HUGE_FORCE;
436 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
437 static const char *shmem_format_huge(int huge)
440 case SHMEM_HUGE_NEVER:
442 case SHMEM_HUGE_ALWAYS:
444 case SHMEM_HUGE_WITHIN_SIZE:
445 return "within_size";
446 case SHMEM_HUGE_ADVISE:
448 case SHMEM_HUGE_DENY:
450 case SHMEM_HUGE_FORCE:
459 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
460 struct shrink_control *sc, unsigned long nr_to_split)
462 LIST_HEAD(list), *pos, *next;
463 LIST_HEAD(to_remove);
465 struct shmem_inode_info *info;
467 unsigned long batch = sc ? sc->nr_to_scan : 128;
468 int removed = 0, split = 0;
470 if (list_empty(&sbinfo->shrinklist))
473 spin_lock(&sbinfo->shrinklist_lock);
474 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
475 info = list_entry(pos, struct shmem_inode_info, shrinklist);
478 inode = igrab(&info->vfs_inode);
480 /* inode is about to be evicted */
482 list_del_init(&info->shrinklist);
487 /* Check if there's anything to gain */
488 if (round_up(inode->i_size, PAGE_SIZE) ==
489 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
490 list_move(&info->shrinklist, &to_remove);
495 list_move(&info->shrinklist, &list);
500 spin_unlock(&sbinfo->shrinklist_lock);
502 list_for_each_safe(pos, next, &to_remove) {
503 info = list_entry(pos, struct shmem_inode_info, shrinklist);
504 inode = &info->vfs_inode;
505 list_del_init(&info->shrinklist);
509 list_for_each_safe(pos, next, &list) {
512 info = list_entry(pos, struct shmem_inode_info, shrinklist);
513 inode = &info->vfs_inode;
515 if (nr_to_split && split >= nr_to_split)
518 page = find_get_page(inode->i_mapping,
519 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
523 /* No huge page at the end of the file: nothing to split */
524 if (!PageTransHuge(page)) {
530 * Leave the inode on the list if we failed to lock
531 * the page at this time.
533 * Waiting for the lock may lead to deadlock in the
536 if (!trylock_page(page)) {
541 ret = split_huge_page(page);
545 /* If split failed leave the inode on the list */
551 list_del_init(&info->shrinklist);
557 spin_lock(&sbinfo->shrinklist_lock);
558 list_splice_tail(&list, &sbinfo->shrinklist);
559 sbinfo->shrinklist_len -= removed;
560 spin_unlock(&sbinfo->shrinklist_lock);
565 static long shmem_unused_huge_scan(struct super_block *sb,
566 struct shrink_control *sc)
568 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
570 if (!READ_ONCE(sbinfo->shrinklist_len))
573 return shmem_unused_huge_shrink(sbinfo, sc, 0);
576 static long shmem_unused_huge_count(struct super_block *sb,
577 struct shrink_control *sc)
579 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
580 return READ_ONCE(sbinfo->shrinklist_len);
582 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
584 #define shmem_huge SHMEM_HUGE_DENY
586 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
587 struct shrink_control *sc, unsigned long nr_to_split)
591 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
593 static inline bool is_huge_enabled(struct shmem_sb_info *sbinfo)
595 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
596 (shmem_huge == SHMEM_HUGE_FORCE || sbinfo->huge) &&
597 shmem_huge != SHMEM_HUGE_DENY)
603 * Like add_to_page_cache_locked, but error if expected item has gone.
605 static int shmem_add_to_page_cache(struct page *page,
606 struct address_space *mapping,
607 pgoff_t index, void *expected, gfp_t gfp)
609 XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
611 unsigned long nr = 1UL << compound_order(page);
613 VM_BUG_ON_PAGE(PageTail(page), page);
614 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
615 VM_BUG_ON_PAGE(!PageLocked(page), page);
616 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
617 VM_BUG_ON(expected && PageTransHuge(page));
619 page_ref_add(page, nr);
620 page->mapping = mapping;
626 entry = xas_find_conflict(&xas);
627 if (entry != expected)
628 xas_set_err(&xas, -EEXIST);
629 xas_create_range(&xas);
633 xas_store(&xas, page + i);
638 if (PageTransHuge(page)) {
639 count_vm_event(THP_FILE_ALLOC);
640 __inc_node_page_state(page, NR_SHMEM_THPS);
642 mapping->nrpages += nr;
643 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
644 __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
646 xas_unlock_irq(&xas);
647 } while (xas_nomem(&xas, gfp));
649 if (xas_error(&xas)) {
650 page->mapping = NULL;
651 page_ref_sub(page, nr);
652 return xas_error(&xas);
659 * Like delete_from_page_cache, but substitutes swap for page.
661 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
663 struct address_space *mapping = page->mapping;
666 VM_BUG_ON_PAGE(PageCompound(page), page);
668 xa_lock_irq(&mapping->i_pages);
669 error = shmem_replace_entry(mapping, page->index, page, radswap);
670 page->mapping = NULL;
672 __dec_node_page_state(page, NR_FILE_PAGES);
673 __dec_node_page_state(page, NR_SHMEM);
674 xa_unlock_irq(&mapping->i_pages);
680 * Remove swap entry from page cache, free the swap and its page cache.
682 static int shmem_free_swap(struct address_space *mapping,
683 pgoff_t index, void *radswap)
687 old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
690 free_swap_and_cache(radix_to_swp_entry(radswap));
695 * Determine (in bytes) how many of the shmem object's pages mapped by the
696 * given offsets are swapped out.
698 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
699 * as long as the inode doesn't go away and racy results are not a problem.
701 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
702 pgoff_t start, pgoff_t end)
704 XA_STATE(xas, &mapping->i_pages, start);
706 unsigned long swapped = 0;
709 xas_for_each(&xas, page, end - 1) {
710 if (xas_retry(&xas, page))
712 if (xa_is_value(page))
715 if (need_resched()) {
723 return swapped << PAGE_SHIFT;
727 * Determine (in bytes) how many of the shmem object's pages mapped by the
728 * given vma is swapped out.
730 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
731 * as long as the inode doesn't go away and racy results are not a problem.
733 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
735 struct inode *inode = file_inode(vma->vm_file);
736 struct shmem_inode_info *info = SHMEM_I(inode);
737 struct address_space *mapping = inode->i_mapping;
738 unsigned long swapped;
740 /* Be careful as we don't hold info->lock */
741 swapped = READ_ONCE(info->swapped);
744 * The easier cases are when the shmem object has nothing in swap, or
745 * the vma maps it whole. Then we can simply use the stats that we
751 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
752 return swapped << PAGE_SHIFT;
754 /* Here comes the more involved part */
755 return shmem_partial_swap_usage(mapping,
756 linear_page_index(vma, vma->vm_start),
757 linear_page_index(vma, vma->vm_end));
761 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
763 void shmem_unlock_mapping(struct address_space *mapping)
766 pgoff_t indices[PAGEVEC_SIZE];
771 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
773 while (!mapping_unevictable(mapping)) {
775 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
776 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
778 pvec.nr = find_get_entries(mapping, index,
779 PAGEVEC_SIZE, pvec.pages, indices);
782 index = indices[pvec.nr - 1] + 1;
783 pagevec_remove_exceptionals(&pvec);
784 check_move_unevictable_pages(&pvec);
785 pagevec_release(&pvec);
791 * Remove range of pages and swap entries from page cache, and free them.
792 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
794 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
797 struct address_space *mapping = inode->i_mapping;
798 struct shmem_inode_info *info = SHMEM_I(inode);
799 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
800 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
801 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
802 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
804 pgoff_t indices[PAGEVEC_SIZE];
805 long nr_swaps_freed = 0;
810 end = -1; /* unsigned, so actually very big */
814 while (index < end) {
815 pvec.nr = find_get_entries(mapping, index,
816 min(end - index, (pgoff_t)PAGEVEC_SIZE),
817 pvec.pages, indices);
820 for (i = 0; i < pagevec_count(&pvec); i++) {
821 struct page *page = pvec.pages[i];
827 if (xa_is_value(page)) {
830 nr_swaps_freed += !shmem_free_swap(mapping,
835 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
837 if (!trylock_page(page))
840 if (PageTransTail(page)) {
841 /* Middle of THP: zero out the page */
842 clear_highpage(page);
845 } else if (PageTransHuge(page)) {
846 if (index == round_down(end, HPAGE_PMD_NR)) {
848 * Range ends in the middle of THP:
851 clear_highpage(page);
855 index += HPAGE_PMD_NR - 1;
856 i += HPAGE_PMD_NR - 1;
859 if (!unfalloc || !PageUptodate(page)) {
860 VM_BUG_ON_PAGE(PageTail(page), page);
861 if (page_mapping(page) == mapping) {
862 VM_BUG_ON_PAGE(PageWriteback(page), page);
863 truncate_inode_page(mapping, page);
868 pagevec_remove_exceptionals(&pvec);
869 pagevec_release(&pvec);
875 struct page *page = NULL;
876 shmem_getpage(inode, start - 1, &page, SGP_READ);
878 unsigned int top = PAGE_SIZE;
883 zero_user_segment(page, partial_start, top);
884 set_page_dirty(page);
890 struct page *page = NULL;
891 shmem_getpage(inode, end, &page, SGP_READ);
893 zero_user_segment(page, 0, partial_end);
894 set_page_dirty(page);
903 while (index < end) {
906 pvec.nr = find_get_entries(mapping, index,
907 min(end - index, (pgoff_t)PAGEVEC_SIZE),
908 pvec.pages, indices);
910 /* If all gone or hole-punch or unfalloc, we're done */
911 if (index == start || end != -1)
913 /* But if truncating, restart to make sure all gone */
917 for (i = 0; i < pagevec_count(&pvec); i++) {
918 struct page *page = pvec.pages[i];
924 if (xa_is_value(page)) {
927 if (shmem_free_swap(mapping, index, page)) {
928 /* Swap was replaced by page: retry */
938 if (PageTransTail(page)) {
939 /* Middle of THP: zero out the page */
940 clear_highpage(page);
943 * Partial thp truncate due 'start' in middle
944 * of THP: don't need to look on these pages
945 * again on !pvec.nr restart.
947 if (index != round_down(end, HPAGE_PMD_NR))
950 } else if (PageTransHuge(page)) {
951 if (index == round_down(end, HPAGE_PMD_NR)) {
953 * Range ends in the middle of THP:
956 clear_highpage(page);
960 index += HPAGE_PMD_NR - 1;
961 i += HPAGE_PMD_NR - 1;
964 if (!unfalloc || !PageUptodate(page)) {
965 VM_BUG_ON_PAGE(PageTail(page), page);
966 if (page_mapping(page) == mapping) {
967 VM_BUG_ON_PAGE(PageWriteback(page), page);
968 truncate_inode_page(mapping, page);
970 /* Page was replaced by swap: retry */
978 pagevec_remove_exceptionals(&pvec);
979 pagevec_release(&pvec);
983 spin_lock_irq(&info->lock);
984 info->swapped -= nr_swaps_freed;
985 shmem_recalc_inode(inode);
986 spin_unlock_irq(&info->lock);
989 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
991 shmem_undo_range(inode, lstart, lend, false);
992 inode->i_ctime = inode->i_mtime = current_time(inode);
994 EXPORT_SYMBOL_GPL(shmem_truncate_range);
996 static int shmem_getattr(const struct path *path, struct kstat *stat,
997 u32 request_mask, unsigned int query_flags)
999 struct inode *inode = path->dentry->d_inode;
1000 struct shmem_inode_info *info = SHMEM_I(inode);
1001 struct shmem_sb_info *sb_info = SHMEM_SB(inode->i_sb);
1003 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
1004 spin_lock_irq(&info->lock);
1005 shmem_recalc_inode(inode);
1006 spin_unlock_irq(&info->lock);
1008 generic_fillattr(inode, stat);
1010 if (is_huge_enabled(sb_info))
1011 stat->blksize = HPAGE_PMD_SIZE;
1016 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
1018 struct inode *inode = d_inode(dentry);
1019 struct shmem_inode_info *info = SHMEM_I(inode);
1020 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1023 error = setattr_prepare(dentry, attr);
1027 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1028 loff_t oldsize = inode->i_size;
1029 loff_t newsize = attr->ia_size;
1031 /* protected by i_mutex */
1032 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1033 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1036 if (newsize != oldsize) {
1037 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1041 i_size_write(inode, newsize);
1042 inode->i_ctime = inode->i_mtime = current_time(inode);
1044 if (newsize <= oldsize) {
1045 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1046 if (oldsize > holebegin)
1047 unmap_mapping_range(inode->i_mapping,
1050 shmem_truncate_range(inode,
1051 newsize, (loff_t)-1);
1052 /* unmap again to remove racily COWed private pages */
1053 if (oldsize > holebegin)
1054 unmap_mapping_range(inode->i_mapping,
1058 * Part of the huge page can be beyond i_size: subject
1059 * to shrink under memory pressure.
1061 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
1062 spin_lock(&sbinfo->shrinklist_lock);
1064 * _careful to defend against unlocked access to
1065 * ->shrink_list in shmem_unused_huge_shrink()
1067 if (list_empty_careful(&info->shrinklist)) {
1068 list_add_tail(&info->shrinklist,
1069 &sbinfo->shrinklist);
1070 sbinfo->shrinklist_len++;
1072 spin_unlock(&sbinfo->shrinklist_lock);
1077 setattr_copy(inode, attr);
1078 if (attr->ia_valid & ATTR_MODE)
1079 error = posix_acl_chmod(inode, inode->i_mode);
1083 static void shmem_evict_inode(struct inode *inode)
1085 struct shmem_inode_info *info = SHMEM_I(inode);
1086 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1088 if (inode->i_mapping->a_ops == &shmem_aops) {
1089 shmem_unacct_size(info->flags, inode->i_size);
1091 shmem_truncate_range(inode, 0, (loff_t)-1);
1092 if (!list_empty(&info->shrinklist)) {
1093 spin_lock(&sbinfo->shrinklist_lock);
1094 if (!list_empty(&info->shrinklist)) {
1095 list_del_init(&info->shrinklist);
1096 sbinfo->shrinklist_len--;
1098 spin_unlock(&sbinfo->shrinklist_lock);
1100 while (!list_empty(&info->swaplist)) {
1101 /* Wait while shmem_unuse() is scanning this inode... */
1102 wait_var_event(&info->stop_eviction,
1103 !atomic_read(&info->stop_eviction));
1104 mutex_lock(&shmem_swaplist_mutex);
1105 /* ...but beware of the race if we peeked too early */
1106 if (!atomic_read(&info->stop_eviction))
1107 list_del_init(&info->swaplist);
1108 mutex_unlock(&shmem_swaplist_mutex);
1112 simple_xattrs_free(&info->xattrs);
1113 WARN_ON(inode->i_blocks);
1114 shmem_free_inode(inode->i_sb);
1118 extern struct swap_info_struct *swap_info[];
1120 static int shmem_find_swap_entries(struct address_space *mapping,
1121 pgoff_t start, unsigned int nr_entries,
1122 struct page **entries, pgoff_t *indices,
1123 unsigned int type, bool frontswap)
1125 XA_STATE(xas, &mapping->i_pages, start);
1128 unsigned int ret = 0;
1134 xas_for_each(&xas, page, ULONG_MAX) {
1135 if (xas_retry(&xas, page))
1138 if (!xa_is_value(page))
1141 entry = radix_to_swp_entry(page);
1142 if (swp_type(entry) != type)
1145 !frontswap_test(swap_info[type], swp_offset(entry)))
1148 indices[ret] = xas.xa_index;
1149 entries[ret] = page;
1151 if (need_resched()) {
1155 if (++ret == nr_entries)
1164 * Move the swapped pages for an inode to page cache. Returns the count
1165 * of pages swapped in, or the error in case of failure.
1167 static int shmem_unuse_swap_entries(struct inode *inode, struct pagevec pvec,
1173 struct address_space *mapping = inode->i_mapping;
1175 for (i = 0; i < pvec.nr; i++) {
1176 struct page *page = pvec.pages[i];
1178 if (!xa_is_value(page))
1180 error = shmem_swapin_page(inode, indices[i],
1182 mapping_gfp_mask(mapping),
1189 if (error == -ENOMEM)
1193 return error ? error : ret;
1197 * If swap found in inode, free it and move page from swapcache to filecache.
1199 static int shmem_unuse_inode(struct inode *inode, unsigned int type,
1200 bool frontswap, unsigned long *fs_pages_to_unuse)
1202 struct address_space *mapping = inode->i_mapping;
1204 struct pagevec pvec;
1205 pgoff_t indices[PAGEVEC_SIZE];
1206 bool frontswap_partial = (frontswap && *fs_pages_to_unuse > 0);
1209 pagevec_init(&pvec);
1211 unsigned int nr_entries = PAGEVEC_SIZE;
1213 if (frontswap_partial && *fs_pages_to_unuse < PAGEVEC_SIZE)
1214 nr_entries = *fs_pages_to_unuse;
1216 pvec.nr = shmem_find_swap_entries(mapping, start, nr_entries,
1217 pvec.pages, indices,
1224 ret = shmem_unuse_swap_entries(inode, pvec, indices);
1228 if (frontswap_partial) {
1229 *fs_pages_to_unuse -= ret;
1230 if (*fs_pages_to_unuse == 0) {
1231 ret = FRONTSWAP_PAGES_UNUSED;
1236 start = indices[pvec.nr - 1];
1243 * Read all the shared memory data that resides in the swap
1244 * device 'type' back into memory, so the swap device can be
1247 int shmem_unuse(unsigned int type, bool frontswap,
1248 unsigned long *fs_pages_to_unuse)
1250 struct shmem_inode_info *info, *next;
1253 if (list_empty(&shmem_swaplist))
1256 mutex_lock(&shmem_swaplist_mutex);
1257 list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1258 if (!info->swapped) {
1259 list_del_init(&info->swaplist);
1263 * Drop the swaplist mutex while searching the inode for swap;
1264 * but before doing so, make sure shmem_evict_inode() will not
1265 * remove placeholder inode from swaplist, nor let it be freed
1266 * (igrab() would protect from unlink, but not from unmount).
1268 atomic_inc(&info->stop_eviction);
1269 mutex_unlock(&shmem_swaplist_mutex);
1271 error = shmem_unuse_inode(&info->vfs_inode, type, frontswap,
1275 mutex_lock(&shmem_swaplist_mutex);
1276 next = list_next_entry(info, swaplist);
1278 list_del_init(&info->swaplist);
1279 if (atomic_dec_and_test(&info->stop_eviction))
1280 wake_up_var(&info->stop_eviction);
1284 mutex_unlock(&shmem_swaplist_mutex);
1290 * Move the page from the page cache to the swap cache.
1292 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1294 struct shmem_inode_info *info;
1295 struct address_space *mapping;
1296 struct inode *inode;
1300 VM_BUG_ON_PAGE(PageCompound(page), page);
1301 BUG_ON(!PageLocked(page));
1302 mapping = page->mapping;
1303 index = page->index;
1304 inode = mapping->host;
1305 info = SHMEM_I(inode);
1306 if (info->flags & VM_LOCKED)
1308 if (!total_swap_pages)
1312 * Our capabilities prevent regular writeback or sync from ever calling
1313 * shmem_writepage; but a stacking filesystem might use ->writepage of
1314 * its underlying filesystem, in which case tmpfs should write out to
1315 * swap only in response to memory pressure, and not for the writeback
1318 if (!wbc->for_reclaim) {
1319 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1324 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1325 * value into swapfile.c, the only way we can correctly account for a
1326 * fallocated page arriving here is now to initialize it and write it.
1328 * That's okay for a page already fallocated earlier, but if we have
1329 * not yet completed the fallocation, then (a) we want to keep track
1330 * of this page in case we have to undo it, and (b) it may not be a
1331 * good idea to continue anyway, once we're pushing into swap. So
1332 * reactivate the page, and let shmem_fallocate() quit when too many.
1334 if (!PageUptodate(page)) {
1335 if (inode->i_private) {
1336 struct shmem_falloc *shmem_falloc;
1337 spin_lock(&inode->i_lock);
1338 shmem_falloc = inode->i_private;
1340 !shmem_falloc->waitq &&
1341 index >= shmem_falloc->start &&
1342 index < shmem_falloc->next)
1343 shmem_falloc->nr_unswapped++;
1345 shmem_falloc = NULL;
1346 spin_unlock(&inode->i_lock);
1350 clear_highpage(page);
1351 flush_dcache_page(page);
1352 SetPageUptodate(page);
1355 swap = get_swap_page(page);
1360 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1361 * if it's not already there. Do it now before the page is
1362 * moved to swap cache, when its pagelock no longer protects
1363 * the inode from eviction. But don't unlock the mutex until
1364 * we've incremented swapped, because shmem_unuse_inode() will
1365 * prune a !swapped inode from the swaplist under this mutex.
1367 mutex_lock(&shmem_swaplist_mutex);
1368 if (list_empty(&info->swaplist))
1369 list_add(&info->swaplist, &shmem_swaplist);
1371 if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1372 spin_lock_irq(&info->lock);
1373 shmem_recalc_inode(inode);
1375 spin_unlock_irq(&info->lock);
1377 swap_shmem_alloc(swap);
1378 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1380 mutex_unlock(&shmem_swaplist_mutex);
1381 BUG_ON(page_mapped(page));
1382 swap_writepage(page, wbc);
1386 mutex_unlock(&shmem_swaplist_mutex);
1387 put_swap_page(page, swap);
1389 set_page_dirty(page);
1390 if (wbc->for_reclaim)
1391 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1396 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1397 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1401 if (!mpol || mpol->mode == MPOL_DEFAULT)
1402 return; /* show nothing */
1404 mpol_to_str(buffer, sizeof(buffer), mpol);
1406 seq_printf(seq, ",mpol=%s", buffer);
1409 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1411 struct mempolicy *mpol = NULL;
1413 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1414 mpol = sbinfo->mpol;
1416 spin_unlock(&sbinfo->stat_lock);
1420 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1421 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1424 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1428 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1430 #define vm_policy vm_private_data
1433 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1434 struct shmem_inode_info *info, pgoff_t index)
1436 /* Create a pseudo vma that just contains the policy */
1437 vma_init(vma, NULL);
1438 /* Bias interleave by inode number to distribute better across nodes */
1439 vma->vm_pgoff = index + info->vfs_inode.i_ino;
1440 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1443 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1445 /* Drop reference taken by mpol_shared_policy_lookup() */
1446 mpol_cond_put(vma->vm_policy);
1449 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1450 struct shmem_inode_info *info, pgoff_t index)
1452 struct vm_area_struct pvma;
1454 struct vm_fault vmf;
1456 shmem_pseudo_vma_init(&pvma, info, index);
1459 page = swap_cluster_readahead(swap, gfp, &vmf);
1460 shmem_pseudo_vma_destroy(&pvma);
1465 static struct page *shmem_alloc_hugepage(gfp_t gfp,
1466 struct shmem_inode_info *info, pgoff_t index)
1468 struct vm_area_struct pvma;
1469 struct address_space *mapping = info->vfs_inode.i_mapping;
1473 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1476 hindex = round_down(index, HPAGE_PMD_NR);
1477 if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
1481 shmem_pseudo_vma_init(&pvma, info, hindex);
1482 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1483 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id());
1484 shmem_pseudo_vma_destroy(&pvma);
1486 prep_transhuge_page(page);
1490 static struct page *shmem_alloc_page(gfp_t gfp,
1491 struct shmem_inode_info *info, pgoff_t index)
1493 struct vm_area_struct pvma;
1496 shmem_pseudo_vma_init(&pvma, info, index);
1497 page = alloc_page_vma(gfp, &pvma, 0);
1498 shmem_pseudo_vma_destroy(&pvma);
1503 static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1504 struct inode *inode,
1505 pgoff_t index, bool huge)
1507 struct shmem_inode_info *info = SHMEM_I(inode);
1512 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1514 nr = huge ? HPAGE_PMD_NR : 1;
1516 if (!shmem_inode_acct_block(inode, nr))
1520 page = shmem_alloc_hugepage(gfp, info, index);
1522 page = shmem_alloc_page(gfp, info, index);
1524 __SetPageLocked(page);
1525 __SetPageSwapBacked(page);
1530 shmem_inode_unacct_blocks(inode, nr);
1532 return ERR_PTR(err);
1536 * When a page is moved from swapcache to shmem filecache (either by the
1537 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1538 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1539 * ignorance of the mapping it belongs to. If that mapping has special
1540 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1541 * we may need to copy to a suitable page before moving to filecache.
1543 * In a future release, this may well be extended to respect cpuset and
1544 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1545 * but for now it is a simple matter of zone.
1547 static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1549 return page_zonenum(page) > gfp_zone(gfp);
1552 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1553 struct shmem_inode_info *info, pgoff_t index)
1555 struct page *oldpage, *newpage;
1556 struct address_space *swap_mapping;
1562 entry.val = page_private(oldpage);
1563 swap_index = swp_offset(entry);
1564 swap_mapping = page_mapping(oldpage);
1567 * We have arrived here because our zones are constrained, so don't
1568 * limit chance of success by further cpuset and node constraints.
1570 gfp &= ~GFP_CONSTRAINT_MASK;
1571 newpage = shmem_alloc_page(gfp, info, index);
1576 copy_highpage(newpage, oldpage);
1577 flush_dcache_page(newpage);
1579 __SetPageLocked(newpage);
1580 __SetPageSwapBacked(newpage);
1581 SetPageUptodate(newpage);
1582 set_page_private(newpage, entry.val);
1583 SetPageSwapCache(newpage);
1586 * Our caller will very soon move newpage out of swapcache, but it's
1587 * a nice clean interface for us to replace oldpage by newpage there.
1589 xa_lock_irq(&swap_mapping->i_pages);
1590 error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
1592 __inc_node_page_state(newpage, NR_FILE_PAGES);
1593 __dec_node_page_state(oldpage, NR_FILE_PAGES);
1595 xa_unlock_irq(&swap_mapping->i_pages);
1597 if (unlikely(error)) {
1599 * Is this possible? I think not, now that our callers check
1600 * both PageSwapCache and page_private after getting page lock;
1601 * but be defensive. Reverse old to newpage for clear and free.
1605 mem_cgroup_migrate(oldpage, newpage);
1606 lru_cache_add_anon(newpage);
1610 ClearPageSwapCache(oldpage);
1611 set_page_private(oldpage, 0);
1613 unlock_page(oldpage);
1620 * Swap in the page pointed to by *pagep.
1621 * Caller has to make sure that *pagep contains a valid swapped page.
1622 * Returns 0 and the page in pagep if success. On failure, returns the
1623 * the error code and NULL in *pagep.
1625 static int shmem_swapin_page(struct inode *inode, pgoff_t index,
1626 struct page **pagep, enum sgp_type sgp,
1627 gfp_t gfp, struct vm_area_struct *vma,
1628 vm_fault_t *fault_type)
1630 struct address_space *mapping = inode->i_mapping;
1631 struct shmem_inode_info *info = SHMEM_I(inode);
1632 struct mm_struct *charge_mm = vma ? vma->vm_mm : current->mm;
1633 struct mem_cgroup *memcg;
1638 VM_BUG_ON(!*pagep || !xa_is_value(*pagep));
1639 swap = radix_to_swp_entry(*pagep);
1642 /* Look it up and read it in.. */
1643 page = lookup_swap_cache(swap, NULL, 0);
1645 /* Or update major stats only when swapin succeeds?? */
1647 *fault_type |= VM_FAULT_MAJOR;
1648 count_vm_event(PGMAJFAULT);
1649 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1651 /* Here we actually start the io */
1652 page = shmem_swapin(swap, gfp, info, index);
1659 /* We have to do this with page locked to prevent races */
1661 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1662 !shmem_confirm_swap(mapping, index, swap)) {
1666 if (!PageUptodate(page)) {
1670 wait_on_page_writeback(page);
1672 if (shmem_should_replace_page(page, gfp)) {
1673 error = shmem_replace_page(&page, gfp, info, index);
1678 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1681 error = shmem_add_to_page_cache(page, mapping, index,
1682 swp_to_radix_entry(swap), gfp);
1684 * We already confirmed swap under page lock, and make
1685 * no memory allocation here, so usually no possibility
1686 * of error; but free_swap_and_cache() only trylocks a
1687 * page, so it is just possible that the entry has been
1688 * truncated or holepunched since swap was confirmed.
1689 * shmem_undo_range() will have done some of the
1690 * unaccounting, now delete_from_swap_cache() will do
1694 mem_cgroup_cancel_charge(page, memcg, false);
1695 delete_from_swap_cache(page);
1701 mem_cgroup_commit_charge(page, memcg, true, false);
1703 spin_lock_irq(&info->lock);
1705 shmem_recalc_inode(inode);
1706 spin_unlock_irq(&info->lock);
1708 if (sgp == SGP_WRITE)
1709 mark_page_accessed(page);
1711 delete_from_swap_cache(page);
1712 set_page_dirty(page);
1718 if (!shmem_confirm_swap(mapping, index, swap))
1730 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1732 * If we allocate a new one we do not mark it dirty. That's up to the
1733 * vm. If we swap it in we mark it dirty since we also free the swap
1734 * entry since a page cannot live in both the swap and page cache.
1736 * fault_mm and fault_type are only supplied by shmem_fault:
1737 * otherwise they are NULL.
1739 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1740 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1741 struct vm_area_struct *vma, struct vm_fault *vmf,
1742 vm_fault_t *fault_type)
1744 struct address_space *mapping = inode->i_mapping;
1745 struct shmem_inode_info *info = SHMEM_I(inode);
1746 struct shmem_sb_info *sbinfo;
1747 struct mm_struct *charge_mm;
1748 struct mem_cgroup *memcg;
1750 enum sgp_type sgp_huge = sgp;
1751 pgoff_t hindex = index;
1756 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1758 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1761 if (sgp <= SGP_CACHE &&
1762 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1766 sbinfo = SHMEM_SB(inode->i_sb);
1767 charge_mm = vma ? vma->vm_mm : current->mm;
1769 page = find_lock_entry(mapping, index);
1770 if (xa_is_value(page)) {
1771 error = shmem_swapin_page(inode, index, &page,
1772 sgp, gfp, vma, fault_type);
1773 if (error == -EEXIST)
1780 if (page && sgp == SGP_WRITE)
1781 mark_page_accessed(page);
1783 /* fallocated page? */
1784 if (page && !PageUptodate(page)) {
1785 if (sgp != SGP_READ)
1791 if (page || sgp == SGP_READ) {
1797 * Fast cache lookup did not find it:
1798 * bring it back from swap or allocate.
1801 if (vma && userfaultfd_missing(vma)) {
1802 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1806 /* shmem_symlink() */
1807 if (mapping->a_ops != &shmem_aops)
1809 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1811 if (shmem_huge == SHMEM_HUGE_FORCE)
1813 switch (sbinfo->huge) {
1816 case SHMEM_HUGE_NEVER:
1818 case SHMEM_HUGE_WITHIN_SIZE:
1819 off = round_up(index, HPAGE_PMD_NR);
1820 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1821 if (i_size >= HPAGE_PMD_SIZE &&
1822 i_size >> PAGE_SHIFT >= off)
1825 case SHMEM_HUGE_ADVISE:
1826 if (sgp_huge == SGP_HUGE)
1828 /* TODO: implement fadvise() hints */
1833 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1836 page = shmem_alloc_and_acct_page(gfp, inode,
1842 error = PTR_ERR(page);
1844 if (error != -ENOSPC)
1847 * Try to reclaim some space by splitting a huge page
1848 * beyond i_size on the filesystem.
1853 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1854 if (ret == SHRINK_STOP)
1862 if (PageTransHuge(page))
1863 hindex = round_down(index, HPAGE_PMD_NR);
1867 if (sgp == SGP_WRITE)
1868 __SetPageReferenced(page);
1870 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1871 PageTransHuge(page));
1874 error = shmem_add_to_page_cache(page, mapping, hindex,
1875 NULL, gfp & GFP_RECLAIM_MASK);
1877 mem_cgroup_cancel_charge(page, memcg,
1878 PageTransHuge(page));
1881 mem_cgroup_commit_charge(page, memcg, false,
1882 PageTransHuge(page));
1883 lru_cache_add_anon(page);
1885 spin_lock_irq(&info->lock);
1886 info->alloced += 1 << compound_order(page);
1887 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1888 shmem_recalc_inode(inode);
1889 spin_unlock_irq(&info->lock);
1892 if (PageTransHuge(page) &&
1893 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1894 hindex + HPAGE_PMD_NR - 1) {
1896 * Part of the huge page is beyond i_size: subject
1897 * to shrink under memory pressure.
1899 spin_lock(&sbinfo->shrinklist_lock);
1901 * _careful to defend against unlocked access to
1902 * ->shrink_list in shmem_unused_huge_shrink()
1904 if (list_empty_careful(&info->shrinklist)) {
1905 list_add_tail(&info->shrinklist,
1906 &sbinfo->shrinklist);
1907 sbinfo->shrinklist_len++;
1909 spin_unlock(&sbinfo->shrinklist_lock);
1913 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1915 if (sgp == SGP_FALLOC)
1919 * Let SGP_WRITE caller clear ends if write does not fill page;
1920 * but SGP_FALLOC on a page fallocated earlier must initialize
1921 * it now, lest undo on failure cancel our earlier guarantee.
1923 if (sgp != SGP_WRITE && !PageUptodate(page)) {
1924 struct page *head = compound_head(page);
1927 for (i = 0; i < (1 << compound_order(head)); i++) {
1928 clear_highpage(head + i);
1929 flush_dcache_page(head + i);
1931 SetPageUptodate(head);
1934 /* Perhaps the file has been truncated since we checked */
1935 if (sgp <= SGP_CACHE &&
1936 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1938 ClearPageDirty(page);
1939 delete_from_page_cache(page);
1940 spin_lock_irq(&info->lock);
1941 shmem_recalc_inode(inode);
1942 spin_unlock_irq(&info->lock);
1947 *pagep = page + index - hindex;
1954 shmem_inode_unacct_blocks(inode, 1 << compound_order(page));
1956 if (PageTransHuge(page)) {
1966 if (error == -ENOSPC && !once++) {
1967 spin_lock_irq(&info->lock);
1968 shmem_recalc_inode(inode);
1969 spin_unlock_irq(&info->lock);
1972 if (error == -EEXIST)
1978 * This is like autoremove_wake_function, but it removes the wait queue
1979 * entry unconditionally - even if something else had already woken the
1982 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
1984 int ret = default_wake_function(wait, mode, sync, key);
1985 list_del_init(&wait->entry);
1989 static vm_fault_t shmem_fault(struct vm_fault *vmf)
1991 struct vm_area_struct *vma = vmf->vma;
1992 struct inode *inode = file_inode(vma->vm_file);
1993 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1996 vm_fault_t ret = VM_FAULT_LOCKED;
1999 * Trinity finds that probing a hole which tmpfs is punching can
2000 * prevent the hole-punch from ever completing: which in turn
2001 * locks writers out with its hold on i_mutex. So refrain from
2002 * faulting pages into the hole while it's being punched. Although
2003 * shmem_undo_range() does remove the additions, it may be unable to
2004 * keep up, as each new page needs its own unmap_mapping_range() call,
2005 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2007 * It does not matter if we sometimes reach this check just before the
2008 * hole-punch begins, so that one fault then races with the punch:
2009 * we just need to make racing faults a rare case.
2011 * The implementation below would be much simpler if we just used a
2012 * standard mutex or completion: but we cannot take i_mutex in fault,
2013 * and bloating every shmem inode for this unlikely case would be sad.
2015 if (unlikely(inode->i_private)) {
2016 struct shmem_falloc *shmem_falloc;
2018 spin_lock(&inode->i_lock);
2019 shmem_falloc = inode->i_private;
2021 shmem_falloc->waitq &&
2022 vmf->pgoff >= shmem_falloc->start &&
2023 vmf->pgoff < shmem_falloc->next) {
2024 wait_queue_head_t *shmem_falloc_waitq;
2025 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
2027 ret = VM_FAULT_NOPAGE;
2028 if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
2029 !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
2030 /* It's polite to up mmap_sem if we can */
2031 up_read(&vma->vm_mm->mmap_sem);
2032 ret = VM_FAULT_RETRY;
2035 shmem_falloc_waitq = shmem_falloc->waitq;
2036 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
2037 TASK_UNINTERRUPTIBLE);
2038 spin_unlock(&inode->i_lock);
2042 * shmem_falloc_waitq points into the shmem_fallocate()
2043 * stack of the hole-punching task: shmem_falloc_waitq
2044 * is usually invalid by the time we reach here, but
2045 * finish_wait() does not dereference it in that case;
2046 * though i_lock needed lest racing with wake_up_all().
2048 spin_lock(&inode->i_lock);
2049 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2050 spin_unlock(&inode->i_lock);
2053 spin_unlock(&inode->i_lock);
2058 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
2059 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
2061 else if (vma->vm_flags & VM_HUGEPAGE)
2064 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
2065 gfp, vma, vmf, &ret);
2067 return vmf_error(err);
2071 unsigned long shmem_get_unmapped_area(struct file *file,
2072 unsigned long uaddr, unsigned long len,
2073 unsigned long pgoff, unsigned long flags)
2075 unsigned long (*get_area)(struct file *,
2076 unsigned long, unsigned long, unsigned long, unsigned long);
2078 unsigned long offset;
2079 unsigned long inflated_len;
2080 unsigned long inflated_addr;
2081 unsigned long inflated_offset;
2083 if (len > TASK_SIZE)
2086 get_area = current->mm->get_unmapped_area;
2087 addr = get_area(file, uaddr, len, pgoff, flags);
2089 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
2091 if (IS_ERR_VALUE(addr))
2093 if (addr & ~PAGE_MASK)
2095 if (addr > TASK_SIZE - len)
2098 if (shmem_huge == SHMEM_HUGE_DENY)
2100 if (len < HPAGE_PMD_SIZE)
2102 if (flags & MAP_FIXED)
2105 * Our priority is to support MAP_SHARED mapped hugely;
2106 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2107 * But if caller specified an address hint, respect that as before.
2112 if (shmem_huge != SHMEM_HUGE_FORCE) {
2113 struct super_block *sb;
2116 VM_BUG_ON(file->f_op != &shmem_file_operations);
2117 sb = file_inode(file)->i_sb;
2120 * Called directly from mm/mmap.c, or drivers/char/mem.c
2121 * for "/dev/zero", to create a shared anonymous object.
2123 if (IS_ERR(shm_mnt))
2125 sb = shm_mnt->mnt_sb;
2127 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2131 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2132 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2134 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2137 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2138 if (inflated_len > TASK_SIZE)
2140 if (inflated_len < len)
2143 inflated_addr = get_area(NULL, 0, inflated_len, 0, flags);
2144 if (IS_ERR_VALUE(inflated_addr))
2146 if (inflated_addr & ~PAGE_MASK)
2149 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2150 inflated_addr += offset - inflated_offset;
2151 if (inflated_offset > offset)
2152 inflated_addr += HPAGE_PMD_SIZE;
2154 if (inflated_addr > TASK_SIZE - len)
2156 return inflated_addr;
2160 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2162 struct inode *inode = file_inode(vma->vm_file);
2163 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2166 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2169 struct inode *inode = file_inode(vma->vm_file);
2172 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2173 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2177 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2179 struct inode *inode = file_inode(file);
2180 struct shmem_inode_info *info = SHMEM_I(inode);
2181 int retval = -ENOMEM;
2183 spin_lock_irq(&info->lock);
2184 if (lock && !(info->flags & VM_LOCKED)) {
2185 if (!user_shm_lock(inode->i_size, user))
2187 info->flags |= VM_LOCKED;
2188 mapping_set_unevictable(file->f_mapping);
2190 if (!lock && (info->flags & VM_LOCKED) && user) {
2191 user_shm_unlock(inode->i_size, user);
2192 info->flags &= ~VM_LOCKED;
2193 mapping_clear_unevictable(file->f_mapping);
2198 spin_unlock_irq(&info->lock);
2202 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2204 struct shmem_inode_info *info = SHMEM_I(file_inode(file));
2206 if (info->seals & F_SEAL_FUTURE_WRITE) {
2208 * New PROT_WRITE and MAP_SHARED mmaps are not allowed when
2209 * "future write" seal active.
2211 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_WRITE))
2215 * Since the F_SEAL_FUTURE_WRITE seals allow for a MAP_SHARED
2216 * read-only mapping, take care to not allow mprotect to revert
2219 vma->vm_flags &= ~(VM_MAYWRITE);
2222 file_accessed(file);
2223 vma->vm_ops = &shmem_vm_ops;
2224 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
2225 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2226 (vma->vm_end & HPAGE_PMD_MASK)) {
2227 khugepaged_enter(vma, vma->vm_flags);
2232 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
2233 umode_t mode, dev_t dev, unsigned long flags)
2235 struct inode *inode;
2236 struct shmem_inode_info *info;
2237 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2239 if (shmem_reserve_inode(sb))
2242 inode = new_inode(sb);
2244 inode->i_ino = get_next_ino();
2245 inode_init_owner(inode, dir, mode);
2246 inode->i_blocks = 0;
2247 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2248 inode->i_generation = prandom_u32();
2249 info = SHMEM_I(inode);
2250 memset(info, 0, (char *)inode - (char *)info);
2251 spin_lock_init(&info->lock);
2252 atomic_set(&info->stop_eviction, 0);
2253 info->seals = F_SEAL_SEAL;
2254 info->flags = flags & VM_NORESERVE;
2255 INIT_LIST_HEAD(&info->shrinklist);
2256 INIT_LIST_HEAD(&info->swaplist);
2257 simple_xattrs_init(&info->xattrs);
2258 cache_no_acl(inode);
2260 switch (mode & S_IFMT) {
2262 inode->i_op = &shmem_special_inode_operations;
2263 init_special_inode(inode, mode, dev);
2266 inode->i_mapping->a_ops = &shmem_aops;
2267 inode->i_op = &shmem_inode_operations;
2268 inode->i_fop = &shmem_file_operations;
2269 mpol_shared_policy_init(&info->policy,
2270 shmem_get_sbmpol(sbinfo));
2274 /* Some things misbehave if size == 0 on a directory */
2275 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2276 inode->i_op = &shmem_dir_inode_operations;
2277 inode->i_fop = &simple_dir_operations;
2281 * Must not load anything in the rbtree,
2282 * mpol_free_shared_policy will not be called.
2284 mpol_shared_policy_init(&info->policy, NULL);
2288 lockdep_annotate_inode_mutex_key(inode);
2290 shmem_free_inode(sb);
2294 bool shmem_mapping(struct address_space *mapping)
2296 return mapping->a_ops == &shmem_aops;
2299 static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2301 struct vm_area_struct *dst_vma,
2302 unsigned long dst_addr,
2303 unsigned long src_addr,
2305 struct page **pagep)
2307 struct inode *inode = file_inode(dst_vma->vm_file);
2308 struct shmem_inode_info *info = SHMEM_I(inode);
2309 struct address_space *mapping = inode->i_mapping;
2310 gfp_t gfp = mapping_gfp_mask(mapping);
2311 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2312 struct mem_cgroup *memcg;
2316 pte_t _dst_pte, *dst_pte;
2318 pgoff_t offset, max_off;
2321 if (!shmem_inode_acct_block(inode, 1))
2325 page = shmem_alloc_page(gfp, info, pgoff);
2327 goto out_unacct_blocks;
2329 if (!zeropage) { /* mcopy_atomic */
2330 page_kaddr = kmap_atomic(page);
2331 ret = copy_from_user(page_kaddr,
2332 (const void __user *)src_addr,
2334 kunmap_atomic(page_kaddr);
2336 /* fallback to copy_from_user outside mmap_sem */
2337 if (unlikely(ret)) {
2339 shmem_inode_unacct_blocks(inode, 1);
2340 /* don't free the page */
2343 } else { /* mfill_zeropage_atomic */
2344 clear_highpage(page);
2351 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2352 __SetPageLocked(page);
2353 __SetPageSwapBacked(page);
2354 __SetPageUptodate(page);
2357 offset = linear_page_index(dst_vma, dst_addr);
2358 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2359 if (unlikely(offset >= max_off))
2362 ret = mem_cgroup_try_charge_delay(page, dst_mm, gfp, &memcg, false);
2366 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
2367 gfp & GFP_RECLAIM_MASK);
2369 goto out_release_uncharge;
2371 mem_cgroup_commit_charge(page, memcg, false, false);
2373 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2374 if (dst_vma->vm_flags & VM_WRITE)
2375 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
2378 * We don't set the pte dirty if the vma has no
2379 * VM_WRITE permission, so mark the page dirty or it
2380 * could be freed from under us. We could do it
2381 * unconditionally before unlock_page(), but doing it
2382 * only if VM_WRITE is not set is faster.
2384 set_page_dirty(page);
2387 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
2390 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2391 if (unlikely(offset >= max_off))
2392 goto out_release_uncharge_unlock;
2395 if (!pte_none(*dst_pte))
2396 goto out_release_uncharge_unlock;
2398 lru_cache_add_anon(page);
2400 spin_lock(&info->lock);
2402 inode->i_blocks += BLOCKS_PER_PAGE;
2403 shmem_recalc_inode(inode);
2404 spin_unlock(&info->lock);
2406 inc_mm_counter(dst_mm, mm_counter_file(page));
2407 page_add_file_rmap(page, false);
2408 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2410 /* No need to invalidate - it was non-present before */
2411 update_mmu_cache(dst_vma, dst_addr, dst_pte);
2412 pte_unmap_unlock(dst_pte, ptl);
2417 out_release_uncharge_unlock:
2418 pte_unmap_unlock(dst_pte, ptl);
2419 ClearPageDirty(page);
2420 delete_from_page_cache(page);
2421 out_release_uncharge:
2422 mem_cgroup_cancel_charge(page, memcg, false);
2427 shmem_inode_unacct_blocks(inode, 1);
2431 int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2433 struct vm_area_struct *dst_vma,
2434 unsigned long dst_addr,
2435 unsigned long src_addr,
2436 struct page **pagep)
2438 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2439 dst_addr, src_addr, false, pagep);
2442 int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2444 struct vm_area_struct *dst_vma,
2445 unsigned long dst_addr)
2447 struct page *page = NULL;
2449 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2450 dst_addr, 0, true, &page);
2454 static const struct inode_operations shmem_symlink_inode_operations;
2455 static const struct inode_operations shmem_short_symlink_operations;
2457 #ifdef CONFIG_TMPFS_XATTR
2458 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2460 #define shmem_initxattrs NULL
2464 shmem_write_begin(struct file *file, struct address_space *mapping,
2465 loff_t pos, unsigned len, unsigned flags,
2466 struct page **pagep, void **fsdata)
2468 struct inode *inode = mapping->host;
2469 struct shmem_inode_info *info = SHMEM_I(inode);
2470 pgoff_t index = pos >> PAGE_SHIFT;
2472 /* i_mutex is held by caller */
2473 if (unlikely(info->seals & (F_SEAL_GROW |
2474 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
2475 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
2477 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2481 return shmem_getpage(inode, index, pagep, SGP_WRITE);
2485 shmem_write_end(struct file *file, struct address_space *mapping,
2486 loff_t pos, unsigned len, unsigned copied,
2487 struct page *page, void *fsdata)
2489 struct inode *inode = mapping->host;
2491 if (pos + copied > inode->i_size)
2492 i_size_write(inode, pos + copied);
2494 if (!PageUptodate(page)) {
2495 struct page *head = compound_head(page);
2496 if (PageTransCompound(page)) {
2499 for (i = 0; i < HPAGE_PMD_NR; i++) {
2500 if (head + i == page)
2502 clear_highpage(head + i);
2503 flush_dcache_page(head + i);
2506 if (copied < PAGE_SIZE) {
2507 unsigned from = pos & (PAGE_SIZE - 1);
2508 zero_user_segments(page, 0, from,
2509 from + copied, PAGE_SIZE);
2511 SetPageUptodate(head);
2513 set_page_dirty(page);
2520 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2522 struct file *file = iocb->ki_filp;
2523 struct inode *inode = file_inode(file);
2524 struct address_space *mapping = inode->i_mapping;
2526 unsigned long offset;
2527 enum sgp_type sgp = SGP_READ;
2530 loff_t *ppos = &iocb->ki_pos;
2533 * Might this read be for a stacking filesystem? Then when reading
2534 * holes of a sparse file, we actually need to allocate those pages,
2535 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2537 if (!iter_is_iovec(to))
2540 index = *ppos >> PAGE_SHIFT;
2541 offset = *ppos & ~PAGE_MASK;
2544 struct page *page = NULL;
2546 unsigned long nr, ret;
2547 loff_t i_size = i_size_read(inode);
2549 end_index = i_size >> PAGE_SHIFT;
2550 if (index > end_index)
2552 if (index == end_index) {
2553 nr = i_size & ~PAGE_MASK;
2558 error = shmem_getpage(inode, index, &page, sgp);
2560 if (error == -EINVAL)
2565 if (sgp == SGP_CACHE)
2566 set_page_dirty(page);
2571 * We must evaluate after, since reads (unlike writes)
2572 * are called without i_mutex protection against truncate
2575 i_size = i_size_read(inode);
2576 end_index = i_size >> PAGE_SHIFT;
2577 if (index == end_index) {
2578 nr = i_size & ~PAGE_MASK;
2589 * If users can be writing to this page using arbitrary
2590 * virtual addresses, take care about potential aliasing
2591 * before reading the page on the kernel side.
2593 if (mapping_writably_mapped(mapping))
2594 flush_dcache_page(page);
2596 * Mark the page accessed if we read the beginning.
2599 mark_page_accessed(page);
2601 page = ZERO_PAGE(0);
2606 * Ok, we have the page, and it's up-to-date, so
2607 * now we can copy it to user space...
2609 ret = copy_page_to_iter(page, offset, nr, to);
2612 index += offset >> PAGE_SHIFT;
2613 offset &= ~PAGE_MASK;
2616 if (!iov_iter_count(to))
2625 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2626 file_accessed(file);
2627 return retval ? retval : error;
2631 * llseek SEEK_DATA or SEEK_HOLE through the page cache.
2633 static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2634 pgoff_t index, pgoff_t end, int whence)
2637 struct pagevec pvec;
2638 pgoff_t indices[PAGEVEC_SIZE];
2642 pagevec_init(&pvec);
2643 pvec.nr = 1; /* start small: we may be there already */
2645 pvec.nr = find_get_entries(mapping, index,
2646 pvec.nr, pvec.pages, indices);
2648 if (whence == SEEK_DATA)
2652 for (i = 0; i < pvec.nr; i++, index++) {
2653 if (index < indices[i]) {
2654 if (whence == SEEK_HOLE) {
2660 page = pvec.pages[i];
2661 if (page && !xa_is_value(page)) {
2662 if (!PageUptodate(page))
2666 (page && whence == SEEK_DATA) ||
2667 (!page && whence == SEEK_HOLE)) {
2672 pagevec_remove_exceptionals(&pvec);
2673 pagevec_release(&pvec);
2674 pvec.nr = PAGEVEC_SIZE;
2680 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2682 struct address_space *mapping = file->f_mapping;
2683 struct inode *inode = mapping->host;
2687 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2688 return generic_file_llseek_size(file, offset, whence,
2689 MAX_LFS_FILESIZE, i_size_read(inode));
2691 /* We're holding i_mutex so we can access i_size directly */
2693 if (offset < 0 || offset >= inode->i_size)
2696 start = offset >> PAGE_SHIFT;
2697 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2698 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
2699 new_offset <<= PAGE_SHIFT;
2700 if (new_offset > offset) {
2701 if (new_offset < inode->i_size)
2702 offset = new_offset;
2703 else if (whence == SEEK_DATA)
2706 offset = inode->i_size;
2711 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2712 inode_unlock(inode);
2716 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2719 struct inode *inode = file_inode(file);
2720 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2721 struct shmem_inode_info *info = SHMEM_I(inode);
2722 struct shmem_falloc shmem_falloc;
2723 pgoff_t start, index, end;
2726 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2731 if (mode & FALLOC_FL_PUNCH_HOLE) {
2732 struct address_space *mapping = file->f_mapping;
2733 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2734 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2735 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2737 /* protected by i_mutex */
2738 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
2743 shmem_falloc.waitq = &shmem_falloc_waitq;
2744 shmem_falloc.start = unmap_start >> PAGE_SHIFT;
2745 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2746 spin_lock(&inode->i_lock);
2747 inode->i_private = &shmem_falloc;
2748 spin_unlock(&inode->i_lock);
2750 if ((u64)unmap_end > (u64)unmap_start)
2751 unmap_mapping_range(mapping, unmap_start,
2752 1 + unmap_end - unmap_start, 0);
2753 shmem_truncate_range(inode, offset, offset + len - 1);
2754 /* No need to unmap again: hole-punching leaves COWed pages */
2756 spin_lock(&inode->i_lock);
2757 inode->i_private = NULL;
2758 wake_up_all(&shmem_falloc_waitq);
2759 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2760 spin_unlock(&inode->i_lock);
2765 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2766 error = inode_newsize_ok(inode, offset + len);
2770 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2775 start = offset >> PAGE_SHIFT;
2776 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2777 /* Try to avoid a swapstorm if len is impossible to satisfy */
2778 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2783 shmem_falloc.waitq = NULL;
2784 shmem_falloc.start = start;
2785 shmem_falloc.next = start;
2786 shmem_falloc.nr_falloced = 0;
2787 shmem_falloc.nr_unswapped = 0;
2788 spin_lock(&inode->i_lock);
2789 inode->i_private = &shmem_falloc;
2790 spin_unlock(&inode->i_lock);
2792 for (index = start; index < end; index++) {
2796 * Good, the fallocate(2) manpage permits EINTR: we may have
2797 * been interrupted because we are using up too much memory.
2799 if (signal_pending(current))
2801 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2804 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2806 /* Remove the !PageUptodate pages we added */
2807 if (index > start) {
2808 shmem_undo_range(inode,
2809 (loff_t)start << PAGE_SHIFT,
2810 ((loff_t)index << PAGE_SHIFT) - 1, true);
2816 * Inform shmem_writepage() how far we have reached.
2817 * No need for lock or barrier: we have the page lock.
2819 shmem_falloc.next++;
2820 if (!PageUptodate(page))
2821 shmem_falloc.nr_falloced++;
2824 * If !PageUptodate, leave it that way so that freeable pages
2825 * can be recognized if we need to rollback on error later.
2826 * But set_page_dirty so that memory pressure will swap rather
2827 * than free the pages we are allocating (and SGP_CACHE pages
2828 * might still be clean: we now need to mark those dirty too).
2830 set_page_dirty(page);
2836 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2837 i_size_write(inode, offset + len);
2838 inode->i_ctime = current_time(inode);
2840 spin_lock(&inode->i_lock);
2841 inode->i_private = NULL;
2842 spin_unlock(&inode->i_lock);
2844 inode_unlock(inode);
2848 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2850 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2852 buf->f_type = TMPFS_MAGIC;
2853 buf->f_bsize = PAGE_SIZE;
2854 buf->f_namelen = NAME_MAX;
2855 if (sbinfo->max_blocks) {
2856 buf->f_blocks = sbinfo->max_blocks;
2858 buf->f_bfree = sbinfo->max_blocks -
2859 percpu_counter_sum(&sbinfo->used_blocks);
2861 if (sbinfo->max_inodes) {
2862 buf->f_files = sbinfo->max_inodes;
2863 buf->f_ffree = sbinfo->free_inodes;
2865 /* else leave those fields 0 like simple_statfs */
2870 * File creation. Allocate an inode, and we're done..
2873 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2875 struct inode *inode;
2876 int error = -ENOSPC;
2878 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2880 error = simple_acl_create(dir, inode);
2883 error = security_inode_init_security(inode, dir,
2885 shmem_initxattrs, NULL);
2886 if (error && error != -EOPNOTSUPP)
2890 dir->i_size += BOGO_DIRENT_SIZE;
2891 dir->i_ctime = dir->i_mtime = current_time(dir);
2892 d_instantiate(dentry, inode);
2893 dget(dentry); /* Extra count - pin the dentry in core */
2902 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2904 struct inode *inode;
2905 int error = -ENOSPC;
2907 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2909 error = security_inode_init_security(inode, dir,
2911 shmem_initxattrs, NULL);
2912 if (error && error != -EOPNOTSUPP)
2914 error = simple_acl_create(dir, inode);
2917 d_tmpfile(dentry, inode);
2925 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2929 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
2935 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2938 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
2944 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2946 struct inode *inode = d_inode(old_dentry);
2950 * No ordinary (disk based) filesystem counts links as inodes;
2951 * but each new link needs a new dentry, pinning lowmem, and
2952 * tmpfs dentries cannot be pruned until they are unlinked.
2953 * But if an O_TMPFILE file is linked into the tmpfs, the
2954 * first link must skip that, to get the accounting right.
2956 if (inode->i_nlink) {
2957 ret = shmem_reserve_inode(inode->i_sb);
2962 dir->i_size += BOGO_DIRENT_SIZE;
2963 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2965 ihold(inode); /* New dentry reference */
2966 dget(dentry); /* Extra pinning count for the created dentry */
2967 d_instantiate(dentry, inode);
2972 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
2974 struct inode *inode = d_inode(dentry);
2976 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
2977 shmem_free_inode(inode->i_sb);
2979 dir->i_size -= BOGO_DIRENT_SIZE;
2980 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2982 dput(dentry); /* Undo the count from "create" - this does all the work */
2986 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
2988 if (!simple_empty(dentry))
2991 drop_nlink(d_inode(dentry));
2993 return shmem_unlink(dir, dentry);
2996 static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
2998 bool old_is_dir = d_is_dir(old_dentry);
2999 bool new_is_dir = d_is_dir(new_dentry);
3001 if (old_dir != new_dir && old_is_dir != new_is_dir) {
3003 drop_nlink(old_dir);
3006 drop_nlink(new_dir);
3010 old_dir->i_ctime = old_dir->i_mtime =
3011 new_dir->i_ctime = new_dir->i_mtime =
3012 d_inode(old_dentry)->i_ctime =
3013 d_inode(new_dentry)->i_ctime = current_time(old_dir);
3018 static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
3020 struct dentry *whiteout;
3023 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
3027 error = shmem_mknod(old_dir, whiteout,
3028 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
3034 * Cheat and hash the whiteout while the old dentry is still in
3035 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3037 * d_lookup() will consistently find one of them at this point,
3038 * not sure which one, but that isn't even important.
3045 * The VFS layer already does all the dentry stuff for rename,
3046 * we just have to decrement the usage count for the target if
3047 * it exists so that the VFS layer correctly free's it when it
3050 static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
3052 struct inode *inode = d_inode(old_dentry);
3053 int they_are_dirs = S_ISDIR(inode->i_mode);
3055 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3058 if (flags & RENAME_EXCHANGE)
3059 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
3061 if (!simple_empty(new_dentry))
3064 if (flags & RENAME_WHITEOUT) {
3067 error = shmem_whiteout(old_dir, old_dentry);
3072 if (d_really_is_positive(new_dentry)) {
3073 (void) shmem_unlink(new_dir, new_dentry);
3074 if (they_are_dirs) {
3075 drop_nlink(d_inode(new_dentry));
3076 drop_nlink(old_dir);
3078 } else if (they_are_dirs) {
3079 drop_nlink(old_dir);
3083 old_dir->i_size -= BOGO_DIRENT_SIZE;
3084 new_dir->i_size += BOGO_DIRENT_SIZE;
3085 old_dir->i_ctime = old_dir->i_mtime =
3086 new_dir->i_ctime = new_dir->i_mtime =
3087 inode->i_ctime = current_time(old_dir);
3091 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
3095 struct inode *inode;
3098 len = strlen(symname) + 1;
3099 if (len > PAGE_SIZE)
3100 return -ENAMETOOLONG;
3102 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
3107 error = security_inode_init_security(inode, dir, &dentry->d_name,
3108 shmem_initxattrs, NULL);
3110 if (error != -EOPNOTSUPP) {
3117 inode->i_size = len-1;
3118 if (len <= SHORT_SYMLINK_LEN) {
3119 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3120 if (!inode->i_link) {
3124 inode->i_op = &shmem_short_symlink_operations;
3126 inode_nohighmem(inode);
3127 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
3132 inode->i_mapping->a_ops = &shmem_aops;
3133 inode->i_op = &shmem_symlink_inode_operations;
3134 memcpy(page_address(page), symname, len);
3135 SetPageUptodate(page);
3136 set_page_dirty(page);
3140 dir->i_size += BOGO_DIRENT_SIZE;
3141 dir->i_ctime = dir->i_mtime = current_time(dir);
3142 d_instantiate(dentry, inode);
3147 static void shmem_put_link(void *arg)
3149 mark_page_accessed(arg);
3153 static const char *shmem_get_link(struct dentry *dentry,
3154 struct inode *inode,
3155 struct delayed_call *done)
3157 struct page *page = NULL;
3160 page = find_get_page(inode->i_mapping, 0);
3162 return ERR_PTR(-ECHILD);
3163 if (!PageUptodate(page)) {
3165 return ERR_PTR(-ECHILD);
3168 error = shmem_getpage(inode, 0, &page, SGP_READ);
3170 return ERR_PTR(error);
3173 set_delayed_call(done, shmem_put_link, page);
3174 return page_address(page);
3177 #ifdef CONFIG_TMPFS_XATTR
3179 * Superblocks without xattr inode operations may get some security.* xattr
3180 * support from the LSM "for free". As soon as we have any other xattrs
3181 * like ACLs, we also need to implement the security.* handlers at
3182 * filesystem level, though.
3186 * Callback for security_inode_init_security() for acquiring xattrs.
3188 static int shmem_initxattrs(struct inode *inode,
3189 const struct xattr *xattr_array,
3192 struct shmem_inode_info *info = SHMEM_I(inode);
3193 const struct xattr *xattr;
3194 struct simple_xattr *new_xattr;
3197 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3198 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3202 len = strlen(xattr->name) + 1;
3203 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3205 if (!new_xattr->name) {
3210 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3211 XATTR_SECURITY_PREFIX_LEN);
3212 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3215 simple_xattr_list_add(&info->xattrs, new_xattr);
3221 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3222 struct dentry *unused, struct inode *inode,
3223 const char *name, void *buffer, size_t size)
3225 struct shmem_inode_info *info = SHMEM_I(inode);
3227 name = xattr_full_name(handler, name);
3228 return simple_xattr_get(&info->xattrs, name, buffer, size);
3231 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3232 struct dentry *unused, struct inode *inode,
3233 const char *name, const void *value,
3234 size_t size, int flags)
3236 struct shmem_inode_info *info = SHMEM_I(inode);
3238 name = xattr_full_name(handler, name);
3239 return simple_xattr_set(&info->xattrs, name, value, size, flags);
3242 static const struct xattr_handler shmem_security_xattr_handler = {
3243 .prefix = XATTR_SECURITY_PREFIX,
3244 .get = shmem_xattr_handler_get,
3245 .set = shmem_xattr_handler_set,
3248 static const struct xattr_handler shmem_trusted_xattr_handler = {
3249 .prefix = XATTR_TRUSTED_PREFIX,
3250 .get = shmem_xattr_handler_get,
3251 .set = shmem_xattr_handler_set,
3254 static const struct xattr_handler *shmem_xattr_handlers[] = {
3255 #ifdef CONFIG_TMPFS_POSIX_ACL
3256 &posix_acl_access_xattr_handler,
3257 &posix_acl_default_xattr_handler,
3259 &shmem_security_xattr_handler,
3260 &shmem_trusted_xattr_handler,
3264 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3266 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3267 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3269 #endif /* CONFIG_TMPFS_XATTR */
3271 static const struct inode_operations shmem_short_symlink_operations = {
3272 .get_link = simple_get_link,
3273 #ifdef CONFIG_TMPFS_XATTR
3274 .listxattr = shmem_listxattr,
3278 static const struct inode_operations shmem_symlink_inode_operations = {
3279 .get_link = shmem_get_link,
3280 #ifdef CONFIG_TMPFS_XATTR
3281 .listxattr = shmem_listxattr,
3285 static struct dentry *shmem_get_parent(struct dentry *child)
3287 return ERR_PTR(-ESTALE);
3290 static int shmem_match(struct inode *ino, void *vfh)
3294 inum = (inum << 32) | fh[1];
3295 return ino->i_ino == inum && fh[0] == ino->i_generation;
3298 /* Find any alias of inode, but prefer a hashed alias */
3299 static struct dentry *shmem_find_alias(struct inode *inode)
3301 struct dentry *alias = d_find_alias(inode);
3303 return alias ?: d_find_any_alias(inode);
3307 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3308 struct fid *fid, int fh_len, int fh_type)
3310 struct inode *inode;
3311 struct dentry *dentry = NULL;
3318 inum = (inum << 32) | fid->raw[1];
3320 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3321 shmem_match, fid->raw);
3323 dentry = shmem_find_alias(inode);
3330 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3331 struct inode *parent)
3335 return FILEID_INVALID;
3338 if (inode_unhashed(inode)) {
3339 /* Unfortunately insert_inode_hash is not idempotent,
3340 * so as we hash inodes here rather than at creation
3341 * time, we need a lock to ensure we only try
3344 static DEFINE_SPINLOCK(lock);
3346 if (inode_unhashed(inode))
3347 __insert_inode_hash(inode,
3348 inode->i_ino + inode->i_generation);
3352 fh[0] = inode->i_generation;
3353 fh[1] = inode->i_ino;
3354 fh[2] = ((__u64)inode->i_ino) >> 32;
3360 static const struct export_operations shmem_export_ops = {
3361 .get_parent = shmem_get_parent,
3362 .encode_fh = shmem_encode_fh,
3363 .fh_to_dentry = shmem_fh_to_dentry,
3366 static int shmem_parse_options(char *options, struct shmem_options *ctx)
3368 char *this_char, *value, *rest;
3369 struct mempolicy *mpol = NULL;
3373 while (options != NULL) {
3374 this_char = options;
3377 * NUL-terminate this option: unfortunately,
3378 * mount options form a comma-separated list,
3379 * but mpol's nodelist may also contain commas.
3381 options = strchr(options, ',');
3382 if (options == NULL)
3385 if (!isdigit(*options)) {
3392 if ((value = strchr(this_char,'=')) != NULL) {
3395 pr_err("tmpfs: No value for mount option '%s'\n",
3400 if (!strcmp(this_char,"size")) {
3401 unsigned long long size;
3402 size = memparse(value,&rest);
3404 size <<= PAGE_SHIFT;
3405 size *= totalram_pages();
3411 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
3412 ctx->seen |= SHMEM_SEEN_BLOCKS;
3413 } else if (!strcmp(this_char,"nr_blocks")) {
3414 ctx->blocks = memparse(value, &rest);
3417 ctx->seen |= SHMEM_SEEN_BLOCKS;
3418 } else if (!strcmp(this_char,"nr_inodes")) {
3419 ctx->inodes = memparse(value, &rest);
3422 ctx->seen |= SHMEM_SEEN_INODES;
3423 } else if (!strcmp(this_char,"mode")) {
3424 ctx->mode = simple_strtoul(value, &rest, 8) & 07777;
3427 } else if (!strcmp(this_char,"uid")) {
3428 uid = simple_strtoul(value, &rest, 0);
3431 ctx->uid = make_kuid(current_user_ns(), uid);
3432 if (!uid_valid(ctx->uid))
3434 } else if (!strcmp(this_char,"gid")) {
3435 gid = simple_strtoul(value, &rest, 0);
3438 ctx->gid = make_kgid(current_user_ns(), gid);
3439 if (!gid_valid(ctx->gid))
3441 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3442 } else if (!strcmp(this_char, "huge")) {
3444 huge = shmem_parse_huge(value);
3447 if (!has_transparent_hugepage() &&
3448 huge != SHMEM_HUGE_NEVER)
3451 ctx->seen |= SHMEM_SEEN_HUGE;
3454 } else if (!strcmp(this_char,"mpol")) {
3457 if (mpol_parse_str(value, &mpol))
3461 pr_err("tmpfs: Bad mount option %s\n", this_char);
3469 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3477 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
3479 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3480 struct shmem_options ctx = {.seen = 0};
3481 unsigned long inodes;
3482 int error = -EINVAL;
3484 if (shmem_parse_options(data, &ctx))
3487 spin_lock(&sbinfo->stat_lock);
3488 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3490 * Those tests disallow limited->unlimited while any are in use;
3491 * but we must separately disallow unlimited->limited, because
3492 * in that case we have no record of how much is already in use.
3494 if ((ctx.seen & SHMEM_SEEN_BLOCKS) && ctx.blocks) {
3495 if (!sbinfo->max_blocks)
3497 if (percpu_counter_compare(&sbinfo->used_blocks,
3501 if ((ctx.seen & SHMEM_SEEN_INODES) && ctx.inodes) {
3502 if (!sbinfo->max_inodes)
3504 if (ctx.inodes < inodes)
3509 if (ctx.seen & SHMEM_SEEN_HUGE)
3510 sbinfo->huge = ctx.huge;
3511 if (ctx.seen & SHMEM_SEEN_BLOCKS)
3512 sbinfo->max_blocks = ctx.blocks;
3513 if (ctx.seen & SHMEM_SEEN_INODES) {
3514 sbinfo->max_inodes = ctx.inodes;
3515 sbinfo->free_inodes = ctx.inodes - inodes;
3519 * Preserve previous mempolicy unless mpol remount option was specified.
3522 mpol_put(sbinfo->mpol);
3523 sbinfo->mpol = ctx.mpol; /* transfers initial ref */
3526 spin_unlock(&sbinfo->stat_lock);
3530 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3532 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3534 if (sbinfo->max_blocks != shmem_default_max_blocks())
3535 seq_printf(seq, ",size=%luk",
3536 sbinfo->max_blocks << (PAGE_SHIFT - 10));
3537 if (sbinfo->max_inodes != shmem_default_max_inodes())
3538 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3539 if (sbinfo->mode != (0777 | S_ISVTX))
3540 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3541 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3542 seq_printf(seq, ",uid=%u",
3543 from_kuid_munged(&init_user_ns, sbinfo->uid));
3544 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3545 seq_printf(seq, ",gid=%u",
3546 from_kgid_munged(&init_user_ns, sbinfo->gid));
3547 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3548 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3550 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3552 shmem_show_mpol(seq, sbinfo->mpol);
3556 #endif /* CONFIG_TMPFS */
3558 static void shmem_put_super(struct super_block *sb)
3560 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3562 percpu_counter_destroy(&sbinfo->used_blocks);
3563 mpol_put(sbinfo->mpol);
3565 sb->s_fs_info = NULL;
3568 static int shmem_fill_super(struct super_block *sb, void *data, int silent)
3570 struct inode *inode;
3571 struct shmem_sb_info *sbinfo;
3572 struct shmem_options ctx = {.mode = 0777 | S_ISVTX,
3573 .uid = current_fsuid(),
3574 .gid = current_fsgid()};
3577 /* Round up to L1_CACHE_BYTES to resist false sharing */
3578 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3579 L1_CACHE_BYTES), GFP_KERNEL);
3583 sb->s_fs_info = sbinfo;
3587 * Per default we only allow half of the physical ram per
3588 * tmpfs instance, limiting inodes to one per page of lowmem;
3589 * but the internal instance is left unlimited.
3591 if (!(sb->s_flags & SB_KERNMOUNT)) {
3592 ctx.blocks = shmem_default_max_blocks();
3593 ctx.inodes = shmem_default_max_inodes();
3594 if (shmem_parse_options(data, &ctx)) {
3599 sb->s_flags |= SB_NOUSER;
3601 sb->s_export_op = &shmem_export_ops;
3602 sb->s_flags |= SB_NOSEC;
3604 sb->s_flags |= SB_NOUSER;
3606 sbinfo->max_blocks = ctx.blocks;
3607 sbinfo->free_inodes = sbinfo->max_inodes = ctx.inodes;
3608 sbinfo->uid = ctx.uid;
3609 sbinfo->gid = ctx.gid;
3610 sbinfo->mode = ctx.mode;
3611 sbinfo->huge = ctx.huge;
3612 sbinfo->mpol = ctx.mpol;
3614 spin_lock_init(&sbinfo->stat_lock);
3615 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3617 spin_lock_init(&sbinfo->shrinklist_lock);
3618 INIT_LIST_HEAD(&sbinfo->shrinklist);
3620 sb->s_maxbytes = MAX_LFS_FILESIZE;
3621 sb->s_blocksize = PAGE_SIZE;
3622 sb->s_blocksize_bits = PAGE_SHIFT;
3623 sb->s_magic = TMPFS_MAGIC;
3624 sb->s_op = &shmem_ops;
3625 sb->s_time_gran = 1;
3626 #ifdef CONFIG_TMPFS_XATTR
3627 sb->s_xattr = shmem_xattr_handlers;
3629 #ifdef CONFIG_TMPFS_POSIX_ACL
3630 sb->s_flags |= SB_POSIXACL;
3632 uuid_gen(&sb->s_uuid);
3634 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3637 inode->i_uid = sbinfo->uid;
3638 inode->i_gid = sbinfo->gid;
3639 sb->s_root = d_make_root(inode);
3645 shmem_put_super(sb);
3649 static struct kmem_cache *shmem_inode_cachep;
3651 static struct inode *shmem_alloc_inode(struct super_block *sb)
3653 struct shmem_inode_info *info;
3654 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3657 return &info->vfs_inode;
3660 static void shmem_free_in_core_inode(struct inode *inode)
3662 if (S_ISLNK(inode->i_mode))
3663 kfree(inode->i_link);
3664 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3667 static void shmem_destroy_inode(struct inode *inode)
3669 if (S_ISREG(inode->i_mode))
3670 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3673 static void shmem_init_inode(void *foo)
3675 struct shmem_inode_info *info = foo;
3676 inode_init_once(&info->vfs_inode);
3679 static void shmem_init_inodecache(void)
3681 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3682 sizeof(struct shmem_inode_info),
3683 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3686 static void shmem_destroy_inodecache(void)
3688 kmem_cache_destroy(shmem_inode_cachep);
3691 static const struct address_space_operations shmem_aops = {
3692 .writepage = shmem_writepage,
3693 .set_page_dirty = __set_page_dirty_no_writeback,
3695 .write_begin = shmem_write_begin,
3696 .write_end = shmem_write_end,
3698 #ifdef CONFIG_MIGRATION
3699 .migratepage = migrate_page,
3701 .error_remove_page = generic_error_remove_page,
3704 static const struct file_operations shmem_file_operations = {
3706 .get_unmapped_area = shmem_get_unmapped_area,
3708 .llseek = shmem_file_llseek,
3709 .read_iter = shmem_file_read_iter,
3710 .write_iter = generic_file_write_iter,
3711 .fsync = noop_fsync,
3712 .splice_read = generic_file_splice_read,
3713 .splice_write = iter_file_splice_write,
3714 .fallocate = shmem_fallocate,
3718 static const struct inode_operations shmem_inode_operations = {
3719 .getattr = shmem_getattr,
3720 .setattr = shmem_setattr,
3721 #ifdef CONFIG_TMPFS_XATTR
3722 .listxattr = shmem_listxattr,
3723 .set_acl = simple_set_acl,
3727 static const struct inode_operations shmem_dir_inode_operations = {
3729 .create = shmem_create,
3730 .lookup = simple_lookup,
3732 .unlink = shmem_unlink,
3733 .symlink = shmem_symlink,
3734 .mkdir = shmem_mkdir,
3735 .rmdir = shmem_rmdir,
3736 .mknod = shmem_mknod,
3737 .rename = shmem_rename2,
3738 .tmpfile = shmem_tmpfile,
3740 #ifdef CONFIG_TMPFS_XATTR
3741 .listxattr = shmem_listxattr,
3743 #ifdef CONFIG_TMPFS_POSIX_ACL
3744 .setattr = shmem_setattr,
3745 .set_acl = simple_set_acl,
3749 static const struct inode_operations shmem_special_inode_operations = {
3750 #ifdef CONFIG_TMPFS_XATTR
3751 .listxattr = shmem_listxattr,
3753 #ifdef CONFIG_TMPFS_POSIX_ACL
3754 .setattr = shmem_setattr,
3755 .set_acl = simple_set_acl,
3759 static const struct super_operations shmem_ops = {
3760 .alloc_inode = shmem_alloc_inode,
3761 .free_inode = shmem_free_in_core_inode,
3762 .destroy_inode = shmem_destroy_inode,
3764 .statfs = shmem_statfs,
3765 .remount_fs = shmem_remount_fs,
3766 .show_options = shmem_show_options,
3768 .evict_inode = shmem_evict_inode,
3769 .drop_inode = generic_delete_inode,
3770 .put_super = shmem_put_super,
3771 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3772 .nr_cached_objects = shmem_unused_huge_count,
3773 .free_cached_objects = shmem_unused_huge_scan,
3777 static const struct vm_operations_struct shmem_vm_ops = {
3778 .fault = shmem_fault,
3779 .map_pages = filemap_map_pages,
3781 .set_policy = shmem_set_policy,
3782 .get_policy = shmem_get_policy,
3786 struct dentry *shmem_mount(struct file_system_type *fs_type,
3787 int flags, const char *dev_name, void *data)
3789 return mount_nodev(fs_type, flags, data, shmem_fill_super);
3792 static struct file_system_type shmem_fs_type = {
3793 .owner = THIS_MODULE,
3795 .mount = shmem_mount,
3796 .kill_sb = kill_litter_super,
3797 .fs_flags = FS_USERNS_MOUNT,
3800 int __init shmem_init(void)
3804 shmem_init_inodecache();
3806 error = register_filesystem(&shmem_fs_type);
3808 pr_err("Could not register tmpfs\n");
3812 shm_mnt = kern_mount(&shmem_fs_type);
3813 if (IS_ERR(shm_mnt)) {
3814 error = PTR_ERR(shm_mnt);
3815 pr_err("Could not kern_mount tmpfs\n");
3819 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3820 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
3821 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3823 shmem_huge = 0; /* just in case it was patched */
3828 unregister_filesystem(&shmem_fs_type);
3830 shmem_destroy_inodecache();
3831 shm_mnt = ERR_PTR(error);
3835 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
3836 static ssize_t shmem_enabled_show(struct kobject *kobj,
3837 struct kobj_attribute *attr, char *buf)
3841 SHMEM_HUGE_WITHIN_SIZE,
3849 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
3850 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
3852 count += sprintf(buf + count, fmt,
3853 shmem_format_huge(values[i]));
3855 buf[count - 1] = '\n';
3859 static ssize_t shmem_enabled_store(struct kobject *kobj,
3860 struct kobj_attribute *attr, const char *buf, size_t count)
3865 if (count + 1 > sizeof(tmp))
3867 memcpy(tmp, buf, count);
3869 if (count && tmp[count - 1] == '\n')
3870 tmp[count - 1] = '\0';
3872 huge = shmem_parse_huge(tmp);
3873 if (huge == -EINVAL)
3875 if (!has_transparent_hugepage() &&
3876 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
3880 if (shmem_huge > SHMEM_HUGE_DENY)
3881 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3885 struct kobj_attribute shmem_enabled_attr =
3886 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
3887 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
3889 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3890 bool shmem_huge_enabled(struct vm_area_struct *vma)
3892 struct inode *inode = file_inode(vma->vm_file);
3893 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3897 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
3898 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
3900 if (shmem_huge == SHMEM_HUGE_FORCE)
3902 if (shmem_huge == SHMEM_HUGE_DENY)
3904 switch (sbinfo->huge) {
3905 case SHMEM_HUGE_NEVER:
3907 case SHMEM_HUGE_ALWAYS:
3909 case SHMEM_HUGE_WITHIN_SIZE:
3910 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
3911 i_size = round_up(i_size_read(inode), PAGE_SIZE);
3912 if (i_size >= HPAGE_PMD_SIZE &&
3913 i_size >> PAGE_SHIFT >= off)
3916 case SHMEM_HUGE_ADVISE:
3917 /* TODO: implement fadvise() hints */
3918 return (vma->vm_flags & VM_HUGEPAGE);
3924 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
3926 #else /* !CONFIG_SHMEM */
3929 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3931 * This is intended for small system where the benefits of the full
3932 * shmem code (swap-backed and resource-limited) are outweighed by
3933 * their complexity. On systems without swap this code should be
3934 * effectively equivalent, but much lighter weight.
3937 static struct file_system_type shmem_fs_type = {
3939 .mount = ramfs_mount,
3940 .kill_sb = kill_litter_super,
3941 .fs_flags = FS_USERNS_MOUNT,
3944 int __init shmem_init(void)
3946 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3948 shm_mnt = kern_mount(&shmem_fs_type);
3949 BUG_ON(IS_ERR(shm_mnt));
3954 int shmem_unuse(unsigned int type, bool frontswap,
3955 unsigned long *fs_pages_to_unuse)
3960 int shmem_lock(struct file *file, int lock, struct user_struct *user)
3965 void shmem_unlock_mapping(struct address_space *mapping)
3970 unsigned long shmem_get_unmapped_area(struct file *file,
3971 unsigned long addr, unsigned long len,
3972 unsigned long pgoff, unsigned long flags)
3974 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
3978 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
3980 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
3982 EXPORT_SYMBOL_GPL(shmem_truncate_range);
3984 #define shmem_vm_ops generic_file_vm_ops
3985 #define shmem_file_operations ramfs_file_operations
3986 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
3987 #define shmem_acct_size(flags, size) 0
3988 #define shmem_unacct_size(flags, size) do {} while (0)
3990 #endif /* CONFIG_SHMEM */
3994 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
3995 unsigned long flags, unsigned int i_flags)
3997 struct inode *inode;
4001 return ERR_CAST(mnt);
4003 if (size < 0 || size > MAX_LFS_FILESIZE)
4004 return ERR_PTR(-EINVAL);
4006 if (shmem_acct_size(flags, size))
4007 return ERR_PTR(-ENOMEM);
4009 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
4011 if (unlikely(!inode)) {
4012 shmem_unacct_size(flags, size);
4013 return ERR_PTR(-ENOSPC);
4015 inode->i_flags |= i_flags;
4016 inode->i_size = size;
4017 clear_nlink(inode); /* It is unlinked */
4018 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
4020 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
4021 &shmem_file_operations);
4028 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4029 * kernel internal. There will be NO LSM permission checks against the
4030 * underlying inode. So users of this interface must do LSM checks at a
4031 * higher layer. The users are the big_key and shm implementations. LSM
4032 * checks are provided at the key or shm level rather than the inode.
4033 * @name: name for dentry (to be seen in /proc/<pid>/maps
4034 * @size: size to be set for the file
4035 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4037 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4039 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
4043 * shmem_file_setup - get an unlinked file living in tmpfs
4044 * @name: name for dentry (to be seen in /proc/<pid>/maps
4045 * @size: size to be set for the file
4046 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4048 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4050 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
4052 EXPORT_SYMBOL_GPL(shmem_file_setup);
4055 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4056 * @mnt: the tmpfs mount where the file will be created
4057 * @name: name for dentry (to be seen in /proc/<pid>/maps
4058 * @size: size to be set for the file
4059 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4061 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4062 loff_t size, unsigned long flags)
4064 return __shmem_file_setup(mnt, name, size, flags, 0);
4066 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4069 * shmem_zero_setup - setup a shared anonymous mapping
4070 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
4072 int shmem_zero_setup(struct vm_area_struct *vma)
4075 loff_t size = vma->vm_end - vma->vm_start;
4078 * Cloning a new file under mmap_sem leads to a lock ordering conflict
4079 * between XFS directory reading and selinux: since this file is only
4080 * accessible to the user through its mapping, use S_PRIVATE flag to
4081 * bypass file security, in the same way as shmem_kernel_file_setup().
4083 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
4085 return PTR_ERR(file);
4089 vma->vm_file = file;
4090 vma->vm_ops = &shmem_vm_ops;
4092 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
4093 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4094 (vma->vm_end & HPAGE_PMD_MASK)) {
4095 khugepaged_enter(vma, vma->vm_flags);
4102 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4103 * @mapping: the page's address_space
4104 * @index: the page index
4105 * @gfp: the page allocator flags to use if allocating
4107 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4108 * with any new page allocations done using the specified allocation flags.
4109 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4110 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4111 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4113 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4114 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4116 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4117 pgoff_t index, gfp_t gfp)
4120 struct inode *inode = mapping->host;
4124 BUG_ON(mapping->a_ops != &shmem_aops);
4125 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4126 gfp, NULL, NULL, NULL);
4128 page = ERR_PTR(error);
4134 * The tiny !SHMEM case uses ramfs without swap
4136 return read_cache_page_gfp(mapping, index, gfp);
4139 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);