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/sched/signal.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/uio.h>
36 #include <linux/khugepaged.h>
37 #include <linux/hugetlb.h>
39 #include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
41 static struct vfsmount *shm_mnt;
45 * This virtual memory filesystem is heavily based on the ramfs. It
46 * extends ramfs by the ability to use swap and honor resource limits
47 * which makes it a completely usable filesystem.
50 #include <linux/xattr.h>
51 #include <linux/exportfs.h>
52 #include <linux/posix_acl.h>
53 #include <linux/posix_acl_xattr.h>
54 #include <linux/mman.h>
55 #include <linux/string.h>
56 #include <linux/slab.h>
57 #include <linux/backing-dev.h>
58 #include <linux/shmem_fs.h>
59 #include <linux/writeback.h>
60 #include <linux/blkdev.h>
61 #include <linux/pagevec.h>
62 #include <linux/percpu_counter.h>
63 #include <linux/falloc.h>
64 #include <linux/splice.h>
65 #include <linux/security.h>
66 #include <linux/swapops.h>
67 #include <linux/mempolicy.h>
68 #include <linux/namei.h>
69 #include <linux/ctype.h>
70 #include <linux/migrate.h>
71 #include <linux/highmem.h>
72 #include <linux/seq_file.h>
73 #include <linux/magic.h>
74 #include <linux/syscalls.h>
75 #include <linux/fcntl.h>
76 #include <uapi/linux/memfd.h>
77 #include <linux/userfaultfd_k.h>
78 #include <linux/rmap.h>
79 #include <linux/uuid.h>
81 #include <linux/uaccess.h>
82 #include <asm/pgtable.h>
86 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
87 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
89 /* Pretend that each entry is of this size in directory's i_size */
90 #define BOGO_DIRENT_SIZE 20
92 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
93 #define SHORT_SYMLINK_LEN 128
96 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
97 * inode->i_private (with i_mutex making sure that it has only one user at
98 * a time): we would prefer not to enlarge the shmem inode just for that.
100 struct shmem_falloc {
101 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
102 pgoff_t start; /* start of range currently being fallocated */
103 pgoff_t next; /* the next page offset to be fallocated */
104 pgoff_t nr_falloced; /* how many new pages have been fallocated */
105 pgoff_t nr_unswapped; /* how often writepage refused to swap out */
109 static unsigned long shmem_default_max_blocks(void)
111 return totalram_pages / 2;
114 static unsigned long shmem_default_max_inodes(void)
116 return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
120 static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
121 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
122 struct shmem_inode_info *info, pgoff_t index);
123 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
124 struct page **pagep, enum sgp_type sgp,
125 gfp_t gfp, struct vm_area_struct *vma,
126 struct vm_fault *vmf, int *fault_type);
128 int shmem_getpage(struct inode *inode, pgoff_t index,
129 struct page **pagep, enum sgp_type sgp)
131 return shmem_getpage_gfp(inode, index, pagep, sgp,
132 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
135 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
137 return sb->s_fs_info;
141 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
142 * for shared memory and for shared anonymous (/dev/zero) mappings
143 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
144 * consistent with the pre-accounting of private mappings ...
146 static inline int shmem_acct_size(unsigned long flags, loff_t size)
148 return (flags & VM_NORESERVE) ?
149 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
152 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
154 if (!(flags & VM_NORESERVE))
155 vm_unacct_memory(VM_ACCT(size));
158 static inline int shmem_reacct_size(unsigned long flags,
159 loff_t oldsize, loff_t newsize)
161 if (!(flags & VM_NORESERVE)) {
162 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
163 return security_vm_enough_memory_mm(current->mm,
164 VM_ACCT(newsize) - VM_ACCT(oldsize));
165 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
166 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
172 * ... whereas tmpfs objects are accounted incrementally as
173 * pages are allocated, in order to allow large sparse files.
174 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
175 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
177 static inline int shmem_acct_block(unsigned long flags, long pages)
179 if (!(flags & VM_NORESERVE))
182 return security_vm_enough_memory_mm(current->mm,
183 pages * VM_ACCT(PAGE_SIZE));
186 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
188 if (flags & VM_NORESERVE)
189 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
192 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
194 struct shmem_inode_info *info = SHMEM_I(inode);
195 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
197 if (shmem_acct_block(info->flags, pages))
200 if (sbinfo->max_blocks) {
201 if (percpu_counter_compare(&sbinfo->used_blocks,
202 sbinfo->max_blocks - pages) > 0)
204 percpu_counter_add(&sbinfo->used_blocks, pages);
210 shmem_unacct_blocks(info->flags, pages);
214 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
216 struct shmem_inode_info *info = SHMEM_I(inode);
217 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
219 if (sbinfo->max_blocks)
220 percpu_counter_sub(&sbinfo->used_blocks, pages);
221 shmem_unacct_blocks(info->flags, pages);
224 static const struct super_operations shmem_ops;
225 static const struct address_space_operations shmem_aops;
226 static const struct file_operations shmem_file_operations;
227 static const struct inode_operations shmem_inode_operations;
228 static const struct inode_operations shmem_dir_inode_operations;
229 static const struct inode_operations shmem_special_inode_operations;
230 static const struct vm_operations_struct shmem_vm_ops;
231 static struct file_system_type shmem_fs_type;
233 bool vma_is_shmem(struct vm_area_struct *vma)
235 return vma->vm_ops == &shmem_vm_ops;
238 static LIST_HEAD(shmem_swaplist);
239 static DEFINE_MUTEX(shmem_swaplist_mutex);
241 static int shmem_reserve_inode(struct super_block *sb)
243 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
244 if (sbinfo->max_inodes) {
245 spin_lock(&sbinfo->stat_lock);
246 if (!sbinfo->free_inodes) {
247 spin_unlock(&sbinfo->stat_lock);
250 sbinfo->free_inodes--;
251 spin_unlock(&sbinfo->stat_lock);
256 static void shmem_free_inode(struct super_block *sb)
258 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
259 if (sbinfo->max_inodes) {
260 spin_lock(&sbinfo->stat_lock);
261 sbinfo->free_inodes++;
262 spin_unlock(&sbinfo->stat_lock);
267 * shmem_recalc_inode - recalculate the block usage of an inode
268 * @inode: inode to recalc
270 * We have to calculate the free blocks since the mm can drop
271 * undirtied hole pages behind our back.
273 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
274 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
276 * It has to be called with the spinlock held.
278 static void shmem_recalc_inode(struct inode *inode)
280 struct shmem_inode_info *info = SHMEM_I(inode);
283 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
285 info->alloced -= freed;
286 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
287 shmem_inode_unacct_blocks(inode, freed);
291 bool shmem_charge(struct inode *inode, long pages)
293 struct shmem_inode_info *info = SHMEM_I(inode);
296 if (!shmem_inode_acct_block(inode, pages))
299 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
300 inode->i_mapping->nrpages += pages;
302 spin_lock_irqsave(&info->lock, flags);
303 info->alloced += pages;
304 inode->i_blocks += pages * BLOCKS_PER_PAGE;
305 shmem_recalc_inode(inode);
306 spin_unlock_irqrestore(&info->lock, flags);
311 void shmem_uncharge(struct inode *inode, long pages)
313 struct shmem_inode_info *info = SHMEM_I(inode);
316 /* nrpages adjustment done by __delete_from_page_cache() or caller */
318 spin_lock_irqsave(&info->lock, flags);
319 info->alloced -= pages;
320 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
321 shmem_recalc_inode(inode);
322 spin_unlock_irqrestore(&info->lock, flags);
324 shmem_inode_unacct_blocks(inode, pages);
328 * Replace item expected in radix tree by a new item, while holding tree lock.
330 static int shmem_radix_tree_replace(struct address_space *mapping,
331 pgoff_t index, void *expected, void *replacement)
333 struct radix_tree_node *node;
337 VM_BUG_ON(!expected);
338 VM_BUG_ON(!replacement);
339 item = __radix_tree_lookup(&mapping->page_tree, index, &node, &pslot);
342 if (item != expected)
344 __radix_tree_replace(&mapping->page_tree, node, pslot,
345 replacement, NULL, NULL);
350 * Sometimes, before we decide whether to proceed or to fail, we must check
351 * that an entry was not already brought back from swap by a racing thread.
353 * Checking page is not enough: by the time a SwapCache page is locked, it
354 * might be reused, and again be SwapCache, using the same swap as before.
356 static bool shmem_confirm_swap(struct address_space *mapping,
357 pgoff_t index, swp_entry_t swap)
362 item = radix_tree_lookup(&mapping->page_tree, index);
364 return item == swp_to_radix_entry(swap);
368 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
371 * disables huge pages for the mount;
373 * enables huge pages for the mount;
374 * SHMEM_HUGE_WITHIN_SIZE:
375 * only allocate huge pages if the page will be fully within i_size,
376 * also respect fadvise()/madvise() hints;
378 * only allocate huge pages if requested with fadvise()/madvise();
381 #define SHMEM_HUGE_NEVER 0
382 #define SHMEM_HUGE_ALWAYS 1
383 #define SHMEM_HUGE_WITHIN_SIZE 2
384 #define SHMEM_HUGE_ADVISE 3
388 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
391 * disables huge on shm_mnt and all mounts, for emergency use;
393 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
396 #define SHMEM_HUGE_DENY (-1)
397 #define SHMEM_HUGE_FORCE (-2)
399 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
400 /* ifdef here to avoid bloating shmem.o when not necessary */
402 int shmem_huge __read_mostly;
404 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
405 static int shmem_parse_huge(const char *str)
407 if (!strcmp(str, "never"))
408 return SHMEM_HUGE_NEVER;
409 if (!strcmp(str, "always"))
410 return SHMEM_HUGE_ALWAYS;
411 if (!strcmp(str, "within_size"))
412 return SHMEM_HUGE_WITHIN_SIZE;
413 if (!strcmp(str, "advise"))
414 return SHMEM_HUGE_ADVISE;
415 if (!strcmp(str, "deny"))
416 return SHMEM_HUGE_DENY;
417 if (!strcmp(str, "force"))
418 return SHMEM_HUGE_FORCE;
422 static const char *shmem_format_huge(int huge)
425 case SHMEM_HUGE_NEVER:
427 case SHMEM_HUGE_ALWAYS:
429 case SHMEM_HUGE_WITHIN_SIZE:
430 return "within_size";
431 case SHMEM_HUGE_ADVISE:
433 case SHMEM_HUGE_DENY:
435 case SHMEM_HUGE_FORCE:
444 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
445 struct shrink_control *sc, unsigned long nr_to_split)
447 LIST_HEAD(list), *pos, *next;
448 LIST_HEAD(to_remove);
450 struct shmem_inode_info *info;
452 unsigned long batch = sc ? sc->nr_to_scan : 128;
455 if (list_empty(&sbinfo->shrinklist))
458 spin_lock(&sbinfo->shrinklist_lock);
459 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
460 info = list_entry(pos, struct shmem_inode_info, shrinklist);
463 inode = igrab(&info->vfs_inode);
465 /* inode is about to be evicted */
467 list_del_init(&info->shrinklist);
471 /* Check if there's anything to gain */
472 if (round_up(inode->i_size, PAGE_SIZE) ==
473 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
474 list_move(&info->shrinklist, &to_remove);
478 list_move(&info->shrinklist, &list);
480 sbinfo->shrinklist_len--;
484 spin_unlock(&sbinfo->shrinklist_lock);
486 list_for_each_safe(pos, next, &to_remove) {
487 info = list_entry(pos, struct shmem_inode_info, shrinklist);
488 inode = &info->vfs_inode;
489 list_del_init(&info->shrinklist);
493 list_for_each_safe(pos, next, &list) {
496 info = list_entry(pos, struct shmem_inode_info, shrinklist);
497 inode = &info->vfs_inode;
499 if (nr_to_split && split >= nr_to_split)
502 page = find_get_page(inode->i_mapping,
503 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
507 /* No huge page at the end of the file: nothing to split */
508 if (!PageTransHuge(page)) {
514 * Move the inode on the list back to shrinklist if we failed
515 * to lock the page at this time.
517 * Waiting for the lock may lead to deadlock in the
520 if (!trylock_page(page)) {
525 ret = split_huge_page(page);
529 /* If split failed move the inode on the list back to shrinklist */
535 list_del_init(&info->shrinklist);
539 * Make sure the inode is either on the global list or deleted
540 * from any local list before iput() since it could be deleted
541 * in another thread once we put the inode (then the local list
544 spin_lock(&sbinfo->shrinklist_lock);
545 list_move(&info->shrinklist, &sbinfo->shrinklist);
546 sbinfo->shrinklist_len++;
547 spin_unlock(&sbinfo->shrinklist_lock);
555 static long shmem_unused_huge_scan(struct super_block *sb,
556 struct shrink_control *sc)
558 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
560 if (!READ_ONCE(sbinfo->shrinklist_len))
563 return shmem_unused_huge_shrink(sbinfo, sc, 0);
566 static long shmem_unused_huge_count(struct super_block *sb,
567 struct shrink_control *sc)
569 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
570 return READ_ONCE(sbinfo->shrinklist_len);
572 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
574 #define shmem_huge SHMEM_HUGE_DENY
576 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
577 struct shrink_control *sc, unsigned long nr_to_split)
581 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
584 * Like add_to_page_cache_locked, but error if expected item has gone.
586 static int shmem_add_to_page_cache(struct page *page,
587 struct address_space *mapping,
588 pgoff_t index, void *expected)
590 int error, nr = hpage_nr_pages(page);
592 VM_BUG_ON_PAGE(PageTail(page), page);
593 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
594 VM_BUG_ON_PAGE(!PageLocked(page), page);
595 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
596 VM_BUG_ON(expected && PageTransHuge(page));
598 page_ref_add(page, nr);
599 page->mapping = mapping;
602 spin_lock_irq(&mapping->tree_lock);
603 if (PageTransHuge(page)) {
604 void __rcu **results;
609 if (radix_tree_gang_lookup_slot(&mapping->page_tree,
610 &results, &idx, index, 1) &&
611 idx < index + HPAGE_PMD_NR) {
616 for (i = 0; i < HPAGE_PMD_NR; i++) {
617 error = radix_tree_insert(&mapping->page_tree,
618 index + i, page + i);
621 count_vm_event(THP_FILE_ALLOC);
623 } else if (!expected) {
624 error = radix_tree_insert(&mapping->page_tree, index, page);
626 error = shmem_radix_tree_replace(mapping, index, expected,
631 mapping->nrpages += nr;
632 if (PageTransHuge(page))
633 __inc_node_page_state(page, NR_SHMEM_THPS);
634 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
635 __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
636 spin_unlock_irq(&mapping->tree_lock);
638 page->mapping = NULL;
639 spin_unlock_irq(&mapping->tree_lock);
640 page_ref_sub(page, nr);
646 * Like delete_from_page_cache, but substitutes swap for page.
648 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
650 struct address_space *mapping = page->mapping;
653 VM_BUG_ON_PAGE(PageCompound(page), page);
655 spin_lock_irq(&mapping->tree_lock);
656 error = shmem_radix_tree_replace(mapping, page->index, page, radswap);
657 page->mapping = NULL;
659 __dec_node_page_state(page, NR_FILE_PAGES);
660 __dec_node_page_state(page, NR_SHMEM);
661 spin_unlock_irq(&mapping->tree_lock);
667 * Remove swap entry from radix tree, free the swap and its page cache.
669 static int shmem_free_swap(struct address_space *mapping,
670 pgoff_t index, void *radswap)
674 spin_lock_irq(&mapping->tree_lock);
675 old = radix_tree_delete_item(&mapping->page_tree, index, radswap);
676 spin_unlock_irq(&mapping->tree_lock);
679 free_swap_and_cache(radix_to_swp_entry(radswap));
684 * Determine (in bytes) how many of the shmem object's pages mapped by the
685 * given offsets are swapped out.
687 * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
688 * as long as the inode doesn't go away and racy results are not a problem.
690 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
691 pgoff_t start, pgoff_t end)
693 struct radix_tree_iter iter;
696 unsigned long swapped = 0;
700 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
701 if (iter.index >= end)
704 page = radix_tree_deref_slot(slot);
706 if (radix_tree_deref_retry(page)) {
707 slot = radix_tree_iter_retry(&iter);
711 if (radix_tree_exceptional_entry(page))
714 if (need_resched()) {
715 slot = radix_tree_iter_resume(slot, &iter);
722 return swapped << PAGE_SHIFT;
726 * Determine (in bytes) how many of the shmem object's pages mapped by the
727 * given vma is swapped out.
729 * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
730 * as long as the inode doesn't go away and racy results are not a problem.
732 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
734 struct inode *inode = file_inode(vma->vm_file);
735 struct shmem_inode_info *info = SHMEM_I(inode);
736 struct address_space *mapping = inode->i_mapping;
737 unsigned long swapped;
739 /* Be careful as we don't hold info->lock */
740 swapped = READ_ONCE(info->swapped);
743 * The easier cases are when the shmem object has nothing in swap, or
744 * the vma maps it whole. Then we can simply use the stats that we
750 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
751 return swapped << PAGE_SHIFT;
753 /* Here comes the more involved part */
754 return shmem_partial_swap_usage(mapping,
755 linear_page_index(vma, vma->vm_start),
756 linear_page_index(vma, vma->vm_end));
760 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
762 void shmem_unlock_mapping(struct address_space *mapping)
765 pgoff_t indices[PAGEVEC_SIZE];
768 pagevec_init(&pvec, 0);
770 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
772 while (!mapping_unevictable(mapping)) {
774 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
775 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
777 pvec.nr = find_get_entries(mapping, index,
778 PAGEVEC_SIZE, pvec.pages, indices);
781 index = indices[pvec.nr - 1] + 1;
782 pagevec_remove_exceptionals(&pvec);
783 check_move_unevictable_pages(pvec.pages, pvec.nr);
784 pagevec_release(&pvec);
790 * Remove range of pages and swap entries from radix tree, and free them.
791 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
793 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
796 struct address_space *mapping = inode->i_mapping;
797 struct shmem_inode_info *info = SHMEM_I(inode);
798 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
799 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
800 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
801 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
803 pgoff_t indices[PAGEVEC_SIZE];
804 long nr_swaps_freed = 0;
809 end = -1; /* unsigned, so actually very big */
811 pagevec_init(&pvec, 0);
813 while (index < end) {
814 pvec.nr = find_get_entries(mapping, index,
815 min(end - index, (pgoff_t)PAGEVEC_SIZE),
816 pvec.pages, indices);
819 for (i = 0; i < pagevec_count(&pvec); i++) {
820 struct page *page = pvec.pages[i];
826 if (radix_tree_exceptional_entry(page)) {
829 nr_swaps_freed += !shmem_free_swap(mapping,
834 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
836 if (!trylock_page(page))
839 if (PageTransTail(page)) {
840 /* Middle of THP: zero out the page */
841 clear_highpage(page);
844 } else if (PageTransHuge(page)) {
845 if (index == round_down(end, HPAGE_PMD_NR)) {
847 * Range ends in the middle of THP:
850 clear_highpage(page);
854 index += HPAGE_PMD_NR - 1;
855 i += HPAGE_PMD_NR - 1;
858 if (!unfalloc || !PageUptodate(page)) {
859 VM_BUG_ON_PAGE(PageTail(page), page);
860 if (page_mapping(page) == mapping) {
861 VM_BUG_ON_PAGE(PageWriteback(page), page);
862 truncate_inode_page(mapping, page);
867 pagevec_remove_exceptionals(&pvec);
868 pagevec_release(&pvec);
874 struct page *page = NULL;
875 shmem_getpage(inode, start - 1, &page, SGP_READ);
877 unsigned int top = PAGE_SIZE;
882 zero_user_segment(page, partial_start, top);
883 set_page_dirty(page);
889 struct page *page = NULL;
890 shmem_getpage(inode, end, &page, SGP_READ);
892 zero_user_segment(page, 0, partial_end);
893 set_page_dirty(page);
902 while (index < end) {
905 pvec.nr = find_get_entries(mapping, index,
906 min(end - index, (pgoff_t)PAGEVEC_SIZE),
907 pvec.pages, indices);
909 /* If all gone or hole-punch or unfalloc, we're done */
910 if (index == start || end != -1)
912 /* But if truncating, restart to make sure all gone */
916 for (i = 0; i < pagevec_count(&pvec); i++) {
917 struct page *page = pvec.pages[i];
923 if (radix_tree_exceptional_entry(page)) {
926 if (shmem_free_swap(mapping, index, page)) {
927 /* Swap was replaced by page: retry */
937 if (PageTransTail(page)) {
938 /* Middle of THP: zero out the page */
939 clear_highpage(page);
942 * Partial thp truncate due 'start' in middle
943 * of THP: don't need to look on these pages
944 * again on !pvec.nr restart.
946 if (index != round_down(end, HPAGE_PMD_NR))
949 } else if (PageTransHuge(page)) {
950 if (index == round_down(end, HPAGE_PMD_NR)) {
952 * Range ends in the middle of THP:
955 clear_highpage(page);
959 index += HPAGE_PMD_NR - 1;
960 i += HPAGE_PMD_NR - 1;
963 if (!unfalloc || !PageUptodate(page)) {
964 VM_BUG_ON_PAGE(PageTail(page), page);
965 if (page_mapping(page) == mapping) {
966 VM_BUG_ON_PAGE(PageWriteback(page), page);
967 truncate_inode_page(mapping, page);
969 /* Page was replaced by swap: retry */
977 pagevec_remove_exceptionals(&pvec);
978 pagevec_release(&pvec);
982 spin_lock_irq(&info->lock);
983 info->swapped -= nr_swaps_freed;
984 shmem_recalc_inode(inode);
985 spin_unlock_irq(&info->lock);
988 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
990 shmem_undo_range(inode, lstart, lend, false);
991 inode->i_ctime = inode->i_mtime = current_time(inode);
993 EXPORT_SYMBOL_GPL(shmem_truncate_range);
995 static int shmem_getattr(const struct path *path, struct kstat *stat,
996 u32 request_mask, unsigned int query_flags)
998 struct inode *inode = path->dentry->d_inode;
999 struct shmem_inode_info *info = SHMEM_I(inode);
1001 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
1002 spin_lock_irq(&info->lock);
1003 shmem_recalc_inode(inode);
1004 spin_unlock_irq(&info->lock);
1006 generic_fillattr(inode, stat);
1010 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
1012 struct inode *inode = d_inode(dentry);
1013 struct shmem_inode_info *info = SHMEM_I(inode);
1014 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1017 error = setattr_prepare(dentry, attr);
1021 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1022 loff_t oldsize = inode->i_size;
1023 loff_t newsize = attr->ia_size;
1025 /* protected by i_mutex */
1026 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1027 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1030 if (newsize != oldsize) {
1031 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1035 i_size_write(inode, newsize);
1036 inode->i_ctime = inode->i_mtime = current_time(inode);
1038 if (newsize <= oldsize) {
1039 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1040 if (oldsize > holebegin)
1041 unmap_mapping_range(inode->i_mapping,
1044 shmem_truncate_range(inode,
1045 newsize, (loff_t)-1);
1046 /* unmap again to remove racily COWed private pages */
1047 if (oldsize > holebegin)
1048 unmap_mapping_range(inode->i_mapping,
1052 * Part of the huge page can be beyond i_size: subject
1053 * to shrink under memory pressure.
1055 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
1056 spin_lock(&sbinfo->shrinklist_lock);
1058 * _careful to defend against unlocked access to
1059 * ->shrink_list in shmem_unused_huge_shrink()
1061 if (list_empty_careful(&info->shrinklist)) {
1062 list_add_tail(&info->shrinklist,
1063 &sbinfo->shrinklist);
1064 sbinfo->shrinklist_len++;
1066 spin_unlock(&sbinfo->shrinklist_lock);
1071 setattr_copy(inode, attr);
1072 if (attr->ia_valid & ATTR_MODE)
1073 error = posix_acl_chmod(inode, inode->i_mode);
1077 static void shmem_evict_inode(struct inode *inode)
1079 struct shmem_inode_info *info = SHMEM_I(inode);
1080 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1082 if (inode->i_mapping->a_ops == &shmem_aops) {
1083 shmem_unacct_size(info->flags, inode->i_size);
1085 shmem_truncate_range(inode, 0, (loff_t)-1);
1086 if (!list_empty(&info->shrinklist)) {
1087 spin_lock(&sbinfo->shrinklist_lock);
1088 if (!list_empty(&info->shrinklist)) {
1089 list_del_init(&info->shrinklist);
1090 sbinfo->shrinklist_len--;
1092 spin_unlock(&sbinfo->shrinklist_lock);
1094 if (!list_empty(&info->swaplist)) {
1095 mutex_lock(&shmem_swaplist_mutex);
1096 list_del_init(&info->swaplist);
1097 mutex_unlock(&shmem_swaplist_mutex);
1101 simple_xattrs_free(&info->xattrs);
1102 WARN_ON(inode->i_blocks);
1103 shmem_free_inode(inode->i_sb);
1107 static unsigned long find_swap_entry(struct radix_tree_root *root, void *item)
1109 struct radix_tree_iter iter;
1111 unsigned long found = -1;
1112 unsigned int checked = 0;
1115 radix_tree_for_each_slot(slot, root, &iter, 0) {
1116 if (*slot == item) {
1121 if ((checked % 4096) != 0)
1123 slot = radix_tree_iter_resume(slot, &iter);
1132 * If swap found in inode, free it and move page from swapcache to filecache.
1134 static int shmem_unuse_inode(struct shmem_inode_info *info,
1135 swp_entry_t swap, struct page **pagep)
1137 struct address_space *mapping = info->vfs_inode.i_mapping;
1143 radswap = swp_to_radix_entry(swap);
1144 index = find_swap_entry(&mapping->page_tree, radswap);
1146 return -EAGAIN; /* tell shmem_unuse we found nothing */
1149 * Move _head_ to start search for next from here.
1150 * But be careful: shmem_evict_inode checks list_empty without taking
1151 * mutex, and there's an instant in list_move_tail when info->swaplist
1152 * would appear empty, if it were the only one on shmem_swaplist.
1154 if (shmem_swaplist.next != &info->swaplist)
1155 list_move_tail(&shmem_swaplist, &info->swaplist);
1157 gfp = mapping_gfp_mask(mapping);
1158 if (shmem_should_replace_page(*pagep, gfp)) {
1159 mutex_unlock(&shmem_swaplist_mutex);
1160 error = shmem_replace_page(pagep, gfp, info, index);
1161 mutex_lock(&shmem_swaplist_mutex);
1163 * We needed to drop mutex to make that restrictive page
1164 * allocation, but the inode might have been freed while we
1165 * dropped it: although a racing shmem_evict_inode() cannot
1166 * complete without emptying the radix_tree, our page lock
1167 * on this swapcache page is not enough to prevent that -
1168 * free_swap_and_cache() of our swap entry will only
1169 * trylock_page(), removing swap from radix_tree whatever.
1171 * We must not proceed to shmem_add_to_page_cache() if the
1172 * inode has been freed, but of course we cannot rely on
1173 * inode or mapping or info to check that. However, we can
1174 * safely check if our swap entry is still in use (and here
1175 * it can't have got reused for another page): if it's still
1176 * in use, then the inode cannot have been freed yet, and we
1177 * can safely proceed (if it's no longer in use, that tells
1178 * nothing about the inode, but we don't need to unuse swap).
1180 if (!page_swapcount(*pagep))
1185 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
1186 * but also to hold up shmem_evict_inode(): so inode cannot be freed
1187 * beneath us (pagelock doesn't help until the page is in pagecache).
1190 error = shmem_add_to_page_cache(*pagep, mapping, index,
1192 if (error != -ENOMEM) {
1194 * Truncation and eviction use free_swap_and_cache(), which
1195 * only does trylock page: if we raced, best clean up here.
1197 delete_from_swap_cache(*pagep);
1198 set_page_dirty(*pagep);
1200 spin_lock_irq(&info->lock);
1202 spin_unlock_irq(&info->lock);
1210 * Search through swapped inodes to find and replace swap by page.
1212 int shmem_unuse(swp_entry_t swap, struct page *page)
1214 struct list_head *this, *next;
1215 struct shmem_inode_info *info;
1216 struct mem_cgroup *memcg;
1220 * There's a faint possibility that swap page was replaced before
1221 * caller locked it: caller will come back later with the right page.
1223 if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
1227 * Charge page using GFP_KERNEL while we can wait, before taking
1228 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1229 * Charged back to the user (not to caller) when swap account is used.
1231 error = mem_cgroup_try_charge(page, current->mm, GFP_KERNEL, &memcg,
1235 /* No radix_tree_preload: swap entry keeps a place for page in tree */
1238 mutex_lock(&shmem_swaplist_mutex);
1239 list_for_each_safe(this, next, &shmem_swaplist) {
1240 info = list_entry(this, struct shmem_inode_info, swaplist);
1242 error = shmem_unuse_inode(info, swap, &page);
1244 list_del_init(&info->swaplist);
1246 if (error != -EAGAIN)
1248 /* found nothing in this: move on to search the next */
1250 mutex_unlock(&shmem_swaplist_mutex);
1253 if (error != -ENOMEM)
1255 mem_cgroup_cancel_charge(page, memcg, false);
1257 mem_cgroup_commit_charge(page, memcg, true, false);
1265 * Move the page from the page cache to the swap cache.
1267 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1269 struct shmem_inode_info *info;
1270 struct address_space *mapping;
1271 struct inode *inode;
1275 VM_BUG_ON_PAGE(PageCompound(page), page);
1276 BUG_ON(!PageLocked(page));
1277 mapping = page->mapping;
1278 index = page->index;
1279 inode = mapping->host;
1280 info = SHMEM_I(inode);
1281 if (info->flags & VM_LOCKED)
1283 if (!total_swap_pages)
1287 * Our capabilities prevent regular writeback or sync from ever calling
1288 * shmem_writepage; but a stacking filesystem might use ->writepage of
1289 * its underlying filesystem, in which case tmpfs should write out to
1290 * swap only in response to memory pressure, and not for the writeback
1293 if (!wbc->for_reclaim) {
1294 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1299 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1300 * value into swapfile.c, the only way we can correctly account for a
1301 * fallocated page arriving here is now to initialize it and write it.
1303 * That's okay for a page already fallocated earlier, but if we have
1304 * not yet completed the fallocation, then (a) we want to keep track
1305 * of this page in case we have to undo it, and (b) it may not be a
1306 * good idea to continue anyway, once we're pushing into swap. So
1307 * reactivate the page, and let shmem_fallocate() quit when too many.
1309 if (!PageUptodate(page)) {
1310 if (inode->i_private) {
1311 struct shmem_falloc *shmem_falloc;
1312 spin_lock(&inode->i_lock);
1313 shmem_falloc = inode->i_private;
1315 !shmem_falloc->waitq &&
1316 index >= shmem_falloc->start &&
1317 index < shmem_falloc->next)
1318 shmem_falloc->nr_unswapped++;
1320 shmem_falloc = NULL;
1321 spin_unlock(&inode->i_lock);
1325 clear_highpage(page);
1326 flush_dcache_page(page);
1327 SetPageUptodate(page);
1330 swap = get_swap_page(page);
1334 if (mem_cgroup_try_charge_swap(page, swap))
1338 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1339 * if it's not already there. Do it now before the page is
1340 * moved to swap cache, when its pagelock no longer protects
1341 * the inode from eviction. But don't unlock the mutex until
1342 * we've incremented swapped, because shmem_unuse_inode() will
1343 * prune a !swapped inode from the swaplist under this mutex.
1345 mutex_lock(&shmem_swaplist_mutex);
1346 if (list_empty(&info->swaplist))
1347 list_add_tail(&info->swaplist, &shmem_swaplist);
1349 if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1350 spin_lock_irq(&info->lock);
1351 shmem_recalc_inode(inode);
1353 spin_unlock_irq(&info->lock);
1355 swap_shmem_alloc(swap);
1356 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1358 mutex_unlock(&shmem_swaplist_mutex);
1359 BUG_ON(page_mapped(page));
1360 swap_writepage(page, wbc);
1364 mutex_unlock(&shmem_swaplist_mutex);
1366 put_swap_page(page, swap);
1368 set_page_dirty(page);
1369 if (wbc->for_reclaim)
1370 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1375 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1376 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1380 if (!mpol || mpol->mode == MPOL_DEFAULT)
1381 return; /* show nothing */
1383 mpol_to_str(buffer, sizeof(buffer), mpol);
1385 seq_printf(seq, ",mpol=%s", buffer);
1388 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1390 struct mempolicy *mpol = NULL;
1392 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1393 mpol = sbinfo->mpol;
1395 spin_unlock(&sbinfo->stat_lock);
1399 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1400 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1403 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1407 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1409 #define vm_policy vm_private_data
1412 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1413 struct shmem_inode_info *info, pgoff_t index)
1415 /* Create a pseudo vma that just contains the policy */
1417 /* Bias interleave by inode number to distribute better across nodes */
1418 vma->vm_pgoff = index + info->vfs_inode.i_ino;
1420 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1423 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1425 /* Drop reference taken by mpol_shared_policy_lookup() */
1426 mpol_cond_put(vma->vm_policy);
1429 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1430 struct shmem_inode_info *info, pgoff_t index)
1432 struct vm_area_struct pvma;
1435 shmem_pseudo_vma_init(&pvma, info, index);
1436 page = swapin_readahead(swap, gfp, &pvma, 0);
1437 shmem_pseudo_vma_destroy(&pvma);
1442 static struct page *shmem_alloc_hugepage(gfp_t gfp,
1443 struct shmem_inode_info *info, pgoff_t index)
1445 struct vm_area_struct pvma;
1446 struct inode *inode = &info->vfs_inode;
1447 struct address_space *mapping = inode->i_mapping;
1448 pgoff_t idx, hindex;
1449 void __rcu **results;
1452 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1455 hindex = round_down(index, HPAGE_PMD_NR);
1457 if (radix_tree_gang_lookup_slot(&mapping->page_tree, &results, &idx,
1458 hindex, 1) && idx < hindex + HPAGE_PMD_NR) {
1464 shmem_pseudo_vma_init(&pvma, info, hindex);
1465 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1466 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
1467 shmem_pseudo_vma_destroy(&pvma);
1469 prep_transhuge_page(page);
1473 static struct page *shmem_alloc_page(gfp_t gfp,
1474 struct shmem_inode_info *info, pgoff_t index)
1476 struct vm_area_struct pvma;
1479 shmem_pseudo_vma_init(&pvma, info, index);
1480 page = alloc_page_vma(gfp, &pvma, 0);
1481 shmem_pseudo_vma_destroy(&pvma);
1486 static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1487 struct inode *inode,
1488 pgoff_t index, bool huge)
1490 struct shmem_inode_info *info = SHMEM_I(inode);
1495 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1497 nr = huge ? HPAGE_PMD_NR : 1;
1499 if (!shmem_inode_acct_block(inode, nr))
1503 page = shmem_alloc_hugepage(gfp, info, index);
1505 page = shmem_alloc_page(gfp, info, index);
1507 __SetPageLocked(page);
1508 __SetPageSwapBacked(page);
1513 shmem_inode_unacct_blocks(inode, nr);
1515 return ERR_PTR(err);
1519 * When a page is moved from swapcache to shmem filecache (either by the
1520 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1521 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1522 * ignorance of the mapping it belongs to. If that mapping has special
1523 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1524 * we may need to copy to a suitable page before moving to filecache.
1526 * In a future release, this may well be extended to respect cpuset and
1527 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1528 * but for now it is a simple matter of zone.
1530 static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1532 return page_zonenum(page) > gfp_zone(gfp);
1535 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1536 struct shmem_inode_info *info, pgoff_t index)
1538 struct page *oldpage, *newpage;
1539 struct address_space *swap_mapping;
1545 entry.val = page_private(oldpage);
1546 swap_index = swp_offset(entry);
1547 swap_mapping = page_mapping(oldpage);
1550 * We have arrived here because our zones are constrained, so don't
1551 * limit chance of success by further cpuset and node constraints.
1553 gfp &= ~GFP_CONSTRAINT_MASK;
1554 newpage = shmem_alloc_page(gfp, info, index);
1559 copy_highpage(newpage, oldpage);
1560 flush_dcache_page(newpage);
1562 __SetPageLocked(newpage);
1563 __SetPageSwapBacked(newpage);
1564 SetPageUptodate(newpage);
1565 set_page_private(newpage, entry.val);
1566 SetPageSwapCache(newpage);
1569 * Our caller will very soon move newpage out of swapcache, but it's
1570 * a nice clean interface for us to replace oldpage by newpage there.
1572 spin_lock_irq(&swap_mapping->tree_lock);
1573 error = shmem_radix_tree_replace(swap_mapping, swap_index, oldpage,
1576 __inc_node_page_state(newpage, NR_FILE_PAGES);
1577 __dec_node_page_state(oldpage, NR_FILE_PAGES);
1579 spin_unlock_irq(&swap_mapping->tree_lock);
1581 if (unlikely(error)) {
1583 * Is this possible? I think not, now that our callers check
1584 * both PageSwapCache and page_private after getting page lock;
1585 * but be defensive. Reverse old to newpage for clear and free.
1589 mem_cgroup_migrate(oldpage, newpage);
1590 lru_cache_add_anon(newpage);
1594 ClearPageSwapCache(oldpage);
1595 set_page_private(oldpage, 0);
1597 unlock_page(oldpage);
1604 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1606 * If we allocate a new one we do not mark it dirty. That's up to the
1607 * vm. If we swap it in we mark it dirty since we also free the swap
1608 * entry since a page cannot live in both the swap and page cache.
1610 * fault_mm and fault_type are only supplied by shmem_fault:
1611 * otherwise they are NULL.
1613 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1614 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1615 struct vm_area_struct *vma, struct vm_fault *vmf, int *fault_type)
1617 struct address_space *mapping = inode->i_mapping;
1618 struct shmem_inode_info *info = SHMEM_I(inode);
1619 struct shmem_sb_info *sbinfo;
1620 struct mm_struct *charge_mm;
1621 struct mem_cgroup *memcg;
1624 enum sgp_type sgp_huge = sgp;
1625 pgoff_t hindex = index;
1630 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1632 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1636 page = find_lock_entry(mapping, index);
1637 if (radix_tree_exceptional_entry(page)) {
1638 swap = radix_to_swp_entry(page);
1642 if (sgp <= SGP_CACHE &&
1643 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1648 if (page && sgp == SGP_WRITE)
1649 mark_page_accessed(page);
1651 /* fallocated page? */
1652 if (page && !PageUptodate(page)) {
1653 if (sgp != SGP_READ)
1659 if (page || (sgp == SGP_READ && !swap.val)) {
1665 * Fast cache lookup did not find it:
1666 * bring it back from swap or allocate.
1668 sbinfo = SHMEM_SB(inode->i_sb);
1669 charge_mm = vma ? vma->vm_mm : current->mm;
1672 /* Look it up and read it in.. */
1673 page = lookup_swap_cache(swap, NULL, 0);
1675 /* Or update major stats only when swapin succeeds?? */
1677 *fault_type |= VM_FAULT_MAJOR;
1678 count_vm_event(PGMAJFAULT);
1679 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1681 /* Here we actually start the io */
1682 page = shmem_swapin(swap, gfp, info, index);
1689 /* We have to do this with page locked to prevent races */
1691 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1692 !shmem_confirm_swap(mapping, index, swap)) {
1693 error = -EEXIST; /* try again */
1696 if (!PageUptodate(page)) {
1700 wait_on_page_writeback(page);
1702 if (shmem_should_replace_page(page, gfp)) {
1703 error = shmem_replace_page(&page, gfp, info, index);
1708 error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
1711 error = shmem_add_to_page_cache(page, mapping, index,
1712 swp_to_radix_entry(swap));
1714 * We already confirmed swap under page lock, and make
1715 * no memory allocation here, so usually no possibility
1716 * of error; but free_swap_and_cache() only trylocks a
1717 * page, so it is just possible that the entry has been
1718 * truncated or holepunched since swap was confirmed.
1719 * shmem_undo_range() will have done some of the
1720 * unaccounting, now delete_from_swap_cache() will do
1722 * Reset swap.val? No, leave it so "failed" goes back to
1723 * "repeat": reading a hole and writing should succeed.
1726 mem_cgroup_cancel_charge(page, memcg, false);
1727 delete_from_swap_cache(page);
1733 mem_cgroup_commit_charge(page, memcg, true, false);
1735 spin_lock_irq(&info->lock);
1737 shmem_recalc_inode(inode);
1738 spin_unlock_irq(&info->lock);
1740 if (sgp == SGP_WRITE)
1741 mark_page_accessed(page);
1743 delete_from_swap_cache(page);
1744 set_page_dirty(page);
1748 if (vma && userfaultfd_missing(vma)) {
1749 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1753 /* shmem_symlink() */
1754 if (mapping->a_ops != &shmem_aops)
1756 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1758 if (shmem_huge == SHMEM_HUGE_FORCE)
1760 switch (sbinfo->huge) {
1763 case SHMEM_HUGE_NEVER:
1765 case SHMEM_HUGE_WITHIN_SIZE:
1766 off = round_up(index, HPAGE_PMD_NR);
1767 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1768 if (i_size >= HPAGE_PMD_SIZE &&
1769 i_size >> PAGE_SHIFT >= off)
1772 case SHMEM_HUGE_ADVISE:
1773 if (sgp_huge == SGP_HUGE)
1775 /* TODO: implement fadvise() hints */
1780 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1782 alloc_nohuge: page = shmem_alloc_and_acct_page(gfp, inode,
1787 error = PTR_ERR(page);
1789 if (error != -ENOSPC)
1792 * Try to reclaim some spece by splitting a huge page
1793 * beyond i_size on the filesystem.
1797 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1798 if (ret == SHRINK_STOP)
1806 if (PageTransHuge(page))
1807 hindex = round_down(index, HPAGE_PMD_NR);
1811 if (sgp == SGP_WRITE)
1812 __SetPageReferenced(page);
1814 error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
1815 PageTransHuge(page));
1818 error = radix_tree_maybe_preload_order(gfp & GFP_RECLAIM_MASK,
1819 compound_order(page));
1821 error = shmem_add_to_page_cache(page, mapping, hindex,
1823 radix_tree_preload_end();
1826 mem_cgroup_cancel_charge(page, memcg,
1827 PageTransHuge(page));
1830 mem_cgroup_commit_charge(page, memcg, false,
1831 PageTransHuge(page));
1832 lru_cache_add_anon(page);
1834 spin_lock_irq(&info->lock);
1835 info->alloced += 1 << compound_order(page);
1836 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1837 shmem_recalc_inode(inode);
1838 spin_unlock_irq(&info->lock);
1841 if (PageTransHuge(page) &&
1842 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1843 hindex + HPAGE_PMD_NR - 1) {
1845 * Part of the huge page is beyond i_size: subject
1846 * to shrink under memory pressure.
1848 spin_lock(&sbinfo->shrinklist_lock);
1850 * _careful to defend against unlocked access to
1851 * ->shrink_list in shmem_unused_huge_shrink()
1853 if (list_empty_careful(&info->shrinklist)) {
1854 list_add_tail(&info->shrinklist,
1855 &sbinfo->shrinklist);
1856 sbinfo->shrinklist_len++;
1858 spin_unlock(&sbinfo->shrinklist_lock);
1862 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1864 if (sgp == SGP_FALLOC)
1868 * Let SGP_WRITE caller clear ends if write does not fill page;
1869 * but SGP_FALLOC on a page fallocated earlier must initialize
1870 * it now, lest undo on failure cancel our earlier guarantee.
1872 if (sgp != SGP_WRITE && !PageUptodate(page)) {
1873 struct page *head = compound_head(page);
1876 for (i = 0; i < (1 << compound_order(head)); i++) {
1877 clear_highpage(head + i);
1878 flush_dcache_page(head + i);
1880 SetPageUptodate(head);
1884 /* Perhaps the file has been truncated since we checked */
1885 if (sgp <= SGP_CACHE &&
1886 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1888 ClearPageDirty(page);
1889 delete_from_page_cache(page);
1890 spin_lock_irq(&info->lock);
1891 shmem_recalc_inode(inode);
1892 spin_unlock_irq(&info->lock);
1897 *pagep = page + index - hindex;
1904 shmem_inode_unacct_blocks(inode, 1 << compound_order(page));
1906 if (PageTransHuge(page)) {
1912 if (swap.val && !shmem_confirm_swap(mapping, index, swap))
1919 if (error == -ENOSPC && !once++) {
1920 spin_lock_irq(&info->lock);
1921 shmem_recalc_inode(inode);
1922 spin_unlock_irq(&info->lock);
1925 if (error == -EEXIST) /* from above or from radix_tree_insert */
1931 * This is like autoremove_wake_function, but it removes the wait queue
1932 * entry unconditionally - even if something else had already woken the
1935 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
1937 int ret = default_wake_function(wait, mode, sync, key);
1938 list_del_init(&wait->entry);
1942 static int shmem_fault(struct vm_fault *vmf)
1944 struct vm_area_struct *vma = vmf->vma;
1945 struct inode *inode = file_inode(vma->vm_file);
1946 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1949 int ret = VM_FAULT_LOCKED;
1952 * Trinity finds that probing a hole which tmpfs is punching can
1953 * prevent the hole-punch from ever completing: which in turn
1954 * locks writers out with its hold on i_mutex. So refrain from
1955 * faulting pages into the hole while it's being punched. Although
1956 * shmem_undo_range() does remove the additions, it may be unable to
1957 * keep up, as each new page needs its own unmap_mapping_range() call,
1958 * and the i_mmap tree grows ever slower to scan if new vmas are added.
1960 * It does not matter if we sometimes reach this check just before the
1961 * hole-punch begins, so that one fault then races with the punch:
1962 * we just need to make racing faults a rare case.
1964 * The implementation below would be much simpler if we just used a
1965 * standard mutex or completion: but we cannot take i_mutex in fault,
1966 * and bloating every shmem inode for this unlikely case would be sad.
1968 if (unlikely(inode->i_private)) {
1969 struct shmem_falloc *shmem_falloc;
1971 spin_lock(&inode->i_lock);
1972 shmem_falloc = inode->i_private;
1974 shmem_falloc->waitq &&
1975 vmf->pgoff >= shmem_falloc->start &&
1976 vmf->pgoff < shmem_falloc->next) {
1977 wait_queue_head_t *shmem_falloc_waitq;
1978 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
1980 ret = VM_FAULT_NOPAGE;
1981 if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
1982 !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
1983 /* It's polite to up mmap_sem if we can */
1984 up_read(&vma->vm_mm->mmap_sem);
1985 ret = VM_FAULT_RETRY;
1988 shmem_falloc_waitq = shmem_falloc->waitq;
1989 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
1990 TASK_UNINTERRUPTIBLE);
1991 spin_unlock(&inode->i_lock);
1995 * shmem_falloc_waitq points into the shmem_fallocate()
1996 * stack of the hole-punching task: shmem_falloc_waitq
1997 * is usually invalid by the time we reach here, but
1998 * finish_wait() does not dereference it in that case;
1999 * though i_lock needed lest racing with wake_up_all().
2001 spin_lock(&inode->i_lock);
2002 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2003 spin_unlock(&inode->i_lock);
2006 spin_unlock(&inode->i_lock);
2011 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
2012 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
2014 else if (vma->vm_flags & VM_HUGEPAGE)
2017 error = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
2018 gfp, vma, vmf, &ret);
2020 return ((error == -ENOMEM) ? VM_FAULT_OOM : VM_FAULT_SIGBUS);
2024 unsigned long shmem_get_unmapped_area(struct file *file,
2025 unsigned long uaddr, unsigned long len,
2026 unsigned long pgoff, unsigned long flags)
2028 unsigned long (*get_area)(struct file *,
2029 unsigned long, unsigned long, unsigned long, unsigned long);
2031 unsigned long offset;
2032 unsigned long inflated_len;
2033 unsigned long inflated_addr;
2034 unsigned long inflated_offset;
2036 if (len > TASK_SIZE)
2039 get_area = current->mm->get_unmapped_area;
2040 addr = get_area(file, uaddr, len, pgoff, flags);
2042 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
2044 if (IS_ERR_VALUE(addr))
2046 if (addr & ~PAGE_MASK)
2048 if (addr > TASK_SIZE - len)
2051 if (shmem_huge == SHMEM_HUGE_DENY)
2053 if (len < HPAGE_PMD_SIZE)
2055 if (flags & MAP_FIXED)
2058 * Our priority is to support MAP_SHARED mapped hugely;
2059 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2060 * But if caller specified an address hint and we allocated area there
2061 * successfully, respect that as before.
2066 if (shmem_huge != SHMEM_HUGE_FORCE) {
2067 struct super_block *sb;
2070 VM_BUG_ON(file->f_op != &shmem_file_operations);
2071 sb = file_inode(file)->i_sb;
2074 * Called directly from mm/mmap.c, or drivers/char/mem.c
2075 * for "/dev/zero", to create a shared anonymous object.
2077 if (IS_ERR(shm_mnt))
2079 sb = shm_mnt->mnt_sb;
2081 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2085 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2086 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2088 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2091 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2092 if (inflated_len > TASK_SIZE)
2094 if (inflated_len < len)
2097 inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
2098 if (IS_ERR_VALUE(inflated_addr))
2100 if (inflated_addr & ~PAGE_MASK)
2103 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2104 inflated_addr += offset - inflated_offset;
2105 if (inflated_offset > offset)
2106 inflated_addr += HPAGE_PMD_SIZE;
2108 if (inflated_addr > TASK_SIZE - len)
2110 return inflated_addr;
2114 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2116 struct inode *inode = file_inode(vma->vm_file);
2117 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2120 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2123 struct inode *inode = file_inode(vma->vm_file);
2126 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2127 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2131 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2133 struct inode *inode = file_inode(file);
2134 struct shmem_inode_info *info = SHMEM_I(inode);
2135 int retval = -ENOMEM;
2138 * What serializes the accesses to info->flags?
2139 * ipc_lock_object() when called from shmctl_do_lock(),
2140 * no serialization needed when called from shm_destroy().
2142 if (lock && !(info->flags & VM_LOCKED)) {
2143 if (!user_shm_lock(inode->i_size, user))
2145 info->flags |= VM_LOCKED;
2146 mapping_set_unevictable(file->f_mapping);
2148 if (!lock && (info->flags & VM_LOCKED) && user) {
2149 user_shm_unlock(inode->i_size, user);
2150 info->flags &= ~VM_LOCKED;
2151 mapping_clear_unevictable(file->f_mapping);
2159 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2161 file_accessed(file);
2162 vma->vm_ops = &shmem_vm_ops;
2163 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
2164 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2165 (vma->vm_end & HPAGE_PMD_MASK)) {
2166 khugepaged_enter(vma, vma->vm_flags);
2171 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
2172 umode_t mode, dev_t dev, unsigned long flags)
2174 struct inode *inode;
2175 struct shmem_inode_info *info;
2176 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2178 if (shmem_reserve_inode(sb))
2181 inode = new_inode(sb);
2183 inode->i_ino = get_next_ino();
2184 inode_init_owner(inode, dir, mode);
2185 inode->i_blocks = 0;
2186 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2187 inode->i_generation = get_seconds();
2188 info = SHMEM_I(inode);
2189 memset(info, 0, (char *)inode - (char *)info);
2190 spin_lock_init(&info->lock);
2191 info->seals = F_SEAL_SEAL;
2192 info->flags = flags & VM_NORESERVE;
2193 INIT_LIST_HEAD(&info->shrinklist);
2194 INIT_LIST_HEAD(&info->swaplist);
2195 simple_xattrs_init(&info->xattrs);
2196 cache_no_acl(inode);
2198 switch (mode & S_IFMT) {
2200 inode->i_op = &shmem_special_inode_operations;
2201 init_special_inode(inode, mode, dev);
2204 inode->i_mapping->a_ops = &shmem_aops;
2205 inode->i_op = &shmem_inode_operations;
2206 inode->i_fop = &shmem_file_operations;
2207 mpol_shared_policy_init(&info->policy,
2208 shmem_get_sbmpol(sbinfo));
2212 /* Some things misbehave if size == 0 on a directory */
2213 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2214 inode->i_op = &shmem_dir_inode_operations;
2215 inode->i_fop = &simple_dir_operations;
2219 * Must not load anything in the rbtree,
2220 * mpol_free_shared_policy will not be called.
2222 mpol_shared_policy_init(&info->policy, NULL);
2226 lockdep_annotate_inode_mutex_key(inode);
2228 shmem_free_inode(sb);
2232 bool shmem_mapping(struct address_space *mapping)
2234 return mapping->a_ops == &shmem_aops;
2237 static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2239 struct vm_area_struct *dst_vma,
2240 unsigned long dst_addr,
2241 unsigned long src_addr,
2243 struct page **pagep)
2245 struct inode *inode = file_inode(dst_vma->vm_file);
2246 struct shmem_inode_info *info = SHMEM_I(inode);
2247 struct address_space *mapping = inode->i_mapping;
2248 gfp_t gfp = mapping_gfp_mask(mapping);
2249 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2250 struct mem_cgroup *memcg;
2254 pte_t _dst_pte, *dst_pte;
2256 pgoff_t offset, max_off;
2259 if (!shmem_inode_acct_block(inode, 1)) {
2261 * We may have got a page, returned -ENOENT triggering a retry,
2262 * and now we find ourselves with -ENOMEM. Release the page, to
2263 * avoid a BUG_ON in our caller.
2265 if (unlikely(*pagep)) {
2273 page = shmem_alloc_page(gfp, info, pgoff);
2275 goto out_unacct_blocks;
2277 if (!zeropage) { /* mcopy_atomic */
2278 page_kaddr = kmap_atomic(page);
2279 ret = copy_from_user(page_kaddr,
2280 (const void __user *)src_addr,
2282 kunmap_atomic(page_kaddr);
2284 /* fallback to copy_from_user outside mmap_sem */
2285 if (unlikely(ret)) {
2287 shmem_inode_unacct_blocks(inode, 1);
2288 /* don't free the page */
2291 } else { /* mfill_zeropage_atomic */
2292 clear_highpage(page);
2299 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2300 __SetPageLocked(page);
2301 __SetPageSwapBacked(page);
2302 __SetPageUptodate(page);
2305 offset = linear_page_index(dst_vma, dst_addr);
2306 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2307 if (unlikely(offset >= max_off))
2310 ret = mem_cgroup_try_charge(page, dst_mm, gfp, &memcg, false);
2314 ret = radix_tree_maybe_preload(gfp & GFP_RECLAIM_MASK);
2316 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL);
2317 radix_tree_preload_end();
2320 goto out_release_uncharge;
2322 mem_cgroup_commit_charge(page, memcg, false, false);
2324 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2325 if (dst_vma->vm_flags & VM_WRITE)
2326 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
2329 * We don't set the pte dirty if the vma has no
2330 * VM_WRITE permission, so mark the page dirty or it
2331 * could be freed from under us. We could do it
2332 * unconditionally before unlock_page(), but doing it
2333 * only if VM_WRITE is not set is faster.
2335 set_page_dirty(page);
2338 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
2341 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2342 if (unlikely(offset >= max_off))
2343 goto out_release_uncharge_unlock;
2346 if (!pte_none(*dst_pte))
2347 goto out_release_uncharge_unlock;
2349 lru_cache_add_anon(page);
2351 spin_lock_irq(&info->lock);
2353 inode->i_blocks += BLOCKS_PER_PAGE;
2354 shmem_recalc_inode(inode);
2355 spin_unlock_irq(&info->lock);
2357 inc_mm_counter(dst_mm, mm_counter_file(page));
2358 page_add_file_rmap(page, false);
2359 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2361 /* No need to invalidate - it was non-present before */
2362 update_mmu_cache(dst_vma, dst_addr, dst_pte);
2363 pte_unmap_unlock(dst_pte, ptl);
2368 out_release_uncharge_unlock:
2369 pte_unmap_unlock(dst_pte, ptl);
2370 ClearPageDirty(page);
2371 delete_from_page_cache(page);
2372 out_release_uncharge:
2373 mem_cgroup_cancel_charge(page, memcg, false);
2378 shmem_inode_unacct_blocks(inode, 1);
2382 int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2384 struct vm_area_struct *dst_vma,
2385 unsigned long dst_addr,
2386 unsigned long src_addr,
2387 struct page **pagep)
2389 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2390 dst_addr, src_addr, false, pagep);
2393 int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2395 struct vm_area_struct *dst_vma,
2396 unsigned long dst_addr)
2398 struct page *page = NULL;
2400 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2401 dst_addr, 0, true, &page);
2405 static const struct inode_operations shmem_symlink_inode_operations;
2406 static const struct inode_operations shmem_short_symlink_operations;
2408 #ifdef CONFIG_TMPFS_XATTR
2409 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2411 #define shmem_initxattrs NULL
2415 shmem_write_begin(struct file *file, struct address_space *mapping,
2416 loff_t pos, unsigned len, unsigned flags,
2417 struct page **pagep, void **fsdata)
2419 struct inode *inode = mapping->host;
2420 struct shmem_inode_info *info = SHMEM_I(inode);
2421 pgoff_t index = pos >> PAGE_SHIFT;
2423 /* i_mutex is held by caller */
2424 if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
2425 if (info->seals & F_SEAL_WRITE)
2427 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2431 return shmem_getpage(inode, index, pagep, SGP_WRITE);
2435 shmem_write_end(struct file *file, struct address_space *mapping,
2436 loff_t pos, unsigned len, unsigned copied,
2437 struct page *page, void *fsdata)
2439 struct inode *inode = mapping->host;
2441 if (pos + copied > inode->i_size)
2442 i_size_write(inode, pos + copied);
2444 if (!PageUptodate(page)) {
2445 struct page *head = compound_head(page);
2446 if (PageTransCompound(page)) {
2449 for (i = 0; i < HPAGE_PMD_NR; i++) {
2450 if (head + i == page)
2452 clear_highpage(head + i);
2453 flush_dcache_page(head + i);
2456 if (copied < PAGE_SIZE) {
2457 unsigned from = pos & (PAGE_SIZE - 1);
2458 zero_user_segments(page, 0, from,
2459 from + copied, PAGE_SIZE);
2461 SetPageUptodate(head);
2463 set_page_dirty(page);
2470 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2472 struct file *file = iocb->ki_filp;
2473 struct inode *inode = file_inode(file);
2474 struct address_space *mapping = inode->i_mapping;
2476 unsigned long offset;
2477 enum sgp_type sgp = SGP_READ;
2480 loff_t *ppos = &iocb->ki_pos;
2483 * Might this read be for a stacking filesystem? Then when reading
2484 * holes of a sparse file, we actually need to allocate those pages,
2485 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2487 if (!iter_is_iovec(to))
2490 index = *ppos >> PAGE_SHIFT;
2491 offset = *ppos & ~PAGE_MASK;
2494 struct page *page = NULL;
2496 unsigned long nr, ret;
2497 loff_t i_size = i_size_read(inode);
2499 end_index = i_size >> PAGE_SHIFT;
2500 if (index > end_index)
2502 if (index == end_index) {
2503 nr = i_size & ~PAGE_MASK;
2508 error = shmem_getpage(inode, index, &page, sgp);
2510 if (error == -EINVAL)
2515 if (sgp == SGP_CACHE)
2516 set_page_dirty(page);
2521 * We must evaluate after, since reads (unlike writes)
2522 * are called without i_mutex protection against truncate
2525 i_size = i_size_read(inode);
2526 end_index = i_size >> PAGE_SHIFT;
2527 if (index == end_index) {
2528 nr = i_size & ~PAGE_MASK;
2539 * If users can be writing to this page using arbitrary
2540 * virtual addresses, take care about potential aliasing
2541 * before reading the page on the kernel side.
2543 if (mapping_writably_mapped(mapping))
2544 flush_dcache_page(page);
2546 * Mark the page accessed if we read the beginning.
2549 mark_page_accessed(page);
2551 page = ZERO_PAGE(0);
2556 * Ok, we have the page, and it's up-to-date, so
2557 * now we can copy it to user space...
2559 ret = copy_page_to_iter(page, offset, nr, to);
2562 index += offset >> PAGE_SHIFT;
2563 offset &= ~PAGE_MASK;
2566 if (!iov_iter_count(to))
2575 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2576 file_accessed(file);
2577 return retval ? retval : error;
2581 * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
2583 static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2584 pgoff_t index, pgoff_t end, int whence)
2587 struct pagevec pvec;
2588 pgoff_t indices[PAGEVEC_SIZE];
2592 pagevec_init(&pvec, 0);
2593 pvec.nr = 1; /* start small: we may be there already */
2595 pvec.nr = find_get_entries(mapping, index,
2596 pvec.nr, pvec.pages, indices);
2598 if (whence == SEEK_DATA)
2602 for (i = 0; i < pvec.nr; i++, index++) {
2603 if (index < indices[i]) {
2604 if (whence == SEEK_HOLE) {
2610 page = pvec.pages[i];
2611 if (page && !radix_tree_exceptional_entry(page)) {
2612 if (!PageUptodate(page))
2616 (page && whence == SEEK_DATA) ||
2617 (!page && whence == SEEK_HOLE)) {
2622 pagevec_remove_exceptionals(&pvec);
2623 pagevec_release(&pvec);
2624 pvec.nr = PAGEVEC_SIZE;
2630 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2632 struct address_space *mapping = file->f_mapping;
2633 struct inode *inode = mapping->host;
2637 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2638 return generic_file_llseek_size(file, offset, whence,
2639 MAX_LFS_FILESIZE, i_size_read(inode));
2641 /* We're holding i_mutex so we can access i_size directly */
2643 if (offset < 0 || offset >= inode->i_size)
2646 start = offset >> PAGE_SHIFT;
2647 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2648 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
2649 new_offset <<= PAGE_SHIFT;
2650 if (new_offset > offset) {
2651 if (new_offset < inode->i_size)
2652 offset = new_offset;
2653 else if (whence == SEEK_DATA)
2656 offset = inode->i_size;
2661 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2662 inode_unlock(inode);
2667 * We need a tag: a new tag would expand every radix_tree_node by 8 bytes,
2668 * so reuse a tag which we firmly believe is never set or cleared on shmem.
2670 #define SHMEM_TAG_PINNED PAGECACHE_TAG_TOWRITE
2671 #define LAST_SCAN 4 /* about 150ms max */
2673 static void shmem_tag_pins(struct address_space *mapping)
2675 struct radix_tree_iter iter;
2679 unsigned int tagged = 0;
2684 spin_lock_irq(&mapping->tree_lock);
2685 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
2686 page = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
2687 if (!page || radix_tree_exception(page)) {
2688 if (radix_tree_deref_retry(page)) {
2689 slot = radix_tree_iter_retry(&iter);
2692 } else if (page_count(page) - page_mapcount(page) > 1) {
2693 radix_tree_tag_set(&mapping->page_tree, iter.index,
2697 if (++tagged % 1024)
2700 slot = radix_tree_iter_resume(slot, &iter);
2701 spin_unlock_irq(&mapping->tree_lock);
2703 spin_lock_irq(&mapping->tree_lock);
2705 spin_unlock_irq(&mapping->tree_lock);
2709 * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
2710 * via get_user_pages(), drivers might have some pending I/O without any active
2711 * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
2712 * and see whether it has an elevated ref-count. If so, we tag them and wait for
2713 * them to be dropped.
2714 * The caller must guarantee that no new user will acquire writable references
2715 * to those pages to avoid races.
2717 static int shmem_wait_for_pins(struct address_space *mapping)
2719 struct radix_tree_iter iter;
2725 shmem_tag_pins(mapping);
2728 for (scan = 0; scan <= LAST_SCAN; scan++) {
2729 if (!radix_tree_tagged(&mapping->page_tree, SHMEM_TAG_PINNED))
2733 lru_add_drain_all();
2734 else if (schedule_timeout_killable((HZ << scan) / 200))
2739 radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter,
2740 start, SHMEM_TAG_PINNED) {
2742 page = radix_tree_deref_slot(slot);
2743 if (radix_tree_exception(page)) {
2744 if (radix_tree_deref_retry(page)) {
2745 slot = radix_tree_iter_retry(&iter);
2753 page_count(page) - page_mapcount(page) != 1) {
2754 if (scan < LAST_SCAN)
2755 goto continue_resched;
2758 * On the last scan, we clean up all those tags
2759 * we inserted; but make a note that we still
2760 * found pages pinned.
2765 spin_lock_irq(&mapping->tree_lock);
2766 radix_tree_tag_clear(&mapping->page_tree,
2767 iter.index, SHMEM_TAG_PINNED);
2768 spin_unlock_irq(&mapping->tree_lock);
2770 if (need_resched()) {
2771 slot = radix_tree_iter_resume(slot, &iter);
2781 #define F_ALL_SEALS (F_SEAL_SEAL | \
2786 int shmem_add_seals(struct file *file, unsigned int seals)
2788 struct inode *inode = file_inode(file);
2789 struct shmem_inode_info *info = SHMEM_I(inode);
2794 * Sealing allows multiple parties to share a shmem-file but restrict
2795 * access to a specific subset of file operations. Seals can only be
2796 * added, but never removed. This way, mutually untrusted parties can
2797 * share common memory regions with a well-defined policy. A malicious
2798 * peer can thus never perform unwanted operations on a shared object.
2800 * Seals are only supported on special shmem-files and always affect
2801 * the whole underlying inode. Once a seal is set, it may prevent some
2802 * kinds of access to the file. Currently, the following seals are
2804 * SEAL_SEAL: Prevent further seals from being set on this file
2805 * SEAL_SHRINK: Prevent the file from shrinking
2806 * SEAL_GROW: Prevent the file from growing
2807 * SEAL_WRITE: Prevent write access to the file
2809 * As we don't require any trust relationship between two parties, we
2810 * must prevent seals from being removed. Therefore, sealing a file
2811 * only adds a given set of seals to the file, it never touches
2812 * existing seals. Furthermore, the "setting seals"-operation can be
2813 * sealed itself, which basically prevents any further seal from being
2816 * Semantics of sealing are only defined on volatile files. Only
2817 * anonymous shmem files support sealing. More importantly, seals are
2818 * never written to disk. Therefore, there's no plan to support it on
2822 if (file->f_op != &shmem_file_operations)
2824 if (!(file->f_mode & FMODE_WRITE))
2826 if (seals & ~(unsigned int)F_ALL_SEALS)
2831 if (info->seals & F_SEAL_SEAL) {
2836 if ((seals & F_SEAL_WRITE) && !(info->seals & F_SEAL_WRITE)) {
2837 error = mapping_deny_writable(file->f_mapping);
2841 error = shmem_wait_for_pins(file->f_mapping);
2843 mapping_allow_writable(file->f_mapping);
2848 info->seals |= seals;
2852 inode_unlock(inode);
2855 EXPORT_SYMBOL_GPL(shmem_add_seals);
2857 int shmem_get_seals(struct file *file)
2859 if (file->f_op != &shmem_file_operations)
2862 return SHMEM_I(file_inode(file))->seals;
2864 EXPORT_SYMBOL_GPL(shmem_get_seals);
2866 long shmem_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
2872 /* disallow upper 32bit */
2876 error = shmem_add_seals(file, arg);
2879 error = shmem_get_seals(file);
2889 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2892 struct inode *inode = file_inode(file);
2893 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2894 struct shmem_inode_info *info = SHMEM_I(inode);
2895 struct shmem_falloc shmem_falloc;
2896 pgoff_t start, index, end;
2899 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2904 if (mode & FALLOC_FL_PUNCH_HOLE) {
2905 struct address_space *mapping = file->f_mapping;
2906 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2907 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2908 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2910 /* protected by i_mutex */
2911 if (info->seals & F_SEAL_WRITE) {
2916 shmem_falloc.waitq = &shmem_falloc_waitq;
2917 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
2918 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2919 spin_lock(&inode->i_lock);
2920 inode->i_private = &shmem_falloc;
2921 spin_unlock(&inode->i_lock);
2923 if ((u64)unmap_end > (u64)unmap_start)
2924 unmap_mapping_range(mapping, unmap_start,
2925 1 + unmap_end - unmap_start, 0);
2926 shmem_truncate_range(inode, offset, offset + len - 1);
2927 /* No need to unmap again: hole-punching leaves COWed pages */
2929 spin_lock(&inode->i_lock);
2930 inode->i_private = NULL;
2931 wake_up_all(&shmem_falloc_waitq);
2932 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2933 spin_unlock(&inode->i_lock);
2938 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2939 error = inode_newsize_ok(inode, offset + len);
2943 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2948 start = offset >> PAGE_SHIFT;
2949 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2950 /* Try to avoid a swapstorm if len is impossible to satisfy */
2951 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2956 shmem_falloc.waitq = NULL;
2957 shmem_falloc.start = start;
2958 shmem_falloc.next = start;
2959 shmem_falloc.nr_falloced = 0;
2960 shmem_falloc.nr_unswapped = 0;
2961 spin_lock(&inode->i_lock);
2962 inode->i_private = &shmem_falloc;
2963 spin_unlock(&inode->i_lock);
2965 for (index = start; index < end; index++) {
2969 * Good, the fallocate(2) manpage permits EINTR: we may have
2970 * been interrupted because we are using up too much memory.
2972 if (signal_pending(current))
2974 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2977 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2979 /* Remove the !PageUptodate pages we added */
2980 if (index > start) {
2981 shmem_undo_range(inode,
2982 (loff_t)start << PAGE_SHIFT,
2983 ((loff_t)index << PAGE_SHIFT) - 1, true);
2989 * Inform shmem_writepage() how far we have reached.
2990 * No need for lock or barrier: we have the page lock.
2992 shmem_falloc.next++;
2993 if (!PageUptodate(page))
2994 shmem_falloc.nr_falloced++;
2997 * If !PageUptodate, leave it that way so that freeable pages
2998 * can be recognized if we need to rollback on error later.
2999 * But set_page_dirty so that memory pressure will swap rather
3000 * than free the pages we are allocating (and SGP_CACHE pages
3001 * might still be clean: we now need to mark those dirty too).
3003 set_page_dirty(page);
3009 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
3010 i_size_write(inode, offset + len);
3011 inode->i_ctime = current_time(inode);
3013 spin_lock(&inode->i_lock);
3014 inode->i_private = NULL;
3015 spin_unlock(&inode->i_lock);
3017 inode_unlock(inode);
3021 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
3023 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
3025 buf->f_type = TMPFS_MAGIC;
3026 buf->f_bsize = PAGE_SIZE;
3027 buf->f_namelen = NAME_MAX;
3028 if (sbinfo->max_blocks) {
3029 buf->f_blocks = sbinfo->max_blocks;
3031 buf->f_bfree = sbinfo->max_blocks -
3032 percpu_counter_sum(&sbinfo->used_blocks);
3034 if (sbinfo->max_inodes) {
3035 buf->f_files = sbinfo->max_inodes;
3036 buf->f_ffree = sbinfo->free_inodes;
3038 /* else leave those fields 0 like simple_statfs */
3043 * File creation. Allocate an inode, and we're done..
3046 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3048 struct inode *inode;
3049 int error = -ENOSPC;
3051 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
3053 error = simple_acl_create(dir, inode);
3056 error = security_inode_init_security(inode, dir,
3058 shmem_initxattrs, NULL);
3059 if (error && error != -EOPNOTSUPP)
3063 dir->i_size += BOGO_DIRENT_SIZE;
3064 dir->i_ctime = dir->i_mtime = current_time(dir);
3065 d_instantiate(dentry, inode);
3066 dget(dentry); /* Extra count - pin the dentry in core */
3075 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
3077 struct inode *inode;
3078 int error = -ENOSPC;
3080 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
3082 error = security_inode_init_security(inode, dir,
3084 shmem_initxattrs, NULL);
3085 if (error && error != -EOPNOTSUPP)
3087 error = simple_acl_create(dir, inode);
3090 d_tmpfile(dentry, inode);
3098 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
3102 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
3108 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
3111 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
3117 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
3119 struct inode *inode = d_inode(old_dentry);
3123 * No ordinary (disk based) filesystem counts links as inodes;
3124 * but each new link needs a new dentry, pinning lowmem, and
3125 * tmpfs dentries cannot be pruned until they are unlinked.
3126 * But if an O_TMPFILE file is linked into the tmpfs, the
3127 * first link must skip that, to get the accounting right.
3129 if (inode->i_nlink) {
3130 ret = shmem_reserve_inode(inode->i_sb);
3135 dir->i_size += BOGO_DIRENT_SIZE;
3136 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3138 ihold(inode); /* New dentry reference */
3139 dget(dentry); /* Extra pinning count for the created dentry */
3140 d_instantiate(dentry, inode);
3145 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
3147 struct inode *inode = d_inode(dentry);
3149 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
3150 shmem_free_inode(inode->i_sb);
3152 dir->i_size -= BOGO_DIRENT_SIZE;
3153 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
3155 dput(dentry); /* Undo the count from "create" - this does all the work */
3159 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
3161 if (!simple_empty(dentry))
3164 drop_nlink(d_inode(dentry));
3166 return shmem_unlink(dir, dentry);
3169 static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
3171 bool old_is_dir = d_is_dir(old_dentry);
3172 bool new_is_dir = d_is_dir(new_dentry);
3174 if (old_dir != new_dir && old_is_dir != new_is_dir) {
3176 drop_nlink(old_dir);
3179 drop_nlink(new_dir);
3183 old_dir->i_ctime = old_dir->i_mtime =
3184 new_dir->i_ctime = new_dir->i_mtime =
3185 d_inode(old_dentry)->i_ctime =
3186 d_inode(new_dentry)->i_ctime = current_time(old_dir);
3191 static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
3193 struct dentry *whiteout;
3196 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
3200 error = shmem_mknod(old_dir, whiteout,
3201 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
3207 * Cheat and hash the whiteout while the old dentry is still in
3208 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3210 * d_lookup() will consistently find one of them at this point,
3211 * not sure which one, but that isn't even important.
3218 * The VFS layer already does all the dentry stuff for rename,
3219 * we just have to decrement the usage count for the target if
3220 * it exists so that the VFS layer correctly free's it when it
3223 static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
3225 struct inode *inode = d_inode(old_dentry);
3226 int they_are_dirs = S_ISDIR(inode->i_mode);
3228 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
3231 if (flags & RENAME_EXCHANGE)
3232 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
3234 if (!simple_empty(new_dentry))
3237 if (flags & RENAME_WHITEOUT) {
3240 error = shmem_whiteout(old_dir, old_dentry);
3245 if (d_really_is_positive(new_dentry)) {
3246 (void) shmem_unlink(new_dir, new_dentry);
3247 if (they_are_dirs) {
3248 drop_nlink(d_inode(new_dentry));
3249 drop_nlink(old_dir);
3251 } else if (they_are_dirs) {
3252 drop_nlink(old_dir);
3256 old_dir->i_size -= BOGO_DIRENT_SIZE;
3257 new_dir->i_size += BOGO_DIRENT_SIZE;
3258 old_dir->i_ctime = old_dir->i_mtime =
3259 new_dir->i_ctime = new_dir->i_mtime =
3260 inode->i_ctime = current_time(old_dir);
3264 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
3268 struct inode *inode;
3270 struct shmem_inode_info *info;
3272 len = strlen(symname) + 1;
3273 if (len > PAGE_SIZE)
3274 return -ENAMETOOLONG;
3276 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
3280 error = security_inode_init_security(inode, dir, &dentry->d_name,
3281 shmem_initxattrs, NULL);
3283 if (error != -EOPNOTSUPP) {
3290 info = SHMEM_I(inode);
3291 inode->i_size = len-1;
3292 if (len <= SHORT_SYMLINK_LEN) {
3293 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3294 if (!inode->i_link) {
3298 inode->i_op = &shmem_short_symlink_operations;
3300 inode_nohighmem(inode);
3301 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
3306 inode->i_mapping->a_ops = &shmem_aops;
3307 inode->i_op = &shmem_symlink_inode_operations;
3308 memcpy(page_address(page), symname, len);
3309 SetPageUptodate(page);
3310 set_page_dirty(page);
3314 dir->i_size += BOGO_DIRENT_SIZE;
3315 dir->i_ctime = dir->i_mtime = current_time(dir);
3316 d_instantiate(dentry, inode);
3321 static void shmem_put_link(void *arg)
3323 mark_page_accessed(arg);
3327 static const char *shmem_get_link(struct dentry *dentry,
3328 struct inode *inode,
3329 struct delayed_call *done)
3331 struct page *page = NULL;
3334 page = find_get_page(inode->i_mapping, 0);
3336 return ERR_PTR(-ECHILD);
3337 if (!PageUptodate(page)) {
3339 return ERR_PTR(-ECHILD);
3342 error = shmem_getpage(inode, 0, &page, SGP_READ);
3344 return ERR_PTR(error);
3347 set_delayed_call(done, shmem_put_link, page);
3348 return page_address(page);
3351 #ifdef CONFIG_TMPFS_XATTR
3353 * Superblocks without xattr inode operations may get some security.* xattr
3354 * support from the LSM "for free". As soon as we have any other xattrs
3355 * like ACLs, we also need to implement the security.* handlers at
3356 * filesystem level, though.
3360 * Callback for security_inode_init_security() for acquiring xattrs.
3362 static int shmem_initxattrs(struct inode *inode,
3363 const struct xattr *xattr_array,
3366 struct shmem_inode_info *info = SHMEM_I(inode);
3367 const struct xattr *xattr;
3368 struct simple_xattr *new_xattr;
3371 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3372 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3376 len = strlen(xattr->name) + 1;
3377 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3379 if (!new_xattr->name) {
3384 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3385 XATTR_SECURITY_PREFIX_LEN);
3386 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3389 simple_xattr_list_add(&info->xattrs, new_xattr);
3395 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3396 struct dentry *unused, struct inode *inode,
3397 const char *name, void *buffer, size_t size)
3399 struct shmem_inode_info *info = SHMEM_I(inode);
3401 name = xattr_full_name(handler, name);
3402 return simple_xattr_get(&info->xattrs, name, buffer, size);
3405 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3406 struct dentry *unused, struct inode *inode,
3407 const char *name, const void *value,
3408 size_t size, int flags)
3410 struct shmem_inode_info *info = SHMEM_I(inode);
3412 name = xattr_full_name(handler, name);
3413 return simple_xattr_set(&info->xattrs, name, value, size, flags);
3416 static const struct xattr_handler shmem_security_xattr_handler = {
3417 .prefix = XATTR_SECURITY_PREFIX,
3418 .get = shmem_xattr_handler_get,
3419 .set = shmem_xattr_handler_set,
3422 static const struct xattr_handler shmem_trusted_xattr_handler = {
3423 .prefix = XATTR_TRUSTED_PREFIX,
3424 .get = shmem_xattr_handler_get,
3425 .set = shmem_xattr_handler_set,
3428 static const struct xattr_handler *shmem_xattr_handlers[] = {
3429 #ifdef CONFIG_TMPFS_POSIX_ACL
3430 &posix_acl_access_xattr_handler,
3431 &posix_acl_default_xattr_handler,
3433 &shmem_security_xattr_handler,
3434 &shmem_trusted_xattr_handler,
3438 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3440 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3441 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3443 #endif /* CONFIG_TMPFS_XATTR */
3445 static const struct inode_operations shmem_short_symlink_operations = {
3446 .get_link = simple_get_link,
3447 #ifdef CONFIG_TMPFS_XATTR
3448 .listxattr = shmem_listxattr,
3452 static const struct inode_operations shmem_symlink_inode_operations = {
3453 .get_link = shmem_get_link,
3454 #ifdef CONFIG_TMPFS_XATTR
3455 .listxattr = shmem_listxattr,
3459 static struct dentry *shmem_get_parent(struct dentry *child)
3461 return ERR_PTR(-ESTALE);
3464 static int shmem_match(struct inode *ino, void *vfh)
3468 inum = (inum << 32) | fh[1];
3469 return ino->i_ino == inum && fh[0] == ino->i_generation;
3472 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3473 struct fid *fid, int fh_len, int fh_type)
3475 struct inode *inode;
3476 struct dentry *dentry = NULL;
3483 inum = (inum << 32) | fid->raw[1];
3485 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3486 shmem_match, fid->raw);
3488 dentry = d_find_alias(inode);
3495 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3496 struct inode *parent)
3500 return FILEID_INVALID;
3503 if (inode_unhashed(inode)) {
3504 /* Unfortunately insert_inode_hash is not idempotent,
3505 * so as we hash inodes here rather than at creation
3506 * time, we need a lock to ensure we only try
3509 static DEFINE_SPINLOCK(lock);
3511 if (inode_unhashed(inode))
3512 __insert_inode_hash(inode,
3513 inode->i_ino + inode->i_generation);
3517 fh[0] = inode->i_generation;
3518 fh[1] = inode->i_ino;
3519 fh[2] = ((__u64)inode->i_ino) >> 32;
3525 static const struct export_operations shmem_export_ops = {
3526 .get_parent = shmem_get_parent,
3527 .encode_fh = shmem_encode_fh,
3528 .fh_to_dentry = shmem_fh_to_dentry,
3531 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
3534 char *this_char, *value, *rest;
3535 struct mempolicy *mpol = NULL;
3539 while (options != NULL) {
3540 this_char = options;
3543 * NUL-terminate this option: unfortunately,
3544 * mount options form a comma-separated list,
3545 * but mpol's nodelist may also contain commas.
3547 options = strchr(options, ',');
3548 if (options == NULL)
3551 if (!isdigit(*options)) {
3558 if ((value = strchr(this_char,'=')) != NULL) {
3561 pr_err("tmpfs: No value for mount option '%s'\n",
3566 if (!strcmp(this_char,"size")) {
3567 unsigned long long size;
3568 size = memparse(value,&rest);
3570 size <<= PAGE_SHIFT;
3571 size *= totalram_pages;
3577 sbinfo->max_blocks =
3578 DIV_ROUND_UP(size, PAGE_SIZE);
3579 } else if (!strcmp(this_char,"nr_blocks")) {
3580 sbinfo->max_blocks = memparse(value, &rest);
3583 } else if (!strcmp(this_char,"nr_inodes")) {
3584 sbinfo->max_inodes = memparse(value, &rest);
3587 } else if (!strcmp(this_char,"mode")) {
3590 sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
3593 } else if (!strcmp(this_char,"uid")) {
3596 uid = simple_strtoul(value, &rest, 0);
3599 sbinfo->uid = make_kuid(current_user_ns(), uid);
3600 if (!uid_valid(sbinfo->uid))
3602 } else if (!strcmp(this_char,"gid")) {
3605 gid = simple_strtoul(value, &rest, 0);
3608 sbinfo->gid = make_kgid(current_user_ns(), gid);
3609 if (!gid_valid(sbinfo->gid))
3611 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3612 } else if (!strcmp(this_char, "huge")) {
3614 huge = shmem_parse_huge(value);
3617 if (!has_transparent_hugepage() &&
3618 huge != SHMEM_HUGE_NEVER)
3620 sbinfo->huge = huge;
3623 } else if (!strcmp(this_char,"mpol")) {
3626 if (mpol_parse_str(value, &mpol))
3630 pr_err("tmpfs: Bad mount option %s\n", this_char);
3634 sbinfo->mpol = mpol;
3638 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3646 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
3648 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3649 struct shmem_sb_info config = *sbinfo;
3650 unsigned long inodes;
3651 int error = -EINVAL;
3654 if (shmem_parse_options(data, &config, true))
3657 spin_lock(&sbinfo->stat_lock);
3658 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3659 if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
3661 if (config.max_inodes < inodes)
3664 * Those tests disallow limited->unlimited while any are in use;
3665 * but we must separately disallow unlimited->limited, because
3666 * in that case we have no record of how much is already in use.
3668 if (config.max_blocks && !sbinfo->max_blocks)
3670 if (config.max_inodes && !sbinfo->max_inodes)
3674 sbinfo->huge = config.huge;
3675 sbinfo->max_blocks = config.max_blocks;
3676 sbinfo->max_inodes = config.max_inodes;
3677 sbinfo->free_inodes = config.max_inodes - inodes;
3680 * Preserve previous mempolicy unless mpol remount option was specified.
3683 mpol_put(sbinfo->mpol);
3684 sbinfo->mpol = config.mpol; /* transfers initial ref */
3687 spin_unlock(&sbinfo->stat_lock);
3691 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3693 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3695 if (sbinfo->max_blocks != shmem_default_max_blocks())
3696 seq_printf(seq, ",size=%luk",
3697 sbinfo->max_blocks << (PAGE_SHIFT - 10));
3698 if (sbinfo->max_inodes != shmem_default_max_inodes())
3699 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3700 if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
3701 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3702 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3703 seq_printf(seq, ",uid=%u",
3704 from_kuid_munged(&init_user_ns, sbinfo->uid));
3705 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3706 seq_printf(seq, ",gid=%u",
3707 from_kgid_munged(&init_user_ns, sbinfo->gid));
3708 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3709 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3711 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3713 shmem_show_mpol(seq, sbinfo->mpol);
3717 #define MFD_NAME_PREFIX "memfd:"
3718 #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
3719 #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
3721 #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_HUGETLB)
3723 SYSCALL_DEFINE2(memfd_create,
3724 const char __user *, uname,
3725 unsigned int, flags)
3727 struct shmem_inode_info *info;
3733 if (!(flags & MFD_HUGETLB)) {
3734 if (flags & ~(unsigned int)MFD_ALL_FLAGS)
3737 /* Sealing not supported in hugetlbfs (MFD_HUGETLB) */
3738 if (flags & MFD_ALLOW_SEALING)
3740 /* Allow huge page size encoding in flags. */
3741 if (flags & ~(unsigned int)(MFD_ALL_FLAGS |
3742 (MFD_HUGE_MASK << MFD_HUGE_SHIFT)))
3746 /* length includes terminating zero */
3747 len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
3750 if (len > MFD_NAME_MAX_LEN + 1)
3753 name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_KERNEL);
3757 strcpy(name, MFD_NAME_PREFIX);
3758 if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
3763 /* terminating-zero may have changed after strnlen_user() returned */
3764 if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
3769 fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
3775 if (flags & MFD_HUGETLB) {
3776 struct user_struct *user = NULL;
3778 file = hugetlb_file_setup(name, 0, VM_NORESERVE, &user,
3779 HUGETLB_ANONHUGE_INODE,
3780 (flags >> MFD_HUGE_SHIFT) &
3783 file = shmem_file_setup(name, 0, VM_NORESERVE);
3785 error = PTR_ERR(file);
3788 file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
3789 file->f_flags |= O_RDWR | O_LARGEFILE;
3791 if (flags & MFD_ALLOW_SEALING) {
3793 * flags check at beginning of function ensures
3794 * this is not a hugetlbfs (MFD_HUGETLB) file.
3796 info = SHMEM_I(file_inode(file));
3797 info->seals &= ~F_SEAL_SEAL;
3800 fd_install(fd, file);
3811 #endif /* CONFIG_TMPFS */
3813 static void shmem_put_super(struct super_block *sb)
3815 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3817 percpu_counter_destroy(&sbinfo->used_blocks);
3818 mpol_put(sbinfo->mpol);
3820 sb->s_fs_info = NULL;
3823 int shmem_fill_super(struct super_block *sb, void *data, int silent)
3825 struct inode *inode;
3826 struct shmem_sb_info *sbinfo;
3829 /* Round up to L1_CACHE_BYTES to resist false sharing */
3830 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3831 L1_CACHE_BYTES), GFP_KERNEL);
3835 sbinfo->mode = S_IRWXUGO | S_ISVTX;
3836 sbinfo->uid = current_fsuid();
3837 sbinfo->gid = current_fsgid();
3838 sb->s_fs_info = sbinfo;
3842 * Per default we only allow half of the physical ram per
3843 * tmpfs instance, limiting inodes to one per page of lowmem;
3844 * but the internal instance is left unlimited.
3846 if (!(sb->s_flags & MS_KERNMOUNT)) {
3847 sbinfo->max_blocks = shmem_default_max_blocks();
3848 sbinfo->max_inodes = shmem_default_max_inodes();
3849 if (shmem_parse_options(data, sbinfo, false)) {
3854 sb->s_flags |= MS_NOUSER;
3856 sb->s_export_op = &shmem_export_ops;
3857 sb->s_flags |= MS_NOSEC;
3859 sb->s_flags |= MS_NOUSER;
3862 spin_lock_init(&sbinfo->stat_lock);
3863 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3865 sbinfo->free_inodes = sbinfo->max_inodes;
3866 spin_lock_init(&sbinfo->shrinklist_lock);
3867 INIT_LIST_HEAD(&sbinfo->shrinklist);
3869 sb->s_maxbytes = MAX_LFS_FILESIZE;
3870 sb->s_blocksize = PAGE_SIZE;
3871 sb->s_blocksize_bits = PAGE_SHIFT;
3872 sb->s_magic = TMPFS_MAGIC;
3873 sb->s_op = &shmem_ops;
3874 sb->s_time_gran = 1;
3875 #ifdef CONFIG_TMPFS_XATTR
3876 sb->s_xattr = shmem_xattr_handlers;
3878 #ifdef CONFIG_TMPFS_POSIX_ACL
3879 sb->s_flags |= MS_POSIXACL;
3881 uuid_gen(&sb->s_uuid);
3883 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3886 inode->i_uid = sbinfo->uid;
3887 inode->i_gid = sbinfo->gid;
3888 sb->s_root = d_make_root(inode);
3894 shmem_put_super(sb);
3898 static struct kmem_cache *shmem_inode_cachep;
3900 static struct inode *shmem_alloc_inode(struct super_block *sb)
3902 struct shmem_inode_info *info;
3903 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3906 return &info->vfs_inode;
3909 static void shmem_destroy_callback(struct rcu_head *head)
3911 struct inode *inode = container_of(head, struct inode, i_rcu);
3912 if (S_ISLNK(inode->i_mode))
3913 kfree(inode->i_link);
3914 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3917 static void shmem_destroy_inode(struct inode *inode)
3919 if (S_ISREG(inode->i_mode))
3920 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3921 call_rcu(&inode->i_rcu, shmem_destroy_callback);
3924 static void shmem_init_inode(void *foo)
3926 struct shmem_inode_info *info = foo;
3927 inode_init_once(&info->vfs_inode);
3930 static int shmem_init_inodecache(void)
3932 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3933 sizeof(struct shmem_inode_info),
3934 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3938 static void shmem_destroy_inodecache(void)
3940 kmem_cache_destroy(shmem_inode_cachep);
3943 static const struct address_space_operations shmem_aops = {
3944 .writepage = shmem_writepage,
3945 .set_page_dirty = __set_page_dirty_no_writeback,
3947 .write_begin = shmem_write_begin,
3948 .write_end = shmem_write_end,
3950 #ifdef CONFIG_MIGRATION
3951 .migratepage = migrate_page,
3953 .error_remove_page = generic_error_remove_page,
3956 static const struct file_operations shmem_file_operations = {
3958 .get_unmapped_area = shmem_get_unmapped_area,
3960 .llseek = shmem_file_llseek,
3961 .read_iter = shmem_file_read_iter,
3962 .write_iter = generic_file_write_iter,
3963 .fsync = noop_fsync,
3964 .splice_read = generic_file_splice_read,
3965 .splice_write = iter_file_splice_write,
3966 .fallocate = shmem_fallocate,
3970 static const struct inode_operations shmem_inode_operations = {
3971 .getattr = shmem_getattr,
3972 .setattr = shmem_setattr,
3973 #ifdef CONFIG_TMPFS_XATTR
3974 .listxattr = shmem_listxattr,
3975 .set_acl = simple_set_acl,
3979 static const struct inode_operations shmem_dir_inode_operations = {
3981 .create = shmem_create,
3982 .lookup = simple_lookup,
3984 .unlink = shmem_unlink,
3985 .symlink = shmem_symlink,
3986 .mkdir = shmem_mkdir,
3987 .rmdir = shmem_rmdir,
3988 .mknod = shmem_mknod,
3989 .rename = shmem_rename2,
3990 .tmpfile = shmem_tmpfile,
3992 #ifdef CONFIG_TMPFS_XATTR
3993 .listxattr = shmem_listxattr,
3995 #ifdef CONFIG_TMPFS_POSIX_ACL
3996 .setattr = shmem_setattr,
3997 .set_acl = simple_set_acl,
4001 static const struct inode_operations shmem_special_inode_operations = {
4002 #ifdef CONFIG_TMPFS_XATTR
4003 .listxattr = shmem_listxattr,
4005 #ifdef CONFIG_TMPFS_POSIX_ACL
4006 .setattr = shmem_setattr,
4007 .set_acl = simple_set_acl,
4011 static const struct super_operations shmem_ops = {
4012 .alloc_inode = shmem_alloc_inode,
4013 .destroy_inode = shmem_destroy_inode,
4015 .statfs = shmem_statfs,
4016 .remount_fs = shmem_remount_fs,
4017 .show_options = shmem_show_options,
4019 .evict_inode = shmem_evict_inode,
4020 .drop_inode = generic_delete_inode,
4021 .put_super = shmem_put_super,
4022 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
4023 .nr_cached_objects = shmem_unused_huge_count,
4024 .free_cached_objects = shmem_unused_huge_scan,
4028 static const struct vm_operations_struct shmem_vm_ops = {
4029 .fault = shmem_fault,
4030 .map_pages = filemap_map_pages,
4032 .set_policy = shmem_set_policy,
4033 .get_policy = shmem_get_policy,
4037 static struct dentry *shmem_mount(struct file_system_type *fs_type,
4038 int flags, const char *dev_name, void *data)
4040 return mount_nodev(fs_type, flags, data, shmem_fill_super);
4043 static struct file_system_type shmem_fs_type = {
4044 .owner = THIS_MODULE,
4046 .mount = shmem_mount,
4047 .kill_sb = kill_litter_super,
4048 .fs_flags = FS_USERNS_MOUNT,
4051 int __init shmem_init(void)
4055 /* If rootfs called this, don't re-init */
4056 if (shmem_inode_cachep)
4059 error = shmem_init_inodecache();
4063 error = register_filesystem(&shmem_fs_type);
4065 pr_err("Could not register tmpfs\n");
4069 shm_mnt = kern_mount(&shmem_fs_type);
4070 if (IS_ERR(shm_mnt)) {
4071 error = PTR_ERR(shm_mnt);
4072 pr_err("Could not kern_mount tmpfs\n");
4076 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
4077 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
4078 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4080 shmem_huge = 0; /* just in case it was patched */
4085 unregister_filesystem(&shmem_fs_type);
4087 shmem_destroy_inodecache();
4089 shm_mnt = ERR_PTR(error);
4093 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
4094 static ssize_t shmem_enabled_show(struct kobject *kobj,
4095 struct kobj_attribute *attr, char *buf)
4099 SHMEM_HUGE_WITHIN_SIZE,
4107 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
4108 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
4110 count += sprintf(buf + count, fmt,
4111 shmem_format_huge(values[i]));
4113 buf[count - 1] = '\n';
4117 static ssize_t shmem_enabled_store(struct kobject *kobj,
4118 struct kobj_attribute *attr, const char *buf, size_t count)
4123 if (count + 1 > sizeof(tmp))
4125 memcpy(tmp, buf, count);
4127 if (count && tmp[count - 1] == '\n')
4128 tmp[count - 1] = '\0';
4130 huge = shmem_parse_huge(tmp);
4131 if (huge == -EINVAL)
4133 if (!has_transparent_hugepage() &&
4134 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
4138 if (shmem_huge > SHMEM_HUGE_DENY)
4139 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
4143 struct kobj_attribute shmem_enabled_attr =
4144 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
4145 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
4147 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
4148 bool shmem_huge_enabled(struct vm_area_struct *vma)
4150 struct inode *inode = file_inode(vma->vm_file);
4151 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
4155 if (shmem_huge == SHMEM_HUGE_FORCE)
4157 if (shmem_huge == SHMEM_HUGE_DENY)
4159 switch (sbinfo->huge) {
4160 case SHMEM_HUGE_NEVER:
4162 case SHMEM_HUGE_ALWAYS:
4164 case SHMEM_HUGE_WITHIN_SIZE:
4165 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
4166 i_size = round_up(i_size_read(inode), PAGE_SIZE);
4167 if (i_size >= HPAGE_PMD_SIZE &&
4168 i_size >> PAGE_SHIFT >= off)
4170 case SHMEM_HUGE_ADVISE:
4171 /* TODO: implement fadvise() hints */
4172 return (vma->vm_flags & VM_HUGEPAGE);
4178 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
4180 #else /* !CONFIG_SHMEM */
4183 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
4185 * This is intended for small system where the benefits of the full
4186 * shmem code (swap-backed and resource-limited) are outweighed by
4187 * their complexity. On systems without swap this code should be
4188 * effectively equivalent, but much lighter weight.
4191 static struct file_system_type shmem_fs_type = {
4193 .mount = ramfs_mount,
4194 .kill_sb = kill_litter_super,
4195 .fs_flags = FS_USERNS_MOUNT,
4198 int __init shmem_init(void)
4200 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
4202 shm_mnt = kern_mount(&shmem_fs_type);
4203 BUG_ON(IS_ERR(shm_mnt));
4208 int shmem_unuse(swp_entry_t swap, struct page *page)
4213 int shmem_lock(struct file *file, int lock, struct user_struct *user)
4218 void shmem_unlock_mapping(struct address_space *mapping)
4223 unsigned long shmem_get_unmapped_area(struct file *file,
4224 unsigned long addr, unsigned long len,
4225 unsigned long pgoff, unsigned long flags)
4227 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
4231 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
4233 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
4235 EXPORT_SYMBOL_GPL(shmem_truncate_range);
4237 #define shmem_vm_ops generic_file_vm_ops
4238 #define shmem_file_operations ramfs_file_operations
4239 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
4240 #define shmem_acct_size(flags, size) 0
4241 #define shmem_unacct_size(flags, size) do {} while (0)
4243 #endif /* CONFIG_SHMEM */
4247 static const struct dentry_operations anon_ops = {
4248 .d_dname = simple_dname
4251 static struct file *__shmem_file_setup(const char *name, loff_t size,
4252 unsigned long flags, unsigned int i_flags)
4255 struct inode *inode;
4257 struct super_block *sb;
4260 if (IS_ERR(shm_mnt))
4261 return ERR_CAST(shm_mnt);
4263 if (size < 0 || size > MAX_LFS_FILESIZE)
4264 return ERR_PTR(-EINVAL);
4266 if (shmem_acct_size(flags, size))
4267 return ERR_PTR(-ENOMEM);
4269 res = ERR_PTR(-ENOMEM);
4271 this.len = strlen(name);
4272 this.hash = 0; /* will go */
4273 sb = shm_mnt->mnt_sb;
4274 path.mnt = mntget(shm_mnt);
4275 path.dentry = d_alloc_pseudo(sb, &this);
4278 d_set_d_op(path.dentry, &anon_ops);
4280 res = ERR_PTR(-ENOSPC);
4281 inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
4285 inode->i_flags |= i_flags;
4286 d_instantiate(path.dentry, inode);
4287 inode->i_size = size;
4288 clear_nlink(inode); /* It is unlinked */
4289 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
4293 res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
4294 &shmem_file_operations);
4301 shmem_unacct_size(flags, size);
4308 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4309 * kernel internal. There will be NO LSM permission checks against the
4310 * underlying inode. So users of this interface must do LSM checks at a
4311 * higher layer. The users are the big_key and shm implementations. LSM
4312 * checks are provided at the key or shm level rather than the inode.
4313 * @name: name for dentry (to be seen in /proc/<pid>/maps
4314 * @size: size to be set for the file
4315 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4317 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
4319 return __shmem_file_setup(name, size, flags, S_PRIVATE);
4323 * shmem_file_setup - get an unlinked file living in tmpfs
4324 * @name: name for dentry (to be seen in /proc/<pid>/maps
4325 * @size: size to be set for the file
4326 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4328 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
4330 return __shmem_file_setup(name, size, flags, 0);
4332 EXPORT_SYMBOL_GPL(shmem_file_setup);
4335 * shmem_zero_setup - setup a shared anonymous mapping
4336 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
4338 int shmem_zero_setup(struct vm_area_struct *vma)
4341 loff_t size = vma->vm_end - vma->vm_start;
4344 * Cloning a new file under mmap_sem leads to a lock ordering conflict
4345 * between XFS directory reading and selinux: since this file is only
4346 * accessible to the user through its mapping, use S_PRIVATE flag to
4347 * bypass file security, in the same way as shmem_kernel_file_setup().
4349 file = __shmem_file_setup("dev/zero", size, vma->vm_flags, S_PRIVATE);
4351 return PTR_ERR(file);
4355 vma->vm_file = file;
4356 vma->vm_ops = &shmem_vm_ops;
4358 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
4359 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4360 (vma->vm_end & HPAGE_PMD_MASK)) {
4361 khugepaged_enter(vma, vma->vm_flags);
4368 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4369 * @mapping: the page's address_space
4370 * @index: the page index
4371 * @gfp: the page allocator flags to use if allocating
4373 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4374 * with any new page allocations done using the specified allocation flags.
4375 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4376 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4377 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4379 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4380 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4382 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4383 pgoff_t index, gfp_t gfp)
4386 struct inode *inode = mapping->host;
4390 BUG_ON(mapping->a_ops != &shmem_aops);
4391 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4392 gfp, NULL, NULL, NULL);
4394 page = ERR_PTR(error);
4400 * The tiny !SHMEM case uses ramfs without swap
4402 return read_cache_page_gfp(mapping, index, gfp);
4405 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);