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 int shmem_default_max_inodes(void)
119 ul
= min3(ul
, totalram_pages
- totalhigh_pages
, totalram_pages
/ 2);
124 static bool shmem_should_replace_page(struct page
*page
, gfp_t gfp
);
125 static int shmem_replace_page(struct page
**pagep
, gfp_t gfp
,
126 struct shmem_inode_info
*info
, pgoff_t index
);
127 static int shmem_getpage_gfp(struct inode
*inode
, pgoff_t index
,
128 struct page
**pagep
, enum sgp_type sgp
,
129 gfp_t gfp
, struct vm_area_struct
*vma
,
130 struct vm_fault
*vmf
, int *fault_type
);
132 int shmem_getpage(struct inode
*inode
, pgoff_t index
,
133 struct page
**pagep
, enum sgp_type sgp
)
135 return shmem_getpage_gfp(inode
, index
, pagep
, sgp
,
136 mapping_gfp_mask(inode
->i_mapping
), NULL
, NULL
, NULL
);
139 static inline struct shmem_sb_info
*SHMEM_SB(struct super_block
*sb
)
141 return sb
->s_fs_info
;
145 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
146 * for shared memory and for shared anonymous (/dev/zero) mappings
147 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
148 * consistent with the pre-accounting of private mappings ...
150 static inline int shmem_acct_size(unsigned long flags
, loff_t size
)
152 return (flags
& VM_NORESERVE
) ?
153 0 : security_vm_enough_memory_mm(current
->mm
, VM_ACCT(size
));
156 static inline void shmem_unacct_size(unsigned long flags
, loff_t size
)
158 if (!(flags
& VM_NORESERVE
))
159 vm_unacct_memory(VM_ACCT(size
));
162 static inline int shmem_reacct_size(unsigned long flags
,
163 loff_t oldsize
, loff_t newsize
)
165 if (!(flags
& VM_NORESERVE
)) {
166 if (VM_ACCT(newsize
) > VM_ACCT(oldsize
))
167 return security_vm_enough_memory_mm(current
->mm
,
168 VM_ACCT(newsize
) - VM_ACCT(oldsize
));
169 else if (VM_ACCT(newsize
) < VM_ACCT(oldsize
))
170 vm_unacct_memory(VM_ACCT(oldsize
) - VM_ACCT(newsize
));
176 * ... whereas tmpfs objects are accounted incrementally as
177 * pages are allocated, in order to allow large sparse files.
178 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
179 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
181 static inline int shmem_acct_block(unsigned long flags
, long pages
)
183 if (!(flags
& VM_NORESERVE
))
186 return security_vm_enough_memory_mm(current
->mm
,
187 pages
* VM_ACCT(PAGE_SIZE
));
190 static inline void shmem_unacct_blocks(unsigned long flags
, long pages
)
192 if (flags
& VM_NORESERVE
)
193 vm_unacct_memory(pages
* VM_ACCT(PAGE_SIZE
));
196 static inline bool shmem_inode_acct_block(struct inode
*inode
, long pages
)
198 struct shmem_inode_info
*info
= SHMEM_I(inode
);
199 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
201 if (shmem_acct_block(info
->flags
, pages
))
204 if (sbinfo
->max_blocks
) {
205 if (percpu_counter_compare(&sbinfo
->used_blocks
,
206 sbinfo
->max_blocks
- pages
) > 0)
208 percpu_counter_add(&sbinfo
->used_blocks
, pages
);
214 shmem_unacct_blocks(info
->flags
, pages
);
218 static inline void shmem_inode_unacct_blocks(struct inode
*inode
, long pages
)
220 struct shmem_inode_info
*info
= SHMEM_I(inode
);
221 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
223 if (sbinfo
->max_blocks
)
224 percpu_counter_sub(&sbinfo
->used_blocks
, pages
);
225 shmem_unacct_blocks(info
->flags
, pages
);
228 static const struct super_operations shmem_ops
;
229 static const struct address_space_operations shmem_aops
;
230 static const struct file_operations shmem_file_operations
;
231 static const struct inode_operations shmem_inode_operations
;
232 static const struct inode_operations shmem_dir_inode_operations
;
233 static const struct inode_operations shmem_special_inode_operations
;
234 static const struct vm_operations_struct shmem_vm_ops
;
235 static struct file_system_type shmem_fs_type
;
237 bool vma_is_shmem(struct vm_area_struct
*vma
)
239 return vma
->vm_ops
== &shmem_vm_ops
;
242 static LIST_HEAD(shmem_swaplist
);
243 static DEFINE_MUTEX(shmem_swaplist_mutex
);
245 static int shmem_reserve_inode(struct super_block
*sb
)
247 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
248 if (sbinfo
->max_inodes
) {
249 spin_lock(&sbinfo
->stat_lock
);
250 if (!sbinfo
->free_inodes
) {
251 spin_unlock(&sbinfo
->stat_lock
);
254 sbinfo
->free_inodes
--;
255 spin_unlock(&sbinfo
->stat_lock
);
260 static void shmem_free_inode(struct super_block
*sb
)
262 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
263 if (sbinfo
->max_inodes
) {
264 spin_lock(&sbinfo
->stat_lock
);
265 sbinfo
->free_inodes
++;
266 spin_unlock(&sbinfo
->stat_lock
);
271 * shmem_recalc_inode - recalculate the block usage of an inode
272 * @inode: inode to recalc
274 * We have to calculate the free blocks since the mm can drop
275 * undirtied hole pages behind our back.
277 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
278 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
280 * It has to be called with the spinlock held.
282 static void shmem_recalc_inode(struct inode
*inode
)
284 struct shmem_inode_info
*info
= SHMEM_I(inode
);
287 freed
= info
->alloced
- info
->swapped
- inode
->i_mapping
->nrpages
;
289 info
->alloced
-= freed
;
290 inode
->i_blocks
-= freed
* BLOCKS_PER_PAGE
;
291 shmem_inode_unacct_blocks(inode
, freed
);
295 bool shmem_charge(struct inode
*inode
, long pages
)
297 struct shmem_inode_info
*info
= SHMEM_I(inode
);
300 if (!shmem_inode_acct_block(inode
, pages
))
303 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
304 inode
->i_mapping
->nrpages
+= pages
;
306 spin_lock_irqsave(&info
->lock
, flags
);
307 info
->alloced
+= pages
;
308 inode
->i_blocks
+= pages
* BLOCKS_PER_PAGE
;
309 shmem_recalc_inode(inode
);
310 spin_unlock_irqrestore(&info
->lock
, flags
);
315 void shmem_uncharge(struct inode
*inode
, long pages
)
317 struct shmem_inode_info
*info
= SHMEM_I(inode
);
320 /* nrpages adjustment done by __delete_from_page_cache() or caller */
322 spin_lock_irqsave(&info
->lock
, flags
);
323 info
->alloced
-= pages
;
324 inode
->i_blocks
-= pages
* BLOCKS_PER_PAGE
;
325 shmem_recalc_inode(inode
);
326 spin_unlock_irqrestore(&info
->lock
, flags
);
328 shmem_inode_unacct_blocks(inode
, pages
);
332 * Replace item expected in radix tree by a new item, while holding tree lock.
334 static int shmem_radix_tree_replace(struct address_space
*mapping
,
335 pgoff_t index
, void *expected
, void *replacement
)
337 struct radix_tree_node
*node
;
341 VM_BUG_ON(!expected
);
342 VM_BUG_ON(!replacement
);
343 item
= __radix_tree_lookup(&mapping
->page_tree
, index
, &node
, &pslot
);
346 if (item
!= expected
)
348 __radix_tree_replace(&mapping
->page_tree
, node
, pslot
,
354 * Sometimes, before we decide whether to proceed or to fail, we must check
355 * that an entry was not already brought back from swap by a racing thread.
357 * Checking page is not enough: by the time a SwapCache page is locked, it
358 * might be reused, and again be SwapCache, using the same swap as before.
360 static bool shmem_confirm_swap(struct address_space
*mapping
,
361 pgoff_t index
, swp_entry_t swap
)
366 item
= radix_tree_lookup(&mapping
->page_tree
, index
);
368 return item
== swp_to_radix_entry(swap
);
372 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
375 * disables huge pages for the mount;
377 * enables huge pages for the mount;
378 * SHMEM_HUGE_WITHIN_SIZE:
379 * only allocate huge pages if the page will be fully within i_size,
380 * also respect fadvise()/madvise() hints;
382 * only allocate huge pages if requested with fadvise()/madvise();
385 #define SHMEM_HUGE_NEVER 0
386 #define SHMEM_HUGE_ALWAYS 1
387 #define SHMEM_HUGE_WITHIN_SIZE 2
388 #define SHMEM_HUGE_ADVISE 3
392 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
395 * disables huge on shm_mnt and all mounts, for emergency use;
397 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
400 #define SHMEM_HUGE_DENY (-1)
401 #define SHMEM_HUGE_FORCE (-2)
403 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
404 /* ifdef here to avoid bloating shmem.o when not necessary */
406 int shmem_huge __read_mostly
;
408 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
409 static int shmem_parse_huge(const char *str
)
411 if (!strcmp(str
, "never"))
412 return SHMEM_HUGE_NEVER
;
413 if (!strcmp(str
, "always"))
414 return SHMEM_HUGE_ALWAYS
;
415 if (!strcmp(str
, "within_size"))
416 return SHMEM_HUGE_WITHIN_SIZE
;
417 if (!strcmp(str
, "advise"))
418 return SHMEM_HUGE_ADVISE
;
419 if (!strcmp(str
, "deny"))
420 return SHMEM_HUGE_DENY
;
421 if (!strcmp(str
, "force"))
422 return SHMEM_HUGE_FORCE
;
426 static const char *shmem_format_huge(int huge
)
429 case SHMEM_HUGE_NEVER
:
431 case SHMEM_HUGE_ALWAYS
:
433 case SHMEM_HUGE_WITHIN_SIZE
:
434 return "within_size";
435 case SHMEM_HUGE_ADVISE
:
437 case SHMEM_HUGE_DENY
:
439 case SHMEM_HUGE_FORCE
:
448 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info
*sbinfo
,
449 struct shrink_control
*sc
, unsigned long nr_to_split
)
451 LIST_HEAD(list
), *pos
, *next
;
452 LIST_HEAD(to_remove
);
454 struct shmem_inode_info
*info
;
456 unsigned long batch
= sc
? sc
->nr_to_scan
: 128;
457 int removed
= 0, split
= 0;
459 if (list_empty(&sbinfo
->shrinklist
))
462 spin_lock(&sbinfo
->shrinklist_lock
);
463 list_for_each_safe(pos
, next
, &sbinfo
->shrinklist
) {
464 info
= list_entry(pos
, struct shmem_inode_info
, shrinklist
);
467 inode
= igrab(&info
->vfs_inode
);
469 /* inode is about to be evicted */
471 list_del_init(&info
->shrinklist
);
476 /* Check if there's anything to gain */
477 if (round_up(inode
->i_size
, PAGE_SIZE
) ==
478 round_up(inode
->i_size
, HPAGE_PMD_SIZE
)) {
479 list_move(&info
->shrinklist
, &to_remove
);
484 list_move(&info
->shrinklist
, &list
);
489 spin_unlock(&sbinfo
->shrinklist_lock
);
491 list_for_each_safe(pos
, next
, &to_remove
) {
492 info
= list_entry(pos
, struct shmem_inode_info
, shrinklist
);
493 inode
= &info
->vfs_inode
;
494 list_del_init(&info
->shrinklist
);
498 list_for_each_safe(pos
, next
, &list
) {
501 info
= list_entry(pos
, struct shmem_inode_info
, shrinklist
);
502 inode
= &info
->vfs_inode
;
504 if (nr_to_split
&& split
>= nr_to_split
)
507 page
= find_get_page(inode
->i_mapping
,
508 (inode
->i_size
& HPAGE_PMD_MASK
) >> PAGE_SHIFT
);
512 /* No huge page at the end of the file: nothing to split */
513 if (!PageTransHuge(page
)) {
519 * Leave the inode on the list if we failed to lock
520 * the page at this time.
522 * Waiting for the lock may lead to deadlock in the
525 if (!trylock_page(page
)) {
530 ret
= split_huge_page(page
);
534 /* If split failed leave the inode on the list */
540 list_del_init(&info
->shrinklist
);
546 spin_lock(&sbinfo
->shrinklist_lock
);
547 list_splice_tail(&list
, &sbinfo
->shrinklist
);
548 sbinfo
->shrinklist_len
-= removed
;
549 spin_unlock(&sbinfo
->shrinklist_lock
);
554 static long shmem_unused_huge_scan(struct super_block
*sb
,
555 struct shrink_control
*sc
)
557 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
559 if (!READ_ONCE(sbinfo
->shrinklist_len
))
562 return shmem_unused_huge_shrink(sbinfo
, sc
, 0);
565 static long shmem_unused_huge_count(struct super_block
*sb
,
566 struct shrink_control
*sc
)
568 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
569 return READ_ONCE(sbinfo
->shrinklist_len
);
571 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
573 #define shmem_huge SHMEM_HUGE_DENY
575 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info
*sbinfo
,
576 struct shrink_control
*sc
, unsigned long nr_to_split
)
580 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
583 * Like add_to_page_cache_locked, but error if expected item has gone.
585 static int shmem_add_to_page_cache(struct page
*page
,
586 struct address_space
*mapping
,
587 pgoff_t index
, void *expected
)
589 int error
, nr
= hpage_nr_pages(page
);
591 VM_BUG_ON_PAGE(PageTail(page
), page
);
592 VM_BUG_ON_PAGE(index
!= round_down(index
, nr
), page
);
593 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
594 VM_BUG_ON_PAGE(!PageSwapBacked(page
), page
);
595 VM_BUG_ON(expected
&& PageTransHuge(page
));
597 page_ref_add(page
, nr
);
598 page
->mapping
= mapping
;
601 spin_lock_irq(&mapping
->tree_lock
);
602 if (PageTransHuge(page
)) {
603 void __rcu
**results
;
608 if (radix_tree_gang_lookup_slot(&mapping
->page_tree
,
609 &results
, &idx
, index
, 1) &&
610 idx
< index
+ HPAGE_PMD_NR
) {
615 for (i
= 0; i
< HPAGE_PMD_NR
; i
++) {
616 error
= radix_tree_insert(&mapping
->page_tree
,
617 index
+ i
, page
+ i
);
620 count_vm_event(THP_FILE_ALLOC
);
622 } else if (!expected
) {
623 error
= radix_tree_insert(&mapping
->page_tree
, index
, page
);
625 error
= shmem_radix_tree_replace(mapping
, index
, expected
,
630 mapping
->nrpages
+= nr
;
631 if (PageTransHuge(page
))
632 __inc_node_page_state(page
, NR_SHMEM_THPS
);
633 __mod_node_page_state(page_pgdat(page
), NR_FILE_PAGES
, nr
);
634 __mod_node_page_state(page_pgdat(page
), NR_SHMEM
, nr
);
635 spin_unlock_irq(&mapping
->tree_lock
);
637 page
->mapping
= NULL
;
638 spin_unlock_irq(&mapping
->tree_lock
);
639 page_ref_sub(page
, nr
);
645 * Like delete_from_page_cache, but substitutes swap for page.
647 static void shmem_delete_from_page_cache(struct page
*page
, void *radswap
)
649 struct address_space
*mapping
= page
->mapping
;
652 VM_BUG_ON_PAGE(PageCompound(page
), page
);
654 spin_lock_irq(&mapping
->tree_lock
);
655 error
= shmem_radix_tree_replace(mapping
, page
->index
, page
, radswap
);
656 page
->mapping
= NULL
;
658 __dec_node_page_state(page
, NR_FILE_PAGES
);
659 __dec_node_page_state(page
, NR_SHMEM
);
660 spin_unlock_irq(&mapping
->tree_lock
);
666 * Remove swap entry from radix tree, free the swap and its page cache.
668 static int shmem_free_swap(struct address_space
*mapping
,
669 pgoff_t index
, void *radswap
)
673 spin_lock_irq(&mapping
->tree_lock
);
674 old
= radix_tree_delete_item(&mapping
->page_tree
, index
, radswap
);
675 spin_unlock_irq(&mapping
->tree_lock
);
678 free_swap_and_cache(radix_to_swp_entry(radswap
));
683 * Determine (in bytes) how many of the shmem object's pages mapped by the
684 * given offsets are swapped out.
686 * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
687 * as long as the inode doesn't go away and racy results are not a problem.
689 unsigned long shmem_partial_swap_usage(struct address_space
*mapping
,
690 pgoff_t start
, pgoff_t end
)
692 struct radix_tree_iter iter
;
695 unsigned long swapped
= 0;
699 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
700 if (iter
.index
>= end
)
703 page
= radix_tree_deref_slot(slot
);
705 if (radix_tree_deref_retry(page
)) {
706 slot
= radix_tree_iter_retry(&iter
);
710 if (radix_tree_exceptional_entry(page
))
713 if (need_resched()) {
714 slot
= radix_tree_iter_resume(slot
, &iter
);
721 return swapped
<< PAGE_SHIFT
;
725 * Determine (in bytes) how many of the shmem object's pages mapped by the
726 * given vma is swapped out.
728 * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
729 * as long as the inode doesn't go away and racy results are not a problem.
731 unsigned long shmem_swap_usage(struct vm_area_struct
*vma
)
733 struct inode
*inode
= file_inode(vma
->vm_file
);
734 struct shmem_inode_info
*info
= SHMEM_I(inode
);
735 struct address_space
*mapping
= inode
->i_mapping
;
736 unsigned long swapped
;
738 /* Be careful as we don't hold info->lock */
739 swapped
= READ_ONCE(info
->swapped
);
742 * The easier cases are when the shmem object has nothing in swap, or
743 * the vma maps it whole. Then we can simply use the stats that we
749 if (!vma
->vm_pgoff
&& vma
->vm_end
- vma
->vm_start
>= inode
->i_size
)
750 return swapped
<< PAGE_SHIFT
;
752 /* Here comes the more involved part */
753 return shmem_partial_swap_usage(mapping
,
754 linear_page_index(vma
, vma
->vm_start
),
755 linear_page_index(vma
, vma
->vm_end
));
759 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
761 void shmem_unlock_mapping(struct address_space
*mapping
)
764 pgoff_t indices
[PAGEVEC_SIZE
];
769 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
771 while (!mapping_unevictable(mapping
)) {
773 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
774 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
776 pvec
.nr
= find_get_entries(mapping
, index
,
777 PAGEVEC_SIZE
, pvec
.pages
, indices
);
780 index
= indices
[pvec
.nr
- 1] + 1;
781 pagevec_remove_exceptionals(&pvec
);
782 check_move_unevictable_pages(pvec
.pages
, pvec
.nr
);
783 pagevec_release(&pvec
);
789 * Remove range of pages and swap entries from radix tree, and free them.
790 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
792 static void shmem_undo_range(struct inode
*inode
, loff_t lstart
, loff_t lend
,
795 struct address_space
*mapping
= inode
->i_mapping
;
796 struct shmem_inode_info
*info
= SHMEM_I(inode
);
797 pgoff_t start
= (lstart
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
798 pgoff_t end
= (lend
+ 1) >> PAGE_SHIFT
;
799 unsigned int partial_start
= lstart
& (PAGE_SIZE
- 1);
800 unsigned int partial_end
= (lend
+ 1) & (PAGE_SIZE
- 1);
802 pgoff_t indices
[PAGEVEC_SIZE
];
803 long nr_swaps_freed
= 0;
808 end
= -1; /* unsigned, so actually very big */
812 while (index
< end
) {
813 pvec
.nr
= find_get_entries(mapping
, index
,
814 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
),
815 pvec
.pages
, indices
);
818 for (i
= 0; i
< pagevec_count(&pvec
); i
++) {
819 struct page
*page
= pvec
.pages
[i
];
825 if (radix_tree_exceptional_entry(page
)) {
828 nr_swaps_freed
+= !shmem_free_swap(mapping
,
833 VM_BUG_ON_PAGE(page_to_pgoff(page
) != index
, page
);
835 if (!trylock_page(page
))
838 if (PageTransTail(page
)) {
839 /* Middle of THP: zero out the page */
840 clear_highpage(page
);
843 } else if (PageTransHuge(page
)) {
844 if (index
== round_down(end
, HPAGE_PMD_NR
)) {
846 * Range ends in the middle of THP:
849 clear_highpage(page
);
853 index
+= HPAGE_PMD_NR
- 1;
854 i
+= HPAGE_PMD_NR
- 1;
857 if (!unfalloc
|| !PageUptodate(page
)) {
858 VM_BUG_ON_PAGE(PageTail(page
), page
);
859 if (page_mapping(page
) == mapping
) {
860 VM_BUG_ON_PAGE(PageWriteback(page
), page
);
861 truncate_inode_page(mapping
, page
);
866 pagevec_remove_exceptionals(&pvec
);
867 pagevec_release(&pvec
);
873 struct page
*page
= NULL
;
874 shmem_getpage(inode
, start
- 1, &page
, SGP_READ
);
876 unsigned int top
= PAGE_SIZE
;
881 zero_user_segment(page
, partial_start
, top
);
882 set_page_dirty(page
);
888 struct page
*page
= NULL
;
889 shmem_getpage(inode
, end
, &page
, SGP_READ
);
891 zero_user_segment(page
, 0, partial_end
);
892 set_page_dirty(page
);
901 while (index
< end
) {
904 pvec
.nr
= find_get_entries(mapping
, index
,
905 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
),
906 pvec
.pages
, indices
);
908 /* If all gone or hole-punch or unfalloc, we're done */
909 if (index
== start
|| end
!= -1)
911 /* But if truncating, restart to make sure all gone */
915 for (i
= 0; i
< pagevec_count(&pvec
); i
++) {
916 struct page
*page
= pvec
.pages
[i
];
922 if (radix_tree_exceptional_entry(page
)) {
925 if (shmem_free_swap(mapping
, index
, page
)) {
926 /* Swap was replaced by page: retry */
936 if (PageTransTail(page
)) {
937 /* Middle of THP: zero out the page */
938 clear_highpage(page
);
941 * Partial thp truncate due 'start' in middle
942 * of THP: don't need to look on these pages
943 * again on !pvec.nr restart.
945 if (index
!= round_down(end
, HPAGE_PMD_NR
))
948 } else if (PageTransHuge(page
)) {
949 if (index
== round_down(end
, HPAGE_PMD_NR
)) {
951 * Range ends in the middle of THP:
954 clear_highpage(page
);
958 index
+= HPAGE_PMD_NR
- 1;
959 i
+= HPAGE_PMD_NR
- 1;
962 if (!unfalloc
|| !PageUptodate(page
)) {
963 VM_BUG_ON_PAGE(PageTail(page
), page
);
964 if (page_mapping(page
) == mapping
) {
965 VM_BUG_ON_PAGE(PageWriteback(page
), page
);
966 truncate_inode_page(mapping
, page
);
968 /* Page was replaced by swap: retry */
976 pagevec_remove_exceptionals(&pvec
);
977 pagevec_release(&pvec
);
981 spin_lock_irq(&info
->lock
);
982 info
->swapped
-= nr_swaps_freed
;
983 shmem_recalc_inode(inode
);
984 spin_unlock_irq(&info
->lock
);
987 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
989 shmem_undo_range(inode
, lstart
, lend
, false);
990 inode
->i_ctime
= inode
->i_mtime
= current_time(inode
);
992 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
994 static int shmem_getattr(const struct path
*path
, struct kstat
*stat
,
995 u32 request_mask
, unsigned int query_flags
)
997 struct inode
*inode
= path
->dentry
->d_inode
;
998 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1000 if (info
->alloced
- info
->swapped
!= inode
->i_mapping
->nrpages
) {
1001 spin_lock_irq(&info
->lock
);
1002 shmem_recalc_inode(inode
);
1003 spin_unlock_irq(&info
->lock
);
1005 generic_fillattr(inode
, stat
);
1009 static int shmem_setattr(struct dentry
*dentry
, struct iattr
*attr
)
1011 struct inode
*inode
= d_inode(dentry
);
1012 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1013 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1016 error
= setattr_prepare(dentry
, attr
);
1020 if (S_ISREG(inode
->i_mode
) && (attr
->ia_valid
& ATTR_SIZE
)) {
1021 loff_t oldsize
= inode
->i_size
;
1022 loff_t newsize
= attr
->ia_size
;
1024 /* protected by i_mutex */
1025 if ((newsize
< oldsize
&& (info
->seals
& F_SEAL_SHRINK
)) ||
1026 (newsize
> oldsize
&& (info
->seals
& F_SEAL_GROW
)))
1029 if (newsize
!= oldsize
) {
1030 error
= shmem_reacct_size(SHMEM_I(inode
)->flags
,
1034 i_size_write(inode
, newsize
);
1035 inode
->i_ctime
= inode
->i_mtime
= current_time(inode
);
1037 if (newsize
<= oldsize
) {
1038 loff_t holebegin
= round_up(newsize
, PAGE_SIZE
);
1039 if (oldsize
> holebegin
)
1040 unmap_mapping_range(inode
->i_mapping
,
1043 shmem_truncate_range(inode
,
1044 newsize
, (loff_t
)-1);
1045 /* unmap again to remove racily COWed private pages */
1046 if (oldsize
> holebegin
)
1047 unmap_mapping_range(inode
->i_mapping
,
1051 * Part of the huge page can be beyond i_size: subject
1052 * to shrink under memory pressure.
1054 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE
)) {
1055 spin_lock(&sbinfo
->shrinklist_lock
);
1057 * _careful to defend against unlocked access to
1058 * ->shrink_list in shmem_unused_huge_shrink()
1060 if (list_empty_careful(&info
->shrinklist
)) {
1061 list_add_tail(&info
->shrinklist
,
1062 &sbinfo
->shrinklist
);
1063 sbinfo
->shrinklist_len
++;
1065 spin_unlock(&sbinfo
->shrinklist_lock
);
1070 setattr_copy(inode
, attr
);
1071 if (attr
->ia_valid
& ATTR_MODE
)
1072 error
= posix_acl_chmod(inode
, inode
->i_mode
);
1076 static void shmem_evict_inode(struct inode
*inode
)
1078 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1079 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1081 if (inode
->i_mapping
->a_ops
== &shmem_aops
) {
1082 shmem_unacct_size(info
->flags
, inode
->i_size
);
1084 shmem_truncate_range(inode
, 0, (loff_t
)-1);
1085 if (!list_empty(&info
->shrinklist
)) {
1086 spin_lock(&sbinfo
->shrinklist_lock
);
1087 if (!list_empty(&info
->shrinklist
)) {
1088 list_del_init(&info
->shrinklist
);
1089 sbinfo
->shrinklist_len
--;
1091 spin_unlock(&sbinfo
->shrinklist_lock
);
1093 if (!list_empty(&info
->swaplist
)) {
1094 mutex_lock(&shmem_swaplist_mutex
);
1095 list_del_init(&info
->swaplist
);
1096 mutex_unlock(&shmem_swaplist_mutex
);
1100 simple_xattrs_free(&info
->xattrs
);
1101 WARN_ON(inode
->i_blocks
);
1102 if (!sbinfo
->idr_nouse
&& inode
->i_ino
) {
1103 mutex_lock(&sbinfo
->idr_lock
);
1104 idr_remove(&sbinfo
->idr
, inode
->i_ino
);
1105 mutex_unlock(&sbinfo
->idr_lock
);
1107 shmem_free_inode(inode
->i_sb
);
1111 static unsigned long find_swap_entry(struct radix_tree_root
*root
, void *item
)
1113 struct radix_tree_iter iter
;
1115 unsigned long found
= -1;
1116 unsigned int checked
= 0;
1119 radix_tree_for_each_slot(slot
, root
, &iter
, 0) {
1120 if (*slot
== item
) {
1125 if ((checked
% 4096) != 0)
1127 slot
= radix_tree_iter_resume(slot
, &iter
);
1136 * If swap found in inode, free it and move page from swapcache to filecache.
1138 static int shmem_unuse_inode(struct shmem_inode_info
*info
,
1139 swp_entry_t swap
, struct page
**pagep
)
1141 struct address_space
*mapping
= info
->vfs_inode
.i_mapping
;
1147 radswap
= swp_to_radix_entry(swap
);
1148 index
= find_swap_entry(&mapping
->page_tree
, radswap
);
1150 return -EAGAIN
; /* tell shmem_unuse we found nothing */
1153 * Move _head_ to start search for next from here.
1154 * But be careful: shmem_evict_inode checks list_empty without taking
1155 * mutex, and there's an instant in list_move_tail when info->swaplist
1156 * would appear empty, if it were the only one on shmem_swaplist.
1158 if (shmem_swaplist
.next
!= &info
->swaplist
)
1159 list_move_tail(&shmem_swaplist
, &info
->swaplist
);
1161 gfp
= mapping_gfp_mask(mapping
);
1162 if (shmem_should_replace_page(*pagep
, gfp
)) {
1163 mutex_unlock(&shmem_swaplist_mutex
);
1164 error
= shmem_replace_page(pagep
, gfp
, info
, index
);
1165 mutex_lock(&shmem_swaplist_mutex
);
1167 * We needed to drop mutex to make that restrictive page
1168 * allocation, but the inode might have been freed while we
1169 * dropped it: although a racing shmem_evict_inode() cannot
1170 * complete without emptying the radix_tree, our page lock
1171 * on this swapcache page is not enough to prevent that -
1172 * free_swap_and_cache() of our swap entry will only
1173 * trylock_page(), removing swap from radix_tree whatever.
1175 * We must not proceed to shmem_add_to_page_cache() if the
1176 * inode has been freed, but of course we cannot rely on
1177 * inode or mapping or info to check that. However, we can
1178 * safely check if our swap entry is still in use (and here
1179 * it can't have got reused for another page): if it's still
1180 * in use, then the inode cannot have been freed yet, and we
1181 * can safely proceed (if it's no longer in use, that tells
1182 * nothing about the inode, but we don't need to unuse swap).
1184 if (!page_swapcount(*pagep
))
1189 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
1190 * but also to hold up shmem_evict_inode(): so inode cannot be freed
1191 * beneath us (pagelock doesn't help until the page is in pagecache).
1194 error
= shmem_add_to_page_cache(*pagep
, mapping
, index
,
1196 if (error
!= -ENOMEM
) {
1198 * Truncation and eviction use free_swap_and_cache(), which
1199 * only does trylock page: if we raced, best clean up here.
1201 delete_from_swap_cache(*pagep
);
1202 set_page_dirty(*pagep
);
1204 spin_lock_irq(&info
->lock
);
1206 spin_unlock_irq(&info
->lock
);
1214 * Search through swapped inodes to find and replace swap by page.
1216 int shmem_unuse(swp_entry_t swap
, struct page
*page
)
1218 struct list_head
*this, *next
;
1219 struct shmem_inode_info
*info
;
1220 struct mem_cgroup
*memcg
;
1224 * There's a faint possibility that swap page was replaced before
1225 * caller locked it: caller will come back later with the right page.
1227 if (unlikely(!PageSwapCache(page
) || page_private(page
) != swap
.val
))
1231 * Charge page using GFP_KERNEL while we can wait, before taking
1232 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1233 * Charged back to the user (not to caller) when swap account is used.
1235 error
= mem_cgroup_try_charge(page
, current
->mm
, GFP_KERNEL
, &memcg
,
1239 /* No radix_tree_preload: swap entry keeps a place for page in tree */
1242 mutex_lock(&shmem_swaplist_mutex
);
1243 list_for_each_safe(this, next
, &shmem_swaplist
) {
1244 info
= list_entry(this, struct shmem_inode_info
, swaplist
);
1246 error
= shmem_unuse_inode(info
, swap
, &page
);
1248 list_del_init(&info
->swaplist
);
1250 if (error
!= -EAGAIN
)
1252 /* found nothing in this: move on to search the next */
1254 mutex_unlock(&shmem_swaplist_mutex
);
1257 if (error
!= -ENOMEM
)
1259 mem_cgroup_cancel_charge(page
, memcg
, false);
1261 mem_cgroup_commit_charge(page
, memcg
, true, false);
1269 * Move the page from the page cache to the swap cache.
1271 static int shmem_writepage(struct page
*page
, struct writeback_control
*wbc
)
1273 struct shmem_inode_info
*info
;
1274 struct address_space
*mapping
;
1275 struct inode
*inode
;
1279 VM_BUG_ON_PAGE(PageCompound(page
), page
);
1280 BUG_ON(!PageLocked(page
));
1281 mapping
= page
->mapping
;
1282 index
= page
->index
;
1283 inode
= mapping
->host
;
1284 info
= SHMEM_I(inode
);
1285 if (info
->flags
& VM_LOCKED
)
1287 if (!total_swap_pages
)
1291 * Our capabilities prevent regular writeback or sync from ever calling
1292 * shmem_writepage; but a stacking filesystem might use ->writepage of
1293 * its underlying filesystem, in which case tmpfs should write out to
1294 * swap only in response to memory pressure, and not for the writeback
1297 if (!wbc
->for_reclaim
) {
1298 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1303 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1304 * value into swapfile.c, the only way we can correctly account for a
1305 * fallocated page arriving here is now to initialize it and write it.
1307 * That's okay for a page already fallocated earlier, but if we have
1308 * not yet completed the fallocation, then (a) we want to keep track
1309 * of this page in case we have to undo it, and (b) it may not be a
1310 * good idea to continue anyway, once we're pushing into swap. So
1311 * reactivate the page, and let shmem_fallocate() quit when too many.
1313 if (!PageUptodate(page
)) {
1314 if (inode
->i_private
) {
1315 struct shmem_falloc
*shmem_falloc
;
1316 spin_lock(&inode
->i_lock
);
1317 shmem_falloc
= inode
->i_private
;
1319 !shmem_falloc
->waitq
&&
1320 index
>= shmem_falloc
->start
&&
1321 index
< shmem_falloc
->next
)
1322 shmem_falloc
->nr_unswapped
++;
1324 shmem_falloc
= NULL
;
1325 spin_unlock(&inode
->i_lock
);
1329 clear_highpage(page
);
1330 flush_dcache_page(page
);
1331 SetPageUptodate(page
);
1334 swap
= get_swap_page(page
);
1338 if (mem_cgroup_try_charge_swap(page
, swap
))
1342 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1343 * if it's not already there. Do it now before the page is
1344 * moved to swap cache, when its pagelock no longer protects
1345 * the inode from eviction. But don't unlock the mutex until
1346 * we've incremented swapped, because shmem_unuse_inode() will
1347 * prune a !swapped inode from the swaplist under this mutex.
1349 mutex_lock(&shmem_swaplist_mutex
);
1350 if (list_empty(&info
->swaplist
))
1351 list_add_tail(&info
->swaplist
, &shmem_swaplist
);
1353 if (add_to_swap_cache(page
, swap
, GFP_ATOMIC
) == 0) {
1354 spin_lock_irq(&info
->lock
);
1355 shmem_recalc_inode(inode
);
1357 spin_unlock_irq(&info
->lock
);
1359 swap_shmem_alloc(swap
);
1360 shmem_delete_from_page_cache(page
, swp_to_radix_entry(swap
));
1362 mutex_unlock(&shmem_swaplist_mutex
);
1363 BUG_ON(page_mapped(page
));
1364 swap_writepage(page
, wbc
);
1368 mutex_unlock(&shmem_swaplist_mutex
);
1370 put_swap_page(page
, swap
);
1372 set_page_dirty(page
);
1373 if (wbc
->for_reclaim
)
1374 return AOP_WRITEPAGE_ACTIVATE
; /* Return with page locked */
1379 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1380 static void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1384 if (!mpol
|| mpol
->mode
== MPOL_DEFAULT
)
1385 return; /* show nothing */
1387 mpol_to_str(buffer
, sizeof(buffer
), mpol
);
1389 seq_printf(seq
, ",mpol=%s", buffer
);
1392 static struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1394 struct mempolicy
*mpol
= NULL
;
1396 spin_lock(&sbinfo
->stat_lock
); /* prevent replace/use races */
1397 mpol
= sbinfo
->mpol
;
1399 spin_unlock(&sbinfo
->stat_lock
);
1403 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1404 static inline void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1407 static inline struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1411 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1413 #define vm_policy vm_private_data
1416 static void shmem_pseudo_vma_init(struct vm_area_struct
*vma
,
1417 struct shmem_inode_info
*info
, pgoff_t index
)
1419 /* Create a pseudo vma that just contains the policy */
1421 /* Bias interleave by inode number to distribute better across nodes */
1422 vma
->vm_pgoff
= index
+ info
->vfs_inode
.i_ino
;
1424 vma
->vm_policy
= mpol_shared_policy_lookup(&info
->policy
, index
);
1427 static void shmem_pseudo_vma_destroy(struct vm_area_struct
*vma
)
1429 /* Drop reference taken by mpol_shared_policy_lookup() */
1430 mpol_cond_put(vma
->vm_policy
);
1433 static struct page
*shmem_swapin(swp_entry_t swap
, gfp_t gfp
,
1434 struct shmem_inode_info
*info
, pgoff_t index
)
1436 struct vm_area_struct pvma
;
1439 shmem_pseudo_vma_init(&pvma
, info
, index
);
1440 page
= swapin_readahead(swap
, gfp
, &pvma
, 0);
1441 shmem_pseudo_vma_destroy(&pvma
);
1446 static struct page
*shmem_alloc_hugepage(gfp_t gfp
,
1447 struct shmem_inode_info
*info
, pgoff_t index
)
1449 struct vm_area_struct pvma
;
1450 struct inode
*inode
= &info
->vfs_inode
;
1451 struct address_space
*mapping
= inode
->i_mapping
;
1452 pgoff_t idx
, hindex
;
1453 void __rcu
**results
;
1456 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE
))
1459 hindex
= round_down(index
, HPAGE_PMD_NR
);
1461 if (radix_tree_gang_lookup_slot(&mapping
->page_tree
, &results
, &idx
,
1462 hindex
, 1) && idx
< hindex
+ HPAGE_PMD_NR
) {
1468 shmem_pseudo_vma_init(&pvma
, info
, hindex
);
1469 page
= alloc_pages_vma(gfp
| __GFP_COMP
| __GFP_NORETRY
| __GFP_NOWARN
,
1470 HPAGE_PMD_ORDER
, &pvma
, 0, numa_node_id(), true);
1471 shmem_pseudo_vma_destroy(&pvma
);
1473 prep_transhuge_page(page
);
1477 static struct page
*shmem_alloc_page(gfp_t gfp
,
1478 struct shmem_inode_info
*info
, pgoff_t index
)
1480 struct vm_area_struct pvma
;
1483 shmem_pseudo_vma_init(&pvma
, info
, index
);
1484 page
= alloc_page_vma(gfp
, &pvma
, 0);
1485 shmem_pseudo_vma_destroy(&pvma
);
1490 static struct page
*shmem_alloc_and_acct_page(gfp_t gfp
,
1491 struct inode
*inode
,
1492 pgoff_t index
, bool huge
)
1494 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1499 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE
))
1501 nr
= huge
? HPAGE_PMD_NR
: 1;
1503 if (!shmem_inode_acct_block(inode
, nr
))
1507 page
= shmem_alloc_hugepage(gfp
, info
, index
);
1509 page
= shmem_alloc_page(gfp
, info
, index
);
1511 __SetPageLocked(page
);
1512 __SetPageSwapBacked(page
);
1517 shmem_inode_unacct_blocks(inode
, nr
);
1519 return ERR_PTR(err
);
1523 * When a page is moved from swapcache to shmem filecache (either by the
1524 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1525 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1526 * ignorance of the mapping it belongs to. If that mapping has special
1527 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1528 * we may need to copy to a suitable page before moving to filecache.
1530 * In a future release, this may well be extended to respect cpuset and
1531 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1532 * but for now it is a simple matter of zone.
1534 static bool shmem_should_replace_page(struct page
*page
, gfp_t gfp
)
1536 return page_zonenum(page
) > gfp_zone(gfp
);
1539 static int shmem_replace_page(struct page
**pagep
, gfp_t gfp
,
1540 struct shmem_inode_info
*info
, pgoff_t index
)
1542 struct page
*oldpage
, *newpage
;
1543 struct address_space
*swap_mapping
;
1549 entry
.val
= page_private(oldpage
);
1550 swap_index
= swp_offset(entry
);
1551 swap_mapping
= page_mapping(oldpage
);
1554 * We have arrived here because our zones are constrained, so don't
1555 * limit chance of success by further cpuset and node constraints.
1557 gfp
&= ~GFP_CONSTRAINT_MASK
;
1558 newpage
= shmem_alloc_page(gfp
, info
, index
);
1563 copy_highpage(newpage
, oldpage
);
1564 flush_dcache_page(newpage
);
1566 __SetPageLocked(newpage
);
1567 __SetPageSwapBacked(newpage
);
1568 SetPageUptodate(newpage
);
1569 set_page_private(newpage
, entry
.val
);
1570 SetPageSwapCache(newpage
);
1573 * Our caller will very soon move newpage out of swapcache, but it's
1574 * a nice clean interface for us to replace oldpage by newpage there.
1576 spin_lock_irq(&swap_mapping
->tree_lock
);
1577 error
= shmem_radix_tree_replace(swap_mapping
, swap_index
, oldpage
,
1580 __inc_node_page_state(newpage
, NR_FILE_PAGES
);
1581 __dec_node_page_state(oldpage
, NR_FILE_PAGES
);
1583 spin_unlock_irq(&swap_mapping
->tree_lock
);
1585 if (unlikely(error
)) {
1587 * Is this possible? I think not, now that our callers check
1588 * both PageSwapCache and page_private after getting page lock;
1589 * but be defensive. Reverse old to newpage for clear and free.
1593 mem_cgroup_migrate(oldpage
, newpage
);
1594 lru_cache_add_anon(newpage
);
1598 ClearPageSwapCache(oldpage
);
1599 set_page_private(oldpage
, 0);
1601 unlock_page(oldpage
);
1608 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1610 * If we allocate a new one we do not mark it dirty. That's up to the
1611 * vm. If we swap it in we mark it dirty since we also free the swap
1612 * entry since a page cannot live in both the swap and page cache.
1614 * fault_mm and fault_type are only supplied by shmem_fault:
1615 * otherwise they are NULL.
1617 static int shmem_getpage_gfp(struct inode
*inode
, pgoff_t index
,
1618 struct page
**pagep
, enum sgp_type sgp
, gfp_t gfp
,
1619 struct vm_area_struct
*vma
, struct vm_fault
*vmf
, int *fault_type
)
1621 struct address_space
*mapping
= inode
->i_mapping
;
1622 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1623 struct shmem_sb_info
*sbinfo
;
1624 struct mm_struct
*charge_mm
;
1625 struct mem_cgroup
*memcg
;
1628 enum sgp_type sgp_huge
= sgp
;
1629 pgoff_t hindex
= index
;
1634 if (index
> (MAX_LFS_FILESIZE
>> PAGE_SHIFT
))
1636 if (sgp
== SGP_NOHUGE
|| sgp
== SGP_HUGE
)
1640 page
= find_lock_entry(mapping
, index
);
1641 if (radix_tree_exceptional_entry(page
)) {
1642 swap
= radix_to_swp_entry(page
);
1646 if (sgp
<= SGP_CACHE
&&
1647 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
)) {
1652 if (page
&& sgp
== SGP_WRITE
)
1653 mark_page_accessed(page
);
1655 /* fallocated page? */
1656 if (page
&& !PageUptodate(page
)) {
1657 if (sgp
!= SGP_READ
)
1663 if (page
|| (sgp
== SGP_READ
&& !swap
.val
)) {
1669 * Fast cache lookup did not find it:
1670 * bring it back from swap or allocate.
1672 sbinfo
= SHMEM_SB(inode
->i_sb
);
1673 charge_mm
= vma
? vma
->vm_mm
: current
->mm
;
1676 /* Look it up and read it in.. */
1677 page
= lookup_swap_cache(swap
, NULL
, 0);
1679 /* Or update major stats only when swapin succeeds?? */
1681 *fault_type
|= VM_FAULT_MAJOR
;
1682 count_vm_event(PGMAJFAULT
);
1683 count_memcg_event_mm(charge_mm
, PGMAJFAULT
);
1685 /* Here we actually start the io */
1686 page
= shmem_swapin(swap
, gfp
, info
, index
);
1693 /* We have to do this with page locked to prevent races */
1695 if (!PageSwapCache(page
) || page_private(page
) != swap
.val
||
1696 !shmem_confirm_swap(mapping
, index
, swap
)) {
1697 error
= -EEXIST
; /* try again */
1700 if (!PageUptodate(page
)) {
1704 wait_on_page_writeback(page
);
1706 if (shmem_should_replace_page(page
, gfp
)) {
1707 error
= shmem_replace_page(&page
, gfp
, info
, index
);
1712 error
= mem_cgroup_try_charge(page
, charge_mm
, gfp
, &memcg
,
1715 error
= shmem_add_to_page_cache(page
, mapping
, index
,
1716 swp_to_radix_entry(swap
));
1718 * We already confirmed swap under page lock, and make
1719 * no memory allocation here, so usually no possibility
1720 * of error; but free_swap_and_cache() only trylocks a
1721 * page, so it is just possible that the entry has been
1722 * truncated or holepunched since swap was confirmed.
1723 * shmem_undo_range() will have done some of the
1724 * unaccounting, now delete_from_swap_cache() will do
1726 * Reset swap.val? No, leave it so "failed" goes back to
1727 * "repeat": reading a hole and writing should succeed.
1730 mem_cgroup_cancel_charge(page
, memcg
, false);
1731 delete_from_swap_cache(page
);
1737 mem_cgroup_commit_charge(page
, memcg
, true, false);
1739 spin_lock_irq(&info
->lock
);
1741 shmem_recalc_inode(inode
);
1742 spin_unlock_irq(&info
->lock
);
1744 if (sgp
== SGP_WRITE
)
1745 mark_page_accessed(page
);
1747 delete_from_swap_cache(page
);
1748 set_page_dirty(page
);
1752 if (vma
&& userfaultfd_missing(vma
)) {
1753 *fault_type
= handle_userfault(vmf
, VM_UFFD_MISSING
);
1757 /* shmem_symlink() */
1758 if (mapping
->a_ops
!= &shmem_aops
)
1760 if (shmem_huge
== SHMEM_HUGE_DENY
|| sgp_huge
== SGP_NOHUGE
)
1762 if (shmem_huge
== SHMEM_HUGE_FORCE
)
1764 switch (sbinfo
->huge
) {
1767 case SHMEM_HUGE_NEVER
:
1769 case SHMEM_HUGE_WITHIN_SIZE
:
1770 off
= round_up(index
, HPAGE_PMD_NR
);
1771 i_size
= round_up(i_size_read(inode
), PAGE_SIZE
);
1772 if (i_size
>= HPAGE_PMD_SIZE
&&
1773 i_size
>> PAGE_SHIFT
>= off
)
1776 case SHMEM_HUGE_ADVISE
:
1777 if (sgp_huge
== SGP_HUGE
)
1779 /* TODO: implement fadvise() hints */
1784 page
= shmem_alloc_and_acct_page(gfp
, inode
, index
, true);
1786 alloc_nohuge
: page
= shmem_alloc_and_acct_page(gfp
, inode
,
1791 error
= PTR_ERR(page
);
1793 if (error
!= -ENOSPC
)
1796 * Try to reclaim some spece by splitting a huge page
1797 * beyond i_size on the filesystem.
1801 ret
= shmem_unused_huge_shrink(sbinfo
, NULL
, 1);
1802 if (ret
== SHRINK_STOP
)
1810 if (PageTransHuge(page
))
1811 hindex
= round_down(index
, HPAGE_PMD_NR
);
1815 if (sgp
== SGP_WRITE
)
1816 __SetPageReferenced(page
);
1818 error
= mem_cgroup_try_charge(page
, charge_mm
, gfp
, &memcg
,
1819 PageTransHuge(page
));
1822 error
= radix_tree_maybe_preload_order(gfp
& GFP_RECLAIM_MASK
,
1823 compound_order(page
));
1825 error
= shmem_add_to_page_cache(page
, mapping
, hindex
,
1827 radix_tree_preload_end();
1830 mem_cgroup_cancel_charge(page
, memcg
,
1831 PageTransHuge(page
));
1834 mem_cgroup_commit_charge(page
, memcg
, false,
1835 PageTransHuge(page
));
1836 lru_cache_add_anon(page
);
1838 spin_lock_irq(&info
->lock
);
1839 info
->alloced
+= 1 << compound_order(page
);
1840 inode
->i_blocks
+= BLOCKS_PER_PAGE
<< compound_order(page
);
1841 shmem_recalc_inode(inode
);
1842 spin_unlock_irq(&info
->lock
);
1845 if (PageTransHuge(page
) &&
1846 DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
) <
1847 hindex
+ HPAGE_PMD_NR
- 1) {
1849 * Part of the huge page is beyond i_size: subject
1850 * to shrink under memory pressure.
1852 spin_lock(&sbinfo
->shrinklist_lock
);
1854 * _careful to defend against unlocked access to
1855 * ->shrink_list in shmem_unused_huge_shrink()
1857 if (list_empty_careful(&info
->shrinklist
)) {
1858 list_add_tail(&info
->shrinklist
,
1859 &sbinfo
->shrinklist
);
1860 sbinfo
->shrinklist_len
++;
1862 spin_unlock(&sbinfo
->shrinklist_lock
);
1866 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1868 if (sgp
== SGP_FALLOC
)
1872 * Let SGP_WRITE caller clear ends if write does not fill page;
1873 * but SGP_FALLOC on a page fallocated earlier must initialize
1874 * it now, lest undo on failure cancel our earlier guarantee.
1876 if (sgp
!= SGP_WRITE
&& !PageUptodate(page
)) {
1877 struct page
*head
= compound_head(page
);
1880 for (i
= 0; i
< (1 << compound_order(head
)); i
++) {
1881 clear_highpage(head
+ i
);
1882 flush_dcache_page(head
+ i
);
1884 SetPageUptodate(head
);
1888 /* Perhaps the file has been truncated since we checked */
1889 if (sgp
<= SGP_CACHE
&&
1890 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
)) {
1892 ClearPageDirty(page
);
1893 delete_from_page_cache(page
);
1894 spin_lock_irq(&info
->lock
);
1895 shmem_recalc_inode(inode
);
1896 spin_unlock_irq(&info
->lock
);
1901 *pagep
= page
+ index
- hindex
;
1908 shmem_inode_unacct_blocks(inode
, 1 << compound_order(page
));
1910 if (PageTransHuge(page
)) {
1916 if (swap
.val
&& !shmem_confirm_swap(mapping
, index
, swap
))
1923 if (error
== -ENOSPC
&& !once
++) {
1924 spin_lock_irq(&info
->lock
);
1925 shmem_recalc_inode(inode
);
1926 spin_unlock_irq(&info
->lock
);
1929 if (error
== -EEXIST
) /* from above or from radix_tree_insert */
1935 * This is like autoremove_wake_function, but it removes the wait queue
1936 * entry unconditionally - even if something else had already woken the
1939 static int synchronous_wake_function(wait_queue_entry_t
*wait
, unsigned mode
, int sync
, void *key
)
1941 int ret
= default_wake_function(wait
, mode
, sync
, key
);
1942 list_del_init(&wait
->entry
);
1946 static int shmem_fault(struct vm_fault
*vmf
)
1948 struct vm_area_struct
*vma
= vmf
->vma
;
1949 struct inode
*inode
= file_inode(vma
->vm_file
);
1950 gfp_t gfp
= mapping_gfp_mask(inode
->i_mapping
);
1953 int ret
= VM_FAULT_LOCKED
;
1956 * Trinity finds that probing a hole which tmpfs is punching can
1957 * prevent the hole-punch from ever completing: which in turn
1958 * locks writers out with its hold on i_mutex. So refrain from
1959 * faulting pages into the hole while it's being punched. Although
1960 * shmem_undo_range() does remove the additions, it may be unable to
1961 * keep up, as each new page needs its own unmap_mapping_range() call,
1962 * and the i_mmap tree grows ever slower to scan if new vmas are added.
1964 * It does not matter if we sometimes reach this check just before the
1965 * hole-punch begins, so that one fault then races with the punch:
1966 * we just need to make racing faults a rare case.
1968 * The implementation below would be much simpler if we just used a
1969 * standard mutex or completion: but we cannot take i_mutex in fault,
1970 * and bloating every shmem inode for this unlikely case would be sad.
1972 if (unlikely(inode
->i_private
)) {
1973 struct shmem_falloc
*shmem_falloc
;
1975 spin_lock(&inode
->i_lock
);
1976 shmem_falloc
= inode
->i_private
;
1978 shmem_falloc
->waitq
&&
1979 vmf
->pgoff
>= shmem_falloc
->start
&&
1980 vmf
->pgoff
< shmem_falloc
->next
) {
1981 wait_queue_head_t
*shmem_falloc_waitq
;
1982 DEFINE_WAIT_FUNC(shmem_fault_wait
, synchronous_wake_function
);
1984 ret
= VM_FAULT_NOPAGE
;
1985 if ((vmf
->flags
& FAULT_FLAG_ALLOW_RETRY
) &&
1986 !(vmf
->flags
& FAULT_FLAG_RETRY_NOWAIT
)) {
1987 /* It's polite to up mmap_sem if we can */
1988 up_read(&vma
->vm_mm
->mmap_sem
);
1989 ret
= VM_FAULT_RETRY
;
1992 shmem_falloc_waitq
= shmem_falloc
->waitq
;
1993 prepare_to_wait(shmem_falloc_waitq
, &shmem_fault_wait
,
1994 TASK_UNINTERRUPTIBLE
);
1995 spin_unlock(&inode
->i_lock
);
1999 * shmem_falloc_waitq points into the shmem_fallocate()
2000 * stack of the hole-punching task: shmem_falloc_waitq
2001 * is usually invalid by the time we reach here, but
2002 * finish_wait() does not dereference it in that case;
2003 * though i_lock needed lest racing with wake_up_all().
2005 spin_lock(&inode
->i_lock
);
2006 finish_wait(shmem_falloc_waitq
, &shmem_fault_wait
);
2007 spin_unlock(&inode
->i_lock
);
2010 spin_unlock(&inode
->i_lock
);
2015 if ((vma
->vm_flags
& VM_NOHUGEPAGE
) ||
2016 test_bit(MMF_DISABLE_THP
, &vma
->vm_mm
->flags
))
2018 else if (vma
->vm_flags
& VM_HUGEPAGE
)
2021 error
= shmem_getpage_gfp(inode
, vmf
->pgoff
, &vmf
->page
, sgp
,
2022 gfp
, vma
, vmf
, &ret
);
2024 return ((error
== -ENOMEM
) ? VM_FAULT_OOM
: VM_FAULT_SIGBUS
);
2028 unsigned long shmem_get_unmapped_area(struct file
*file
,
2029 unsigned long uaddr
, unsigned long len
,
2030 unsigned long pgoff
, unsigned long flags
)
2032 unsigned long (*get_area
)(struct file
*,
2033 unsigned long, unsigned long, unsigned long, unsigned long);
2035 unsigned long offset
;
2036 unsigned long inflated_len
;
2037 unsigned long inflated_addr
;
2038 unsigned long inflated_offset
;
2040 if (len
> TASK_SIZE
)
2043 get_area
= current
->mm
->get_unmapped_area
;
2044 addr
= get_area(file
, uaddr
, len
, pgoff
, flags
);
2046 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE
))
2048 if (IS_ERR_VALUE(addr
))
2050 if (addr
& ~PAGE_MASK
)
2052 if (addr
> TASK_SIZE
- len
)
2055 if (shmem_huge
== SHMEM_HUGE_DENY
)
2057 if (len
< HPAGE_PMD_SIZE
)
2059 if (flags
& MAP_FIXED
)
2062 * Our priority is to support MAP_SHARED mapped hugely;
2063 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2064 * But if caller specified an address hint, respect that as before.
2069 if (shmem_huge
!= SHMEM_HUGE_FORCE
) {
2070 struct super_block
*sb
;
2073 VM_BUG_ON(file
->f_op
!= &shmem_file_operations
);
2074 sb
= file_inode(file
)->i_sb
;
2077 * Called directly from mm/mmap.c, or drivers/char/mem.c
2078 * for "/dev/zero", to create a shared anonymous object.
2080 if (IS_ERR(shm_mnt
))
2082 sb
= shm_mnt
->mnt_sb
;
2084 if (SHMEM_SB(sb
)->huge
== SHMEM_HUGE_NEVER
)
2088 offset
= (pgoff
<< PAGE_SHIFT
) & (HPAGE_PMD_SIZE
-1);
2089 if (offset
&& offset
+ len
< 2 * HPAGE_PMD_SIZE
)
2091 if ((addr
& (HPAGE_PMD_SIZE
-1)) == offset
)
2094 inflated_len
= len
+ HPAGE_PMD_SIZE
- PAGE_SIZE
;
2095 if (inflated_len
> TASK_SIZE
)
2097 if (inflated_len
< len
)
2100 inflated_addr
= get_area(NULL
, 0, inflated_len
, 0, flags
);
2101 if (IS_ERR_VALUE(inflated_addr
))
2103 if (inflated_addr
& ~PAGE_MASK
)
2106 inflated_offset
= inflated_addr
& (HPAGE_PMD_SIZE
-1);
2107 inflated_addr
+= offset
- inflated_offset
;
2108 if (inflated_offset
> offset
)
2109 inflated_addr
+= HPAGE_PMD_SIZE
;
2111 if (inflated_addr
> TASK_SIZE
- len
)
2113 return inflated_addr
;
2117 static int shmem_set_policy(struct vm_area_struct
*vma
, struct mempolicy
*mpol
)
2119 struct inode
*inode
= file_inode(vma
->vm_file
);
2120 return mpol_set_shared_policy(&SHMEM_I(inode
)->policy
, vma
, mpol
);
2123 static struct mempolicy
*shmem_get_policy(struct vm_area_struct
*vma
,
2126 struct inode
*inode
= file_inode(vma
->vm_file
);
2129 index
= ((addr
- vma
->vm_start
) >> PAGE_SHIFT
) + vma
->vm_pgoff
;
2130 return mpol_shared_policy_lookup(&SHMEM_I(inode
)->policy
, index
);
2134 int shmem_lock(struct file
*file
, int lock
, struct user_struct
*user
)
2136 struct inode
*inode
= file_inode(file
);
2137 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2138 int retval
= -ENOMEM
;
2140 spin_lock_irq(&info
->lock
);
2141 if (lock
&& !(info
->flags
& VM_LOCKED
)) {
2142 if (!user_shm_lock(inode
->i_size
, user
))
2144 info
->flags
|= VM_LOCKED
;
2145 mapping_set_unevictable(file
->f_mapping
);
2147 if (!lock
&& (info
->flags
& VM_LOCKED
) && user
) {
2148 user_shm_unlock(inode
->i_size
, user
);
2149 info
->flags
&= ~VM_LOCKED
;
2150 mapping_clear_unevictable(file
->f_mapping
);
2155 spin_unlock_irq(&info
->lock
);
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
);
2179 if (shmem_reserve_inode(sb
))
2182 inode
= new_inode(sb
);
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 if (!sbinfo
->idr_nouse
) {
2229 /* inum 0 and 1 are unused */
2230 mutex_lock(&sbinfo
->idr_lock
);
2231 ino
= idr_alloc(&sbinfo
->idr
, inode
, 2, INT_MAX
,
2235 mutex_unlock(&sbinfo
->idr_lock
);
2236 __insert_inode_hash(inode
, inode
->i_ino
);
2239 mutex_unlock(&sbinfo
->idr_lock
);
2241 /* shmem_free_inode() will be called */
2245 inode
->i_ino
= get_next_ino();
2247 shmem_free_inode(sb
);
2251 bool shmem_mapping(struct address_space
*mapping
)
2253 return mapping
->a_ops
== &shmem_aops
;
2256 static int shmem_mfill_atomic_pte(struct mm_struct
*dst_mm
,
2258 struct vm_area_struct
*dst_vma
,
2259 unsigned long dst_addr
,
2260 unsigned long src_addr
,
2262 struct page
**pagep
)
2264 struct inode
*inode
= file_inode(dst_vma
->vm_file
);
2265 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2266 struct address_space
*mapping
= inode
->i_mapping
;
2267 gfp_t gfp
= mapping_gfp_mask(mapping
);
2268 pgoff_t pgoff
= linear_page_index(dst_vma
, dst_addr
);
2269 struct mem_cgroup
*memcg
;
2273 pte_t _dst_pte
, *dst_pte
;
2275 pgoff_t offset
, max_off
;
2278 if (!shmem_inode_acct_block(inode
, 1))
2282 page
= shmem_alloc_page(gfp
, info
, pgoff
);
2284 goto out_unacct_blocks
;
2286 if (!zeropage
) { /* mcopy_atomic */
2287 page_kaddr
= kmap_atomic(page
);
2288 ret
= copy_from_user(page_kaddr
,
2289 (const void __user
*)src_addr
,
2291 kunmap_atomic(page_kaddr
);
2293 /* fallback to copy_from_user outside mmap_sem */
2294 if (unlikely(ret
)) {
2296 shmem_inode_unacct_blocks(inode
, 1);
2297 /* don't free the page */
2300 } else { /* mfill_zeropage_atomic */
2301 clear_highpage(page
);
2308 VM_BUG_ON(PageLocked(page
) || PageSwapBacked(page
));
2309 __SetPageLocked(page
);
2310 __SetPageSwapBacked(page
);
2311 __SetPageUptodate(page
);
2314 offset
= linear_page_index(dst_vma
, dst_addr
);
2315 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
2316 if (unlikely(offset
>= max_off
))
2319 ret
= mem_cgroup_try_charge(page
, dst_mm
, gfp
, &memcg
, false);
2323 ret
= radix_tree_maybe_preload(gfp
& GFP_RECLAIM_MASK
);
2325 ret
= shmem_add_to_page_cache(page
, mapping
, pgoff
, NULL
);
2326 radix_tree_preload_end();
2329 goto out_release_uncharge
;
2331 mem_cgroup_commit_charge(page
, memcg
, false, false);
2333 _dst_pte
= mk_pte(page
, dst_vma
->vm_page_prot
);
2334 if (dst_vma
->vm_flags
& VM_WRITE
)
2335 _dst_pte
= pte_mkwrite(pte_mkdirty(_dst_pte
));
2338 * We don't set the pte dirty if the vma has no
2339 * VM_WRITE permission, so mark the page dirty or it
2340 * could be freed from under us. We could do it
2341 * unconditionally before unlock_page(), but doing it
2342 * only if VM_WRITE is not set is faster.
2344 set_page_dirty(page
);
2347 dst_pte
= pte_offset_map_lock(dst_mm
, dst_pmd
, dst_addr
, &ptl
);
2350 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
2351 if (unlikely(offset
>= max_off
))
2352 goto out_release_uncharge_unlock
;
2355 if (!pte_none(*dst_pte
))
2356 goto out_release_uncharge_unlock
;
2358 lru_cache_add_anon(page
);
2360 spin_lock(&info
->lock
);
2362 inode
->i_blocks
+= BLOCKS_PER_PAGE
;
2363 shmem_recalc_inode(inode
);
2364 spin_unlock(&info
->lock
);
2366 inc_mm_counter(dst_mm
, mm_counter_file(page
));
2367 page_add_file_rmap(page
, false);
2368 set_pte_at(dst_mm
, dst_addr
, dst_pte
, _dst_pte
);
2370 /* No need to invalidate - it was non-present before */
2371 update_mmu_cache(dst_vma
, dst_addr
, dst_pte
);
2372 pte_unmap_unlock(dst_pte
, ptl
);
2377 out_release_uncharge_unlock
:
2378 pte_unmap_unlock(dst_pte
, ptl
);
2379 ClearPageDirty(page
);
2380 delete_from_page_cache(page
);
2381 out_release_uncharge
:
2382 mem_cgroup_cancel_charge(page
, memcg
, false);
2387 shmem_inode_unacct_blocks(inode
, 1);
2391 int shmem_mcopy_atomic_pte(struct mm_struct
*dst_mm
,
2393 struct vm_area_struct
*dst_vma
,
2394 unsigned long dst_addr
,
2395 unsigned long src_addr
,
2396 struct page
**pagep
)
2398 return shmem_mfill_atomic_pte(dst_mm
, dst_pmd
, dst_vma
,
2399 dst_addr
, src_addr
, false, pagep
);
2402 int shmem_mfill_zeropage_pte(struct mm_struct
*dst_mm
,
2404 struct vm_area_struct
*dst_vma
,
2405 unsigned long dst_addr
)
2407 struct page
*page
= NULL
;
2409 return shmem_mfill_atomic_pte(dst_mm
, dst_pmd
, dst_vma
,
2410 dst_addr
, 0, true, &page
);
2414 static const struct inode_operations shmem_symlink_inode_operations
;
2415 static const struct inode_operations shmem_short_symlink_operations
;
2417 #ifdef CONFIG_TMPFS_XATTR
2418 static int shmem_initxattrs(struct inode
*, const struct xattr
*, void *);
2420 #define shmem_initxattrs NULL
2424 shmem_write_begin(struct file
*file
, struct address_space
*mapping
,
2425 loff_t pos
, unsigned len
, unsigned flags
,
2426 struct page
**pagep
, void **fsdata
)
2428 struct inode
*inode
= mapping
->host
;
2429 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2430 pgoff_t index
= pos
>> PAGE_SHIFT
;
2432 /* i_mutex is held by caller */
2433 if (unlikely(info
->seals
& (F_SEAL_WRITE
| F_SEAL_GROW
))) {
2434 if (info
->seals
& F_SEAL_WRITE
)
2436 if ((info
->seals
& F_SEAL_GROW
) && pos
+ len
> inode
->i_size
)
2440 return shmem_getpage(inode
, index
, pagep
, SGP_WRITE
);
2444 shmem_write_end(struct file
*file
, struct address_space
*mapping
,
2445 loff_t pos
, unsigned len
, unsigned copied
,
2446 struct page
*page
, void *fsdata
)
2448 struct inode
*inode
= mapping
->host
;
2450 if (pos
+ copied
> inode
->i_size
)
2451 i_size_write(inode
, pos
+ copied
);
2453 if (!PageUptodate(page
)) {
2454 struct page
*head
= compound_head(page
);
2455 if (PageTransCompound(page
)) {
2458 for (i
= 0; i
< HPAGE_PMD_NR
; i
++) {
2459 if (head
+ i
== page
)
2461 clear_highpage(head
+ i
);
2462 flush_dcache_page(head
+ i
);
2465 if (copied
< PAGE_SIZE
) {
2466 unsigned from
= pos
& (PAGE_SIZE
- 1);
2467 zero_user_segments(page
, 0, from
,
2468 from
+ copied
, PAGE_SIZE
);
2470 SetPageUptodate(head
);
2472 set_page_dirty(page
);
2479 static ssize_t
shmem_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*to
)
2481 struct file
*file
= iocb
->ki_filp
;
2482 struct inode
*inode
= file_inode(file
);
2483 struct address_space
*mapping
= inode
->i_mapping
;
2485 unsigned long offset
;
2486 enum sgp_type sgp
= SGP_READ
;
2489 loff_t
*ppos
= &iocb
->ki_pos
;
2492 * Might this read be for a stacking filesystem? Then when reading
2493 * holes of a sparse file, we actually need to allocate those pages,
2494 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2496 if (!iter_is_iovec(to
))
2499 index
= *ppos
>> PAGE_SHIFT
;
2500 offset
= *ppos
& ~PAGE_MASK
;
2503 struct page
*page
= NULL
;
2505 unsigned long nr
, ret
;
2506 loff_t i_size
= i_size_read(inode
);
2508 end_index
= i_size
>> PAGE_SHIFT
;
2509 if (index
> end_index
)
2511 if (index
== end_index
) {
2512 nr
= i_size
& ~PAGE_MASK
;
2517 error
= shmem_getpage(inode
, index
, &page
, sgp
);
2519 if (error
== -EINVAL
)
2524 if (sgp
== SGP_CACHE
)
2525 set_page_dirty(page
);
2530 * We must evaluate after, since reads (unlike writes)
2531 * are called without i_mutex protection against truncate
2534 i_size
= i_size_read(inode
);
2535 end_index
= i_size
>> PAGE_SHIFT
;
2536 if (index
== end_index
) {
2537 nr
= i_size
& ~PAGE_MASK
;
2548 * If users can be writing to this page using arbitrary
2549 * virtual addresses, take care about potential aliasing
2550 * before reading the page on the kernel side.
2552 if (mapping_writably_mapped(mapping
))
2553 flush_dcache_page(page
);
2555 * Mark the page accessed if we read the beginning.
2558 mark_page_accessed(page
);
2560 page
= ZERO_PAGE(0);
2565 * Ok, we have the page, and it's up-to-date, so
2566 * now we can copy it to user space...
2568 ret
= copy_page_to_iter(page
, offset
, nr
, to
);
2571 index
+= offset
>> PAGE_SHIFT
;
2572 offset
&= ~PAGE_MASK
;
2575 if (!iov_iter_count(to
))
2584 *ppos
= ((loff_t
) index
<< PAGE_SHIFT
) + offset
;
2585 file_accessed(file
);
2586 return retval
? retval
: error
;
2590 * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
2592 static pgoff_t
shmem_seek_hole_data(struct address_space
*mapping
,
2593 pgoff_t index
, pgoff_t end
, int whence
)
2596 struct pagevec pvec
;
2597 pgoff_t indices
[PAGEVEC_SIZE
];
2601 pagevec_init(&pvec
);
2602 pvec
.nr
= 1; /* start small: we may be there already */
2604 pvec
.nr
= find_get_entries(mapping
, index
,
2605 pvec
.nr
, pvec
.pages
, indices
);
2607 if (whence
== SEEK_DATA
)
2611 for (i
= 0; i
< pvec
.nr
; i
++, index
++) {
2612 if (index
< indices
[i
]) {
2613 if (whence
== SEEK_HOLE
) {
2619 page
= pvec
.pages
[i
];
2620 if (page
&& !radix_tree_exceptional_entry(page
)) {
2621 if (!PageUptodate(page
))
2625 (page
&& whence
== SEEK_DATA
) ||
2626 (!page
&& whence
== SEEK_HOLE
)) {
2631 pagevec_remove_exceptionals(&pvec
);
2632 pagevec_release(&pvec
);
2633 pvec
.nr
= PAGEVEC_SIZE
;
2639 static loff_t
shmem_file_llseek(struct file
*file
, loff_t offset
, int whence
)
2641 struct address_space
*mapping
= file
->f_mapping
;
2642 struct inode
*inode
= mapping
->host
;
2646 if (whence
!= SEEK_DATA
&& whence
!= SEEK_HOLE
)
2647 return generic_file_llseek_size(file
, offset
, whence
,
2648 MAX_LFS_FILESIZE
, i_size_read(inode
));
2650 /* We're holding i_mutex so we can access i_size directly */
2652 if (offset
< 0 || offset
>= inode
->i_size
)
2655 start
= offset
>> PAGE_SHIFT
;
2656 end
= (inode
->i_size
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
2657 new_offset
= shmem_seek_hole_data(mapping
, start
, end
, whence
);
2658 new_offset
<<= PAGE_SHIFT
;
2659 if (new_offset
> offset
) {
2660 if (new_offset
< inode
->i_size
)
2661 offset
= new_offset
;
2662 else if (whence
== SEEK_DATA
)
2665 offset
= inode
->i_size
;
2670 offset
= vfs_setpos(file
, offset
, MAX_LFS_FILESIZE
);
2671 inode_unlock(inode
);
2676 * We need a tag: a new tag would expand every radix_tree_node by 8 bytes,
2677 * so reuse a tag which we firmly believe is never set or cleared on shmem.
2679 #define SHMEM_TAG_PINNED PAGECACHE_TAG_TOWRITE
2680 #define LAST_SCAN 4 /* about 150ms max */
2682 static void shmem_tag_pins(struct address_space
*mapping
)
2684 struct radix_tree_iter iter
;
2688 unsigned int tagged
= 0;
2693 spin_lock_irq(&mapping
->tree_lock
);
2694 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
2695 page
= radix_tree_deref_slot(slot
);
2696 if (!page
|| radix_tree_exception(page
)) {
2697 if (radix_tree_deref_retry(page
)) {
2698 slot
= radix_tree_iter_retry(&iter
);
2701 } else if (page_count(page
) - page_mapcount(page
) > 1) {
2702 radix_tree_tag_set(&mapping
->page_tree
, iter
.index
,
2706 if (++tagged
% 1024)
2709 slot
= radix_tree_iter_resume(slot
, &iter
);
2710 spin_unlock_irq(&mapping
->tree_lock
);
2712 spin_lock_irq(&mapping
->tree_lock
);
2714 spin_unlock_irq(&mapping
->tree_lock
);
2718 * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
2719 * via get_user_pages(), drivers might have some pending I/O without any active
2720 * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
2721 * and see whether it has an elevated ref-count. If so, we tag them and wait for
2722 * them to be dropped.
2723 * The caller must guarantee that no new user will acquire writable references
2724 * to those pages to avoid races.
2726 static int shmem_wait_for_pins(struct address_space
*mapping
)
2728 struct radix_tree_iter iter
;
2734 shmem_tag_pins(mapping
);
2737 for (scan
= 0; scan
<= LAST_SCAN
; scan
++) {
2738 if (!radix_tree_tagged(&mapping
->page_tree
, SHMEM_TAG_PINNED
))
2742 lru_add_drain_all();
2743 else if (schedule_timeout_killable((HZ
<< scan
) / 200))
2748 radix_tree_for_each_tagged(slot
, &mapping
->page_tree
, &iter
,
2749 start
, SHMEM_TAG_PINNED
) {
2751 page
= radix_tree_deref_slot(slot
);
2752 if (radix_tree_exception(page
)) {
2753 if (radix_tree_deref_retry(page
)) {
2754 slot
= radix_tree_iter_retry(&iter
);
2762 page_count(page
) - page_mapcount(page
) != 1) {
2763 if (scan
< LAST_SCAN
)
2764 goto continue_resched
;
2767 * On the last scan, we clean up all those tags
2768 * we inserted; but make a note that we still
2769 * found pages pinned.
2774 spin_lock_irq(&mapping
->tree_lock
);
2775 radix_tree_tag_clear(&mapping
->page_tree
,
2776 iter
.index
, SHMEM_TAG_PINNED
);
2777 spin_unlock_irq(&mapping
->tree_lock
);
2779 if (need_resched()) {
2780 slot
= radix_tree_iter_resume(slot
, &iter
);
2790 #define F_ALL_SEALS (F_SEAL_SEAL | \
2795 int shmem_add_seals(struct file
*file
, unsigned int seals
)
2797 struct inode
*inode
= file_inode(file
);
2798 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2803 * Sealing allows multiple parties to share a shmem-file but restrict
2804 * access to a specific subset of file operations. Seals can only be
2805 * added, but never removed. This way, mutually untrusted parties can
2806 * share common memory regions with a well-defined policy. A malicious
2807 * peer can thus never perform unwanted operations on a shared object.
2809 * Seals are only supported on special shmem-files and always affect
2810 * the whole underlying inode. Once a seal is set, it may prevent some
2811 * kinds of access to the file. Currently, the following seals are
2813 * SEAL_SEAL: Prevent further seals from being set on this file
2814 * SEAL_SHRINK: Prevent the file from shrinking
2815 * SEAL_GROW: Prevent the file from growing
2816 * SEAL_WRITE: Prevent write access to the file
2818 * As we don't require any trust relationship between two parties, we
2819 * must prevent seals from being removed. Therefore, sealing a file
2820 * only adds a given set of seals to the file, it never touches
2821 * existing seals. Furthermore, the "setting seals"-operation can be
2822 * sealed itself, which basically prevents any further seal from being
2825 * Semantics of sealing are only defined on volatile files. Only
2826 * anonymous shmem files support sealing. More importantly, seals are
2827 * never written to disk. Therefore, there's no plan to support it on
2831 if (file
->f_op
!= &shmem_file_operations
)
2833 if (!(file
->f_mode
& FMODE_WRITE
))
2835 if (seals
& ~(unsigned int)F_ALL_SEALS
)
2840 if (info
->seals
& F_SEAL_SEAL
) {
2845 if ((seals
& F_SEAL_WRITE
) && !(info
->seals
& F_SEAL_WRITE
)) {
2846 error
= mapping_deny_writable(file
->f_mapping
);
2850 error
= shmem_wait_for_pins(file
->f_mapping
);
2852 mapping_allow_writable(file
->f_mapping
);
2857 info
->seals
|= seals
;
2861 inode_unlock(inode
);
2864 EXPORT_SYMBOL_GPL(shmem_add_seals
);
2866 int shmem_get_seals(struct file
*file
)
2868 if (file
->f_op
!= &shmem_file_operations
)
2871 return SHMEM_I(file_inode(file
))->seals
;
2873 EXPORT_SYMBOL_GPL(shmem_get_seals
);
2875 long shmem_fcntl(struct file
*file
, unsigned int cmd
, unsigned long arg
)
2881 /* disallow upper 32bit */
2885 error
= shmem_add_seals(file
, arg
);
2888 error
= shmem_get_seals(file
);
2898 static long shmem_fallocate(struct file
*file
, int mode
, loff_t offset
,
2901 struct inode
*inode
= file_inode(file
);
2902 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
2903 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2904 struct shmem_falloc shmem_falloc
;
2905 pgoff_t start
, index
, end
;
2908 if (mode
& ~(FALLOC_FL_KEEP_SIZE
| FALLOC_FL_PUNCH_HOLE
))
2913 if (mode
& FALLOC_FL_PUNCH_HOLE
) {
2914 struct address_space
*mapping
= file
->f_mapping
;
2915 loff_t unmap_start
= round_up(offset
, PAGE_SIZE
);
2916 loff_t unmap_end
= round_down(offset
+ len
, PAGE_SIZE
) - 1;
2917 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq
);
2919 /* protected by i_mutex */
2920 if (info
->seals
& F_SEAL_WRITE
) {
2925 shmem_falloc
.waitq
= &shmem_falloc_waitq
;
2926 shmem_falloc
.start
= unmap_start
>> PAGE_SHIFT
;
2927 shmem_falloc
.next
= (unmap_end
+ 1) >> PAGE_SHIFT
;
2928 spin_lock(&inode
->i_lock
);
2929 inode
->i_private
= &shmem_falloc
;
2930 spin_unlock(&inode
->i_lock
);
2932 if ((u64
)unmap_end
> (u64
)unmap_start
)
2933 unmap_mapping_range(mapping
, unmap_start
,
2934 1 + unmap_end
- unmap_start
, 0);
2935 shmem_truncate_range(inode
, offset
, offset
+ len
- 1);
2936 /* No need to unmap again: hole-punching leaves COWed pages */
2938 spin_lock(&inode
->i_lock
);
2939 inode
->i_private
= NULL
;
2940 wake_up_all(&shmem_falloc_waitq
);
2941 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq
.head
));
2942 spin_unlock(&inode
->i_lock
);
2947 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2948 error
= inode_newsize_ok(inode
, offset
+ len
);
2952 if ((info
->seals
& F_SEAL_GROW
) && offset
+ len
> inode
->i_size
) {
2957 start
= offset
>> PAGE_SHIFT
;
2958 end
= (offset
+ len
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
2959 /* Try to avoid a swapstorm if len is impossible to satisfy */
2960 if (sbinfo
->max_blocks
&& end
- start
> sbinfo
->max_blocks
) {
2965 shmem_falloc
.waitq
= NULL
;
2966 shmem_falloc
.start
= start
;
2967 shmem_falloc
.next
= start
;
2968 shmem_falloc
.nr_falloced
= 0;
2969 shmem_falloc
.nr_unswapped
= 0;
2970 spin_lock(&inode
->i_lock
);
2971 inode
->i_private
= &shmem_falloc
;
2972 spin_unlock(&inode
->i_lock
);
2974 for (index
= start
; index
< end
; index
++) {
2978 * Good, the fallocate(2) manpage permits EINTR: we may have
2979 * been interrupted because we are using up too much memory.
2981 if (signal_pending(current
))
2983 else if (shmem_falloc
.nr_unswapped
> shmem_falloc
.nr_falloced
)
2986 error
= shmem_getpage(inode
, index
, &page
, SGP_FALLOC
);
2988 /* Remove the !PageUptodate pages we added */
2989 if (index
> start
) {
2990 shmem_undo_range(inode
,
2991 (loff_t
)start
<< PAGE_SHIFT
,
2992 ((loff_t
)index
<< PAGE_SHIFT
) - 1, true);
2998 * Inform shmem_writepage() how far we have reached.
2999 * No need for lock or barrier: we have the page lock.
3001 shmem_falloc
.next
++;
3002 if (!PageUptodate(page
))
3003 shmem_falloc
.nr_falloced
++;
3006 * If !PageUptodate, leave it that way so that freeable pages
3007 * can be recognized if we need to rollback on error later.
3008 * But set_page_dirty so that memory pressure will swap rather
3009 * than free the pages we are allocating (and SGP_CACHE pages
3010 * might still be clean: we now need to mark those dirty too).
3012 set_page_dirty(page
);
3018 if (!(mode
& FALLOC_FL_KEEP_SIZE
) && offset
+ len
> inode
->i_size
)
3019 i_size_write(inode
, offset
+ len
);
3020 inode
->i_ctime
= current_time(inode
);
3022 spin_lock(&inode
->i_lock
);
3023 inode
->i_private
= NULL
;
3024 spin_unlock(&inode
->i_lock
);
3026 inode_unlock(inode
);
3030 static int shmem_statfs(struct dentry
*dentry
, struct kstatfs
*buf
)
3032 struct shmem_sb_info
*sbinfo
= SHMEM_SB(dentry
->d_sb
);
3034 buf
->f_type
= TMPFS_MAGIC
;
3035 buf
->f_bsize
= PAGE_SIZE
;
3036 buf
->f_namelen
= NAME_MAX
;
3037 if (sbinfo
->max_blocks
) {
3038 buf
->f_blocks
= sbinfo
->max_blocks
;
3040 buf
->f_bfree
= sbinfo
->max_blocks
-
3041 percpu_counter_sum(&sbinfo
->used_blocks
);
3043 if (sbinfo
->max_inodes
) {
3044 buf
->f_files
= sbinfo
->max_inodes
;
3045 buf
->f_ffree
= sbinfo
->free_inodes
;
3047 /* else leave those fields 0 like simple_statfs */
3052 * File creation. Allocate an inode, and we're done..
3055 shmem_mknod(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
, dev_t dev
)
3057 struct inode
*inode
;
3058 int error
= -ENOSPC
;
3060 inode
= shmem_get_inode(dir
->i_sb
, dir
, mode
, dev
, VM_NORESERVE
);
3062 error
= simple_acl_create(dir
, inode
);
3065 error
= security_inode_init_security(inode
, dir
,
3067 shmem_initxattrs
, NULL
);
3068 if (error
&& error
!= -EOPNOTSUPP
)
3072 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3073 dir
->i_ctime
= dir
->i_mtime
= current_time(dir
);
3074 d_instantiate(dentry
, inode
);
3075 dget(dentry
); /* Extra count - pin the dentry in core */
3084 shmem_tmpfile(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
3086 struct inode
*inode
;
3087 int error
= -ENOSPC
;
3089 inode
= shmem_get_inode(dir
->i_sb
, dir
, mode
, 0, VM_NORESERVE
);
3091 error
= security_inode_init_security(inode
, dir
,
3093 shmem_initxattrs
, NULL
);
3094 if (error
&& error
!= -EOPNOTSUPP
)
3096 error
= simple_acl_create(dir
, inode
);
3099 d_tmpfile(dentry
, inode
);
3107 static int shmem_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
3111 if ((error
= shmem_mknod(dir
, dentry
, mode
| S_IFDIR
, 0)))
3117 static int shmem_create(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
,
3120 return shmem_mknod(dir
, dentry
, mode
| S_IFREG
, 0);
3126 static int shmem_link(struct dentry
*old_dentry
, struct inode
*dir
, struct dentry
*dentry
)
3128 struct inode
*inode
= d_inode(old_dentry
);
3132 * No ordinary (disk based) filesystem counts links as inodes;
3133 * but each new link needs a new dentry, pinning lowmem, and
3134 * tmpfs dentries cannot be pruned until they are unlinked.
3135 * But if an O_TMPFILE file is linked into the tmpfs, the
3136 * first link must skip that, to get the accounting right.
3138 if (inode
->i_nlink
) {
3139 ret
= shmem_reserve_inode(inode
->i_sb
);
3144 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3145 inode
->i_ctime
= dir
->i_ctime
= dir
->i_mtime
= current_time(inode
);
3147 ihold(inode
); /* New dentry reference */
3148 dget(dentry
); /* Extra pinning count for the created dentry */
3149 d_instantiate(dentry
, inode
);
3154 static int shmem_unlink(struct inode
*dir
, struct dentry
*dentry
)
3156 struct inode
*inode
= d_inode(dentry
);
3158 if (inode
->i_nlink
> 1 && !S_ISDIR(inode
->i_mode
))
3159 shmem_free_inode(inode
->i_sb
);
3161 dir
->i_size
-= BOGO_DIRENT_SIZE
;
3162 inode
->i_ctime
= dir
->i_ctime
= dir
->i_mtime
= current_time(inode
);
3164 dput(dentry
); /* Undo the count from "create" - this does all the work */
3168 static int shmem_rmdir(struct inode
*dir
, struct dentry
*dentry
)
3170 if (!simple_empty(dentry
))
3173 drop_nlink(d_inode(dentry
));
3175 return shmem_unlink(dir
, dentry
);
3178 static int shmem_exchange(struct inode
*old_dir
, struct dentry
*old_dentry
, struct inode
*new_dir
, struct dentry
*new_dentry
)
3180 bool old_is_dir
= d_is_dir(old_dentry
);
3181 bool new_is_dir
= d_is_dir(new_dentry
);
3183 if (old_dir
!= new_dir
&& old_is_dir
!= new_is_dir
) {
3185 drop_nlink(old_dir
);
3188 drop_nlink(new_dir
);
3192 old_dir
->i_ctime
= old_dir
->i_mtime
=
3193 new_dir
->i_ctime
= new_dir
->i_mtime
=
3194 d_inode(old_dentry
)->i_ctime
=
3195 d_inode(new_dentry
)->i_ctime
= current_time(old_dir
);
3200 static int shmem_whiteout(struct inode
*old_dir
, struct dentry
*old_dentry
)
3202 struct dentry
*whiteout
;
3205 whiteout
= d_alloc(old_dentry
->d_parent
, &old_dentry
->d_name
);
3209 error
= shmem_mknod(old_dir
, whiteout
,
3210 S_IFCHR
| WHITEOUT_MODE
, WHITEOUT_DEV
);
3216 * Cheat and hash the whiteout while the old dentry is still in
3217 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3219 * d_lookup() will consistently find one of them at this point,
3220 * not sure which one, but that isn't even important.
3227 * The VFS layer already does all the dentry stuff for rename,
3228 * we just have to decrement the usage count for the target if
3229 * it exists so that the VFS layer correctly free's it when it
3232 static int shmem_rename2(struct inode
*old_dir
, struct dentry
*old_dentry
, struct inode
*new_dir
, struct dentry
*new_dentry
, unsigned int flags
)
3234 struct inode
*inode
= d_inode(old_dentry
);
3235 int they_are_dirs
= S_ISDIR(inode
->i_mode
);
3237 if (flags
& ~(RENAME_NOREPLACE
| RENAME_EXCHANGE
| RENAME_WHITEOUT
))
3240 if (flags
& RENAME_EXCHANGE
)
3241 return shmem_exchange(old_dir
, old_dentry
, new_dir
, new_dentry
);
3243 if (!simple_empty(new_dentry
))
3246 if (flags
& RENAME_WHITEOUT
) {
3249 error
= shmem_whiteout(old_dir
, old_dentry
);
3254 if (d_really_is_positive(new_dentry
)) {
3255 (void) shmem_unlink(new_dir
, new_dentry
);
3256 if (they_are_dirs
) {
3257 drop_nlink(d_inode(new_dentry
));
3258 drop_nlink(old_dir
);
3260 } else if (they_are_dirs
) {
3261 drop_nlink(old_dir
);
3265 old_dir
->i_size
-= BOGO_DIRENT_SIZE
;
3266 new_dir
->i_size
+= BOGO_DIRENT_SIZE
;
3267 old_dir
->i_ctime
= old_dir
->i_mtime
=
3268 new_dir
->i_ctime
= new_dir
->i_mtime
=
3269 inode
->i_ctime
= current_time(old_dir
);
3273 static int shmem_symlink(struct inode
*dir
, struct dentry
*dentry
, const char *symname
)
3277 struct inode
*inode
;
3280 len
= strlen(symname
) + 1;
3281 if (len
> PAGE_SIZE
)
3282 return -ENAMETOOLONG
;
3284 inode
= shmem_get_inode(dir
->i_sb
, dir
, S_IFLNK
|S_IRWXUGO
, 0, VM_NORESERVE
);
3288 error
= security_inode_init_security(inode
, dir
, &dentry
->d_name
,
3289 shmem_initxattrs
, NULL
);
3291 if (error
!= -EOPNOTSUPP
) {
3298 inode
->i_size
= len
-1;
3299 if (len
<= SHORT_SYMLINK_LEN
) {
3300 inode
->i_link
= kmemdup(symname
, len
, GFP_KERNEL
);
3301 if (!inode
->i_link
) {
3305 inode
->i_op
= &shmem_short_symlink_operations
;
3307 inode_nohighmem(inode
);
3308 error
= shmem_getpage(inode
, 0, &page
, SGP_WRITE
);
3313 inode
->i_mapping
->a_ops
= &shmem_aops
;
3314 inode
->i_op
= &shmem_symlink_inode_operations
;
3315 memcpy(page_address(page
), symname
, len
);
3316 SetPageUptodate(page
);
3317 set_page_dirty(page
);
3321 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3322 dir
->i_ctime
= dir
->i_mtime
= current_time(dir
);
3323 d_instantiate(dentry
, inode
);
3328 static void shmem_put_link(void *arg
)
3330 mark_page_accessed(arg
);
3334 static const char *shmem_get_link(struct dentry
*dentry
,
3335 struct inode
*inode
,
3336 struct delayed_call
*done
)
3338 struct page
*page
= NULL
;
3341 page
= find_get_page(inode
->i_mapping
, 0);
3343 return ERR_PTR(-ECHILD
);
3344 if (!PageUptodate(page
)) {
3346 return ERR_PTR(-ECHILD
);
3349 error
= shmem_getpage(inode
, 0, &page
, SGP_READ
);
3351 return ERR_PTR(error
);
3354 set_delayed_call(done
, shmem_put_link
, page
);
3355 return page_address(page
);
3358 #ifdef CONFIG_TMPFS_XATTR
3360 * Superblocks without xattr inode operations may get some security.* xattr
3361 * support from the LSM "for free". As soon as we have any other xattrs
3362 * like ACLs, we also need to implement the security.* handlers at
3363 * filesystem level, though.
3367 * Callback for security_inode_init_security() for acquiring xattrs.
3369 static int shmem_initxattrs(struct inode
*inode
,
3370 const struct xattr
*xattr_array
,
3373 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3374 const struct xattr
*xattr
;
3375 struct simple_xattr
*new_xattr
;
3378 for (xattr
= xattr_array
; xattr
->name
!= NULL
; xattr
++) {
3379 new_xattr
= simple_xattr_alloc(xattr
->value
, xattr
->value_len
);
3383 len
= strlen(xattr
->name
) + 1;
3384 new_xattr
->name
= kmalloc(XATTR_SECURITY_PREFIX_LEN
+ len
,
3386 if (!new_xattr
->name
) {
3391 memcpy(new_xattr
->name
, XATTR_SECURITY_PREFIX
,
3392 XATTR_SECURITY_PREFIX_LEN
);
3393 memcpy(new_xattr
->name
+ XATTR_SECURITY_PREFIX_LEN
,
3396 simple_xattr_list_add(&info
->xattrs
, new_xattr
);
3402 static int shmem_xattr_handler_get(const struct xattr_handler
*handler
,
3403 struct dentry
*unused
, struct inode
*inode
,
3404 const char *name
, void *buffer
, size_t size
)
3406 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3408 name
= xattr_full_name(handler
, name
);
3409 return simple_xattr_get(&info
->xattrs
, name
, buffer
, size
);
3412 static int shmem_xattr_handler_set(const struct xattr_handler
*handler
,
3413 struct dentry
*unused
, struct inode
*inode
,
3414 const char *name
, const void *value
,
3415 size_t size
, int flags
)
3417 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3419 name
= xattr_full_name(handler
, name
);
3420 return simple_xattr_set(&info
->xattrs
, name
, value
, size
, flags
);
3423 static const struct xattr_handler shmem_security_xattr_handler
= {
3424 .prefix
= XATTR_SECURITY_PREFIX
,
3425 .get
= shmem_xattr_handler_get
,
3426 .set
= shmem_xattr_handler_set
,
3429 static const struct xattr_handler shmem_trusted_xattr_handler
= {
3430 .prefix
= XATTR_TRUSTED_PREFIX
,
3431 .get
= shmem_xattr_handler_get
,
3432 .set
= shmem_xattr_handler_set
,
3435 static const struct xattr_handler
*shmem_xattr_handlers
[] = {
3436 #ifdef CONFIG_TMPFS_POSIX_ACL
3437 &posix_acl_access_xattr_handler
,
3438 &posix_acl_default_xattr_handler
,
3440 &shmem_security_xattr_handler
,
3441 &shmem_trusted_xattr_handler
,
3445 static ssize_t
shmem_listxattr(struct dentry
*dentry
, char *buffer
, size_t size
)
3447 struct shmem_inode_info
*info
= SHMEM_I(d_inode(dentry
));
3448 return simple_xattr_list(d_inode(dentry
), &info
->xattrs
, buffer
, size
);
3450 #endif /* CONFIG_TMPFS_XATTR */
3452 static const struct inode_operations shmem_short_symlink_operations
= {
3453 .get_link
= simple_get_link
,
3454 #ifdef CONFIG_TMPFS_XATTR
3455 .listxattr
= shmem_listxattr
,
3459 static const struct inode_operations shmem_symlink_inode_operations
= {
3460 .get_link
= shmem_get_link
,
3461 #ifdef CONFIG_TMPFS_XATTR
3462 .listxattr
= shmem_listxattr
,
3466 static struct dentry
*shmem_get_parent(struct dentry
*child
)
3468 return ERR_PTR(-ESTALE
);
3471 static int shmem_match(struct inode
*ino
, void *vfh
)
3475 return ino
->i_ino
== inum
&& fh
[0] == ino
->i_generation
;
3478 static struct dentry
*shmem_fh_to_dentry(struct super_block
*sb
,
3479 struct fid
*fid
, int fh_len
, int fh_type
)
3481 struct inode
*inode
;
3482 struct dentry
*dentry
= NULL
;
3489 inode
= ilookup5(sb
, inum
, shmem_match
, fid
->raw
);
3491 dentry
= d_find_alias(inode
);
3498 static int shmem_encode_fh(struct inode
*inode
, __u32
*fh
, int *len
,
3499 struct inode
*parent
)
3503 return FILEID_INVALID
;
3506 fh
[0] = inode
->i_generation
;
3507 fh
[1] = inode
->i_ino
;
3513 static const struct export_operations shmem_export_ops
= {
3514 .get_parent
= shmem_get_parent
,
3515 .encode_fh
= shmem_encode_fh
,
3516 .fh_to_dentry
= shmem_fh_to_dentry
,
3519 static int shmem_parse_options(char *options
, struct shmem_sb_info
*sbinfo
,
3522 char *this_char
, *value
, *rest
;
3523 struct mempolicy
*mpol
= NULL
;
3527 while (options
!= NULL
) {
3528 this_char
= options
;
3531 * NUL-terminate this option: unfortunately,
3532 * mount options form a comma-separated list,
3533 * but mpol's nodelist may also contain commas.
3535 options
= strchr(options
, ',');
3536 if (options
== NULL
)
3539 if (!isdigit(*options
)) {
3546 if ((value
= strchr(this_char
,'=')) != NULL
) {
3549 pr_err("tmpfs: No value for mount option '%s'\n",
3554 if (!strcmp(this_char
,"size")) {
3555 unsigned long long size
;
3556 size
= memparse(value
,&rest
);
3558 size
<<= PAGE_SHIFT
;
3559 size
*= totalram_pages
;
3565 sbinfo
->max_blocks
=
3566 DIV_ROUND_UP(size
, PAGE_SIZE
);
3567 } else if (!strcmp(this_char
,"nr_blocks")) {
3568 sbinfo
->max_blocks
= memparse(value
, &rest
);
3571 } else if (!strcmp(this_char
,"nr_inodes")) {
3572 sbinfo
->max_inodes
= memparse(value
, &rest
);
3573 if (*rest
|| sbinfo
->max_inodes
< 2)
3575 } else if (!strcmp(this_char
,"mode")) {
3578 sbinfo
->mode
= simple_strtoul(value
, &rest
, 8) & 07777;
3581 } else if (!strcmp(this_char
,"uid")) {
3584 uid
= simple_strtoul(value
, &rest
, 0);
3587 sbinfo
->uid
= make_kuid(current_user_ns(), uid
);
3588 if (!uid_valid(sbinfo
->uid
))
3590 } else if (!strcmp(this_char
,"gid")) {
3593 gid
= simple_strtoul(value
, &rest
, 0);
3596 sbinfo
->gid
= make_kgid(current_user_ns(), gid
);
3597 if (!gid_valid(sbinfo
->gid
))
3599 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3600 } else if (!strcmp(this_char
, "huge")) {
3602 huge
= shmem_parse_huge(value
);
3605 if (!has_transparent_hugepage() &&
3606 huge
!= SHMEM_HUGE_NEVER
)
3608 sbinfo
->huge
= huge
;
3611 } else if (!strcmp(this_char
,"mpol")) {
3614 if (mpol_parse_str(value
, &mpol
))
3618 pr_err("tmpfs: Bad mount option %s\n", this_char
);
3622 sbinfo
->mpol
= mpol
;
3626 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3634 static int shmem_remount_fs(struct super_block
*sb
, int *flags
, char *data
)
3636 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
3637 struct shmem_sb_info config
= *sbinfo
;
3639 int error
= -EINVAL
;
3642 if (shmem_parse_options(data
, &config
, true))
3645 spin_lock(&sbinfo
->stat_lock
);
3646 inodes
= sbinfo
->max_inodes
- sbinfo
->free_inodes
;
3647 if (percpu_counter_compare(&sbinfo
->used_blocks
, config
.max_blocks
) > 0)
3649 if (config
.max_inodes
< inodes
)
3652 * Those tests disallow limited->unlimited while any are in use;
3653 * but we must separately disallow unlimited->limited, because
3654 * in that case we have no record of how much is already in use.
3656 if (config
.max_blocks
&& !sbinfo
->max_blocks
)
3658 if (config
.max_inodes
&& !sbinfo
->max_inodes
)
3662 sbinfo
->huge
= config
.huge
;
3663 sbinfo
->max_blocks
= config
.max_blocks
;
3664 sbinfo
->max_inodes
= config
.max_inodes
;
3665 sbinfo
->free_inodes
= config
.max_inodes
- inodes
;
3668 * Preserve previous mempolicy unless mpol remount option was specified.
3671 mpol_put(sbinfo
->mpol
);
3672 sbinfo
->mpol
= config
.mpol
; /* transfers initial ref */
3675 spin_unlock(&sbinfo
->stat_lock
);
3679 static int shmem_show_options(struct seq_file
*seq
, struct dentry
*root
)
3681 struct shmem_sb_info
*sbinfo
= SHMEM_SB(root
->d_sb
);
3683 if (sbinfo
->max_blocks
!= shmem_default_max_blocks())
3684 seq_printf(seq
, ",size=%luk",
3685 sbinfo
->max_blocks
<< (PAGE_SHIFT
- 10));
3686 if (sbinfo
->max_inodes
!= shmem_default_max_inodes())
3687 seq_printf(seq
, ",nr_inodes=%d", sbinfo
->max_inodes
);
3688 if (sbinfo
->mode
!= (S_IRWXUGO
| S_ISVTX
))
3689 seq_printf(seq
, ",mode=%03ho", sbinfo
->mode
);
3690 if (!uid_eq(sbinfo
->uid
, GLOBAL_ROOT_UID
))
3691 seq_printf(seq
, ",uid=%u",
3692 from_kuid_munged(&init_user_ns
, sbinfo
->uid
));
3693 if (!gid_eq(sbinfo
->gid
, GLOBAL_ROOT_GID
))
3694 seq_printf(seq
, ",gid=%u",
3695 from_kgid_munged(&init_user_ns
, sbinfo
->gid
));
3696 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3697 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3699 seq_printf(seq
, ",huge=%s", shmem_format_huge(sbinfo
->huge
));
3701 shmem_show_mpol(seq
, sbinfo
->mpol
);
3705 #define MFD_NAME_PREFIX "memfd:"
3706 #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
3707 #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
3709 #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_HUGETLB)
3711 SYSCALL_DEFINE2(memfd_create
,
3712 const char __user
*, uname
,
3713 unsigned int, flags
)
3715 struct shmem_inode_info
*info
;
3721 if (!(flags
& MFD_HUGETLB
)) {
3722 if (flags
& ~(unsigned int)MFD_ALL_FLAGS
)
3725 /* Sealing not supported in hugetlbfs (MFD_HUGETLB) */
3726 if (flags
& MFD_ALLOW_SEALING
)
3728 /* Allow huge page size encoding in flags. */
3729 if (flags
& ~(unsigned int)(MFD_ALL_FLAGS
|
3730 (MFD_HUGE_MASK
<< MFD_HUGE_SHIFT
)))
3734 /* length includes terminating zero */
3735 len
= strnlen_user(uname
, MFD_NAME_MAX_LEN
+ 1);
3738 if (len
> MFD_NAME_MAX_LEN
+ 1)
3741 name
= kmalloc(len
+ MFD_NAME_PREFIX_LEN
, GFP_KERNEL
);
3745 strcpy(name
, MFD_NAME_PREFIX
);
3746 if (copy_from_user(&name
[MFD_NAME_PREFIX_LEN
], uname
, len
)) {
3751 /* terminating-zero may have changed after strnlen_user() returned */
3752 if (name
[len
+ MFD_NAME_PREFIX_LEN
- 1]) {
3757 fd
= get_unused_fd_flags((flags
& MFD_CLOEXEC
) ? O_CLOEXEC
: 0);
3763 if (flags
& MFD_HUGETLB
) {
3764 struct user_struct
*user
= NULL
;
3766 file
= hugetlb_file_setup(name
, 0, VM_NORESERVE
, &user
,
3767 HUGETLB_ANONHUGE_INODE
,
3768 (flags
>> MFD_HUGE_SHIFT
) &
3771 file
= shmem_file_setup(name
, 0, VM_NORESERVE
);
3773 error
= PTR_ERR(file
);
3776 file
->f_mode
|= FMODE_LSEEK
| FMODE_PREAD
| FMODE_PWRITE
;
3777 file
->f_flags
|= O_RDWR
| O_LARGEFILE
;
3779 if (flags
& MFD_ALLOW_SEALING
) {
3781 * flags check at beginning of function ensures
3782 * this is not a hugetlbfs (MFD_HUGETLB) file.
3784 info
= SHMEM_I(file_inode(file
));
3785 info
->seals
&= ~F_SEAL_SEAL
;
3788 fd_install(fd
, file
);
3799 #endif /* CONFIG_TMPFS */
3801 static void shmem_put_super(struct super_block
*sb
)
3803 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
3805 if (!sbinfo
->idr_nouse
)
3806 idr_destroy(&sbinfo
->idr
);
3807 percpu_counter_destroy(&sbinfo
->used_blocks
);
3808 mpol_put(sbinfo
->mpol
);
3810 sb
->s_fs_info
= NULL
;
3813 int shmem_fill_super(struct super_block
*sb
, void *data
, int silent
)
3815 struct inode
*inode
;
3816 struct shmem_sb_info
*sbinfo
;
3819 /* Round up to L1_CACHE_BYTES to resist false sharing */
3820 sbinfo
= kzalloc(max((int)sizeof(struct shmem_sb_info
),
3821 L1_CACHE_BYTES
), GFP_KERNEL
);
3825 mutex_init(&sbinfo
->idr_lock
);
3826 idr_init(&sbinfo
->idr
);
3827 sbinfo
->mode
= S_IRWXUGO
| S_ISVTX
;
3828 sbinfo
->uid
= current_fsuid();
3829 sbinfo
->gid
= current_fsgid();
3830 sb
->s_fs_info
= sbinfo
;
3834 * Per default we only allow half of the physical ram per
3835 * tmpfs instance, limiting inodes to one per page of lowmem;
3836 * but the internal instance is left unlimited.
3838 if (!(sb
->s_flags
& SB_KERNMOUNT
)) {
3839 sbinfo
->max_blocks
= shmem_default_max_blocks();
3840 sbinfo
->max_inodes
= shmem_default_max_inodes();
3841 if (shmem_parse_options(data
, sbinfo
, false)) {
3846 sb
->s_flags
|= SB_NOUSER
;
3848 sb
->s_export_op
= &shmem_export_ops
;
3849 sb
->s_flags
|= SB_NOSEC
;
3851 sb
->s_flags
|= SB_NOUSER
;
3854 spin_lock_init(&sbinfo
->stat_lock
);
3855 if (percpu_counter_init(&sbinfo
->used_blocks
, 0, GFP_KERNEL
))
3857 sbinfo
->free_inodes
= sbinfo
->max_inodes
;
3858 spin_lock_init(&sbinfo
->shrinklist_lock
);
3859 INIT_LIST_HEAD(&sbinfo
->shrinklist
);
3861 sb
->s_maxbytes
= MAX_LFS_FILESIZE
;
3862 sb
->s_blocksize
= PAGE_SIZE
;
3863 sb
->s_blocksize_bits
= PAGE_SHIFT
;
3864 sb
->s_magic
= TMPFS_MAGIC
;
3865 sb
->s_op
= &shmem_ops
;
3866 sb
->s_time_gran
= 1;
3867 #ifdef CONFIG_TMPFS_XATTR
3868 sb
->s_xattr
= shmem_xattr_handlers
;
3870 #ifdef CONFIG_TMPFS_POSIX_ACL
3871 sb
->s_flags
|= SB_POSIXACL
;
3873 uuid_gen(&sb
->s_uuid
);
3875 inode
= shmem_get_inode(sb
, NULL
, S_IFDIR
| sbinfo
->mode
, 0, VM_NORESERVE
);
3878 inode
->i_uid
= sbinfo
->uid
;
3879 inode
->i_gid
= sbinfo
->gid
;
3880 sb
->s_root
= d_make_root(inode
);
3886 shmem_put_super(sb
);
3890 static struct kmem_cache
*shmem_inode_cachep
;
3892 static struct inode
*shmem_alloc_inode(struct super_block
*sb
)
3894 struct shmem_inode_info
*info
;
3895 info
= kmem_cache_alloc(shmem_inode_cachep
, GFP_KERNEL
);
3898 return &info
->vfs_inode
;
3901 static void shmem_destroy_callback(struct rcu_head
*head
)
3903 struct inode
*inode
= container_of(head
, struct inode
, i_rcu
);
3904 if (S_ISLNK(inode
->i_mode
))
3905 kfree(inode
->i_link
);
3906 kmem_cache_free(shmem_inode_cachep
, SHMEM_I(inode
));
3909 static void shmem_destroy_inode(struct inode
*inode
)
3911 if (S_ISREG(inode
->i_mode
))
3912 mpol_free_shared_policy(&SHMEM_I(inode
)->policy
);
3913 call_rcu(&inode
->i_rcu
, shmem_destroy_callback
);
3916 static void shmem_init_inode(void *foo
)
3918 struct shmem_inode_info
*info
= foo
;
3919 inode_init_once(&info
->vfs_inode
);
3922 static void shmem_init_inodecache(void)
3924 shmem_inode_cachep
= kmem_cache_create("shmem_inode_cache",
3925 sizeof(struct shmem_inode_info
),
3926 0, SLAB_PANIC
|SLAB_ACCOUNT
, shmem_init_inode
);
3929 static void shmem_destroy_inodecache(void)
3931 kmem_cache_destroy(shmem_inode_cachep
);
3934 static __init
void shmem_no_idr(struct super_block
*sb
)
3936 struct shmem_sb_info
*sbinfo
;
3938 sbinfo
= SHMEM_SB(sb
);
3939 sbinfo
->idr_nouse
= true;
3940 idr_destroy(&sbinfo
->idr
);
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 shmem_init_inodecache();
4061 error
= register_filesystem(&shmem_fs_type
);
4063 pr_err("Could not register tmpfs\n");
4067 shm_mnt
= kern_mount(&shmem_fs_type
);
4068 if (IS_ERR(shm_mnt
)) {
4069 error
= PTR_ERR(shm_mnt
);
4070 pr_err("Could not kern_mount tmpfs\n");
4073 shmem_no_idr(shm_mnt
->mnt_sb
);
4075 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
4076 if (has_transparent_hugepage() && shmem_huge
> SHMEM_HUGE_DENY
)
4077 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
4079 shmem_huge
= 0; /* just in case it was patched */
4084 unregister_filesystem(&shmem_fs_type
);
4086 shmem_destroy_inodecache();
4087 shm_mnt
= ERR_PTR(error
);
4091 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
4092 static ssize_t
shmem_enabled_show(struct kobject
*kobj
,
4093 struct kobj_attribute
*attr
, char *buf
)
4097 SHMEM_HUGE_WITHIN_SIZE
,
4105 for (i
= 0, count
= 0; i
< ARRAY_SIZE(values
); i
++) {
4106 const char *fmt
= shmem_huge
== values
[i
] ? "[%s] " : "%s ";
4108 count
+= sprintf(buf
+ count
, fmt
,
4109 shmem_format_huge(values
[i
]));
4111 buf
[count
- 1] = '\n';
4115 static ssize_t
shmem_enabled_store(struct kobject
*kobj
,
4116 struct kobj_attribute
*attr
, const char *buf
, size_t count
)
4121 if (count
+ 1 > sizeof(tmp
))
4123 memcpy(tmp
, buf
, count
);
4125 if (count
&& tmp
[count
- 1] == '\n')
4126 tmp
[count
- 1] = '\0';
4128 huge
= shmem_parse_huge(tmp
);
4129 if (huge
== -EINVAL
)
4131 if (!has_transparent_hugepage() &&
4132 huge
!= SHMEM_HUGE_NEVER
&& huge
!= SHMEM_HUGE_DENY
)
4136 if (shmem_huge
> SHMEM_HUGE_DENY
)
4137 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
4141 struct kobj_attribute shmem_enabled_attr
=
4142 __ATTR(shmem_enabled
, 0644, shmem_enabled_show
, shmem_enabled_store
);
4143 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
4145 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
4146 bool shmem_huge_enabled(struct vm_area_struct
*vma
)
4148 struct inode
*inode
= file_inode(vma
->vm_file
);
4149 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
4153 if (shmem_huge
== SHMEM_HUGE_FORCE
)
4155 if (shmem_huge
== SHMEM_HUGE_DENY
)
4157 switch (sbinfo
->huge
) {
4158 case SHMEM_HUGE_NEVER
:
4160 case SHMEM_HUGE_ALWAYS
:
4162 case SHMEM_HUGE_WITHIN_SIZE
:
4163 off
= round_up(vma
->vm_pgoff
, HPAGE_PMD_NR
);
4164 i_size
= round_up(i_size_read(inode
), PAGE_SIZE
);
4165 if (i_size
>= HPAGE_PMD_SIZE
&&
4166 i_size
>> PAGE_SHIFT
>= off
)
4169 case SHMEM_HUGE_ADVISE
:
4170 /* TODO: implement fadvise() hints */
4171 return (vma
->vm_flags
& VM_HUGEPAGE
);
4177 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
4179 #else /* !CONFIG_SHMEM */
4182 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
4184 * This is intended for small system where the benefits of the full
4185 * shmem code (swap-backed and resource-limited) are outweighed by
4186 * their complexity. On systems without swap this code should be
4187 * effectively equivalent, but much lighter weight.
4190 static struct file_system_type shmem_fs_type
= {
4192 .mount
= ramfs_mount
,
4193 .kill_sb
= kill_litter_super
,
4194 .fs_flags
= FS_USERNS_MOUNT
,
4197 int __init
shmem_init(void)
4199 BUG_ON(register_filesystem(&shmem_fs_type
) != 0);
4201 shm_mnt
= kern_mount(&shmem_fs_type
);
4202 BUG_ON(IS_ERR(shm_mnt
));
4207 int shmem_unuse(swp_entry_t swap
, struct page
*page
)
4212 int shmem_lock(struct file
*file
, int lock
, struct user_struct
*user
)
4217 void shmem_unlock_mapping(struct address_space
*mapping
)
4222 unsigned long shmem_get_unmapped_area(struct file
*file
,
4223 unsigned long addr
, unsigned long len
,
4224 unsigned long pgoff
, unsigned long flags
)
4226 return current
->mm
->get_unmapped_area(file
, addr
, len
, pgoff
, flags
);
4230 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
4232 truncate_inode_pages_range(inode
->i_mapping
, lstart
, lend
);
4234 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
4236 #define shmem_vm_ops generic_file_vm_ops
4237 #define shmem_file_operations ramfs_file_operations
4238 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
4239 #define shmem_acct_size(flags, size) 0
4240 #define shmem_unacct_size(flags, size) do {} while (0)
4242 #endif /* CONFIG_SHMEM */
4246 static const struct dentry_operations anon_ops
= {
4247 .d_dname
= simple_dname
4250 static struct file
*__shmem_file_setup(struct vfsmount
*mnt
, const char *name
, loff_t size
,
4251 unsigned long flags
, unsigned int i_flags
)
4254 struct inode
*inode
;
4256 struct super_block
*sb
;
4260 return ERR_CAST(mnt
);
4262 if (size
< 0 || size
> MAX_LFS_FILESIZE
)
4263 return ERR_PTR(-EINVAL
);
4265 if (shmem_acct_size(flags
, size
))
4266 return ERR_PTR(-ENOMEM
);
4268 res
= ERR_PTR(-ENOMEM
);
4270 this.len
= strlen(name
);
4271 this.hash
= 0; /* will go */
4273 path
.mnt
= mntget(mnt
);
4274 path
.dentry
= d_alloc_pseudo(sb
, &this);
4277 d_set_d_op(path
.dentry
, &anon_ops
);
4279 res
= ERR_PTR(-ENOSPC
);
4280 inode
= shmem_get_inode(sb
, NULL
, S_IFREG
| S_IRWXUGO
, 0, flags
);
4284 inode
->i_flags
|= i_flags
;
4285 d_instantiate(path
.dentry
, inode
);
4286 inode
->i_size
= size
;
4287 clear_nlink(inode
); /* It is unlinked */
4288 res
= ERR_PTR(ramfs_nommu_expand_for_mapping(inode
, size
));
4292 res
= alloc_file(&path
, FMODE_WRITE
| FMODE_READ
,
4293 &shmem_file_operations
);
4300 shmem_unacct_size(flags
, size
);
4307 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
4308 * kernel internal. There will be NO LSM permission checks against the
4309 * underlying inode. So users of this interface must do LSM checks at a
4310 * higher layer. The users are the big_key and shm implementations. LSM
4311 * checks are provided at the key or shm level rather than the inode.
4312 * @name: name for dentry (to be seen in /proc/<pid>/maps
4313 * @size: size to be set for the file
4314 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4316 struct file
*shmem_kernel_file_setup(const char *name
, loff_t size
, unsigned long flags
)
4318 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, S_PRIVATE
);
4322 * shmem_file_setup - get an unlinked file living in tmpfs
4323 * @name: name for dentry (to be seen in /proc/<pid>/maps
4324 * @size: size to be set for the file
4325 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4327 struct file
*shmem_file_setup(const char *name
, loff_t size
, unsigned long flags
)
4329 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, 0);
4331 EXPORT_SYMBOL_GPL(shmem_file_setup
);
4334 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
4335 * @mnt: the tmpfs mount where the file will be created
4336 * @name: name for dentry (to be seen in /proc/<pid>/maps
4337 * @size: size to be set for the file
4338 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
4340 struct file
*shmem_file_setup_with_mnt(struct vfsmount
*mnt
, const char *name
,
4341 loff_t size
, unsigned long flags
)
4343 return __shmem_file_setup(mnt
, name
, size
, flags
, 0);
4345 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt
);
4348 * shmem_zero_setup - setup a shared anonymous mapping
4349 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
4351 int shmem_zero_setup(struct vm_area_struct
*vma
)
4354 loff_t size
= vma
->vm_end
- vma
->vm_start
;
4357 * Cloning a new file under mmap_sem leads to a lock ordering conflict
4358 * between XFS directory reading and selinux: since this file is only
4359 * accessible to the user through its mapping, use S_PRIVATE flag to
4360 * bypass file security, in the same way as shmem_kernel_file_setup().
4362 file
= shmem_kernel_file_setup("dev/zero", size
, vma
->vm_flags
);
4364 return PTR_ERR(file
);
4368 vma
->vm_file
= file
;
4369 vma
->vm_ops
= &shmem_vm_ops
;
4371 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE
) &&
4372 ((vma
->vm_start
+ ~HPAGE_PMD_MASK
) & HPAGE_PMD_MASK
) <
4373 (vma
->vm_end
& HPAGE_PMD_MASK
)) {
4374 khugepaged_enter(vma
, vma
->vm_flags
);
4381 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4382 * @mapping: the page's address_space
4383 * @index: the page index
4384 * @gfp: the page allocator flags to use if allocating
4386 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4387 * with any new page allocations done using the specified allocation flags.
4388 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4389 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4390 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4392 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4393 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4395 struct page
*shmem_read_mapping_page_gfp(struct address_space
*mapping
,
4396 pgoff_t index
, gfp_t gfp
)
4399 struct inode
*inode
= mapping
->host
;
4403 BUG_ON(mapping
->a_ops
!= &shmem_aops
);
4404 error
= shmem_getpage_gfp(inode
, index
, &page
, SGP_CACHE
,
4405 gfp
, NULL
, NULL
, NULL
);
4407 page
= ERR_PTR(error
);
4413 * The tiny !SHMEM case uses ramfs without swap
4415 return read_cache_page_gfp(mapping
, index
, gfp
);
4418 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp
);