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>
40 #include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
42 static struct vfsmount *shm_mnt;
46 * This virtual memory filesystem is heavily based on the ramfs. It
47 * extends ramfs by the ability to use swap and honor resource limits
48 * which makes it a completely usable filesystem.
51 #include <linux/xattr.h>
52 #include <linux/exportfs.h>
53 #include <linux/posix_acl.h>
54 #include <linux/posix_acl_xattr.h>
55 #include <linux/mman.h>
56 #include <linux/string.h>
57 #include <linux/slab.h>
58 #include <linux/backing-dev.h>
59 #include <linux/shmem_fs.h>
60 #include <linux/writeback.h>
61 #include <linux/blkdev.h>
62 #include <linux/pagevec.h>
63 #include <linux/percpu_counter.h>
64 #include <linux/falloc.h>
65 #include <linux/splice.h>
66 #include <linux/security.h>
67 #include <linux/swapops.h>
68 #include <linux/mempolicy.h>
69 #include <linux/namei.h>
70 #include <linux/ctype.h>
71 #include <linux/migrate.h>
72 #include <linux/highmem.h>
73 #include <linux/seq_file.h>
74 #include <linux/magic.h>
75 #include <linux/syscalls.h>
76 #include <linux/fcntl.h>
77 #include <uapi/linux/memfd.h>
78 #include <linux/userfaultfd_k.h>
79 #include <linux/rmap.h>
80 #include <linux/uuid.h>
82 #include <linux/uaccess.h>
83 #include <asm/pgtable.h>
87 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
88 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
90 /* Pretend that each entry is of this size in directory's i_size */
91 #define BOGO_DIRENT_SIZE 20
93 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
94 #define SHORT_SYMLINK_LEN 128
97 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
98 * inode->i_private (with i_mutex making sure that it has only one user at
99 * a time): we would prefer not to enlarge the shmem inode just for that.
101 struct shmem_falloc {
102 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
103 pgoff_t start; /* start of range currently being fallocated */
104 pgoff_t next; /* the next page offset to be fallocated */
105 pgoff_t nr_falloced; /* how many new pages have been fallocated */
106 pgoff_t nr_unswapped; /* how often writepage refused to swap out */
110 static unsigned long shmem_default_max_blocks(void)
112 return totalram_pages / 2;
115 static unsigned long shmem_default_max_inodes(void)
117 return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
121 static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
122 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
123 struct shmem_inode_info *info, pgoff_t index);
124 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
125 struct page **pagep, enum sgp_type sgp,
126 gfp_t gfp, struct vm_area_struct *vma,
127 struct vm_fault *vmf, vm_fault_t *fault_type);
129 int shmem_getpage(struct inode *inode, pgoff_t index,
130 struct page **pagep, enum sgp_type sgp)
132 return shmem_getpage_gfp(inode, index, pagep, sgp,
133 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
136 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
138 return sb->s_fs_info;
142 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
143 * for shared memory and for shared anonymous (/dev/zero) mappings
144 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
145 * consistent with the pre-accounting of private mappings ...
147 static inline int shmem_acct_size(unsigned long flags, loff_t size)
149 return (flags & VM_NORESERVE) ?
150 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
153 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
155 if (!(flags & VM_NORESERVE))
156 vm_unacct_memory(VM_ACCT(size));
159 static inline int shmem_reacct_size(unsigned long flags,
160 loff_t oldsize, loff_t newsize)
162 if (!(flags & VM_NORESERVE)) {
163 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
164 return security_vm_enough_memory_mm(current->mm,
165 VM_ACCT(newsize) - VM_ACCT(oldsize));
166 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
167 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
173 * ... whereas tmpfs objects are accounted incrementally as
174 * pages are allocated, in order to allow large sparse files.
175 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
176 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
178 static inline int shmem_acct_block(unsigned long flags, long pages)
180 if (!(flags & VM_NORESERVE))
183 return security_vm_enough_memory_mm(current->mm,
184 pages * VM_ACCT(PAGE_SIZE));
187 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
189 if (flags & VM_NORESERVE)
190 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
193 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
195 struct shmem_inode_info *info = SHMEM_I(inode);
196 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
198 if (shmem_acct_block(info->flags, pages))
201 if (sbinfo->max_blocks) {
202 if (percpu_counter_compare(&sbinfo->used_blocks,
203 sbinfo->max_blocks - pages) > 0)
205 percpu_counter_add(&sbinfo->used_blocks, pages);
211 shmem_unacct_blocks(info->flags, pages);
215 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
217 struct shmem_inode_info *info = SHMEM_I(inode);
218 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
220 if (sbinfo->max_blocks)
221 percpu_counter_sub(&sbinfo->used_blocks, pages);
222 shmem_unacct_blocks(info->flags, pages);
225 static const struct super_operations shmem_ops;
226 static const struct address_space_operations shmem_aops;
227 static const struct file_operations shmem_file_operations;
228 static const struct inode_operations shmem_inode_operations;
229 static const struct inode_operations shmem_dir_inode_operations;
230 static const struct inode_operations shmem_special_inode_operations;
231 static const struct vm_operations_struct shmem_vm_ops;
232 static struct file_system_type shmem_fs_type;
234 bool vma_is_shmem(struct vm_area_struct *vma)
236 return vma->vm_ops == &shmem_vm_ops;
239 static LIST_HEAD(shmem_swaplist);
240 static DEFINE_MUTEX(shmem_swaplist_mutex);
242 static int shmem_reserve_inode(struct super_block *sb)
244 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
245 if (sbinfo->max_inodes) {
246 spin_lock(&sbinfo->stat_lock);
247 if (!sbinfo->free_inodes) {
248 spin_unlock(&sbinfo->stat_lock);
251 sbinfo->free_inodes--;
252 spin_unlock(&sbinfo->stat_lock);
257 static void shmem_free_inode(struct super_block *sb)
259 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
260 if (sbinfo->max_inodes) {
261 spin_lock(&sbinfo->stat_lock);
262 sbinfo->free_inodes++;
263 spin_unlock(&sbinfo->stat_lock);
268 * shmem_recalc_inode - recalculate the block usage of an inode
269 * @inode: inode to recalc
271 * We have to calculate the free blocks since the mm can drop
272 * undirtied hole pages behind our back.
274 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
275 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
277 * It has to be called with the spinlock held.
279 static void shmem_recalc_inode(struct inode *inode)
281 struct shmem_inode_info *info = SHMEM_I(inode);
284 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
286 info->alloced -= freed;
287 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
288 shmem_inode_unacct_blocks(inode, freed);
292 bool shmem_charge(struct inode *inode, long pages)
294 struct shmem_inode_info *info = SHMEM_I(inode);
297 if (!shmem_inode_acct_block(inode, pages))
300 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
301 inode->i_mapping->nrpages += pages;
303 spin_lock_irqsave(&info->lock, flags);
304 info->alloced += pages;
305 inode->i_blocks += pages * BLOCKS_PER_PAGE;
306 shmem_recalc_inode(inode);
307 spin_unlock_irqrestore(&info->lock, flags);
312 void shmem_uncharge(struct inode *inode, long pages)
314 struct shmem_inode_info *info = SHMEM_I(inode);
317 /* nrpages adjustment done by __delete_from_page_cache() or caller */
319 spin_lock_irqsave(&info->lock, flags);
320 info->alloced -= pages;
321 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
322 shmem_recalc_inode(inode);
323 spin_unlock_irqrestore(&info->lock, flags);
325 shmem_inode_unacct_blocks(inode, pages);
329 * Replace item expected in radix tree by a new item, while holding tree lock.
331 static int shmem_radix_tree_replace(struct address_space *mapping,
332 pgoff_t index, void *expected, void *replacement)
334 struct radix_tree_node *node;
338 VM_BUG_ON(!expected);
339 VM_BUG_ON(!replacement);
340 item = __radix_tree_lookup(&mapping->i_pages, index, &node, &pslot);
343 if (item != expected)
345 __radix_tree_replace(&mapping->i_pages, node, pslot,
351 * Sometimes, before we decide whether to proceed or to fail, we must check
352 * that an entry was not already brought back from swap by a racing thread.
354 * Checking page is not enough: by the time a SwapCache page is locked, it
355 * might be reused, and again be SwapCache, using the same swap as before.
357 static bool shmem_confirm_swap(struct address_space *mapping,
358 pgoff_t index, swp_entry_t swap)
363 item = radix_tree_lookup(&mapping->i_pages, index);
365 return item == swp_to_radix_entry(swap);
369 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
372 * disables huge pages for the mount;
374 * enables huge pages for the mount;
375 * SHMEM_HUGE_WITHIN_SIZE:
376 * only allocate huge pages if the page will be fully within i_size,
377 * also respect fadvise()/madvise() hints;
379 * only allocate huge pages if requested with fadvise()/madvise();
382 #define SHMEM_HUGE_NEVER 0
383 #define SHMEM_HUGE_ALWAYS 1
384 #define SHMEM_HUGE_WITHIN_SIZE 2
385 #define SHMEM_HUGE_ADVISE 3
389 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
392 * disables huge on shm_mnt and all mounts, for emergency use;
394 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
397 #define SHMEM_HUGE_DENY (-1)
398 #define SHMEM_HUGE_FORCE (-2)
400 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
401 /* ifdef here to avoid bloating shmem.o when not necessary */
403 static int shmem_huge __read_mostly;
405 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
406 static int shmem_parse_huge(const char *str)
408 if (!strcmp(str, "never"))
409 return SHMEM_HUGE_NEVER;
410 if (!strcmp(str, "always"))
411 return SHMEM_HUGE_ALWAYS;
412 if (!strcmp(str, "within_size"))
413 return SHMEM_HUGE_WITHIN_SIZE;
414 if (!strcmp(str, "advise"))
415 return SHMEM_HUGE_ADVISE;
416 if (!strcmp(str, "deny"))
417 return SHMEM_HUGE_DENY;
418 if (!strcmp(str, "force"))
419 return SHMEM_HUGE_FORCE;
423 static const char *shmem_format_huge(int huge)
426 case SHMEM_HUGE_NEVER:
428 case SHMEM_HUGE_ALWAYS:
430 case SHMEM_HUGE_WITHIN_SIZE:
431 return "within_size";
432 case SHMEM_HUGE_ADVISE:
434 case SHMEM_HUGE_DENY:
436 case SHMEM_HUGE_FORCE:
445 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
446 struct shrink_control *sc, unsigned long nr_to_split)
448 LIST_HEAD(list), *pos, *next;
449 LIST_HEAD(to_remove);
451 struct shmem_inode_info *info;
453 unsigned long batch = sc ? sc->nr_to_scan : 128;
456 if (list_empty(&sbinfo->shrinklist))
459 spin_lock(&sbinfo->shrinklist_lock);
460 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
461 info = list_entry(pos, struct shmem_inode_info, shrinklist);
464 inode = igrab(&info->vfs_inode);
466 /* inode is about to be evicted */
468 list_del_init(&info->shrinklist);
472 /* Check if there's anything to gain */
473 if (round_up(inode->i_size, PAGE_SIZE) ==
474 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
475 list_move(&info->shrinklist, &to_remove);
479 list_move(&info->shrinklist, &list);
481 sbinfo->shrinklist_len--;
485 spin_unlock(&sbinfo->shrinklist_lock);
487 list_for_each_safe(pos, next, &to_remove) {
488 info = list_entry(pos, struct shmem_inode_info, shrinklist);
489 inode = &info->vfs_inode;
490 list_del_init(&info->shrinklist);
494 list_for_each_safe(pos, next, &list) {
497 info = list_entry(pos, struct shmem_inode_info, shrinklist);
498 inode = &info->vfs_inode;
500 if (nr_to_split && split >= nr_to_split)
503 page = find_get_page(inode->i_mapping,
504 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
508 /* No huge page at the end of the file: nothing to split */
509 if (!PageTransHuge(page)) {
515 * Move the inode on the list back to shrinklist if we failed
516 * to lock the page at this time.
518 * Waiting for the lock may lead to deadlock in the
521 if (!trylock_page(page)) {
526 ret = split_huge_page(page);
530 /* If split failed move the inode on the list back to shrinklist */
536 list_del_init(&info->shrinklist);
540 * Make sure the inode is either on the global list or deleted
541 * from any local list before iput() since it could be deleted
542 * in another thread once we put the inode (then the local list
545 spin_lock(&sbinfo->shrinklist_lock);
546 list_move(&info->shrinklist, &sbinfo->shrinklist);
547 sbinfo->shrinklist_len++;
548 spin_unlock(&sbinfo->shrinklist_lock);
556 static long shmem_unused_huge_scan(struct super_block *sb,
557 struct shrink_control *sc)
559 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
561 if (!READ_ONCE(sbinfo->shrinklist_len))
564 return shmem_unused_huge_shrink(sbinfo, sc, 0);
567 static long shmem_unused_huge_count(struct super_block *sb,
568 struct shrink_control *sc)
570 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
571 return READ_ONCE(sbinfo->shrinklist_len);
573 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
575 #define shmem_huge SHMEM_HUGE_DENY
577 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
578 struct shrink_control *sc, unsigned long nr_to_split)
582 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
584 static inline bool is_huge_enabled(struct shmem_sb_info *sbinfo)
586 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
587 (shmem_huge == SHMEM_HUGE_FORCE || sbinfo->huge) &&
588 shmem_huge != SHMEM_HUGE_DENY)
594 * Like add_to_page_cache_locked, but error if expected item has gone.
596 static int shmem_add_to_page_cache(struct page *page,
597 struct address_space *mapping,
598 pgoff_t index, void *expected)
600 int error, nr = hpage_nr_pages(page);
602 VM_BUG_ON_PAGE(PageTail(page), page);
603 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
604 VM_BUG_ON_PAGE(!PageLocked(page), page);
605 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
606 VM_BUG_ON(expected && PageTransHuge(page));
608 page_ref_add(page, nr);
609 page->mapping = mapping;
612 xa_lock_irq(&mapping->i_pages);
613 if (PageTransHuge(page)) {
614 void __rcu **results;
619 if (radix_tree_gang_lookup_slot(&mapping->i_pages,
620 &results, &idx, index, 1) &&
621 idx < index + HPAGE_PMD_NR) {
626 for (i = 0; i < HPAGE_PMD_NR; i++) {
627 error = radix_tree_insert(&mapping->i_pages,
628 index + i, page + i);
631 count_vm_event(THP_FILE_ALLOC);
633 } else if (!expected) {
634 error = radix_tree_insert(&mapping->i_pages, index, page);
636 error = shmem_radix_tree_replace(mapping, index, expected,
641 mapping->nrpages += nr;
642 if (PageTransHuge(page))
643 __inc_node_page_state(page, NR_SHMEM_THPS);
644 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
645 __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
646 xa_unlock_irq(&mapping->i_pages);
648 page->mapping = NULL;
649 xa_unlock_irq(&mapping->i_pages);
650 page_ref_sub(page, nr);
656 * Like delete_from_page_cache, but substitutes swap for page.
658 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
660 struct address_space *mapping = page->mapping;
663 VM_BUG_ON_PAGE(PageCompound(page), page);
665 xa_lock_irq(&mapping->i_pages);
666 error = shmem_radix_tree_replace(mapping, page->index, page, radswap);
667 page->mapping = NULL;
669 __dec_node_page_state(page, NR_FILE_PAGES);
670 __dec_node_page_state(page, NR_SHMEM);
671 xa_unlock_irq(&mapping->i_pages);
677 * Remove swap entry from radix tree, free the swap and its page cache.
679 static int shmem_free_swap(struct address_space *mapping,
680 pgoff_t index, void *radswap)
684 xa_lock_irq(&mapping->i_pages);
685 old = radix_tree_delete_item(&mapping->i_pages, index, radswap);
686 xa_unlock_irq(&mapping->i_pages);
689 free_swap_and_cache(radix_to_swp_entry(radswap));
694 * Determine (in bytes) how many of the shmem object's pages mapped by the
695 * given offsets are swapped out.
697 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
698 * as long as the inode doesn't go away and racy results are not a problem.
700 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
701 pgoff_t start, pgoff_t end)
703 struct radix_tree_iter iter;
706 unsigned long swapped = 0;
710 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
711 if (iter.index >= end)
714 page = radix_tree_deref_slot(slot);
716 if (radix_tree_deref_retry(page)) {
717 slot = radix_tree_iter_retry(&iter);
721 if (radix_tree_exceptional_entry(page))
724 if (need_resched()) {
725 slot = radix_tree_iter_resume(slot, &iter);
732 return swapped << PAGE_SHIFT;
736 * Determine (in bytes) how many of the shmem object's pages mapped by the
737 * given vma is swapped out.
739 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
740 * as long as the inode doesn't go away and racy results are not a problem.
742 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
744 struct inode *inode = file_inode(vma->vm_file);
745 struct shmem_inode_info *info = SHMEM_I(inode);
746 struct address_space *mapping = inode->i_mapping;
747 unsigned long swapped;
749 /* Be careful as we don't hold info->lock */
750 swapped = READ_ONCE(info->swapped);
753 * The easier cases are when the shmem object has nothing in swap, or
754 * the vma maps it whole. Then we can simply use the stats that we
760 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
761 return swapped << PAGE_SHIFT;
763 /* Here comes the more involved part */
764 return shmem_partial_swap_usage(mapping,
765 linear_page_index(vma, vma->vm_start),
766 linear_page_index(vma, vma->vm_end));
770 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
772 void shmem_unlock_mapping(struct address_space *mapping)
775 pgoff_t indices[PAGEVEC_SIZE];
780 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
782 while (!mapping_unevictable(mapping)) {
784 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
785 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
787 pvec.nr = find_get_entries(mapping, index,
788 PAGEVEC_SIZE, pvec.pages, indices);
791 index = indices[pvec.nr - 1] + 1;
792 pagevec_remove_exceptionals(&pvec);
793 check_move_unevictable_pages(pvec.pages, pvec.nr);
794 pagevec_release(&pvec);
800 * Remove range of pages and swap entries from radix tree, and free them.
801 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
803 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
806 struct address_space *mapping = inode->i_mapping;
807 struct shmem_inode_info *info = SHMEM_I(inode);
808 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
809 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
810 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
811 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
813 pgoff_t indices[PAGEVEC_SIZE];
814 long nr_swaps_freed = 0;
819 end = -1; /* unsigned, so actually very big */
823 while (index < end) {
824 pvec.nr = find_get_entries(mapping, index,
825 min(end - index, (pgoff_t)PAGEVEC_SIZE),
826 pvec.pages, indices);
829 for (i = 0; i < pagevec_count(&pvec); i++) {
830 struct page *page = pvec.pages[i];
836 if (radix_tree_exceptional_entry(page)) {
839 nr_swaps_freed += !shmem_free_swap(mapping,
844 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
846 if (!trylock_page(page))
849 if (PageTransTail(page)) {
850 /* Middle of THP: zero out the page */
851 clear_highpage(page);
854 } else if (PageTransHuge(page)) {
855 if (index == round_down(end, HPAGE_PMD_NR)) {
857 * Range ends in the middle of THP:
860 clear_highpage(page);
864 index += HPAGE_PMD_NR - 1;
865 i += HPAGE_PMD_NR - 1;
868 if (!unfalloc || !PageUptodate(page)) {
869 VM_BUG_ON_PAGE(PageTail(page), page);
870 if (page_mapping(page) == mapping) {
871 VM_BUG_ON_PAGE(PageWriteback(page), page);
872 truncate_inode_page(mapping, page);
877 pagevec_remove_exceptionals(&pvec);
878 pagevec_release(&pvec);
884 struct page *page = NULL;
885 shmem_getpage(inode, start - 1, &page, SGP_READ);
887 unsigned int top = PAGE_SIZE;
892 zero_user_segment(page, partial_start, top);
893 set_page_dirty(page);
899 struct page *page = NULL;
900 shmem_getpage(inode, end, &page, SGP_READ);
902 zero_user_segment(page, 0, partial_end);
903 set_page_dirty(page);
912 while (index < end) {
915 pvec.nr = find_get_entries(mapping, index,
916 min(end - index, (pgoff_t)PAGEVEC_SIZE),
917 pvec.pages, indices);
919 /* If all gone or hole-punch or unfalloc, we're done */
920 if (index == start || end != -1)
922 /* But if truncating, restart to make sure all gone */
926 for (i = 0; i < pagevec_count(&pvec); i++) {
927 struct page *page = pvec.pages[i];
933 if (radix_tree_exceptional_entry(page)) {
936 if (shmem_free_swap(mapping, index, page)) {
937 /* Swap was replaced by page: retry */
947 if (PageTransTail(page)) {
948 /* Middle of THP: zero out the page */
949 clear_highpage(page);
952 * Partial thp truncate due 'start' in middle
953 * of THP: don't need to look on these pages
954 * again on !pvec.nr restart.
956 if (index != round_down(end, HPAGE_PMD_NR))
959 } else if (PageTransHuge(page)) {
960 if (index == round_down(end, HPAGE_PMD_NR)) {
962 * Range ends in the middle of THP:
965 clear_highpage(page);
969 index += HPAGE_PMD_NR - 1;
970 i += HPAGE_PMD_NR - 1;
973 if (!unfalloc || !PageUptodate(page)) {
974 VM_BUG_ON_PAGE(PageTail(page), page);
975 if (page_mapping(page) == mapping) {
976 VM_BUG_ON_PAGE(PageWriteback(page), page);
977 truncate_inode_page(mapping, page);
979 /* Page was replaced by swap: retry */
987 pagevec_remove_exceptionals(&pvec);
988 pagevec_release(&pvec);
992 spin_lock_irq(&info->lock);
993 info->swapped -= nr_swaps_freed;
994 shmem_recalc_inode(inode);
995 spin_unlock_irq(&info->lock);
998 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
1000 shmem_undo_range(inode, lstart, lend, false);
1001 inode->i_ctime = inode->i_mtime = current_time(inode);
1003 EXPORT_SYMBOL_GPL(shmem_truncate_range);
1005 static int shmem_getattr(const struct path *path, struct kstat *stat,
1006 u32 request_mask, unsigned int query_flags)
1008 struct inode *inode = path->dentry->d_inode;
1009 struct shmem_inode_info *info = SHMEM_I(inode);
1010 struct shmem_sb_info *sb_info = SHMEM_SB(inode->i_sb);
1012 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
1013 spin_lock_irq(&info->lock);
1014 shmem_recalc_inode(inode);
1015 spin_unlock_irq(&info->lock);
1017 generic_fillattr(inode, stat);
1019 if (is_huge_enabled(sb_info))
1020 stat->blksize = HPAGE_PMD_SIZE;
1025 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
1027 struct inode *inode = d_inode(dentry);
1028 struct shmem_inode_info *info = SHMEM_I(inode);
1029 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1032 error = setattr_prepare(dentry, attr);
1036 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1037 loff_t oldsize = inode->i_size;
1038 loff_t newsize = attr->ia_size;
1040 /* protected by i_mutex */
1041 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1042 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1045 if (newsize != oldsize) {
1046 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1050 i_size_write(inode, newsize);
1051 inode->i_ctime = inode->i_mtime = current_time(inode);
1053 if (newsize <= oldsize) {
1054 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1055 if (oldsize > holebegin)
1056 unmap_mapping_range(inode->i_mapping,
1059 shmem_truncate_range(inode,
1060 newsize, (loff_t)-1);
1061 /* unmap again to remove racily COWed private pages */
1062 if (oldsize > holebegin)
1063 unmap_mapping_range(inode->i_mapping,
1067 * Part of the huge page can be beyond i_size: subject
1068 * to shrink under memory pressure.
1070 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
1071 spin_lock(&sbinfo->shrinklist_lock);
1073 * _careful to defend against unlocked access to
1074 * ->shrink_list in shmem_unused_huge_shrink()
1076 if (list_empty_careful(&info->shrinklist)) {
1077 list_add_tail(&info->shrinklist,
1078 &sbinfo->shrinklist);
1079 sbinfo->shrinklist_len++;
1081 spin_unlock(&sbinfo->shrinklist_lock);
1086 setattr_copy(inode, attr);
1087 if (attr->ia_valid & ATTR_MODE)
1088 error = posix_acl_chmod(inode, inode->i_mode);
1092 static void shmem_evict_inode(struct inode *inode)
1094 struct shmem_inode_info *info = SHMEM_I(inode);
1095 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1097 if (inode->i_mapping->a_ops == &shmem_aops) {
1098 shmem_unacct_size(info->flags, inode->i_size);
1100 shmem_truncate_range(inode, 0, (loff_t)-1);
1101 if (!list_empty(&info->shrinklist)) {
1102 spin_lock(&sbinfo->shrinklist_lock);
1103 if (!list_empty(&info->shrinklist)) {
1104 list_del_init(&info->shrinklist);
1105 sbinfo->shrinklist_len--;
1107 spin_unlock(&sbinfo->shrinklist_lock);
1109 if (!list_empty(&info->swaplist)) {
1110 mutex_lock(&shmem_swaplist_mutex);
1111 list_del_init(&info->swaplist);
1112 mutex_unlock(&shmem_swaplist_mutex);
1116 simple_xattrs_free(&info->xattrs);
1117 WARN_ON(inode->i_blocks);
1118 shmem_free_inode(inode->i_sb);
1122 static unsigned long find_swap_entry(struct radix_tree_root *root, void *item)
1124 struct radix_tree_iter iter;
1126 unsigned long found = -1;
1127 unsigned int checked = 0;
1130 radix_tree_for_each_slot(slot, root, &iter, 0) {
1131 void *entry = radix_tree_deref_slot(slot);
1133 if (radix_tree_deref_retry(entry)) {
1134 slot = radix_tree_iter_retry(&iter);
1137 if (entry == item) {
1142 if ((checked % 4096) != 0)
1144 slot = radix_tree_iter_resume(slot, &iter);
1153 * If swap found in inode, free it and move page from swapcache to filecache.
1155 static int shmem_unuse_inode(struct shmem_inode_info *info,
1156 swp_entry_t swap, struct page **pagep)
1158 struct address_space *mapping = info->vfs_inode.i_mapping;
1164 radswap = swp_to_radix_entry(swap);
1165 index = find_swap_entry(&mapping->i_pages, radswap);
1167 return -EAGAIN; /* tell shmem_unuse we found nothing */
1170 * Move _head_ to start search for next from here.
1171 * But be careful: shmem_evict_inode checks list_empty without taking
1172 * mutex, and there's an instant in list_move_tail when info->swaplist
1173 * would appear empty, if it were the only one on shmem_swaplist.
1175 if (shmem_swaplist.next != &info->swaplist)
1176 list_move_tail(&shmem_swaplist, &info->swaplist);
1178 gfp = mapping_gfp_mask(mapping);
1179 if (shmem_should_replace_page(*pagep, gfp)) {
1180 mutex_unlock(&shmem_swaplist_mutex);
1181 error = shmem_replace_page(pagep, gfp, info, index);
1182 mutex_lock(&shmem_swaplist_mutex);
1184 * We needed to drop mutex to make that restrictive page
1185 * allocation, but the inode might have been freed while we
1186 * dropped it: although a racing shmem_evict_inode() cannot
1187 * complete without emptying the radix_tree, our page lock
1188 * on this swapcache page is not enough to prevent that -
1189 * free_swap_and_cache() of our swap entry will only
1190 * trylock_page(), removing swap from radix_tree whatever.
1192 * We must not proceed to shmem_add_to_page_cache() if the
1193 * inode has been freed, but of course we cannot rely on
1194 * inode or mapping or info to check that. However, we can
1195 * safely check if our swap entry is still in use (and here
1196 * it can't have got reused for another page): if it's still
1197 * in use, then the inode cannot have been freed yet, and we
1198 * can safely proceed (if it's no longer in use, that tells
1199 * nothing about the inode, but we don't need to unuse swap).
1201 if (!page_swapcount(*pagep))
1206 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
1207 * but also to hold up shmem_evict_inode(): so inode cannot be freed
1208 * beneath us (pagelock doesn't help until the page is in pagecache).
1211 error = shmem_add_to_page_cache(*pagep, mapping, index,
1213 if (error != -ENOMEM) {
1215 * Truncation and eviction use free_swap_and_cache(), which
1216 * only does trylock page: if we raced, best clean up here.
1218 delete_from_swap_cache(*pagep);
1219 set_page_dirty(*pagep);
1221 spin_lock_irq(&info->lock);
1223 spin_unlock_irq(&info->lock);
1231 * Search through swapped inodes to find and replace swap by page.
1233 int shmem_unuse(swp_entry_t swap, struct page *page)
1235 struct list_head *this, *next;
1236 struct shmem_inode_info *info;
1237 struct mem_cgroup *memcg;
1241 * There's a faint possibility that swap page was replaced before
1242 * caller locked it: caller will come back later with the right page.
1244 if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
1248 * Charge page using GFP_KERNEL while we can wait, before taking
1249 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1250 * Charged back to the user (not to caller) when swap account is used.
1252 error = mem_cgroup_try_charge_delay(page, current->mm, GFP_KERNEL,
1256 /* No radix_tree_preload: swap entry keeps a place for page in tree */
1259 mutex_lock(&shmem_swaplist_mutex);
1260 list_for_each_safe(this, next, &shmem_swaplist) {
1261 info = list_entry(this, struct shmem_inode_info, swaplist);
1263 error = shmem_unuse_inode(info, swap, &page);
1265 list_del_init(&info->swaplist);
1267 if (error != -EAGAIN)
1269 /* found nothing in this: move on to search the next */
1271 mutex_unlock(&shmem_swaplist_mutex);
1274 if (error != -ENOMEM)
1276 mem_cgroup_cancel_charge(page, memcg, false);
1278 mem_cgroup_commit_charge(page, memcg, true, false);
1286 * Move the page from the page cache to the swap cache.
1288 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1290 struct shmem_inode_info *info;
1291 struct address_space *mapping;
1292 struct inode *inode;
1296 VM_BUG_ON_PAGE(PageCompound(page), page);
1297 BUG_ON(!PageLocked(page));
1298 mapping = page->mapping;
1299 index = page->index;
1300 inode = mapping->host;
1301 info = SHMEM_I(inode);
1302 if (info->flags & VM_LOCKED)
1304 if (!total_swap_pages)
1308 * Our capabilities prevent regular writeback or sync from ever calling
1309 * shmem_writepage; but a stacking filesystem might use ->writepage of
1310 * its underlying filesystem, in which case tmpfs should write out to
1311 * swap only in response to memory pressure, and not for the writeback
1314 if (!wbc->for_reclaim) {
1315 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1320 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1321 * value into swapfile.c, the only way we can correctly account for a
1322 * fallocated page arriving here is now to initialize it and write it.
1324 * That's okay for a page already fallocated earlier, but if we have
1325 * not yet completed the fallocation, then (a) we want to keep track
1326 * of this page in case we have to undo it, and (b) it may not be a
1327 * good idea to continue anyway, once we're pushing into swap. So
1328 * reactivate the page, and let shmem_fallocate() quit when too many.
1330 if (!PageUptodate(page)) {
1331 if (inode->i_private) {
1332 struct shmem_falloc *shmem_falloc;
1333 spin_lock(&inode->i_lock);
1334 shmem_falloc = inode->i_private;
1336 !shmem_falloc->waitq &&
1337 index >= shmem_falloc->start &&
1338 index < shmem_falloc->next)
1339 shmem_falloc->nr_unswapped++;
1341 shmem_falloc = NULL;
1342 spin_unlock(&inode->i_lock);
1346 clear_highpage(page);
1347 flush_dcache_page(page);
1348 SetPageUptodate(page);
1351 swap = get_swap_page(page);
1356 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1357 * if it's not already there. Do it now before the page is
1358 * moved to swap cache, when its pagelock no longer protects
1359 * the inode from eviction. But don't unlock the mutex until
1360 * we've incremented swapped, because shmem_unuse_inode() will
1361 * prune a !swapped inode from the swaplist under this mutex.
1363 mutex_lock(&shmem_swaplist_mutex);
1364 if (list_empty(&info->swaplist))
1365 list_add_tail(&info->swaplist, &shmem_swaplist);
1367 if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1368 spin_lock_irq(&info->lock);
1369 shmem_recalc_inode(inode);
1371 spin_unlock_irq(&info->lock);
1373 swap_shmem_alloc(swap);
1374 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1376 mutex_unlock(&shmem_swaplist_mutex);
1377 BUG_ON(page_mapped(page));
1378 swap_writepage(page, wbc);
1382 mutex_unlock(&shmem_swaplist_mutex);
1383 put_swap_page(page, swap);
1385 set_page_dirty(page);
1386 if (wbc->for_reclaim)
1387 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1392 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1393 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1397 if (!mpol || mpol->mode == MPOL_DEFAULT)
1398 return; /* show nothing */
1400 mpol_to_str(buffer, sizeof(buffer), mpol);
1402 seq_printf(seq, ",mpol=%s", buffer);
1405 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1407 struct mempolicy *mpol = NULL;
1409 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1410 mpol = sbinfo->mpol;
1412 spin_unlock(&sbinfo->stat_lock);
1416 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1417 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1420 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1424 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1426 #define vm_policy vm_private_data
1429 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1430 struct shmem_inode_info *info, pgoff_t index)
1432 /* Create a pseudo vma that just contains the policy */
1433 vma_init(vma, NULL);
1434 /* Bias interleave by inode number to distribute better across nodes */
1435 vma->vm_pgoff = index + info->vfs_inode.i_ino;
1436 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1439 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1441 /* Drop reference taken by mpol_shared_policy_lookup() */
1442 mpol_cond_put(vma->vm_policy);
1445 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1446 struct shmem_inode_info *info, pgoff_t index)
1448 struct vm_area_struct pvma;
1450 struct vm_fault vmf;
1452 shmem_pseudo_vma_init(&pvma, info, index);
1455 page = swap_cluster_readahead(swap, gfp, &vmf);
1456 shmem_pseudo_vma_destroy(&pvma);
1461 static struct page *shmem_alloc_hugepage(gfp_t gfp,
1462 struct shmem_inode_info *info, pgoff_t index)
1464 struct vm_area_struct pvma;
1465 struct inode *inode = &info->vfs_inode;
1466 struct address_space *mapping = inode->i_mapping;
1467 pgoff_t idx, hindex;
1468 void __rcu **results;
1471 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1474 hindex = round_down(index, HPAGE_PMD_NR);
1476 if (radix_tree_gang_lookup_slot(&mapping->i_pages, &results, &idx,
1477 hindex, 1) && idx < hindex + HPAGE_PMD_NR) {
1483 shmem_pseudo_vma_init(&pvma, info, hindex);
1484 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1485 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
1486 shmem_pseudo_vma_destroy(&pvma);
1488 prep_transhuge_page(page);
1492 static struct page *shmem_alloc_page(gfp_t gfp,
1493 struct shmem_inode_info *info, pgoff_t index)
1495 struct vm_area_struct pvma;
1498 shmem_pseudo_vma_init(&pvma, info, index);
1499 page = alloc_page_vma(gfp, &pvma, 0);
1500 shmem_pseudo_vma_destroy(&pvma);
1505 static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1506 struct inode *inode,
1507 pgoff_t index, bool huge)
1509 struct shmem_inode_info *info = SHMEM_I(inode);
1514 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1516 nr = huge ? HPAGE_PMD_NR : 1;
1518 if (!shmem_inode_acct_block(inode, nr))
1522 page = shmem_alloc_hugepage(gfp, info, index);
1524 page = shmem_alloc_page(gfp, info, index);
1526 __SetPageLocked(page);
1527 __SetPageSwapBacked(page);
1532 shmem_inode_unacct_blocks(inode, nr);
1534 return ERR_PTR(err);
1538 * When a page is moved from swapcache to shmem filecache (either by the
1539 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1540 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1541 * ignorance of the mapping it belongs to. If that mapping has special
1542 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1543 * we may need to copy to a suitable page before moving to filecache.
1545 * In a future release, this may well be extended to respect cpuset and
1546 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1547 * but for now it is a simple matter of zone.
1549 static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1551 return page_zonenum(page) > gfp_zone(gfp);
1554 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1555 struct shmem_inode_info *info, pgoff_t index)
1557 struct page *oldpage, *newpage;
1558 struct address_space *swap_mapping;
1564 entry.val = page_private(oldpage);
1565 swap_index = swp_offset(entry);
1566 swap_mapping = page_mapping(oldpage);
1569 * We have arrived here because our zones are constrained, so don't
1570 * limit chance of success by further cpuset and node constraints.
1572 gfp &= ~GFP_CONSTRAINT_MASK;
1573 newpage = shmem_alloc_page(gfp, info, index);
1578 copy_highpage(newpage, oldpage);
1579 flush_dcache_page(newpage);
1581 __SetPageLocked(newpage);
1582 __SetPageSwapBacked(newpage);
1583 SetPageUptodate(newpage);
1584 set_page_private(newpage, entry.val);
1585 SetPageSwapCache(newpage);
1588 * Our caller will very soon move newpage out of swapcache, but it's
1589 * a nice clean interface for us to replace oldpage by newpage there.
1591 xa_lock_irq(&swap_mapping->i_pages);
1592 error = shmem_radix_tree_replace(swap_mapping, swap_index, oldpage,
1595 __inc_node_page_state(newpage, NR_FILE_PAGES);
1596 __dec_node_page_state(oldpage, NR_FILE_PAGES);
1598 xa_unlock_irq(&swap_mapping->i_pages);
1600 if (unlikely(error)) {
1602 * Is this possible? I think not, now that our callers check
1603 * both PageSwapCache and page_private after getting page lock;
1604 * but be defensive. Reverse old to newpage for clear and free.
1608 mem_cgroup_migrate(oldpage, newpage);
1609 lru_cache_add_anon(newpage);
1613 ClearPageSwapCache(oldpage);
1614 set_page_private(oldpage, 0);
1616 unlock_page(oldpage);
1623 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1625 * If we allocate a new one we do not mark it dirty. That's up to the
1626 * vm. If we swap it in we mark it dirty since we also free the swap
1627 * entry since a page cannot live in both the swap and page cache.
1629 * fault_mm and fault_type are only supplied by shmem_fault:
1630 * otherwise they are NULL.
1632 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1633 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1634 struct vm_area_struct *vma, struct vm_fault *vmf,
1635 vm_fault_t *fault_type)
1637 struct address_space *mapping = inode->i_mapping;
1638 struct shmem_inode_info *info = SHMEM_I(inode);
1639 struct shmem_sb_info *sbinfo;
1640 struct mm_struct *charge_mm;
1641 struct mem_cgroup *memcg;
1644 enum sgp_type sgp_huge = sgp;
1645 pgoff_t hindex = index;
1650 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1652 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1656 page = find_lock_entry(mapping, index);
1657 if (radix_tree_exceptional_entry(page)) {
1658 swap = radix_to_swp_entry(page);
1662 if (sgp <= SGP_CACHE &&
1663 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1668 if (page && sgp == SGP_WRITE)
1669 mark_page_accessed(page);
1671 /* fallocated page? */
1672 if (page && !PageUptodate(page)) {
1673 if (sgp != SGP_READ)
1679 if (page || (sgp == SGP_READ && !swap.val)) {
1685 * Fast cache lookup did not find it:
1686 * bring it back from swap or allocate.
1688 sbinfo = SHMEM_SB(inode->i_sb);
1689 charge_mm = vma ? vma->vm_mm : current->mm;
1692 /* Look it up and read it in.. */
1693 page = lookup_swap_cache(swap, NULL, 0);
1695 /* Or update major stats only when swapin succeeds?? */
1697 *fault_type |= VM_FAULT_MAJOR;
1698 count_vm_event(PGMAJFAULT);
1699 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1701 /* Here we actually start the io */
1702 page = shmem_swapin(swap, gfp, info, index);
1709 /* We have to do this with page locked to prevent races */
1711 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1712 !shmem_confirm_swap(mapping, index, swap)) {
1713 error = -EEXIST; /* try again */
1716 if (!PageUptodate(page)) {
1720 wait_on_page_writeback(page);
1722 if (shmem_should_replace_page(page, gfp)) {
1723 error = shmem_replace_page(&page, gfp, info, index);
1728 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1731 error = shmem_add_to_page_cache(page, mapping, index,
1732 swp_to_radix_entry(swap));
1734 * We already confirmed swap under page lock, and make
1735 * no memory allocation here, so usually no possibility
1736 * of error; but free_swap_and_cache() only trylocks a
1737 * page, so it is just possible that the entry has been
1738 * truncated or holepunched since swap was confirmed.
1739 * shmem_undo_range() will have done some of the
1740 * unaccounting, now delete_from_swap_cache() will do
1742 * Reset swap.val? No, leave it so "failed" goes back to
1743 * "repeat": reading a hole and writing should succeed.
1746 mem_cgroup_cancel_charge(page, memcg, false);
1747 delete_from_swap_cache(page);
1753 mem_cgroup_commit_charge(page, memcg, true, false);
1755 spin_lock_irq(&info->lock);
1757 shmem_recalc_inode(inode);
1758 spin_unlock_irq(&info->lock);
1760 if (sgp == SGP_WRITE)
1761 mark_page_accessed(page);
1763 delete_from_swap_cache(page);
1764 set_page_dirty(page);
1768 if (vma && userfaultfd_missing(vma)) {
1769 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1773 /* shmem_symlink() */
1774 if (mapping->a_ops != &shmem_aops)
1776 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1778 if (shmem_huge == SHMEM_HUGE_FORCE)
1780 switch (sbinfo->huge) {
1783 case SHMEM_HUGE_NEVER:
1785 case SHMEM_HUGE_WITHIN_SIZE:
1786 off = round_up(index, HPAGE_PMD_NR);
1787 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1788 if (i_size >= HPAGE_PMD_SIZE &&
1789 i_size >> PAGE_SHIFT >= off)
1792 case SHMEM_HUGE_ADVISE:
1793 if (sgp_huge == SGP_HUGE)
1795 /* TODO: implement fadvise() hints */
1800 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1802 alloc_nohuge: page = shmem_alloc_and_acct_page(gfp, inode,
1807 error = PTR_ERR(page);
1809 if (error != -ENOSPC)
1812 * Try to reclaim some spece by splitting a huge page
1813 * beyond i_size on the filesystem.
1817 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1818 if (ret == SHRINK_STOP)
1826 if (PageTransHuge(page))
1827 hindex = round_down(index, HPAGE_PMD_NR);
1831 if (sgp == SGP_WRITE)
1832 __SetPageReferenced(page);
1834 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1835 PageTransHuge(page));
1838 error = radix_tree_maybe_preload_order(gfp & GFP_RECLAIM_MASK,
1839 compound_order(page));
1841 error = shmem_add_to_page_cache(page, mapping, hindex,
1843 radix_tree_preload_end();
1846 mem_cgroup_cancel_charge(page, memcg,
1847 PageTransHuge(page));
1850 mem_cgroup_commit_charge(page, memcg, false,
1851 PageTransHuge(page));
1852 lru_cache_add_anon(page);
1854 spin_lock_irq(&info->lock);
1855 info->alloced += 1 << compound_order(page);
1856 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1857 shmem_recalc_inode(inode);
1858 spin_unlock_irq(&info->lock);
1861 if (PageTransHuge(page) &&
1862 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1863 hindex + HPAGE_PMD_NR - 1) {
1865 * Part of the huge page is beyond i_size: subject
1866 * to shrink under memory pressure.
1868 spin_lock(&sbinfo->shrinklist_lock);
1870 * _careful to defend against unlocked access to
1871 * ->shrink_list in shmem_unused_huge_shrink()
1873 if (list_empty_careful(&info->shrinklist)) {
1874 list_add_tail(&info->shrinklist,
1875 &sbinfo->shrinklist);
1876 sbinfo->shrinklist_len++;
1878 spin_unlock(&sbinfo->shrinklist_lock);
1882 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1884 if (sgp == SGP_FALLOC)
1888 * Let SGP_WRITE caller clear ends if write does not fill page;
1889 * but SGP_FALLOC on a page fallocated earlier must initialize
1890 * it now, lest undo on failure cancel our earlier guarantee.
1892 if (sgp != SGP_WRITE && !PageUptodate(page)) {
1893 struct page *head = compound_head(page);
1896 for (i = 0; i < (1 << compound_order(head)); i++) {
1897 clear_highpage(head + i);
1898 flush_dcache_page(head + i);
1900 SetPageUptodate(head);
1904 /* Perhaps the file has been truncated since we checked */
1905 if (sgp <= SGP_CACHE &&
1906 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1908 ClearPageDirty(page);
1909 delete_from_page_cache(page);
1910 spin_lock_irq(&info->lock);
1911 shmem_recalc_inode(inode);
1912 spin_unlock_irq(&info->lock);
1917 *pagep = page + index - hindex;
1924 shmem_inode_unacct_blocks(inode, 1 << compound_order(page));
1926 if (PageTransHuge(page)) {
1932 if (swap.val && !shmem_confirm_swap(mapping, index, swap))
1939 if (error == -ENOSPC && !once++) {
1940 spin_lock_irq(&info->lock);
1941 shmem_recalc_inode(inode);
1942 spin_unlock_irq(&info->lock);
1945 if (error == -EEXIST) /* from above or from radix_tree_insert */
1951 * This is like autoremove_wake_function, but it removes the wait queue
1952 * entry unconditionally - even if something else had already woken the
1955 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
1957 int ret = default_wake_function(wait, mode, sync, key);
1958 list_del_init(&wait->entry);
1962 static vm_fault_t shmem_fault(struct vm_fault *vmf)
1964 struct vm_area_struct *vma = vmf->vma;
1965 struct inode *inode = file_inode(vma->vm_file);
1966 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1969 vm_fault_t ret = VM_FAULT_LOCKED;
1972 * Trinity finds that probing a hole which tmpfs is punching can
1973 * prevent the hole-punch from ever completing: which in turn
1974 * locks writers out with its hold on i_mutex. So refrain from
1975 * faulting pages into the hole while it's being punched. Although
1976 * shmem_undo_range() does remove the additions, it may be unable to
1977 * keep up, as each new page needs its own unmap_mapping_range() call,
1978 * and the i_mmap tree grows ever slower to scan if new vmas are added.
1980 * It does not matter if we sometimes reach this check just before the
1981 * hole-punch begins, so that one fault then races with the punch:
1982 * we just need to make racing faults a rare case.
1984 * The implementation below would be much simpler if we just used a
1985 * standard mutex or completion: but we cannot take i_mutex in fault,
1986 * and bloating every shmem inode for this unlikely case would be sad.
1988 if (unlikely(inode->i_private)) {
1989 struct shmem_falloc *shmem_falloc;
1991 spin_lock(&inode->i_lock);
1992 shmem_falloc = inode->i_private;
1994 shmem_falloc->waitq &&
1995 vmf->pgoff >= shmem_falloc->start &&
1996 vmf->pgoff < shmem_falloc->next) {
1997 wait_queue_head_t *shmem_falloc_waitq;
1998 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
2000 ret = VM_FAULT_NOPAGE;
2001 if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
2002 !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
2003 /* It's polite to up mmap_sem if we can */
2004 up_read(&vma->vm_mm->mmap_sem);
2005 ret = VM_FAULT_RETRY;
2008 shmem_falloc_waitq = shmem_falloc->waitq;
2009 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
2010 TASK_UNINTERRUPTIBLE);
2011 spin_unlock(&inode->i_lock);
2015 * shmem_falloc_waitq points into the shmem_fallocate()
2016 * stack of the hole-punching task: shmem_falloc_waitq
2017 * is usually invalid by the time we reach here, but
2018 * finish_wait() does not dereference it in that case;
2019 * though i_lock needed lest racing with wake_up_all().
2021 spin_lock(&inode->i_lock);
2022 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2023 spin_unlock(&inode->i_lock);
2026 spin_unlock(&inode->i_lock);
2031 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
2032 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
2034 else if (vma->vm_flags & VM_HUGEPAGE)
2037 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
2038 gfp, vma, vmf, &ret);
2040 return vmf_error(err);
2044 unsigned long shmem_get_unmapped_area(struct file *file,
2045 unsigned long uaddr, unsigned long len,
2046 unsigned long pgoff, unsigned long flags)
2048 unsigned long (*get_area)(struct file *,
2049 unsigned long, unsigned long, unsigned long, unsigned long);
2051 unsigned long offset;
2052 unsigned long inflated_len;
2053 unsigned long inflated_addr;
2054 unsigned long inflated_offset;
2056 if (len > TASK_SIZE)
2059 get_area = current->mm->get_unmapped_area;
2060 addr = get_area(file, uaddr, len, pgoff, flags);
2062 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
2064 if (IS_ERR_VALUE(addr))
2066 if (addr & ~PAGE_MASK)
2068 if (addr > TASK_SIZE - len)
2071 if (shmem_huge == SHMEM_HUGE_DENY)
2073 if (len < HPAGE_PMD_SIZE)
2075 if (flags & MAP_FIXED)
2078 * Our priority is to support MAP_SHARED mapped hugely;
2079 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2080 * But if caller specified an address hint and we allocated area there
2081 * successfully, respect that as before.
2086 if (shmem_huge != SHMEM_HUGE_FORCE) {
2087 struct super_block *sb;
2090 VM_BUG_ON(file->f_op != &shmem_file_operations);
2091 sb = file_inode(file)->i_sb;
2094 * Called directly from mm/mmap.c, or drivers/char/mem.c
2095 * for "/dev/zero", to create a shared anonymous object.
2097 if (IS_ERR(shm_mnt))
2099 sb = shm_mnt->mnt_sb;
2101 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2105 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2106 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2108 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2111 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2112 if (inflated_len > TASK_SIZE)
2114 if (inflated_len < len)
2117 inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
2118 if (IS_ERR_VALUE(inflated_addr))
2120 if (inflated_addr & ~PAGE_MASK)
2123 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2124 inflated_addr += offset - inflated_offset;
2125 if (inflated_offset > offset)
2126 inflated_addr += HPAGE_PMD_SIZE;
2128 if (inflated_addr > TASK_SIZE - len)
2130 return inflated_addr;
2134 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2136 struct inode *inode = file_inode(vma->vm_file);
2137 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2140 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2143 struct inode *inode = file_inode(vma->vm_file);
2146 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2147 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2151 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2153 struct inode *inode = file_inode(file);
2154 struct shmem_inode_info *info = SHMEM_I(inode);
2155 int retval = -ENOMEM;
2158 * What serializes the accesses to info->flags?
2159 * ipc_lock_object() when called from shmctl_do_lock(),
2160 * no serialization needed when called from shm_destroy().
2162 if (lock && !(info->flags & VM_LOCKED)) {
2163 if (!user_shm_lock(inode->i_size, user))
2165 info->flags |= VM_LOCKED;
2166 mapping_set_unevictable(file->f_mapping);
2168 if (!lock && (info->flags & VM_LOCKED) && user) {
2169 user_shm_unlock(inode->i_size, user);
2170 info->flags &= ~VM_LOCKED;
2171 mapping_clear_unevictable(file->f_mapping);
2179 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2181 file_accessed(file);
2182 vma->vm_ops = &shmem_vm_ops;
2183 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
2184 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2185 (vma->vm_end & HPAGE_PMD_MASK)) {
2186 khugepaged_enter(vma, vma->vm_flags);
2191 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
2192 umode_t mode, dev_t dev, unsigned long flags)
2194 struct inode *inode;
2195 struct shmem_inode_info *info;
2196 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2198 if (shmem_reserve_inode(sb))
2201 inode = new_inode(sb);
2203 inode->i_ino = get_next_ino();
2204 inode_init_owner(inode, dir, mode);
2205 inode->i_blocks = 0;
2206 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2207 inode->i_generation = prandom_u32();
2208 info = SHMEM_I(inode);
2209 memset(info, 0, (char *)inode - (char *)info);
2210 spin_lock_init(&info->lock);
2211 info->seals = F_SEAL_SEAL;
2212 info->flags = flags & VM_NORESERVE;
2213 INIT_LIST_HEAD(&info->shrinklist);
2214 INIT_LIST_HEAD(&info->swaplist);
2215 simple_xattrs_init(&info->xattrs);
2216 cache_no_acl(inode);
2218 switch (mode & S_IFMT) {
2220 inode->i_op = &shmem_special_inode_operations;
2221 init_special_inode(inode, mode, dev);
2224 inode->i_mapping->a_ops = &shmem_aops;
2225 inode->i_op = &shmem_inode_operations;
2226 inode->i_fop = &shmem_file_operations;
2227 mpol_shared_policy_init(&info->policy,
2228 shmem_get_sbmpol(sbinfo));
2232 /* Some things misbehave if size == 0 on a directory */
2233 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2234 inode->i_op = &shmem_dir_inode_operations;
2235 inode->i_fop = &simple_dir_operations;
2239 * Must not load anything in the rbtree,
2240 * mpol_free_shared_policy will not be called.
2242 mpol_shared_policy_init(&info->policy, NULL);
2246 lockdep_annotate_inode_mutex_key(inode);
2248 shmem_free_inode(sb);
2252 bool shmem_mapping(struct address_space *mapping)
2254 return mapping->a_ops == &shmem_aops;
2257 static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2259 struct vm_area_struct *dst_vma,
2260 unsigned long dst_addr,
2261 unsigned long src_addr,
2263 struct page **pagep)
2265 struct inode *inode = file_inode(dst_vma->vm_file);
2266 struct shmem_inode_info *info = SHMEM_I(inode);
2267 struct address_space *mapping = inode->i_mapping;
2268 gfp_t gfp = mapping_gfp_mask(mapping);
2269 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2270 struct mem_cgroup *memcg;
2274 pte_t _dst_pte, *dst_pte;
2276 pgoff_t offset, max_off;
2279 if (!shmem_inode_acct_block(inode, 1)) {
2281 * We may have got a page, returned -ENOENT triggering a retry,
2282 * and now we find ourselves with -ENOMEM. Release the page, to
2283 * avoid a BUG_ON in our caller.
2285 if (unlikely(*pagep)) {
2293 page = shmem_alloc_page(gfp, info, pgoff);
2295 goto out_unacct_blocks;
2297 if (!zeropage) { /* mcopy_atomic */
2298 page_kaddr = kmap_atomic(page);
2299 ret = copy_from_user(page_kaddr,
2300 (const void __user *)src_addr,
2302 kunmap_atomic(page_kaddr);
2304 /* fallback to copy_from_user outside mmap_sem */
2305 if (unlikely(ret)) {
2307 shmem_inode_unacct_blocks(inode, 1);
2308 /* don't free the page */
2311 } else { /* mfill_zeropage_atomic */
2312 clear_highpage(page);
2319 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2320 __SetPageLocked(page);
2321 __SetPageSwapBacked(page);
2322 __SetPageUptodate(page);
2325 offset = linear_page_index(dst_vma, dst_addr);
2326 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2327 if (unlikely(offset >= max_off))
2330 ret = mem_cgroup_try_charge_delay(page, dst_mm, gfp, &memcg, false);
2334 ret = radix_tree_maybe_preload(gfp & GFP_RECLAIM_MASK);
2336 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL);
2337 radix_tree_preload_end();
2340 goto out_release_uncharge;
2342 mem_cgroup_commit_charge(page, memcg, false, false);
2344 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2345 if (dst_vma->vm_flags & VM_WRITE)
2346 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
2349 * We don't set the pte dirty if the vma has no
2350 * VM_WRITE permission, so mark the page dirty or it
2351 * could be freed from under us. We could do it
2352 * unconditionally before unlock_page(), but doing it
2353 * only if VM_WRITE is not set is faster.
2355 set_page_dirty(page);
2358 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
2361 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2362 if (unlikely(offset >= max_off))
2363 goto out_release_uncharge_unlock;
2366 if (!pte_none(*dst_pte))
2367 goto out_release_uncharge_unlock;
2369 lru_cache_add_anon(page);
2371 spin_lock_irq(&info->lock);
2373 inode->i_blocks += BLOCKS_PER_PAGE;
2374 shmem_recalc_inode(inode);
2375 spin_unlock_irq(&info->lock);
2377 inc_mm_counter(dst_mm, mm_counter_file(page));
2378 page_add_file_rmap(page, false);
2379 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2381 /* No need to invalidate - it was non-present before */
2382 update_mmu_cache(dst_vma, dst_addr, dst_pte);
2383 pte_unmap_unlock(dst_pte, ptl);
2388 out_release_uncharge_unlock:
2389 pte_unmap_unlock(dst_pte, ptl);
2390 ClearPageDirty(page);
2391 delete_from_page_cache(page);
2392 out_release_uncharge:
2393 mem_cgroup_cancel_charge(page, memcg, false);
2398 shmem_inode_unacct_blocks(inode, 1);
2402 int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2404 struct vm_area_struct *dst_vma,
2405 unsigned long dst_addr,
2406 unsigned long src_addr,
2407 struct page **pagep)
2409 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2410 dst_addr, src_addr, false, pagep);
2413 int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2415 struct vm_area_struct *dst_vma,
2416 unsigned long dst_addr)
2418 struct page *page = NULL;
2420 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2421 dst_addr, 0, true, &page);
2425 static const struct inode_operations shmem_symlink_inode_operations;
2426 static const struct inode_operations shmem_short_symlink_operations;
2428 #ifdef CONFIG_TMPFS_XATTR
2429 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2431 #define shmem_initxattrs NULL
2435 shmem_write_begin(struct file *file, struct address_space *mapping,
2436 loff_t pos, unsigned len, unsigned flags,
2437 struct page **pagep, void **fsdata)
2439 struct inode *inode = mapping->host;
2440 struct shmem_inode_info *info = SHMEM_I(inode);
2441 pgoff_t index = pos >> PAGE_SHIFT;
2443 /* i_mutex is held by caller */
2444 if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
2445 if (info->seals & F_SEAL_WRITE)
2447 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2451 return shmem_getpage(inode, index, pagep, SGP_WRITE);
2455 shmem_write_end(struct file *file, struct address_space *mapping,
2456 loff_t pos, unsigned len, unsigned copied,
2457 struct page *page, void *fsdata)
2459 struct inode *inode = mapping->host;
2461 if (pos + copied > inode->i_size)
2462 i_size_write(inode, pos + copied);
2464 if (!PageUptodate(page)) {
2465 struct page *head = compound_head(page);
2466 if (PageTransCompound(page)) {
2469 for (i = 0; i < HPAGE_PMD_NR; i++) {
2470 if (head + i == page)
2472 clear_highpage(head + i);
2473 flush_dcache_page(head + i);
2476 if (copied < PAGE_SIZE) {
2477 unsigned from = pos & (PAGE_SIZE - 1);
2478 zero_user_segments(page, 0, from,
2479 from + copied, PAGE_SIZE);
2481 SetPageUptodate(head);
2483 set_page_dirty(page);
2490 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2492 struct file *file = iocb->ki_filp;
2493 struct inode *inode = file_inode(file);
2494 struct address_space *mapping = inode->i_mapping;
2496 unsigned long offset;
2497 enum sgp_type sgp = SGP_READ;
2500 loff_t *ppos = &iocb->ki_pos;
2503 * Might this read be for a stacking filesystem? Then when reading
2504 * holes of a sparse file, we actually need to allocate those pages,
2505 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2507 if (!iter_is_iovec(to))
2510 index = *ppos >> PAGE_SHIFT;
2511 offset = *ppos & ~PAGE_MASK;
2514 struct page *page = NULL;
2516 unsigned long nr, ret;
2517 loff_t i_size = i_size_read(inode);
2519 end_index = i_size >> PAGE_SHIFT;
2520 if (index > end_index)
2522 if (index == end_index) {
2523 nr = i_size & ~PAGE_MASK;
2528 error = shmem_getpage(inode, index, &page, sgp);
2530 if (error == -EINVAL)
2535 if (sgp == SGP_CACHE)
2536 set_page_dirty(page);
2541 * We must evaluate after, since reads (unlike writes)
2542 * are called without i_mutex protection against truncate
2545 i_size = i_size_read(inode);
2546 end_index = i_size >> PAGE_SHIFT;
2547 if (index == end_index) {
2548 nr = i_size & ~PAGE_MASK;
2559 * If users can be writing to this page using arbitrary
2560 * virtual addresses, take care about potential aliasing
2561 * before reading the page on the kernel side.
2563 if (mapping_writably_mapped(mapping))
2564 flush_dcache_page(page);
2566 * Mark the page accessed if we read the beginning.
2569 mark_page_accessed(page);
2571 page = ZERO_PAGE(0);
2576 * Ok, we have the page, and it's up-to-date, so
2577 * now we can copy it to user space...
2579 ret = copy_page_to_iter(page, offset, nr, to);
2582 index += offset >> PAGE_SHIFT;
2583 offset &= ~PAGE_MASK;
2586 if (!iov_iter_count(to))
2595 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2596 file_accessed(file);
2597 return retval ? retval : error;
2601 * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
2603 static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2604 pgoff_t index, pgoff_t end, int whence)
2607 struct pagevec pvec;
2608 pgoff_t indices[PAGEVEC_SIZE];
2612 pagevec_init(&pvec);
2613 pvec.nr = 1; /* start small: we may be there already */
2615 pvec.nr = find_get_entries(mapping, index,
2616 pvec.nr, pvec.pages, indices);
2618 if (whence == SEEK_DATA)
2622 for (i = 0; i < pvec.nr; i++, index++) {
2623 if (index < indices[i]) {
2624 if (whence == SEEK_HOLE) {
2630 page = pvec.pages[i];
2631 if (page && !radix_tree_exceptional_entry(page)) {
2632 if (!PageUptodate(page))
2636 (page && whence == SEEK_DATA) ||
2637 (!page && whence == SEEK_HOLE)) {
2642 pagevec_remove_exceptionals(&pvec);
2643 pagevec_release(&pvec);
2644 pvec.nr = PAGEVEC_SIZE;
2650 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2652 struct address_space *mapping = file->f_mapping;
2653 struct inode *inode = mapping->host;
2657 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2658 return generic_file_llseek_size(file, offset, whence,
2659 MAX_LFS_FILESIZE, i_size_read(inode));
2661 /* We're holding i_mutex so we can access i_size directly */
2663 if (offset < 0 || offset >= inode->i_size)
2666 start = offset >> PAGE_SHIFT;
2667 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2668 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
2669 new_offset <<= PAGE_SHIFT;
2670 if (new_offset > offset) {
2671 if (new_offset < inode->i_size)
2672 offset = new_offset;
2673 else if (whence == SEEK_DATA)
2676 offset = inode->i_size;
2681 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2682 inode_unlock(inode);
2686 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2689 struct inode *inode = file_inode(file);
2690 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2691 struct shmem_inode_info *info = SHMEM_I(inode);
2692 struct shmem_falloc shmem_falloc;
2693 pgoff_t start, index, end;
2696 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2701 if (mode & FALLOC_FL_PUNCH_HOLE) {
2702 struct address_space *mapping = file->f_mapping;
2703 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2704 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2705 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2707 /* protected by i_mutex */
2708 if (info->seals & F_SEAL_WRITE) {
2713 shmem_falloc.waitq = &shmem_falloc_waitq;
2714 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
2715 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2716 spin_lock(&inode->i_lock);
2717 inode->i_private = &shmem_falloc;
2718 spin_unlock(&inode->i_lock);
2720 if ((u64)unmap_end > (u64)unmap_start)
2721 unmap_mapping_range(mapping, unmap_start,
2722 1 + unmap_end - unmap_start, 0);
2723 shmem_truncate_range(inode, offset, offset + len - 1);
2724 /* No need to unmap again: hole-punching leaves COWed pages */
2726 spin_lock(&inode->i_lock);
2727 inode->i_private = NULL;
2728 wake_up_all(&shmem_falloc_waitq);
2729 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2730 spin_unlock(&inode->i_lock);
2735 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2736 error = inode_newsize_ok(inode, offset + len);
2740 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2745 start = offset >> PAGE_SHIFT;
2746 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2747 /* Try to avoid a swapstorm if len is impossible to satisfy */
2748 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2753 shmem_falloc.waitq = NULL;
2754 shmem_falloc.start = start;
2755 shmem_falloc.next = start;
2756 shmem_falloc.nr_falloced = 0;
2757 shmem_falloc.nr_unswapped = 0;
2758 spin_lock(&inode->i_lock);
2759 inode->i_private = &shmem_falloc;
2760 spin_unlock(&inode->i_lock);
2762 for (index = start; index < end; index++) {
2766 * Good, the fallocate(2) manpage permits EINTR: we may have
2767 * been interrupted because we are using up too much memory.
2769 if (signal_pending(current))
2771 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2774 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2776 /* Remove the !PageUptodate pages we added */
2777 if (index > start) {
2778 shmem_undo_range(inode,
2779 (loff_t)start << PAGE_SHIFT,
2780 ((loff_t)index << PAGE_SHIFT) - 1, true);
2786 * Inform shmem_writepage() how far we have reached.
2787 * No need for lock or barrier: we have the page lock.
2789 shmem_falloc.next++;
2790 if (!PageUptodate(page))
2791 shmem_falloc.nr_falloced++;
2794 * If !PageUptodate, leave it that way so that freeable pages
2795 * can be recognized if we need to rollback on error later.
2796 * But set_page_dirty so that memory pressure will swap rather
2797 * than free the pages we are allocating (and SGP_CACHE pages
2798 * might still be clean: we now need to mark those dirty too).
2800 set_page_dirty(page);
2806 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2807 i_size_write(inode, offset + len);
2808 inode->i_ctime = current_time(inode);
2810 spin_lock(&inode->i_lock);
2811 inode->i_private = NULL;
2812 spin_unlock(&inode->i_lock);
2814 inode_unlock(inode);
2818 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2820 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2822 buf->f_type = TMPFS_MAGIC;
2823 buf->f_bsize = PAGE_SIZE;
2824 buf->f_namelen = NAME_MAX;
2825 if (sbinfo->max_blocks) {
2826 buf->f_blocks = sbinfo->max_blocks;
2828 buf->f_bfree = sbinfo->max_blocks -
2829 percpu_counter_sum(&sbinfo->used_blocks);
2831 if (sbinfo->max_inodes) {
2832 buf->f_files = sbinfo->max_inodes;
2833 buf->f_ffree = sbinfo->free_inodes;
2835 /* else leave those fields 0 like simple_statfs */
2840 * File creation. Allocate an inode, and we're done..
2843 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2845 struct inode *inode;
2846 int error = -ENOSPC;
2848 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2850 error = simple_acl_create(dir, inode);
2853 error = security_inode_init_security(inode, dir,
2855 shmem_initxattrs, NULL);
2856 if (error && error != -EOPNOTSUPP)
2860 dir->i_size += BOGO_DIRENT_SIZE;
2861 dir->i_ctime = dir->i_mtime = current_time(dir);
2862 d_instantiate(dentry, inode);
2863 dget(dentry); /* Extra count - pin the dentry in core */
2872 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2874 struct inode *inode;
2875 int error = -ENOSPC;
2877 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2879 error = security_inode_init_security(inode, dir,
2881 shmem_initxattrs, NULL);
2882 if (error && error != -EOPNOTSUPP)
2884 error = simple_acl_create(dir, inode);
2887 d_tmpfile(dentry, inode);
2895 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2899 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
2905 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2908 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
2914 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2916 struct inode *inode = d_inode(old_dentry);
2920 * No ordinary (disk based) filesystem counts links as inodes;
2921 * but each new link needs a new dentry, pinning lowmem, and
2922 * tmpfs dentries cannot be pruned until they are unlinked.
2923 * But if an O_TMPFILE file is linked into the tmpfs, the
2924 * first link must skip that, to get the accounting right.
2926 if (inode->i_nlink) {
2927 ret = shmem_reserve_inode(inode->i_sb);
2932 dir->i_size += BOGO_DIRENT_SIZE;
2933 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2935 ihold(inode); /* New dentry reference */
2936 dget(dentry); /* Extra pinning count for the created dentry */
2937 d_instantiate(dentry, inode);
2942 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
2944 struct inode *inode = d_inode(dentry);
2946 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
2947 shmem_free_inode(inode->i_sb);
2949 dir->i_size -= BOGO_DIRENT_SIZE;
2950 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2952 dput(dentry); /* Undo the count from "create" - this does all the work */
2956 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
2958 if (!simple_empty(dentry))
2961 drop_nlink(d_inode(dentry));
2963 return shmem_unlink(dir, dentry);
2966 static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
2968 bool old_is_dir = d_is_dir(old_dentry);
2969 bool new_is_dir = d_is_dir(new_dentry);
2971 if (old_dir != new_dir && old_is_dir != new_is_dir) {
2973 drop_nlink(old_dir);
2976 drop_nlink(new_dir);
2980 old_dir->i_ctime = old_dir->i_mtime =
2981 new_dir->i_ctime = new_dir->i_mtime =
2982 d_inode(old_dentry)->i_ctime =
2983 d_inode(new_dentry)->i_ctime = current_time(old_dir);
2988 static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
2990 struct dentry *whiteout;
2993 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
2997 error = shmem_mknod(old_dir, whiteout,
2998 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
3004 * Cheat and hash the whiteout while the old dentry is still in
3005 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3007 * d_lookup() will consistently find one of them at this point,
3008 * not sure which one, but that isn't even important.
3015 * The VFS layer already does all the dentry stuff for rename,
3016 * we just have to decrement the usage count for the target if
3017 * it exists so that the VFS layer correctly free's it when it
3020 static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
3022 struct inode *inode = d_inode(old_dentry);
3023 int they_are_dirs = S_ISDIR(inode->i_mode);
3025 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3028 if (flags & RENAME_EXCHANGE)
3029 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
3031 if (!simple_empty(new_dentry))
3034 if (flags & RENAME_WHITEOUT) {
3037 error = shmem_whiteout(old_dir, old_dentry);
3042 if (d_really_is_positive(new_dentry)) {
3043 (void) shmem_unlink(new_dir, new_dentry);
3044 if (they_are_dirs) {
3045 drop_nlink(d_inode(new_dentry));
3046 drop_nlink(old_dir);
3048 } else if (they_are_dirs) {
3049 drop_nlink(old_dir);
3053 old_dir->i_size -= BOGO_DIRENT_SIZE;
3054 new_dir->i_size += BOGO_DIRENT_SIZE;
3055 old_dir->i_ctime = old_dir->i_mtime =
3056 new_dir->i_ctime = new_dir->i_mtime =
3057 inode->i_ctime = current_time(old_dir);
3061 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
3065 struct inode *inode;
3068 len = strlen(symname) + 1;
3069 if (len > PAGE_SIZE)
3070 return -ENAMETOOLONG;
3072 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
3077 error = security_inode_init_security(inode, dir, &dentry->d_name,
3078 shmem_initxattrs, NULL);
3080 if (error != -EOPNOTSUPP) {
3087 inode->i_size = len-1;
3088 if (len <= SHORT_SYMLINK_LEN) {
3089 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3090 if (!inode->i_link) {
3094 inode->i_op = &shmem_short_symlink_operations;
3096 inode_nohighmem(inode);
3097 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
3102 inode->i_mapping->a_ops = &shmem_aops;
3103 inode->i_op = &shmem_symlink_inode_operations;
3104 memcpy(page_address(page), symname, len);
3105 SetPageUptodate(page);
3106 set_page_dirty(page);
3110 dir->i_size += BOGO_DIRENT_SIZE;
3111 dir->i_ctime = dir->i_mtime = current_time(dir);
3112 d_instantiate(dentry, inode);
3117 static void shmem_put_link(void *arg)
3119 mark_page_accessed(arg);
3123 static const char *shmem_get_link(struct dentry *dentry,
3124 struct inode *inode,
3125 struct delayed_call *done)
3127 struct page *page = NULL;
3130 page = find_get_page(inode->i_mapping, 0);
3132 return ERR_PTR(-ECHILD);
3133 if (!PageUptodate(page)) {
3135 return ERR_PTR(-ECHILD);
3138 error = shmem_getpage(inode, 0, &page, SGP_READ);
3140 return ERR_PTR(error);
3143 set_delayed_call(done, shmem_put_link, page);
3144 return page_address(page);
3147 #ifdef CONFIG_TMPFS_XATTR
3149 * Superblocks without xattr inode operations may get some security.* xattr
3150 * support from the LSM "for free". As soon as we have any other xattrs
3151 * like ACLs, we also need to implement the security.* handlers at
3152 * filesystem level, though.
3156 * Callback for security_inode_init_security() for acquiring xattrs.
3158 static int shmem_initxattrs(struct inode *inode,
3159 const struct xattr *xattr_array,
3162 struct shmem_inode_info *info = SHMEM_I(inode);
3163 const struct xattr *xattr;
3164 struct simple_xattr *new_xattr;
3167 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3168 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3172 len = strlen(xattr->name) + 1;
3173 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3175 if (!new_xattr->name) {
3180 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3181 XATTR_SECURITY_PREFIX_LEN);
3182 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3185 simple_xattr_list_add(&info->xattrs, new_xattr);
3191 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3192 struct dentry *unused, struct inode *inode,
3193 const char *name, void *buffer, size_t size)
3195 struct shmem_inode_info *info = SHMEM_I(inode);
3197 name = xattr_full_name(handler, name);
3198 return simple_xattr_get(&info->xattrs, name, buffer, size);
3201 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3202 struct dentry *unused, struct inode *inode,
3203 const char *name, const void *value,
3204 size_t size, int flags)
3206 struct shmem_inode_info *info = SHMEM_I(inode);
3208 name = xattr_full_name(handler, name);
3209 return simple_xattr_set(&info->xattrs, name, value, size, flags);
3212 static const struct xattr_handler shmem_security_xattr_handler = {
3213 .prefix = XATTR_SECURITY_PREFIX,
3214 .get = shmem_xattr_handler_get,
3215 .set = shmem_xattr_handler_set,
3218 static const struct xattr_handler shmem_trusted_xattr_handler = {
3219 .prefix = XATTR_TRUSTED_PREFIX,
3220 .get = shmem_xattr_handler_get,
3221 .set = shmem_xattr_handler_set,
3224 static const struct xattr_handler *shmem_xattr_handlers[] = {
3225 #ifdef CONFIG_TMPFS_POSIX_ACL
3226 &posix_acl_access_xattr_handler,
3227 &posix_acl_default_xattr_handler,
3229 &shmem_security_xattr_handler,
3230 &shmem_trusted_xattr_handler,
3234 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3236 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3237 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3239 #endif /* CONFIG_TMPFS_XATTR */
3241 static const struct inode_operations shmem_short_symlink_operations = {
3242 .get_link = simple_get_link,
3243 #ifdef CONFIG_TMPFS_XATTR
3244 .listxattr = shmem_listxattr,
3248 static const struct inode_operations shmem_symlink_inode_operations = {
3249 .get_link = shmem_get_link,
3250 #ifdef CONFIG_TMPFS_XATTR
3251 .listxattr = shmem_listxattr,
3255 static struct dentry *shmem_get_parent(struct dentry *child)
3257 return ERR_PTR(-ESTALE);
3260 static int shmem_match(struct inode *ino, void *vfh)
3264 inum = (inum << 32) | fh[1];
3265 return ino->i_ino == inum && fh[0] == ino->i_generation;
3268 /* Find any alias of inode, but prefer a hashed alias */
3269 static struct dentry *shmem_find_alias(struct inode *inode)
3271 struct dentry *alias = d_find_alias(inode);
3273 return alias ?: d_find_any_alias(inode);
3277 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3278 struct fid *fid, int fh_len, int fh_type)
3280 struct inode *inode;
3281 struct dentry *dentry = NULL;
3288 inum = (inum << 32) | fid->raw[1];
3290 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3291 shmem_match, fid->raw);
3293 dentry = shmem_find_alias(inode);
3300 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3301 struct inode *parent)
3305 return FILEID_INVALID;
3308 if (inode_unhashed(inode)) {
3309 /* Unfortunately insert_inode_hash is not idempotent,
3310 * so as we hash inodes here rather than at creation
3311 * time, we need a lock to ensure we only try
3314 static DEFINE_SPINLOCK(lock);
3316 if (inode_unhashed(inode))
3317 __insert_inode_hash(inode,
3318 inode->i_ino + inode->i_generation);
3322 fh[0] = inode->i_generation;
3323 fh[1] = inode->i_ino;
3324 fh[2] = ((__u64)inode->i_ino) >> 32;
3330 static const struct export_operations shmem_export_ops = {
3331 .get_parent = shmem_get_parent,
3332 .encode_fh = shmem_encode_fh,
3333 .fh_to_dentry = shmem_fh_to_dentry,
3336 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
3339 char *this_char, *value, *rest;
3340 struct mempolicy *mpol = NULL;
3344 while (options != NULL) {
3345 this_char = options;
3348 * NUL-terminate this option: unfortunately,
3349 * mount options form a comma-separated list,
3350 * but mpol's nodelist may also contain commas.
3352 options = strchr(options, ',');
3353 if (options == NULL)
3356 if (!isdigit(*options)) {
3363 if ((value = strchr(this_char,'=')) != NULL) {
3366 pr_err("tmpfs: No value for mount option '%s'\n",
3371 if (!strcmp(this_char,"size")) {
3372 unsigned long long size;
3373 size = memparse(value,&rest);
3375 size <<= PAGE_SHIFT;
3376 size *= totalram_pages;
3382 sbinfo->max_blocks =
3383 DIV_ROUND_UP(size, PAGE_SIZE);
3384 } else if (!strcmp(this_char,"nr_blocks")) {
3385 sbinfo->max_blocks = memparse(value, &rest);
3388 } else if (!strcmp(this_char,"nr_inodes")) {
3389 sbinfo->max_inodes = memparse(value, &rest);
3392 } else if (!strcmp(this_char,"mode")) {
3395 sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
3398 } else if (!strcmp(this_char,"uid")) {
3401 uid = simple_strtoul(value, &rest, 0);
3404 sbinfo->uid = make_kuid(current_user_ns(), uid);
3405 if (!uid_valid(sbinfo->uid))
3407 } else if (!strcmp(this_char,"gid")) {
3410 gid = simple_strtoul(value, &rest, 0);
3413 sbinfo->gid = make_kgid(current_user_ns(), gid);
3414 if (!gid_valid(sbinfo->gid))
3416 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3417 } else if (!strcmp(this_char, "huge")) {
3419 huge = shmem_parse_huge(value);
3422 if (!has_transparent_hugepage() &&
3423 huge != SHMEM_HUGE_NEVER)
3425 sbinfo->huge = huge;
3428 } else if (!strcmp(this_char,"mpol")) {
3431 if (mpol_parse_str(value, &mpol))
3435 pr_err("tmpfs: Bad mount option %s\n", this_char);
3439 sbinfo->mpol = mpol;
3443 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3451 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
3453 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3454 struct shmem_sb_info config = *sbinfo;
3455 unsigned long inodes;
3456 int error = -EINVAL;
3459 if (shmem_parse_options(data, &config, true))
3462 spin_lock(&sbinfo->stat_lock);
3463 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3464 if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
3466 if (config.max_inodes < inodes)
3469 * Those tests disallow limited->unlimited while any are in use;
3470 * but we must separately disallow unlimited->limited, because
3471 * in that case we have no record of how much is already in use.
3473 if (config.max_blocks && !sbinfo->max_blocks)
3475 if (config.max_inodes && !sbinfo->max_inodes)
3479 sbinfo->huge = config.huge;
3480 sbinfo->max_blocks = config.max_blocks;
3481 sbinfo->max_inodes = config.max_inodes;
3482 sbinfo->free_inodes = config.max_inodes - inodes;
3485 * Preserve previous mempolicy unless mpol remount option was specified.
3488 mpol_put(sbinfo->mpol);
3489 sbinfo->mpol = config.mpol; /* transfers initial ref */
3492 spin_unlock(&sbinfo->stat_lock);
3496 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3498 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3500 if (sbinfo->max_blocks != shmem_default_max_blocks())
3501 seq_printf(seq, ",size=%luk",
3502 sbinfo->max_blocks << (PAGE_SHIFT - 10));
3503 if (sbinfo->max_inodes != shmem_default_max_inodes())
3504 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3505 if (sbinfo->mode != (0777 | S_ISVTX))
3506 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3507 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3508 seq_printf(seq, ",uid=%u",
3509 from_kuid_munged(&init_user_ns, sbinfo->uid));
3510 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3511 seq_printf(seq, ",gid=%u",
3512 from_kgid_munged(&init_user_ns, sbinfo->gid));
3513 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3514 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3516 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3518 shmem_show_mpol(seq, sbinfo->mpol);
3522 #endif /* CONFIG_TMPFS */
3524 static void shmem_put_super(struct super_block *sb)
3526 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3528 percpu_counter_destroy(&sbinfo->used_blocks);
3529 mpol_put(sbinfo->mpol);
3531 sb->s_fs_info = NULL;
3534 int shmem_fill_super(struct super_block *sb, void *data, int silent)
3536 struct inode *inode;
3537 struct shmem_sb_info *sbinfo;
3540 /* Round up to L1_CACHE_BYTES to resist false sharing */
3541 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3542 L1_CACHE_BYTES), GFP_KERNEL);
3546 sbinfo->mode = 0777 | S_ISVTX;
3547 sbinfo->uid = current_fsuid();
3548 sbinfo->gid = current_fsgid();
3549 sb->s_fs_info = sbinfo;
3553 * Per default we only allow half of the physical ram per
3554 * tmpfs instance, limiting inodes to one per page of lowmem;
3555 * but the internal instance is left unlimited.
3557 if (!(sb->s_flags & SB_KERNMOUNT)) {
3558 sbinfo->max_blocks = shmem_default_max_blocks();
3559 sbinfo->max_inodes = shmem_default_max_inodes();
3560 if (shmem_parse_options(data, sbinfo, false)) {
3565 sb->s_flags |= SB_NOUSER;
3567 sb->s_export_op = &shmem_export_ops;
3568 sb->s_flags |= SB_NOSEC;
3570 sb->s_flags |= SB_NOUSER;
3573 spin_lock_init(&sbinfo->stat_lock);
3574 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3576 sbinfo->free_inodes = sbinfo->max_inodes;
3577 spin_lock_init(&sbinfo->shrinklist_lock);
3578 INIT_LIST_HEAD(&sbinfo->shrinklist);
3580 sb->s_maxbytes = MAX_LFS_FILESIZE;
3581 sb->s_blocksize = PAGE_SIZE;
3582 sb->s_blocksize_bits = PAGE_SHIFT;
3583 sb->s_magic = TMPFS_MAGIC;
3584 sb->s_op = &shmem_ops;
3585 sb->s_time_gran = 1;
3586 #ifdef CONFIG_TMPFS_XATTR
3587 sb->s_xattr = shmem_xattr_handlers;
3589 #ifdef CONFIG_TMPFS_POSIX_ACL
3590 sb->s_flags |= SB_POSIXACL;
3592 uuid_gen(&sb->s_uuid);
3594 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3597 inode->i_uid = sbinfo->uid;
3598 inode->i_gid = sbinfo->gid;
3599 sb->s_root = d_make_root(inode);
3605 shmem_put_super(sb);
3609 static struct kmem_cache *shmem_inode_cachep;
3611 static struct inode *shmem_alloc_inode(struct super_block *sb)
3613 struct shmem_inode_info *info;
3614 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3617 return &info->vfs_inode;
3620 static void shmem_destroy_callback(struct rcu_head *head)
3622 struct inode *inode = container_of(head, struct inode, i_rcu);
3623 if (S_ISLNK(inode->i_mode))
3624 kfree(inode->i_link);
3625 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3628 static void shmem_destroy_inode(struct inode *inode)
3630 if (S_ISREG(inode->i_mode))
3631 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3632 call_rcu(&inode->i_rcu, shmem_destroy_callback);
3635 static void shmem_init_inode(void *foo)
3637 struct shmem_inode_info *info = foo;
3638 inode_init_once(&info->vfs_inode);
3641 static void shmem_init_inodecache(void)
3643 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3644 sizeof(struct shmem_inode_info),
3645 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3648 static void shmem_destroy_inodecache(void)
3650 kmem_cache_destroy(shmem_inode_cachep);
3653 static const struct address_space_operations shmem_aops = {
3654 .writepage = shmem_writepage,
3655 .set_page_dirty = __set_page_dirty_no_writeback,
3657 .write_begin = shmem_write_begin,
3658 .write_end = shmem_write_end,
3660 #ifdef CONFIG_MIGRATION
3661 .migratepage = migrate_page,
3663 .error_remove_page = generic_error_remove_page,
3666 static const struct file_operations shmem_file_operations = {
3668 .get_unmapped_area = shmem_get_unmapped_area,
3670 .llseek = shmem_file_llseek,
3671 .read_iter = shmem_file_read_iter,
3672 .write_iter = generic_file_write_iter,
3673 .fsync = noop_fsync,
3674 .splice_read = generic_file_splice_read,
3675 .splice_write = iter_file_splice_write,
3676 .fallocate = shmem_fallocate,
3680 static const struct inode_operations shmem_inode_operations = {
3681 .getattr = shmem_getattr,
3682 .setattr = shmem_setattr,
3683 #ifdef CONFIG_TMPFS_XATTR
3684 .listxattr = shmem_listxattr,
3685 .set_acl = simple_set_acl,
3689 static const struct inode_operations shmem_dir_inode_operations = {
3691 .create = shmem_create,
3692 .lookup = simple_lookup,
3694 .unlink = shmem_unlink,
3695 .symlink = shmem_symlink,
3696 .mkdir = shmem_mkdir,
3697 .rmdir = shmem_rmdir,
3698 .mknod = shmem_mknod,
3699 .rename = shmem_rename2,
3700 .tmpfile = shmem_tmpfile,
3702 #ifdef CONFIG_TMPFS_XATTR
3703 .listxattr = shmem_listxattr,
3705 #ifdef CONFIG_TMPFS_POSIX_ACL
3706 .setattr = shmem_setattr,
3707 .set_acl = simple_set_acl,
3711 static const struct inode_operations shmem_special_inode_operations = {
3712 #ifdef CONFIG_TMPFS_XATTR
3713 .listxattr = shmem_listxattr,
3715 #ifdef CONFIG_TMPFS_POSIX_ACL
3716 .setattr = shmem_setattr,
3717 .set_acl = simple_set_acl,
3721 static const struct super_operations shmem_ops = {
3722 .alloc_inode = shmem_alloc_inode,
3723 .destroy_inode = shmem_destroy_inode,
3725 .statfs = shmem_statfs,
3726 .remount_fs = shmem_remount_fs,
3727 .show_options = shmem_show_options,
3729 .evict_inode = shmem_evict_inode,
3730 .drop_inode = generic_delete_inode,
3731 .put_super = shmem_put_super,
3732 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3733 .nr_cached_objects = shmem_unused_huge_count,
3734 .free_cached_objects = shmem_unused_huge_scan,
3738 static const struct vm_operations_struct shmem_vm_ops = {
3739 .fault = shmem_fault,
3740 .map_pages = filemap_map_pages,
3742 .set_policy = shmem_set_policy,
3743 .get_policy = shmem_get_policy,
3747 static struct dentry *shmem_mount(struct file_system_type *fs_type,
3748 int flags, const char *dev_name, void *data)
3750 return mount_nodev(fs_type, flags, data, shmem_fill_super);
3753 static struct file_system_type shmem_fs_type = {
3754 .owner = THIS_MODULE,
3756 .mount = shmem_mount,
3757 .kill_sb = kill_litter_super,
3758 .fs_flags = FS_USERNS_MOUNT,
3761 int __init shmem_init(void)
3765 /* If rootfs called this, don't re-init */
3766 if (shmem_inode_cachep)
3769 shmem_init_inodecache();
3771 error = register_filesystem(&shmem_fs_type);
3773 pr_err("Could not register tmpfs\n");
3777 shm_mnt = kern_mount(&shmem_fs_type);
3778 if (IS_ERR(shm_mnt)) {
3779 error = PTR_ERR(shm_mnt);
3780 pr_err("Could not kern_mount tmpfs\n");
3784 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3785 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
3786 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3788 shmem_huge = 0; /* just in case it was patched */
3793 unregister_filesystem(&shmem_fs_type);
3795 shmem_destroy_inodecache();
3796 shm_mnt = ERR_PTR(error);
3800 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
3801 static ssize_t shmem_enabled_show(struct kobject *kobj,
3802 struct kobj_attribute *attr, char *buf)
3806 SHMEM_HUGE_WITHIN_SIZE,
3814 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
3815 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
3817 count += sprintf(buf + count, fmt,
3818 shmem_format_huge(values[i]));
3820 buf[count - 1] = '\n';
3824 static ssize_t shmem_enabled_store(struct kobject *kobj,
3825 struct kobj_attribute *attr, const char *buf, size_t count)
3830 if (count + 1 > sizeof(tmp))
3832 memcpy(tmp, buf, count);
3834 if (count && tmp[count - 1] == '\n')
3835 tmp[count - 1] = '\0';
3837 huge = shmem_parse_huge(tmp);
3838 if (huge == -EINVAL)
3840 if (!has_transparent_hugepage() &&
3841 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
3845 if (shmem_huge > SHMEM_HUGE_DENY)
3846 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3850 struct kobj_attribute shmem_enabled_attr =
3851 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
3852 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
3854 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3855 bool shmem_huge_enabled(struct vm_area_struct *vma)
3857 struct inode *inode = file_inode(vma->vm_file);
3858 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3862 if (shmem_huge == SHMEM_HUGE_FORCE)
3864 if (shmem_huge == SHMEM_HUGE_DENY)
3866 switch (sbinfo->huge) {
3867 case SHMEM_HUGE_NEVER:
3869 case SHMEM_HUGE_ALWAYS:
3871 case SHMEM_HUGE_WITHIN_SIZE:
3872 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
3873 i_size = round_up(i_size_read(inode), PAGE_SIZE);
3874 if (i_size >= HPAGE_PMD_SIZE &&
3875 i_size >> PAGE_SHIFT >= off)
3878 case SHMEM_HUGE_ADVISE:
3879 /* TODO: implement fadvise() hints */
3880 return (vma->vm_flags & VM_HUGEPAGE);
3886 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
3888 #else /* !CONFIG_SHMEM */
3891 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3893 * This is intended for small system where the benefits of the full
3894 * shmem code (swap-backed and resource-limited) are outweighed by
3895 * their complexity. On systems without swap this code should be
3896 * effectively equivalent, but much lighter weight.
3899 static struct file_system_type shmem_fs_type = {
3901 .mount = ramfs_mount,
3902 .kill_sb = kill_litter_super,
3903 .fs_flags = FS_USERNS_MOUNT,
3906 int __init shmem_init(void)
3908 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3910 shm_mnt = kern_mount(&shmem_fs_type);
3911 BUG_ON(IS_ERR(shm_mnt));
3916 int shmem_unuse(swp_entry_t swap, struct page *page)
3921 int shmem_lock(struct file *file, int lock, struct user_struct *user)
3926 void shmem_unlock_mapping(struct address_space *mapping)
3931 unsigned long shmem_get_unmapped_area(struct file *file,
3932 unsigned long addr, unsigned long len,
3933 unsigned long pgoff, unsigned long flags)
3935 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
3939 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
3941 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
3943 EXPORT_SYMBOL_GPL(shmem_truncate_range);
3945 #define shmem_vm_ops generic_file_vm_ops
3946 #define shmem_file_operations ramfs_file_operations
3947 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
3948 #define shmem_acct_size(flags, size) 0
3949 #define shmem_unacct_size(flags, size) do {} while (0)
3951 #endif /* CONFIG_SHMEM */
3955 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
3956 unsigned long flags, unsigned int i_flags)
3958 struct inode *inode;
3962 return ERR_CAST(mnt);
3964 if (size < 0 || size > MAX_LFS_FILESIZE)
3965 return ERR_PTR(-EINVAL);
3967 if (shmem_acct_size(flags, size))
3968 return ERR_PTR(-ENOMEM);
3970 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
3972 if (unlikely(!inode)) {
3973 shmem_unacct_size(flags, size);
3974 return ERR_PTR(-ENOSPC);
3976 inode->i_flags |= i_flags;
3977 inode->i_size = size;
3978 clear_nlink(inode); /* It is unlinked */
3979 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
3981 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
3982 &shmem_file_operations);
3989 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
3990 * kernel internal. There will be NO LSM permission checks against the
3991 * underlying inode. So users of this interface must do LSM checks at a
3992 * higher layer. The users are the big_key and shm implementations. LSM
3993 * checks are provided at the key or shm level rather than the inode.
3994 * @name: name for dentry (to be seen in /proc/<pid>/maps
3995 * @size: size to be set for the file
3996 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3998 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4000 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
4004 * shmem_file_setup - get an unlinked file living in tmpfs
4005 * @name: name for dentry (to be seen in /proc/<pid>/maps
4006 * @size: size to be set for the file
4007 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4009 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4011 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
4013 EXPORT_SYMBOL_GPL(shmem_file_setup);
4016 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4017 * @mnt: the tmpfs mount where the file will be created
4018 * @name: name for dentry (to be seen in /proc/<pid>/maps
4019 * @size: size to be set for the file
4020 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4022 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
4023 loff_t size, unsigned long flags)
4025 return __shmem_file_setup(mnt, name, size, flags, 0);
4027 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
4030 * shmem_zero_setup - setup a shared anonymous mapping
4031 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
4033 int shmem_zero_setup(struct vm_area_struct *vma)
4036 loff_t size = vma->vm_end - vma->vm_start;
4039 * Cloning a new file under mmap_sem leads to a lock ordering conflict
4040 * between XFS directory reading and selinux: since this file is only
4041 * accessible to the user through its mapping, use S_PRIVATE flag to
4042 * bypass file security, in the same way as shmem_kernel_file_setup().
4044 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
4046 return PTR_ERR(file);
4050 vma->vm_file = file;
4051 vma->vm_ops = &shmem_vm_ops;
4053 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
4054 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4055 (vma->vm_end & HPAGE_PMD_MASK)) {
4056 khugepaged_enter(vma, vma->vm_flags);
4063 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4064 * @mapping: the page's address_space
4065 * @index: the page index
4066 * @gfp: the page allocator flags to use if allocating
4068 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4069 * with any new page allocations done using the specified allocation flags.
4070 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4071 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4072 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4074 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4075 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4077 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4078 pgoff_t index, gfp_t gfp)
4081 struct inode *inode = mapping->host;
4085 BUG_ON(mapping->a_ops != &shmem_aops);
4086 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4087 gfp, NULL, NULL, NULL);
4089 page = ERR_PTR(error);
4095 * The tiny !SHMEM case uses ramfs without swap
4097 return read_cache_page_gfp(mapping, index, gfp);
4100 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);