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>
31 #include <linux/fileattr.h>
33 #include <linux/random.h>
34 #include <linux/sched/signal.h>
35 #include <linux/export.h>
36 #include <linux/shmem_fs.h>
37 #include <linux/swap.h>
38 #include <linux/uio.h>
39 #include <linux/hugetlb.h>
40 #include <linux/fs_parser.h>
41 #include <linux/swapfile.h>
42 #include <linux/iversion.h>
43 #include <linux/unicode.h>
46 static struct vfsmount
*shm_mnt __ro_after_init
;
50 * This virtual memory filesystem is heavily based on the ramfs. It
51 * extends ramfs by the ability to use swap and honor resource limits
52 * which makes it a completely usable filesystem.
55 #include <linux/xattr.h>
56 #include <linux/exportfs.h>
57 #include <linux/posix_acl.h>
58 #include <linux/posix_acl_xattr.h>
59 #include <linux/mman.h>
60 #include <linux/string.h>
61 #include <linux/slab.h>
62 #include <linux/backing-dev.h>
63 #include <linux/writeback.h>
64 #include <linux/pagevec.h>
65 #include <linux/percpu_counter.h>
66 #include <linux/falloc.h>
67 #include <linux/splice.h>
68 #include <linux/security.h>
69 #include <linux/swapops.h>
70 #include <linux/mempolicy.h>
71 #include <linux/namei.h>
72 #include <linux/ctype.h>
73 #include <linux/migrate.h>
74 #include <linux/highmem.h>
75 #include <linux/seq_file.h>
76 #include <linux/magic.h>
77 #include <linux/syscalls.h>
78 #include <linux/fcntl.h>
79 #include <uapi/linux/memfd.h>
80 #include <linux/rmap.h>
81 #include <linux/uuid.h>
82 #include <linux/quotaops.h>
83 #include <linux/rcupdate_wait.h>
85 #include <linux/uaccess.h>
89 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
90 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
92 /* Pretend that each entry is of this size in directory's i_size */
93 #define BOGO_DIRENT_SIZE 20
95 /* Pretend that one inode + its dentry occupy this much memory */
96 #define BOGO_INODE_SIZE 1024
98 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
99 #define SHORT_SYMLINK_LEN 128
102 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
103 * inode->i_private (with i_rwsem making sure that it has only one user at
104 * a time): we would prefer not to enlarge the shmem inode just for that.
106 struct shmem_falloc
{
107 wait_queue_head_t
*waitq
; /* faults into hole wait for punch to end */
108 pgoff_t start
; /* start of range currently being fallocated */
109 pgoff_t next
; /* the next page offset to be fallocated */
110 pgoff_t nr_falloced
; /* how many new pages have been fallocated */
111 pgoff_t nr_unswapped
; /* how often writepage refused to swap out */
114 struct shmem_options
{
115 unsigned long long blocks
;
116 unsigned long long inodes
;
117 struct mempolicy
*mpol
;
125 unsigned short quota_types
;
126 struct shmem_quota_limits qlimits
;
127 #if IS_ENABLED(CONFIG_UNICODE)
128 struct unicode_map
*encoding
;
129 bool strict_encoding
;
131 #define SHMEM_SEEN_BLOCKS 1
132 #define SHMEM_SEEN_INODES 2
133 #define SHMEM_SEEN_HUGE 4
134 #define SHMEM_SEEN_INUMS 8
135 #define SHMEM_SEEN_NOSWAP 16
136 #define SHMEM_SEEN_QUOTA 32
139 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
140 static unsigned long huge_shmem_orders_always __read_mostly
;
141 static unsigned long huge_shmem_orders_madvise __read_mostly
;
142 static unsigned long huge_shmem_orders_inherit __read_mostly
;
143 static unsigned long huge_shmem_orders_within_size __read_mostly
;
144 static bool shmem_orders_configured __initdata
;
148 static unsigned long shmem_default_max_blocks(void)
150 return totalram_pages() / 2;
153 static unsigned long shmem_default_max_inodes(void)
155 unsigned long nr_pages
= totalram_pages();
157 return min3(nr_pages
- totalhigh_pages(), nr_pages
/ 2,
158 ULONG_MAX
/ BOGO_INODE_SIZE
);
162 static int shmem_swapin_folio(struct inode
*inode
, pgoff_t index
,
163 struct folio
**foliop
, enum sgp_type sgp
, gfp_t gfp
,
164 struct vm_area_struct
*vma
, vm_fault_t
*fault_type
);
166 static inline struct shmem_sb_info
*SHMEM_SB(struct super_block
*sb
)
168 return sb
->s_fs_info
;
172 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
173 * for shared memory and for shared anonymous (/dev/zero) mappings
174 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
175 * consistent with the pre-accounting of private mappings ...
177 static inline int shmem_acct_size(unsigned long flags
, loff_t size
)
179 return (flags
& VM_NORESERVE
) ?
180 0 : security_vm_enough_memory_mm(current
->mm
, VM_ACCT(size
));
183 static inline void shmem_unacct_size(unsigned long flags
, loff_t size
)
185 if (!(flags
& VM_NORESERVE
))
186 vm_unacct_memory(VM_ACCT(size
));
189 static inline int shmem_reacct_size(unsigned long flags
,
190 loff_t oldsize
, loff_t newsize
)
192 if (!(flags
& VM_NORESERVE
)) {
193 if (VM_ACCT(newsize
) > VM_ACCT(oldsize
))
194 return security_vm_enough_memory_mm(current
->mm
,
195 VM_ACCT(newsize
) - VM_ACCT(oldsize
));
196 else if (VM_ACCT(newsize
) < VM_ACCT(oldsize
))
197 vm_unacct_memory(VM_ACCT(oldsize
) - VM_ACCT(newsize
));
203 * ... whereas tmpfs objects are accounted incrementally as
204 * pages are allocated, in order to allow large sparse files.
205 * shmem_get_folio reports shmem_acct_blocks failure as -ENOSPC not -ENOMEM,
206 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
208 static inline int shmem_acct_blocks(unsigned long flags
, long pages
)
210 if (!(flags
& VM_NORESERVE
))
213 return security_vm_enough_memory_mm(current
->mm
,
214 pages
* VM_ACCT(PAGE_SIZE
));
217 static inline void shmem_unacct_blocks(unsigned long flags
, long pages
)
219 if (flags
& VM_NORESERVE
)
220 vm_unacct_memory(pages
* VM_ACCT(PAGE_SIZE
));
223 static int shmem_inode_acct_blocks(struct inode
*inode
, long pages
)
225 struct shmem_inode_info
*info
= SHMEM_I(inode
);
226 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
229 if (shmem_acct_blocks(info
->flags
, pages
))
232 might_sleep(); /* when quotas */
233 if (sbinfo
->max_blocks
) {
234 if (!percpu_counter_limited_add(&sbinfo
->used_blocks
,
235 sbinfo
->max_blocks
, pages
))
238 err
= dquot_alloc_block_nodirty(inode
, pages
);
240 percpu_counter_sub(&sbinfo
->used_blocks
, pages
);
244 err
= dquot_alloc_block_nodirty(inode
, pages
);
252 shmem_unacct_blocks(info
->flags
, pages
);
256 static void shmem_inode_unacct_blocks(struct inode
*inode
, long pages
)
258 struct shmem_inode_info
*info
= SHMEM_I(inode
);
259 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
261 might_sleep(); /* when quotas */
262 dquot_free_block_nodirty(inode
, pages
);
264 if (sbinfo
->max_blocks
)
265 percpu_counter_sub(&sbinfo
->used_blocks
, pages
);
266 shmem_unacct_blocks(info
->flags
, pages
);
269 static const struct super_operations shmem_ops
;
270 static const struct address_space_operations shmem_aops
;
271 static const struct file_operations shmem_file_operations
;
272 static const struct inode_operations shmem_inode_operations
;
273 static const struct inode_operations shmem_dir_inode_operations
;
274 static const struct inode_operations shmem_special_inode_operations
;
275 static const struct vm_operations_struct shmem_vm_ops
;
276 static const struct vm_operations_struct shmem_anon_vm_ops
;
277 static struct file_system_type shmem_fs_type
;
279 bool shmem_mapping(struct address_space
*mapping
)
281 return mapping
->a_ops
== &shmem_aops
;
283 EXPORT_SYMBOL_GPL(shmem_mapping
);
285 bool vma_is_anon_shmem(struct vm_area_struct
*vma
)
287 return vma
->vm_ops
== &shmem_anon_vm_ops
;
290 bool vma_is_shmem(struct vm_area_struct
*vma
)
292 return vma_is_anon_shmem(vma
) || vma
->vm_ops
== &shmem_vm_ops
;
295 static LIST_HEAD(shmem_swaplist
);
296 static DEFINE_MUTEX(shmem_swaplist_mutex
);
298 #ifdef CONFIG_TMPFS_QUOTA
300 static int shmem_enable_quotas(struct super_block
*sb
,
301 unsigned short quota_types
)
305 sb_dqopt(sb
)->flags
|= DQUOT_QUOTA_SYS_FILE
| DQUOT_NOLIST_DIRTY
;
306 for (type
= 0; type
< SHMEM_MAXQUOTAS
; type
++) {
307 if (!(quota_types
& (1 << type
)))
309 err
= dquot_load_quota_sb(sb
, type
, QFMT_SHMEM
,
310 DQUOT_USAGE_ENABLED
|
311 DQUOT_LIMITS_ENABLED
);
318 pr_warn("tmpfs: failed to enable quota tracking (type=%d, err=%d)\n",
320 for (type
--; type
>= 0; type
--)
321 dquot_quota_off(sb
, type
);
325 static void shmem_disable_quotas(struct super_block
*sb
)
329 for (type
= 0; type
< SHMEM_MAXQUOTAS
; type
++)
330 dquot_quota_off(sb
, type
);
333 static struct dquot __rcu
**shmem_get_dquots(struct inode
*inode
)
335 return SHMEM_I(inode
)->i_dquot
;
337 #endif /* CONFIG_TMPFS_QUOTA */
340 * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
341 * produces a novel ino for the newly allocated inode.
343 * It may also be called when making a hard link to permit the space needed by
344 * each dentry. However, in that case, no new inode number is needed since that
345 * internally draws from another pool of inode numbers (currently global
346 * get_next_ino()). This case is indicated by passing NULL as inop.
348 #define SHMEM_INO_BATCH 1024
349 static int shmem_reserve_inode(struct super_block
*sb
, ino_t
*inop
)
351 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
354 if (!(sb
->s_flags
& SB_KERNMOUNT
)) {
355 raw_spin_lock(&sbinfo
->stat_lock
);
356 if (sbinfo
->max_inodes
) {
357 if (sbinfo
->free_ispace
< BOGO_INODE_SIZE
) {
358 raw_spin_unlock(&sbinfo
->stat_lock
);
361 sbinfo
->free_ispace
-= BOGO_INODE_SIZE
;
364 ino
= sbinfo
->next_ino
++;
365 if (unlikely(is_zero_ino(ino
)))
366 ino
= sbinfo
->next_ino
++;
367 if (unlikely(!sbinfo
->full_inums
&&
370 * Emulate get_next_ino uint wraparound for
373 if (IS_ENABLED(CONFIG_64BIT
))
374 pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
375 __func__
, MINOR(sb
->s_dev
));
376 sbinfo
->next_ino
= 1;
377 ino
= sbinfo
->next_ino
++;
381 raw_spin_unlock(&sbinfo
->stat_lock
);
384 * __shmem_file_setup, one of our callers, is lock-free: it
385 * doesn't hold stat_lock in shmem_reserve_inode since
386 * max_inodes is always 0, and is called from potentially
387 * unknown contexts. As such, use a per-cpu batched allocator
388 * which doesn't require the per-sb stat_lock unless we are at
389 * the batch boundary.
391 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
392 * shmem mounts are not exposed to userspace, so we don't need
393 * to worry about things like glibc compatibility.
397 next_ino
= per_cpu_ptr(sbinfo
->ino_batch
, get_cpu());
399 if (unlikely(ino
% SHMEM_INO_BATCH
== 0)) {
400 raw_spin_lock(&sbinfo
->stat_lock
);
401 ino
= sbinfo
->next_ino
;
402 sbinfo
->next_ino
+= SHMEM_INO_BATCH
;
403 raw_spin_unlock(&sbinfo
->stat_lock
);
404 if (unlikely(is_zero_ino(ino
)))
415 static void shmem_free_inode(struct super_block
*sb
, size_t freed_ispace
)
417 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
418 if (sbinfo
->max_inodes
) {
419 raw_spin_lock(&sbinfo
->stat_lock
);
420 sbinfo
->free_ispace
+= BOGO_INODE_SIZE
+ freed_ispace
;
421 raw_spin_unlock(&sbinfo
->stat_lock
);
426 * shmem_recalc_inode - recalculate the block usage of an inode
427 * @inode: inode to recalc
428 * @alloced: the change in number of pages allocated to inode
429 * @swapped: the change in number of pages swapped from inode
431 * We have to calculate the free blocks since the mm can drop
432 * undirtied hole pages behind our back.
434 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
435 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
437 static void shmem_recalc_inode(struct inode
*inode
, long alloced
, long swapped
)
439 struct shmem_inode_info
*info
= SHMEM_I(inode
);
442 spin_lock(&info
->lock
);
443 info
->alloced
+= alloced
;
444 info
->swapped
+= swapped
;
445 freed
= info
->alloced
- info
->swapped
-
446 READ_ONCE(inode
->i_mapping
->nrpages
);
448 * Special case: whereas normally shmem_recalc_inode() is called
449 * after i_mapping->nrpages has already been adjusted (up or down),
450 * shmem_writepage() has to raise swapped before nrpages is lowered -
451 * to stop a racing shmem_recalc_inode() from thinking that a page has
452 * been freed. Compensate here, to avoid the need for a followup call.
457 info
->alloced
-= freed
;
458 spin_unlock(&info
->lock
);
460 /* The quota case may block */
462 shmem_inode_unacct_blocks(inode
, freed
);
465 bool shmem_charge(struct inode
*inode
, long pages
)
467 struct address_space
*mapping
= inode
->i_mapping
;
469 if (shmem_inode_acct_blocks(inode
, pages
))
472 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
473 xa_lock_irq(&mapping
->i_pages
);
474 mapping
->nrpages
+= pages
;
475 xa_unlock_irq(&mapping
->i_pages
);
477 shmem_recalc_inode(inode
, pages
, 0);
481 void shmem_uncharge(struct inode
*inode
, long pages
)
483 /* pages argument is currently unused: keep it to help debugging */
484 /* nrpages adjustment done by __filemap_remove_folio() or caller */
486 shmem_recalc_inode(inode
, 0, 0);
490 * Replace item expected in xarray by a new item, while holding xa_lock.
492 static int shmem_replace_entry(struct address_space
*mapping
,
493 pgoff_t index
, void *expected
, void *replacement
)
495 XA_STATE(xas
, &mapping
->i_pages
, index
);
498 VM_BUG_ON(!expected
);
499 VM_BUG_ON(!replacement
);
500 item
= xas_load(&xas
);
501 if (item
!= expected
)
503 xas_store(&xas
, replacement
);
508 * Sometimes, before we decide whether to proceed or to fail, we must check
509 * that an entry was not already brought back from swap by a racing thread.
511 * Checking folio is not enough: by the time a swapcache folio is locked, it
512 * might be reused, and again be swapcache, using the same swap as before.
514 static bool shmem_confirm_swap(struct address_space
*mapping
,
515 pgoff_t index
, swp_entry_t swap
)
517 return xa_load(&mapping
->i_pages
, index
) == swp_to_radix_entry(swap
);
521 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
524 * disables huge pages for the mount;
526 * enables huge pages for the mount;
527 * SHMEM_HUGE_WITHIN_SIZE:
528 * only allocate huge pages if the page will be fully within i_size,
529 * also respect fadvise()/madvise() hints;
531 * only allocate huge pages if requested with fadvise()/madvise();
534 #define SHMEM_HUGE_NEVER 0
535 #define SHMEM_HUGE_ALWAYS 1
536 #define SHMEM_HUGE_WITHIN_SIZE 2
537 #define SHMEM_HUGE_ADVISE 3
541 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
544 * disables huge on shm_mnt and all mounts, for emergency use;
546 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
549 #define SHMEM_HUGE_DENY (-1)
550 #define SHMEM_HUGE_FORCE (-2)
552 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
553 /* ifdef here to avoid bloating shmem.o when not necessary */
555 static int shmem_huge __read_mostly
= SHMEM_HUGE_NEVER
;
557 static bool shmem_huge_global_enabled(struct inode
*inode
, pgoff_t index
,
558 loff_t write_end
, bool shmem_huge_force
,
559 unsigned long vm_flags
)
563 if (HPAGE_PMD_ORDER
> MAX_PAGECACHE_ORDER
)
565 if (!S_ISREG(inode
->i_mode
))
567 if (shmem_huge
== SHMEM_HUGE_DENY
)
569 if (shmem_huge_force
|| shmem_huge
== SHMEM_HUGE_FORCE
)
572 switch (SHMEM_SB(inode
->i_sb
)->huge
) {
573 case SHMEM_HUGE_ALWAYS
:
575 case SHMEM_HUGE_WITHIN_SIZE
:
576 index
= round_up(index
+ 1, HPAGE_PMD_NR
);
577 i_size
= max(write_end
, i_size_read(inode
));
578 i_size
= round_up(i_size
, PAGE_SIZE
);
579 if (i_size
>> PAGE_SHIFT
>= index
)
582 case SHMEM_HUGE_ADVISE
:
583 if (vm_flags
& VM_HUGEPAGE
)
591 static int shmem_parse_huge(const char *str
)
598 if (!strcmp(str
, "never"))
599 huge
= SHMEM_HUGE_NEVER
;
600 else if (!strcmp(str
, "always"))
601 huge
= SHMEM_HUGE_ALWAYS
;
602 else if (!strcmp(str
, "within_size"))
603 huge
= SHMEM_HUGE_WITHIN_SIZE
;
604 else if (!strcmp(str
, "advise"))
605 huge
= SHMEM_HUGE_ADVISE
;
606 else if (!strcmp(str
, "deny"))
607 huge
= SHMEM_HUGE_DENY
;
608 else if (!strcmp(str
, "force"))
609 huge
= SHMEM_HUGE_FORCE
;
613 if (!has_transparent_hugepage() &&
614 huge
!= SHMEM_HUGE_NEVER
&& huge
!= SHMEM_HUGE_DENY
)
617 /* Do not override huge allocation policy with non-PMD sized mTHP */
618 if (huge
== SHMEM_HUGE_FORCE
&&
619 huge_shmem_orders_inherit
!= BIT(HPAGE_PMD_ORDER
))
625 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
626 static const char *shmem_format_huge(int huge
)
629 case SHMEM_HUGE_NEVER
:
631 case SHMEM_HUGE_ALWAYS
:
633 case SHMEM_HUGE_WITHIN_SIZE
:
634 return "within_size";
635 case SHMEM_HUGE_ADVISE
:
637 case SHMEM_HUGE_DENY
:
639 case SHMEM_HUGE_FORCE
:
648 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info
*sbinfo
,
649 struct shrink_control
*sc
, unsigned long nr_to_free
)
651 LIST_HEAD(list
), *pos
, *next
;
653 struct shmem_inode_info
*info
;
655 unsigned long batch
= sc
? sc
->nr_to_scan
: 128;
656 unsigned long split
= 0, freed
= 0;
658 if (list_empty(&sbinfo
->shrinklist
))
661 spin_lock(&sbinfo
->shrinklist_lock
);
662 list_for_each_safe(pos
, next
, &sbinfo
->shrinklist
) {
663 info
= list_entry(pos
, struct shmem_inode_info
, shrinklist
);
666 inode
= igrab(&info
->vfs_inode
);
668 /* inode is about to be evicted */
670 list_del_init(&info
->shrinklist
);
674 list_move(&info
->shrinklist
, &list
);
676 sbinfo
->shrinklist_len
--;
680 spin_unlock(&sbinfo
->shrinklist_lock
);
682 list_for_each_safe(pos
, next
, &list
) {
687 info
= list_entry(pos
, struct shmem_inode_info
, shrinklist
);
688 inode
= &info
->vfs_inode
;
690 if (nr_to_free
&& freed
>= nr_to_free
)
693 i_size
= i_size_read(inode
);
694 folio
= filemap_get_entry(inode
->i_mapping
, i_size
/ PAGE_SIZE
);
695 if (!folio
|| xa_is_value(folio
))
698 /* No large folio at the end of the file: nothing to split */
699 if (!folio_test_large(folio
)) {
704 /* Check if there is anything to gain from splitting */
705 next
= folio_next_index(folio
);
706 end
= shmem_fallocend(inode
, DIV_ROUND_UP(i_size
, PAGE_SIZE
));
707 if (end
<= folio
->index
|| end
>= next
) {
713 * Move the inode on the list back to shrinklist if we failed
714 * to lock the page at this time.
716 * Waiting for the lock may lead to deadlock in the
719 if (!folio_trylock(folio
)) {
724 ret
= split_folio(folio
);
728 /* If split failed move the inode on the list back to shrinklist */
735 list_del_init(&info
->shrinklist
);
739 * Make sure the inode is either on the global list or deleted
740 * from any local list before iput() since it could be deleted
741 * in another thread once we put the inode (then the local list
744 spin_lock(&sbinfo
->shrinklist_lock
);
745 list_move(&info
->shrinklist
, &sbinfo
->shrinklist
);
746 sbinfo
->shrinklist_len
++;
747 spin_unlock(&sbinfo
->shrinklist_lock
);
755 static long shmem_unused_huge_scan(struct super_block
*sb
,
756 struct shrink_control
*sc
)
758 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
760 if (!READ_ONCE(sbinfo
->shrinklist_len
))
763 return shmem_unused_huge_shrink(sbinfo
, sc
, 0);
766 static long shmem_unused_huge_count(struct super_block
*sb
,
767 struct shrink_control
*sc
)
769 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
770 return READ_ONCE(sbinfo
->shrinklist_len
);
772 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
774 #define shmem_huge SHMEM_HUGE_DENY
776 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info
*sbinfo
,
777 struct shrink_control
*sc
, unsigned long nr_to_free
)
782 static bool shmem_huge_global_enabled(struct inode
*inode
, pgoff_t index
,
783 loff_t write_end
, bool shmem_huge_force
,
784 unsigned long vm_flags
)
788 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
791 * Somewhat like filemap_add_folio, but error if expected item has gone.
793 static int shmem_add_to_page_cache(struct folio
*folio
,
794 struct address_space
*mapping
,
795 pgoff_t index
, void *expected
, gfp_t gfp
)
797 XA_STATE_ORDER(xas
, &mapping
->i_pages
, index
, folio_order(folio
));
798 long nr
= folio_nr_pages(folio
);
800 VM_BUG_ON_FOLIO(index
!= round_down(index
, nr
), folio
);
801 VM_BUG_ON_FOLIO(!folio_test_locked(folio
), folio
);
802 VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio
), folio
);
804 folio_ref_add(folio
, nr
);
805 folio
->mapping
= mapping
;
806 folio
->index
= index
;
808 gfp
&= GFP_RECLAIM_MASK
;
809 folio_throttle_swaprate(folio
, gfp
);
813 if (expected
!= xas_find_conflict(&xas
)) {
814 xas_set_err(&xas
, -EEXIST
);
817 if (expected
&& xas_find_conflict(&xas
)) {
818 xas_set_err(&xas
, -EEXIST
);
821 xas_store(&xas
, folio
);
824 if (folio_test_pmd_mappable(folio
))
825 __lruvec_stat_mod_folio(folio
, NR_SHMEM_THPS
, nr
);
826 __lruvec_stat_mod_folio(folio
, NR_FILE_PAGES
, nr
);
827 __lruvec_stat_mod_folio(folio
, NR_SHMEM
, nr
);
828 mapping
->nrpages
+= nr
;
830 xas_unlock_irq(&xas
);
831 } while (xas_nomem(&xas
, gfp
));
833 if (xas_error(&xas
)) {
834 folio
->mapping
= NULL
;
835 folio_ref_sub(folio
, nr
);
836 return xas_error(&xas
);
843 * Somewhat like filemap_remove_folio, but substitutes swap for @folio.
845 static void shmem_delete_from_page_cache(struct folio
*folio
, void *radswap
)
847 struct address_space
*mapping
= folio
->mapping
;
848 long nr
= folio_nr_pages(folio
);
851 xa_lock_irq(&mapping
->i_pages
);
852 error
= shmem_replace_entry(mapping
, folio
->index
, folio
, radswap
);
853 folio
->mapping
= NULL
;
854 mapping
->nrpages
-= nr
;
855 __lruvec_stat_mod_folio(folio
, NR_FILE_PAGES
, -nr
);
856 __lruvec_stat_mod_folio(folio
, NR_SHMEM
, -nr
);
857 xa_unlock_irq(&mapping
->i_pages
);
858 folio_put_refs(folio
, nr
);
863 * Remove swap entry from page cache, free the swap and its page cache. Returns
864 * the number of pages being freed. 0 means entry not found in XArray (0 pages
867 static long shmem_free_swap(struct address_space
*mapping
,
868 pgoff_t index
, void *radswap
)
870 int order
= xa_get_order(&mapping
->i_pages
, index
);
873 old
= xa_cmpxchg_irq(&mapping
->i_pages
, index
, radswap
, NULL
, 0);
876 free_swap_and_cache_nr(radix_to_swp_entry(radswap
), 1 << order
);
882 * Determine (in bytes) how many of the shmem object's pages mapped by the
883 * given offsets are swapped out.
885 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
886 * as long as the inode doesn't go away and racy results are not a problem.
888 unsigned long shmem_partial_swap_usage(struct address_space
*mapping
,
889 pgoff_t start
, pgoff_t end
)
891 XA_STATE(xas
, &mapping
->i_pages
, start
);
893 unsigned long swapped
= 0;
894 unsigned long max
= end
- 1;
897 xas_for_each(&xas
, page
, max
) {
898 if (xas_retry(&xas
, page
))
900 if (xa_is_value(page
))
901 swapped
+= 1 << xas_get_order(&xas
);
902 if (xas
.xa_index
== max
)
904 if (need_resched()) {
911 return swapped
<< PAGE_SHIFT
;
915 * Determine (in bytes) how many of the shmem object's pages mapped by the
916 * given vma is swapped out.
918 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
919 * as long as the inode doesn't go away and racy results are not a problem.
921 unsigned long shmem_swap_usage(struct vm_area_struct
*vma
)
923 struct inode
*inode
= file_inode(vma
->vm_file
);
924 struct shmem_inode_info
*info
= SHMEM_I(inode
);
925 struct address_space
*mapping
= inode
->i_mapping
;
926 unsigned long swapped
;
928 /* Be careful as we don't hold info->lock */
929 swapped
= READ_ONCE(info
->swapped
);
932 * The easier cases are when the shmem object has nothing in swap, or
933 * the vma maps it whole. Then we can simply use the stats that we
939 if (!vma
->vm_pgoff
&& vma
->vm_end
- vma
->vm_start
>= inode
->i_size
)
940 return swapped
<< PAGE_SHIFT
;
942 /* Here comes the more involved part */
943 return shmem_partial_swap_usage(mapping
, vma
->vm_pgoff
,
944 vma
->vm_pgoff
+ vma_pages(vma
));
948 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
950 void shmem_unlock_mapping(struct address_space
*mapping
)
952 struct folio_batch fbatch
;
955 folio_batch_init(&fbatch
);
957 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
959 while (!mapping_unevictable(mapping
) &&
960 filemap_get_folios(mapping
, &index
, ~0UL, &fbatch
)) {
961 check_move_unevictable_folios(&fbatch
);
962 folio_batch_release(&fbatch
);
967 static struct folio
*shmem_get_partial_folio(struct inode
*inode
, pgoff_t index
)
972 * At first avoid shmem_get_folio(,,,SGP_READ): that fails
973 * beyond i_size, and reports fallocated folios as holes.
975 folio
= filemap_get_entry(inode
->i_mapping
, index
);
978 if (!xa_is_value(folio
)) {
980 if (folio
->mapping
== inode
->i_mapping
)
982 /* The folio has been swapped out */
987 * But read a folio back from swap if any of it is within i_size
988 * (although in some cases this is just a waste of time).
991 shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
996 * Remove range of pages and swap entries from page cache, and free them.
997 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
999 static void shmem_undo_range(struct inode
*inode
, loff_t lstart
, loff_t lend
,
1002 struct address_space
*mapping
= inode
->i_mapping
;
1003 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1004 pgoff_t start
= (lstart
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
1005 pgoff_t end
= (lend
+ 1) >> PAGE_SHIFT
;
1006 struct folio_batch fbatch
;
1007 pgoff_t indices
[PAGEVEC_SIZE
];
1008 struct folio
*folio
;
1010 long nr_swaps_freed
= 0;
1015 end
= -1; /* unsigned, so actually very big */
1017 if (info
->fallocend
> start
&& info
->fallocend
<= end
&& !unfalloc
)
1018 info
->fallocend
= start
;
1020 folio_batch_init(&fbatch
);
1022 while (index
< end
&& find_lock_entries(mapping
, &index
, end
- 1,
1023 &fbatch
, indices
)) {
1024 for (i
= 0; i
< folio_batch_count(&fbatch
); i
++) {
1025 folio
= fbatch
.folios
[i
];
1027 if (xa_is_value(folio
)) {
1030 nr_swaps_freed
+= shmem_free_swap(mapping
,
1035 if (!unfalloc
|| !folio_test_uptodate(folio
))
1036 truncate_inode_folio(mapping
, folio
);
1037 folio_unlock(folio
);
1039 folio_batch_remove_exceptionals(&fbatch
);
1040 folio_batch_release(&fbatch
);
1045 * When undoing a failed fallocate, we want none of the partial folio
1046 * zeroing and splitting below, but shall want to truncate the whole
1047 * folio when !uptodate indicates that it was added by this fallocate,
1048 * even when [lstart, lend] covers only a part of the folio.
1053 same_folio
= (lstart
>> PAGE_SHIFT
) == (lend
>> PAGE_SHIFT
);
1054 folio
= shmem_get_partial_folio(inode
, lstart
>> PAGE_SHIFT
);
1056 same_folio
= lend
< folio_pos(folio
) + folio_size(folio
);
1057 folio_mark_dirty(folio
);
1058 if (!truncate_inode_partial_folio(folio
, lstart
, lend
)) {
1059 start
= folio_next_index(folio
);
1063 folio_unlock(folio
);
1069 folio
= shmem_get_partial_folio(inode
, lend
>> PAGE_SHIFT
);
1071 folio_mark_dirty(folio
);
1072 if (!truncate_inode_partial_folio(folio
, lstart
, lend
))
1074 folio_unlock(folio
);
1081 while (index
< end
) {
1084 if (!find_get_entries(mapping
, &index
, end
- 1, &fbatch
,
1086 /* If all gone or hole-punch or unfalloc, we're done */
1087 if (index
== start
|| end
!= -1)
1089 /* But if truncating, restart to make sure all gone */
1093 for (i
= 0; i
< folio_batch_count(&fbatch
); i
++) {
1094 folio
= fbatch
.folios
[i
];
1096 if (xa_is_value(folio
)) {
1101 swaps_freed
= shmem_free_swap(mapping
, indices
[i
], folio
);
1103 /* Swap was replaced by page: retry */
1107 nr_swaps_freed
+= swaps_freed
;
1113 if (!unfalloc
|| !folio_test_uptodate(folio
)) {
1114 if (folio_mapping(folio
) != mapping
) {
1115 /* Page was replaced by swap: retry */
1116 folio_unlock(folio
);
1120 VM_BUG_ON_FOLIO(folio_test_writeback(folio
),
1123 if (!folio_test_large(folio
)) {
1124 truncate_inode_folio(mapping
, folio
);
1125 } else if (truncate_inode_partial_folio(folio
, lstart
, lend
)) {
1127 * If we split a page, reset the loop so
1128 * that we pick up the new sub pages.
1129 * Otherwise the THP was entirely
1130 * dropped or the target range was
1131 * zeroed, so just continue the loop as
1134 if (!folio_test_large(folio
)) {
1135 folio_unlock(folio
);
1141 folio_unlock(folio
);
1143 folio_batch_remove_exceptionals(&fbatch
);
1144 folio_batch_release(&fbatch
);
1147 shmem_recalc_inode(inode
, 0, -nr_swaps_freed
);
1150 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
1152 shmem_undo_range(inode
, lstart
, lend
, false);
1153 inode_set_mtime_to_ts(inode
, inode_set_ctime_current(inode
));
1154 inode_inc_iversion(inode
);
1156 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
1158 static int shmem_getattr(struct mnt_idmap
*idmap
,
1159 const struct path
*path
, struct kstat
*stat
,
1160 u32 request_mask
, unsigned int query_flags
)
1162 struct inode
*inode
= path
->dentry
->d_inode
;
1163 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1165 if (info
->alloced
- info
->swapped
!= inode
->i_mapping
->nrpages
)
1166 shmem_recalc_inode(inode
, 0, 0);
1168 if (info
->fsflags
& FS_APPEND_FL
)
1169 stat
->attributes
|= STATX_ATTR_APPEND
;
1170 if (info
->fsflags
& FS_IMMUTABLE_FL
)
1171 stat
->attributes
|= STATX_ATTR_IMMUTABLE
;
1172 if (info
->fsflags
& FS_NODUMP_FL
)
1173 stat
->attributes
|= STATX_ATTR_NODUMP
;
1174 stat
->attributes_mask
|= (STATX_ATTR_APPEND
|
1175 STATX_ATTR_IMMUTABLE
|
1177 generic_fillattr(idmap
, request_mask
, inode
, stat
);
1179 if (shmem_huge_global_enabled(inode
, 0, 0, false, 0))
1180 stat
->blksize
= HPAGE_PMD_SIZE
;
1182 if (request_mask
& STATX_BTIME
) {
1183 stat
->result_mask
|= STATX_BTIME
;
1184 stat
->btime
.tv_sec
= info
->i_crtime
.tv_sec
;
1185 stat
->btime
.tv_nsec
= info
->i_crtime
.tv_nsec
;
1191 static int shmem_setattr(struct mnt_idmap
*idmap
,
1192 struct dentry
*dentry
, struct iattr
*attr
)
1194 struct inode
*inode
= d_inode(dentry
);
1195 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1197 bool update_mtime
= false;
1198 bool update_ctime
= true;
1200 error
= setattr_prepare(idmap
, dentry
, attr
);
1204 if ((info
->seals
& F_SEAL_EXEC
) && (attr
->ia_valid
& ATTR_MODE
)) {
1205 if ((inode
->i_mode
^ attr
->ia_mode
) & 0111) {
1210 if (S_ISREG(inode
->i_mode
) && (attr
->ia_valid
& ATTR_SIZE
)) {
1211 loff_t oldsize
= inode
->i_size
;
1212 loff_t newsize
= attr
->ia_size
;
1214 /* protected by i_rwsem */
1215 if ((newsize
< oldsize
&& (info
->seals
& F_SEAL_SHRINK
)) ||
1216 (newsize
> oldsize
&& (info
->seals
& F_SEAL_GROW
)))
1219 if (newsize
!= oldsize
) {
1220 error
= shmem_reacct_size(SHMEM_I(inode
)->flags
,
1224 i_size_write(inode
, newsize
);
1225 update_mtime
= true;
1227 update_ctime
= false;
1229 if (newsize
<= oldsize
) {
1230 loff_t holebegin
= round_up(newsize
, PAGE_SIZE
);
1231 if (oldsize
> holebegin
)
1232 unmap_mapping_range(inode
->i_mapping
,
1235 shmem_truncate_range(inode
,
1236 newsize
, (loff_t
)-1);
1237 /* unmap again to remove racily COWed private pages */
1238 if (oldsize
> holebegin
)
1239 unmap_mapping_range(inode
->i_mapping
,
1244 if (is_quota_modification(idmap
, inode
, attr
)) {
1245 error
= dquot_initialize(inode
);
1250 /* Transfer quota accounting */
1251 if (i_uid_needs_update(idmap
, attr
, inode
) ||
1252 i_gid_needs_update(idmap
, attr
, inode
)) {
1253 error
= dquot_transfer(idmap
, inode
, attr
);
1258 setattr_copy(idmap
, inode
, attr
);
1259 if (attr
->ia_valid
& ATTR_MODE
)
1260 error
= posix_acl_chmod(idmap
, dentry
, inode
->i_mode
);
1261 if (!error
&& update_ctime
) {
1262 inode_set_ctime_current(inode
);
1264 inode_set_mtime_to_ts(inode
, inode_get_ctime(inode
));
1265 inode_inc_iversion(inode
);
1270 static void shmem_evict_inode(struct inode
*inode
)
1272 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1273 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1276 if (shmem_mapping(inode
->i_mapping
)) {
1277 shmem_unacct_size(info
->flags
, inode
->i_size
);
1279 mapping_set_exiting(inode
->i_mapping
);
1280 shmem_truncate_range(inode
, 0, (loff_t
)-1);
1281 if (!list_empty(&info
->shrinklist
)) {
1282 spin_lock(&sbinfo
->shrinklist_lock
);
1283 if (!list_empty(&info
->shrinklist
)) {
1284 list_del_init(&info
->shrinklist
);
1285 sbinfo
->shrinklist_len
--;
1287 spin_unlock(&sbinfo
->shrinklist_lock
);
1289 while (!list_empty(&info
->swaplist
)) {
1290 /* Wait while shmem_unuse() is scanning this inode... */
1291 wait_var_event(&info
->stop_eviction
,
1292 !atomic_read(&info
->stop_eviction
));
1293 mutex_lock(&shmem_swaplist_mutex
);
1294 /* ...but beware of the race if we peeked too early */
1295 if (!atomic_read(&info
->stop_eviction
))
1296 list_del_init(&info
->swaplist
);
1297 mutex_unlock(&shmem_swaplist_mutex
);
1301 simple_xattrs_free(&info
->xattrs
, sbinfo
->max_inodes
? &freed
: NULL
);
1302 shmem_free_inode(inode
->i_sb
, freed
);
1303 WARN_ON(inode
->i_blocks
);
1305 #ifdef CONFIG_TMPFS_QUOTA
1306 dquot_free_inode(inode
);
1311 static int shmem_find_swap_entries(struct address_space
*mapping
,
1312 pgoff_t start
, struct folio_batch
*fbatch
,
1313 pgoff_t
*indices
, unsigned int type
)
1315 XA_STATE(xas
, &mapping
->i_pages
, start
);
1316 struct folio
*folio
;
1320 xas_for_each(&xas
, folio
, ULONG_MAX
) {
1321 if (xas_retry(&xas
, folio
))
1324 if (!xa_is_value(folio
))
1327 entry
= radix_to_swp_entry(folio
);
1329 * swapin error entries can be found in the mapping. But they're
1330 * deliberately ignored here as we've done everything we can do.
1332 if (swp_type(entry
) != type
)
1335 indices
[folio_batch_count(fbatch
)] = xas
.xa_index
;
1336 if (!folio_batch_add(fbatch
, folio
))
1339 if (need_resched()) {
1346 return xas
.xa_index
;
1350 * Move the swapped pages for an inode to page cache. Returns the count
1351 * of pages swapped in, or the error in case of failure.
1353 static int shmem_unuse_swap_entries(struct inode
*inode
,
1354 struct folio_batch
*fbatch
, pgoff_t
*indices
)
1359 struct address_space
*mapping
= inode
->i_mapping
;
1361 for (i
= 0; i
< folio_batch_count(fbatch
); i
++) {
1362 struct folio
*folio
= fbatch
->folios
[i
];
1364 if (!xa_is_value(folio
))
1366 error
= shmem_swapin_folio(inode
, indices
[i
], &folio
, SGP_CACHE
,
1367 mapping_gfp_mask(mapping
), NULL
, NULL
);
1369 folio_unlock(folio
);
1373 if (error
== -ENOMEM
)
1377 return error
? error
: ret
;
1381 * If swap found in inode, free it and move page from swapcache to filecache.
1383 static int shmem_unuse_inode(struct inode
*inode
, unsigned int type
)
1385 struct address_space
*mapping
= inode
->i_mapping
;
1387 struct folio_batch fbatch
;
1388 pgoff_t indices
[PAGEVEC_SIZE
];
1392 folio_batch_init(&fbatch
);
1393 shmem_find_swap_entries(mapping
, start
, &fbatch
, indices
, type
);
1394 if (folio_batch_count(&fbatch
) == 0) {
1399 ret
= shmem_unuse_swap_entries(inode
, &fbatch
, indices
);
1403 start
= indices
[folio_batch_count(&fbatch
) - 1];
1410 * Read all the shared memory data that resides in the swap
1411 * device 'type' back into memory, so the swap device can be
1414 int shmem_unuse(unsigned int type
)
1416 struct shmem_inode_info
*info
, *next
;
1419 if (list_empty(&shmem_swaplist
))
1422 mutex_lock(&shmem_swaplist_mutex
);
1423 list_for_each_entry_safe(info
, next
, &shmem_swaplist
, swaplist
) {
1424 if (!info
->swapped
) {
1425 list_del_init(&info
->swaplist
);
1429 * Drop the swaplist mutex while searching the inode for swap;
1430 * but before doing so, make sure shmem_evict_inode() will not
1431 * remove placeholder inode from swaplist, nor let it be freed
1432 * (igrab() would protect from unlink, but not from unmount).
1434 atomic_inc(&info
->stop_eviction
);
1435 mutex_unlock(&shmem_swaplist_mutex
);
1437 error
= shmem_unuse_inode(&info
->vfs_inode
, type
);
1440 mutex_lock(&shmem_swaplist_mutex
);
1441 next
= list_next_entry(info
, swaplist
);
1443 list_del_init(&info
->swaplist
);
1444 if (atomic_dec_and_test(&info
->stop_eviction
))
1445 wake_up_var(&info
->stop_eviction
);
1449 mutex_unlock(&shmem_swaplist_mutex
);
1455 * Move the page from the page cache to the swap cache.
1457 static int shmem_writepage(struct page
*page
, struct writeback_control
*wbc
)
1459 struct folio
*folio
= page_folio(page
);
1460 struct address_space
*mapping
= folio
->mapping
;
1461 struct inode
*inode
= mapping
->host
;
1462 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1463 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1470 * Our capabilities prevent regular writeback or sync from ever calling
1471 * shmem_writepage; but a stacking filesystem might use ->writepage of
1472 * its underlying filesystem, in which case tmpfs should write out to
1473 * swap only in response to memory pressure, and not for the writeback
1476 if (WARN_ON_ONCE(!wbc
->for_reclaim
))
1479 if (WARN_ON_ONCE((info
->flags
& VM_LOCKED
) || sbinfo
->noswap
))
1482 if (!total_swap_pages
)
1486 * If CONFIG_THP_SWAP is not enabled, the large folio should be
1487 * split when swapping.
1489 * And shrinkage of pages beyond i_size does not split swap, so
1490 * swapout of a large folio crossing i_size needs to split too
1491 * (unless fallocate has been used to preallocate beyond EOF).
1493 if (folio_test_large(folio
)) {
1494 index
= shmem_fallocend(inode
,
1495 DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
));
1496 if ((index
> folio
->index
&& index
< folio_next_index(folio
)) ||
1497 !IS_ENABLED(CONFIG_THP_SWAP
))
1503 /* Ensure the subpages are still dirty */
1504 folio_test_set_dirty(folio
);
1505 if (split_huge_page_to_list_to_order(page
, wbc
->list
, 0))
1507 folio
= page_folio(page
);
1508 folio_clear_dirty(folio
);
1511 index
= folio
->index
;
1512 nr_pages
= folio_nr_pages(folio
);
1515 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1516 * value into swapfile.c, the only way we can correctly account for a
1517 * fallocated folio arriving here is now to initialize it and write it.
1519 * That's okay for a folio already fallocated earlier, but if we have
1520 * not yet completed the fallocation, then (a) we want to keep track
1521 * of this folio in case we have to undo it, and (b) it may not be a
1522 * good idea to continue anyway, once we're pushing into swap. So
1523 * reactivate the folio, and let shmem_fallocate() quit when too many.
1525 if (!folio_test_uptodate(folio
)) {
1526 if (inode
->i_private
) {
1527 struct shmem_falloc
*shmem_falloc
;
1528 spin_lock(&inode
->i_lock
);
1529 shmem_falloc
= inode
->i_private
;
1531 !shmem_falloc
->waitq
&&
1532 index
>= shmem_falloc
->start
&&
1533 index
< shmem_falloc
->next
)
1534 shmem_falloc
->nr_unswapped
++;
1536 shmem_falloc
= NULL
;
1537 spin_unlock(&inode
->i_lock
);
1541 folio_zero_range(folio
, 0, folio_size(folio
));
1542 flush_dcache_folio(folio
);
1543 folio_mark_uptodate(folio
);
1546 swap
= folio_alloc_swap(folio
);
1555 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1556 * if it's not already there. Do it now before the folio is
1557 * moved to swap cache, when its pagelock no longer protects
1558 * the inode from eviction. But don't unlock the mutex until
1559 * we've incremented swapped, because shmem_unuse_inode() will
1560 * prune a !swapped inode from the swaplist under this mutex.
1562 mutex_lock(&shmem_swaplist_mutex
);
1563 if (list_empty(&info
->swaplist
))
1564 list_add(&info
->swaplist
, &shmem_swaplist
);
1566 if (add_to_swap_cache(folio
, swap
,
1567 __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
,
1569 shmem_recalc_inode(inode
, 0, nr_pages
);
1570 swap_shmem_alloc(swap
, nr_pages
);
1571 shmem_delete_from_page_cache(folio
, swp_to_radix_entry(swap
));
1573 mutex_unlock(&shmem_swaplist_mutex
);
1574 BUG_ON(folio_mapped(folio
));
1575 return swap_writepage(&folio
->page
, wbc
);
1578 mutex_unlock(&shmem_swaplist_mutex
);
1579 put_swap_folio(folio
, swap
);
1581 folio_mark_dirty(folio
);
1582 if (wbc
->for_reclaim
)
1583 return AOP_WRITEPAGE_ACTIVATE
; /* Return with folio locked */
1584 folio_unlock(folio
);
1588 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1589 static void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1593 if (!mpol
|| mpol
->mode
== MPOL_DEFAULT
)
1594 return; /* show nothing */
1596 mpol_to_str(buffer
, sizeof(buffer
), mpol
);
1598 seq_printf(seq
, ",mpol=%s", buffer
);
1601 static struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1603 struct mempolicy
*mpol
= NULL
;
1605 raw_spin_lock(&sbinfo
->stat_lock
); /* prevent replace/use races */
1606 mpol
= sbinfo
->mpol
;
1608 raw_spin_unlock(&sbinfo
->stat_lock
);
1612 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1613 static inline void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1616 static inline struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1620 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1622 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
1623 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
);
1625 static struct folio
*shmem_swapin_cluster(swp_entry_t swap
, gfp_t gfp
,
1626 struct shmem_inode_info
*info
, pgoff_t index
)
1628 struct mempolicy
*mpol
;
1630 struct folio
*folio
;
1632 mpol
= shmem_get_pgoff_policy(info
, index
, 0, &ilx
);
1633 folio
= swap_cluster_readahead(swap
, gfp
, mpol
, ilx
);
1634 mpol_cond_put(mpol
);
1640 * Make sure huge_gfp is always more limited than limit_gfp.
1641 * Some of the flags set permissions, while others set limitations.
1643 static gfp_t
limit_gfp_mask(gfp_t huge_gfp
, gfp_t limit_gfp
)
1645 gfp_t allowflags
= __GFP_IO
| __GFP_FS
| __GFP_RECLAIM
;
1646 gfp_t denyflags
= __GFP_NOWARN
| __GFP_NORETRY
;
1647 gfp_t zoneflags
= limit_gfp
& GFP_ZONEMASK
;
1648 gfp_t result
= huge_gfp
& ~(allowflags
| GFP_ZONEMASK
);
1650 /* Allow allocations only from the originally specified zones. */
1651 result
|= zoneflags
;
1654 * Minimize the result gfp by taking the union with the deny flags,
1655 * and the intersection of the allow flags.
1657 result
|= (limit_gfp
& denyflags
);
1658 result
|= (huge_gfp
& limit_gfp
) & allowflags
;
1663 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1664 bool shmem_hpage_pmd_enabled(void)
1666 if (shmem_huge
== SHMEM_HUGE_DENY
)
1668 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_always
))
1670 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_madvise
))
1672 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_within_size
))
1674 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_inherit
) &&
1675 shmem_huge
!= SHMEM_HUGE_NEVER
)
1681 unsigned long shmem_allowable_huge_orders(struct inode
*inode
,
1682 struct vm_area_struct
*vma
, pgoff_t index
,
1683 loff_t write_end
, bool shmem_huge_force
)
1685 unsigned long mask
= READ_ONCE(huge_shmem_orders_always
);
1686 unsigned long within_size_orders
= READ_ONCE(huge_shmem_orders_within_size
);
1687 unsigned long vm_flags
= vma
? vma
->vm_flags
: 0;
1692 if (thp_disabled_by_hw() || (vma
&& vma_thp_disabled(vma
, vm_flags
)))
1695 global_huge
= shmem_huge_global_enabled(inode
, index
, write_end
,
1696 shmem_huge_force
, vm_flags
);
1697 if (!vma
|| !vma_is_anon_shmem(vma
)) {
1699 * For tmpfs, we now only support PMD sized THP if huge page
1700 * is enabled, otherwise fallback to order 0.
1702 return global_huge
? BIT(HPAGE_PMD_ORDER
) : 0;
1706 * Following the 'deny' semantics of the top level, force the huge
1707 * option off from all mounts.
1709 if (shmem_huge
== SHMEM_HUGE_DENY
)
1713 * Only allow inherit orders if the top-level value is 'force', which
1714 * means non-PMD sized THP can not override 'huge' mount option now.
1716 if (shmem_huge
== SHMEM_HUGE_FORCE
)
1717 return READ_ONCE(huge_shmem_orders_inherit
);
1719 /* Allow mTHP that will be fully within i_size. */
1720 order
= highest_order(within_size_orders
);
1721 while (within_size_orders
) {
1722 index
= round_up(index
+ 1, order
);
1723 i_size
= round_up(i_size_read(inode
), PAGE_SIZE
);
1724 if (i_size
>> PAGE_SHIFT
>= index
) {
1725 mask
|= within_size_orders
;
1729 order
= next_order(&within_size_orders
, order
);
1732 if (vm_flags
& VM_HUGEPAGE
)
1733 mask
|= READ_ONCE(huge_shmem_orders_madvise
);
1736 mask
|= READ_ONCE(huge_shmem_orders_inherit
);
1738 return THP_ORDERS_ALL_FILE_DEFAULT
& mask
;
1741 static unsigned long shmem_suitable_orders(struct inode
*inode
, struct vm_fault
*vmf
,
1742 struct address_space
*mapping
, pgoff_t index
,
1743 unsigned long orders
)
1745 struct vm_area_struct
*vma
= vmf
? vmf
->vma
: NULL
;
1746 pgoff_t aligned_index
;
1747 unsigned long pages
;
1751 orders
= thp_vma_suitable_orders(vma
, vmf
->address
, orders
);
1756 /* Find the highest order that can add into the page cache */
1757 order
= highest_order(orders
);
1759 pages
= 1UL << order
;
1760 aligned_index
= round_down(index
, pages
);
1762 * Check for conflict before waiting on a huge allocation.
1763 * Conflict might be that a huge page has just been allocated
1764 * and added to page cache by a racing thread, or that there
1765 * is already at least one small page in the huge extent.
1766 * Be careful to retry when appropriate, but not forever!
1767 * Elsewhere -EEXIST would be the right code, but not here.
1769 if (!xa_find(&mapping
->i_pages
, &aligned_index
,
1770 aligned_index
+ pages
- 1, XA_PRESENT
))
1772 order
= next_order(&orders
, order
);
1778 static unsigned long shmem_suitable_orders(struct inode
*inode
, struct vm_fault
*vmf
,
1779 struct address_space
*mapping
, pgoff_t index
,
1780 unsigned long orders
)
1784 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1786 static struct folio
*shmem_alloc_folio(gfp_t gfp
, int order
,
1787 struct shmem_inode_info
*info
, pgoff_t index
)
1789 struct mempolicy
*mpol
;
1791 struct folio
*folio
;
1793 mpol
= shmem_get_pgoff_policy(info
, index
, order
, &ilx
);
1794 folio
= folio_alloc_mpol(gfp
, order
, mpol
, ilx
, numa_node_id());
1795 mpol_cond_put(mpol
);
1800 static struct folio
*shmem_alloc_and_add_folio(struct vm_fault
*vmf
,
1801 gfp_t gfp
, struct inode
*inode
, pgoff_t index
,
1802 struct mm_struct
*fault_mm
, unsigned long orders
)
1804 struct address_space
*mapping
= inode
->i_mapping
;
1805 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1806 unsigned long suitable_orders
= 0;
1807 struct folio
*folio
= NULL
;
1811 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
))
1815 suitable_orders
= shmem_suitable_orders(inode
, vmf
,
1816 mapping
, index
, orders
);
1818 order
= highest_order(suitable_orders
);
1819 while (suitable_orders
) {
1820 pages
= 1UL << order
;
1821 index
= round_down(index
, pages
);
1822 folio
= shmem_alloc_folio(gfp
, order
, info
, index
);
1826 if (pages
== HPAGE_PMD_NR
)
1827 count_vm_event(THP_FILE_FALLBACK
);
1828 count_mthp_stat(order
, MTHP_STAT_SHMEM_FALLBACK
);
1829 order
= next_order(&suitable_orders
, order
);
1833 folio
= shmem_alloc_folio(gfp
, 0, info
, index
);
1836 return ERR_PTR(-ENOMEM
);
1839 __folio_set_locked(folio
);
1840 __folio_set_swapbacked(folio
);
1842 gfp
&= GFP_RECLAIM_MASK
;
1843 error
= mem_cgroup_charge(folio
, fault_mm
, gfp
);
1845 if (xa_find(&mapping
->i_pages
, &index
,
1846 index
+ pages
- 1, XA_PRESENT
)) {
1848 } else if (pages
> 1) {
1849 if (pages
== HPAGE_PMD_NR
) {
1850 count_vm_event(THP_FILE_FALLBACK
);
1851 count_vm_event(THP_FILE_FALLBACK_CHARGE
);
1853 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_FALLBACK
);
1854 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_FALLBACK_CHARGE
);
1859 error
= shmem_add_to_page_cache(folio
, mapping
, index
, NULL
, gfp
);
1863 error
= shmem_inode_acct_blocks(inode
, pages
);
1865 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1868 * Try to reclaim some space by splitting a few
1869 * large folios beyond i_size on the filesystem.
1871 shmem_unused_huge_shrink(sbinfo
, NULL
, pages
);
1873 * And do a shmem_recalc_inode() to account for freed pages:
1874 * except our folio is there in cache, so not quite balanced.
1876 spin_lock(&info
->lock
);
1877 freed
= pages
+ info
->alloced
- info
->swapped
-
1878 READ_ONCE(mapping
->nrpages
);
1880 info
->alloced
-= freed
;
1881 spin_unlock(&info
->lock
);
1883 shmem_inode_unacct_blocks(inode
, freed
);
1884 error
= shmem_inode_acct_blocks(inode
, pages
);
1886 filemap_remove_folio(folio
);
1891 shmem_recalc_inode(inode
, pages
, 0);
1892 folio_add_lru(folio
);
1896 folio_unlock(folio
);
1898 return ERR_PTR(error
);
1902 * When a page is moved from swapcache to shmem filecache (either by the
1903 * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
1904 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1905 * ignorance of the mapping it belongs to. If that mapping has special
1906 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1907 * we may need to copy to a suitable page before moving to filecache.
1909 * In a future release, this may well be extended to respect cpuset and
1910 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1911 * but for now it is a simple matter of zone.
1913 static bool shmem_should_replace_folio(struct folio
*folio
, gfp_t gfp
)
1915 return folio_zonenum(folio
) > gfp_zone(gfp
);
1918 static int shmem_replace_folio(struct folio
**foliop
, gfp_t gfp
,
1919 struct shmem_inode_info
*info
, pgoff_t index
,
1920 struct vm_area_struct
*vma
)
1922 struct folio
*new, *old
= *foliop
;
1923 swp_entry_t entry
= old
->swap
;
1924 struct address_space
*swap_mapping
= swap_address_space(entry
);
1925 pgoff_t swap_index
= swap_cache_index(entry
);
1926 XA_STATE(xas
, &swap_mapping
->i_pages
, swap_index
);
1927 int nr_pages
= folio_nr_pages(old
);
1931 * We have arrived here because our zones are constrained, so don't
1932 * limit chance of success by further cpuset and node constraints.
1934 gfp
&= ~GFP_CONSTRAINT_MASK
;
1935 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1937 gfp_t huge_gfp
= vma_thp_gfp_mask(vma
);
1939 gfp
= limit_gfp_mask(huge_gfp
, gfp
);
1943 new = shmem_alloc_folio(gfp
, folio_order(old
), info
, index
);
1947 folio_ref_add(new, nr_pages
);
1948 folio_copy(new, old
);
1949 flush_dcache_folio(new);
1951 __folio_set_locked(new);
1952 __folio_set_swapbacked(new);
1953 folio_mark_uptodate(new);
1955 folio_set_swapcache(new);
1957 /* Swap cache still stores N entries instead of a high-order entry */
1958 xa_lock_irq(&swap_mapping
->i_pages
);
1959 for (i
= 0; i
< nr_pages
; i
++) {
1960 void *item
= xas_load(&xas
);
1967 xas_store(&xas
, new);
1971 mem_cgroup_replace_folio(old
, new);
1972 __lruvec_stat_mod_folio(new, NR_FILE_PAGES
, nr_pages
);
1973 __lruvec_stat_mod_folio(new, NR_SHMEM
, nr_pages
);
1974 __lruvec_stat_mod_folio(old
, NR_FILE_PAGES
, -nr_pages
);
1975 __lruvec_stat_mod_folio(old
, NR_SHMEM
, -nr_pages
);
1977 xa_unlock_irq(&swap_mapping
->i_pages
);
1979 if (unlikely(error
)) {
1981 * Is this possible? I think not, now that our callers
1982 * check both the swapcache flag and folio->private
1983 * after getting the folio lock; but be defensive.
1984 * Reverse old to newpage for clear and free.
1992 folio_clear_swapcache(old
);
1993 old
->private = NULL
;
1997 * The old folio are removed from swap cache, drop the 'nr_pages'
1998 * reference, as well as one temporary reference getting from swap
2001 folio_put_refs(old
, nr_pages
+ 1);
2005 static void shmem_set_folio_swapin_error(struct inode
*inode
, pgoff_t index
,
2006 struct folio
*folio
, swp_entry_t swap
)
2008 struct address_space
*mapping
= inode
->i_mapping
;
2009 swp_entry_t swapin_error
;
2013 swapin_error
= make_poisoned_swp_entry();
2014 old
= xa_cmpxchg_irq(&mapping
->i_pages
, index
,
2015 swp_to_radix_entry(swap
),
2016 swp_to_radix_entry(swapin_error
), 0);
2017 if (old
!= swp_to_radix_entry(swap
))
2020 nr_pages
= folio_nr_pages(folio
);
2021 folio_wait_writeback(folio
);
2022 delete_from_swap_cache(folio
);
2024 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks
2025 * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks)
2026 * in shmem_evict_inode().
2028 shmem_recalc_inode(inode
, -nr_pages
, -nr_pages
);
2029 swap_free_nr(swap
, nr_pages
);
2032 static int shmem_split_large_entry(struct inode
*inode
, pgoff_t index
,
2033 swp_entry_t swap
, gfp_t gfp
)
2035 struct address_space
*mapping
= inode
->i_mapping
;
2036 XA_STATE_ORDER(xas
, &mapping
->i_pages
, index
, 0);
2037 void *alloced_shadow
= NULL
;
2038 int alloced_order
= 0, i
;
2040 /* Convert user data gfp flags to xarray node gfp flags */
2041 gfp
&= GFP_RECLAIM_MASK
;
2044 int order
= -1, split_order
= 0;
2048 old
= xas_load(&xas
);
2049 if (!xa_is_value(old
) || swp_to_radix_entry(swap
) != old
) {
2050 xas_set_err(&xas
, -EEXIST
);
2054 order
= xas_get_order(&xas
);
2056 /* Swap entry may have changed before we re-acquire the lock */
2057 if (alloced_order
&&
2058 (old
!= alloced_shadow
|| order
!= alloced_order
)) {
2063 /* Try to split large swap entry in pagecache */
2065 if (!alloced_order
) {
2066 split_order
= order
;
2069 xas_split(&xas
, old
, order
);
2072 * Re-set the swap entry after splitting, and the swap
2073 * offset of the original large entry must be continuous.
2075 for (i
= 0; i
< 1 << order
; i
++) {
2076 pgoff_t aligned_index
= round_down(index
, 1 << order
);
2079 tmp
= swp_entry(swp_type(swap
), swp_offset(swap
) + i
);
2080 __xa_store(&mapping
->i_pages
, aligned_index
+ i
,
2081 swp_to_radix_entry(tmp
), 0);
2086 xas_unlock_irq(&xas
);
2088 /* split needed, alloc here and retry. */
2090 xas_split_alloc(&xas
, old
, split_order
, gfp
);
2091 if (xas_error(&xas
))
2093 alloced_shadow
= old
;
2094 alloced_order
= split_order
;
2099 if (!xas_nomem(&xas
, gfp
))
2104 if (xas_error(&xas
))
2105 return xas_error(&xas
);
2107 return alloced_order
;
2111 * Swap in the folio pointed to by *foliop.
2112 * Caller has to make sure that *foliop contains a valid swapped folio.
2113 * Returns 0 and the folio in foliop if success. On failure, returns the
2114 * error code and NULL in *foliop.
2116 static int shmem_swapin_folio(struct inode
*inode
, pgoff_t index
,
2117 struct folio
**foliop
, enum sgp_type sgp
,
2118 gfp_t gfp
, struct vm_area_struct
*vma
,
2119 vm_fault_t
*fault_type
)
2121 struct address_space
*mapping
= inode
->i_mapping
;
2122 struct mm_struct
*fault_mm
= vma
? vma
->vm_mm
: NULL
;
2123 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2124 struct swap_info_struct
*si
;
2125 struct folio
*folio
= NULL
;
2127 int error
, nr_pages
;
2129 VM_BUG_ON(!*foliop
|| !xa_is_value(*foliop
));
2130 swap
= radix_to_swp_entry(*foliop
);
2133 if (is_poisoned_swp_entry(swap
))
2136 si
= get_swap_device(swap
);
2138 if (!shmem_confirm_swap(mapping
, index
, swap
))
2144 /* Look it up and read it in.. */
2145 folio
= swap_cache_get_folio(swap
, NULL
, 0);
2149 /* Or update major stats only when swapin succeeds?? */
2151 *fault_type
|= VM_FAULT_MAJOR
;
2152 count_vm_event(PGMAJFAULT
);
2153 count_memcg_event_mm(fault_mm
, PGMAJFAULT
);
2157 * Now swap device can only swap in order 0 folio, then we
2158 * should split the large swap entry stored in the pagecache
2161 split_order
= shmem_split_large_entry(inode
, index
, swap
, gfp
);
2162 if (split_order
< 0) {
2163 error
= split_order
;
2168 * If the large swap entry has already been split, it is
2169 * necessary to recalculate the new swap entry based on
2170 * the old order alignment.
2172 if (split_order
> 0) {
2173 pgoff_t offset
= index
- round_down(index
, 1 << split_order
);
2175 swap
= swp_entry(swp_type(swap
), swp_offset(swap
) + offset
);
2178 /* Here we actually start the io */
2179 folio
= shmem_swapin_cluster(swap
, gfp
, info
, index
);
2186 /* We have to do this with folio locked to prevent races */
2188 if (!folio_test_swapcache(folio
) ||
2189 folio
->swap
.val
!= swap
.val
||
2190 !shmem_confirm_swap(mapping
, index
, swap
)) {
2194 if (!folio_test_uptodate(folio
)) {
2198 folio_wait_writeback(folio
);
2199 nr_pages
= folio_nr_pages(folio
);
2202 * Some architectures may have to restore extra metadata to the
2203 * folio after reading from swap.
2205 arch_swap_restore(folio_swap(swap
, folio
), folio
);
2207 if (shmem_should_replace_folio(folio
, gfp
)) {
2208 error
= shmem_replace_folio(&folio
, gfp
, info
, index
, vma
);
2213 error
= shmem_add_to_page_cache(folio
, mapping
,
2214 round_down(index
, nr_pages
),
2215 swp_to_radix_entry(swap
), gfp
);
2219 shmem_recalc_inode(inode
, 0, -nr_pages
);
2221 if (sgp
== SGP_WRITE
)
2222 folio_mark_accessed(folio
);
2224 delete_from_swap_cache(folio
);
2225 folio_mark_dirty(folio
);
2226 swap_free_nr(swap
, nr_pages
);
2227 put_swap_device(si
);
2232 if (!shmem_confirm_swap(mapping
, index
, swap
))
2235 shmem_set_folio_swapin_error(inode
, index
, folio
, swap
);
2238 folio_unlock(folio
);
2241 put_swap_device(si
);
2247 * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
2249 * If we allocate a new one we do not mark it dirty. That's up to the
2250 * vm. If we swap it in we mark it dirty since we also free the swap
2251 * entry since a page cannot live in both the swap and page cache.
2253 * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL.
2255 static int shmem_get_folio_gfp(struct inode
*inode
, pgoff_t index
,
2256 loff_t write_end
, struct folio
**foliop
, enum sgp_type sgp
,
2257 gfp_t gfp
, struct vm_fault
*vmf
, vm_fault_t
*fault_type
)
2259 struct vm_area_struct
*vma
= vmf
? vmf
->vma
: NULL
;
2260 struct mm_struct
*fault_mm
;
2261 struct folio
*folio
;
2264 unsigned long orders
= 0;
2266 if (WARN_ON_ONCE(!shmem_mapping(inode
->i_mapping
)))
2269 if (index
> (MAX_LFS_FILESIZE
>> PAGE_SHIFT
))
2272 if (sgp
<= SGP_CACHE
&&
2273 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
))
2277 fault_mm
= vma
? vma
->vm_mm
: NULL
;
2279 folio
= filemap_get_entry(inode
->i_mapping
, index
);
2280 if (folio
&& vma
&& userfaultfd_minor(vma
)) {
2281 if (!xa_is_value(folio
))
2283 *fault_type
= handle_userfault(vmf
, VM_UFFD_MINOR
);
2287 if (xa_is_value(folio
)) {
2288 error
= shmem_swapin_folio(inode
, index
, &folio
,
2289 sgp
, gfp
, vma
, fault_type
);
2290 if (error
== -EEXIST
)
2300 /* Has the folio been truncated or swapped out? */
2301 if (unlikely(folio
->mapping
!= inode
->i_mapping
)) {
2302 folio_unlock(folio
);
2306 if (sgp
== SGP_WRITE
)
2307 folio_mark_accessed(folio
);
2308 if (folio_test_uptodate(folio
))
2310 /* fallocated folio */
2311 if (sgp
!= SGP_READ
)
2313 folio_unlock(folio
);
2318 * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
2319 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
2322 if (sgp
== SGP_READ
)
2324 if (sgp
== SGP_NOALLOC
)
2328 * Fast cache lookup and swap lookup did not find it: allocate.
2331 if (vma
&& userfaultfd_missing(vma
)) {
2332 *fault_type
= handle_userfault(vmf
, VM_UFFD_MISSING
);
2336 /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */
2337 orders
= shmem_allowable_huge_orders(inode
, vma
, index
, write_end
, false);
2341 huge_gfp
= vma_thp_gfp_mask(vma
);
2342 huge_gfp
= limit_gfp_mask(huge_gfp
, gfp
);
2343 folio
= shmem_alloc_and_add_folio(vmf
, huge_gfp
,
2344 inode
, index
, fault_mm
, orders
);
2345 if (!IS_ERR(folio
)) {
2346 if (folio_test_pmd_mappable(folio
))
2347 count_vm_event(THP_FILE_ALLOC
);
2348 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_ALLOC
);
2351 if (PTR_ERR(folio
) == -EEXIST
)
2355 folio
= shmem_alloc_and_add_folio(vmf
, gfp
, inode
, index
, fault_mm
, 0);
2356 if (IS_ERR(folio
)) {
2357 error
= PTR_ERR(folio
);
2358 if (error
== -EEXIST
)
2366 if (folio_test_large(folio
) &&
2367 DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
) <
2368 folio_next_index(folio
)) {
2369 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
2370 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2372 * Part of the large folio is beyond i_size: subject
2373 * to shrink under memory pressure.
2375 spin_lock(&sbinfo
->shrinklist_lock
);
2377 * _careful to defend against unlocked access to
2378 * ->shrink_list in shmem_unused_huge_shrink()
2380 if (list_empty_careful(&info
->shrinklist
)) {
2381 list_add_tail(&info
->shrinklist
,
2382 &sbinfo
->shrinklist
);
2383 sbinfo
->shrinklist_len
++;
2385 spin_unlock(&sbinfo
->shrinklist_lock
);
2388 if (sgp
== SGP_WRITE
)
2389 folio_set_referenced(folio
);
2391 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
2393 if (sgp
== SGP_FALLOC
)
2397 * Let SGP_WRITE caller clear ends if write does not fill folio;
2398 * but SGP_FALLOC on a folio fallocated earlier must initialize
2399 * it now, lest undo on failure cancel our earlier guarantee.
2401 if (sgp
!= SGP_WRITE
&& !folio_test_uptodate(folio
)) {
2402 long i
, n
= folio_nr_pages(folio
);
2404 for (i
= 0; i
< n
; i
++)
2405 clear_highpage(folio_page(folio
, i
));
2406 flush_dcache_folio(folio
);
2407 folio_mark_uptodate(folio
);
2410 /* Perhaps the file has been truncated since we checked */
2411 if (sgp
<= SGP_CACHE
&&
2412 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
)) {
2425 filemap_remove_folio(folio
);
2426 shmem_recalc_inode(inode
, 0, 0);
2428 folio_unlock(folio
);
2435 * shmem_get_folio - find, and lock a shmem folio.
2436 * @inode: inode to search
2437 * @index: the page index.
2438 * @write_end: end of a write, could extend inode size
2439 * @foliop: pointer to the folio if found
2440 * @sgp: SGP_* flags to control behavior
2442 * Looks up the page cache entry at @inode & @index. If a folio is
2443 * present, it is returned locked with an increased refcount.
2445 * If the caller modifies data in the folio, it must call folio_mark_dirty()
2446 * before unlocking the folio to ensure that the folio is not reclaimed.
2447 * There is no need to reserve space before calling folio_mark_dirty().
2449 * When no folio is found, the behavior depends on @sgp:
2450 * - for SGP_READ, *@foliop is %NULL and 0 is returned
2451 * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned
2452 * - for all other flags a new folio is allocated, inserted into the
2453 * page cache and returned locked in @foliop.
2455 * Context: May sleep.
2456 * Return: 0 if successful, else a negative error code.
2458 int shmem_get_folio(struct inode
*inode
, pgoff_t index
, loff_t write_end
,
2459 struct folio
**foliop
, enum sgp_type sgp
)
2461 return shmem_get_folio_gfp(inode
, index
, write_end
, foliop
, sgp
,
2462 mapping_gfp_mask(inode
->i_mapping
), NULL
, NULL
);
2464 EXPORT_SYMBOL_GPL(shmem_get_folio
);
2467 * This is like autoremove_wake_function, but it removes the wait queue
2468 * entry unconditionally - even if something else had already woken the
2471 static int synchronous_wake_function(wait_queue_entry_t
*wait
,
2472 unsigned int mode
, int sync
, void *key
)
2474 int ret
= default_wake_function(wait
, mode
, sync
, key
);
2475 list_del_init(&wait
->entry
);
2480 * Trinity finds that probing a hole which tmpfs is punching can
2481 * prevent the hole-punch from ever completing: which in turn
2482 * locks writers out with its hold on i_rwsem. So refrain from
2483 * faulting pages into the hole while it's being punched. Although
2484 * shmem_undo_range() does remove the additions, it may be unable to
2485 * keep up, as each new page needs its own unmap_mapping_range() call,
2486 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2488 * It does not matter if we sometimes reach this check just before the
2489 * hole-punch begins, so that one fault then races with the punch:
2490 * we just need to make racing faults a rare case.
2492 * The implementation below would be much simpler if we just used a
2493 * standard mutex or completion: but we cannot take i_rwsem in fault,
2494 * and bloating every shmem inode for this unlikely case would be sad.
2496 static vm_fault_t
shmem_falloc_wait(struct vm_fault
*vmf
, struct inode
*inode
)
2498 struct shmem_falloc
*shmem_falloc
;
2499 struct file
*fpin
= NULL
;
2502 spin_lock(&inode
->i_lock
);
2503 shmem_falloc
= inode
->i_private
;
2505 shmem_falloc
->waitq
&&
2506 vmf
->pgoff
>= shmem_falloc
->start
&&
2507 vmf
->pgoff
< shmem_falloc
->next
) {
2508 wait_queue_head_t
*shmem_falloc_waitq
;
2509 DEFINE_WAIT_FUNC(shmem_fault_wait
, synchronous_wake_function
);
2511 ret
= VM_FAULT_NOPAGE
;
2512 fpin
= maybe_unlock_mmap_for_io(vmf
, NULL
);
2513 shmem_falloc_waitq
= shmem_falloc
->waitq
;
2514 prepare_to_wait(shmem_falloc_waitq
, &shmem_fault_wait
,
2515 TASK_UNINTERRUPTIBLE
);
2516 spin_unlock(&inode
->i_lock
);
2520 * shmem_falloc_waitq points into the shmem_fallocate()
2521 * stack of the hole-punching task: shmem_falloc_waitq
2522 * is usually invalid by the time we reach here, but
2523 * finish_wait() does not dereference it in that case;
2524 * though i_lock needed lest racing with wake_up_all().
2526 spin_lock(&inode
->i_lock
);
2527 finish_wait(shmem_falloc_waitq
, &shmem_fault_wait
);
2529 spin_unlock(&inode
->i_lock
);
2532 ret
= VM_FAULT_RETRY
;
2537 static vm_fault_t
shmem_fault(struct vm_fault
*vmf
)
2539 struct inode
*inode
= file_inode(vmf
->vma
->vm_file
);
2540 gfp_t gfp
= mapping_gfp_mask(inode
->i_mapping
);
2541 struct folio
*folio
= NULL
;
2546 * Trinity finds that probing a hole which tmpfs is punching can
2547 * prevent the hole-punch from ever completing: noted in i_private.
2549 if (unlikely(inode
->i_private
)) {
2550 ret
= shmem_falloc_wait(vmf
, inode
);
2555 WARN_ON_ONCE(vmf
->page
!= NULL
);
2556 err
= shmem_get_folio_gfp(inode
, vmf
->pgoff
, 0, &folio
, SGP_CACHE
,
2559 return vmf_error(err
);
2561 vmf
->page
= folio_file_page(folio
, vmf
->pgoff
);
2562 ret
|= VM_FAULT_LOCKED
;
2567 unsigned long shmem_get_unmapped_area(struct file
*file
,
2568 unsigned long uaddr
, unsigned long len
,
2569 unsigned long pgoff
, unsigned long flags
)
2572 unsigned long offset
;
2573 unsigned long inflated_len
;
2574 unsigned long inflated_addr
;
2575 unsigned long inflated_offset
;
2576 unsigned long hpage_size
;
2578 if (len
> TASK_SIZE
)
2581 addr
= mm_get_unmapped_area(current
->mm
, file
, uaddr
, len
, pgoff
,
2584 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
))
2586 if (IS_ERR_VALUE(addr
))
2588 if (addr
& ~PAGE_MASK
)
2590 if (addr
> TASK_SIZE
- len
)
2593 if (shmem_huge
== SHMEM_HUGE_DENY
)
2595 if (flags
& MAP_FIXED
)
2598 * Our priority is to support MAP_SHARED mapped hugely;
2599 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2600 * But if caller specified an address hint and we allocated area there
2601 * successfully, respect that as before.
2606 hpage_size
= HPAGE_PMD_SIZE
;
2607 if (shmem_huge
!= SHMEM_HUGE_FORCE
) {
2608 struct super_block
*sb
;
2609 unsigned long __maybe_unused hpage_orders
;
2613 VM_BUG_ON(file
->f_op
!= &shmem_file_operations
);
2614 sb
= file_inode(file
)->i_sb
;
2617 * Called directly from mm/mmap.c, or drivers/char/mem.c
2618 * for "/dev/zero", to create a shared anonymous object.
2620 if (IS_ERR(shm_mnt
))
2622 sb
= shm_mnt
->mnt_sb
;
2625 * Find the highest mTHP order used for anonymous shmem to
2626 * provide a suitable alignment address.
2628 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2629 hpage_orders
= READ_ONCE(huge_shmem_orders_always
);
2630 hpage_orders
|= READ_ONCE(huge_shmem_orders_within_size
);
2631 hpage_orders
|= READ_ONCE(huge_shmem_orders_madvise
);
2632 if (SHMEM_SB(sb
)->huge
!= SHMEM_HUGE_NEVER
)
2633 hpage_orders
|= READ_ONCE(huge_shmem_orders_inherit
);
2635 if (hpage_orders
> 0) {
2636 order
= highest_order(hpage_orders
);
2637 hpage_size
= PAGE_SIZE
<< order
;
2641 if (SHMEM_SB(sb
)->huge
== SHMEM_HUGE_NEVER
&& !order
)
2645 if (len
< hpage_size
)
2648 offset
= (pgoff
<< PAGE_SHIFT
) & (hpage_size
- 1);
2649 if (offset
&& offset
+ len
< 2 * hpage_size
)
2651 if ((addr
& (hpage_size
- 1)) == offset
)
2654 inflated_len
= len
+ hpage_size
- PAGE_SIZE
;
2655 if (inflated_len
> TASK_SIZE
)
2657 if (inflated_len
< len
)
2660 inflated_addr
= mm_get_unmapped_area(current
->mm
, NULL
, uaddr
,
2661 inflated_len
, 0, flags
);
2662 if (IS_ERR_VALUE(inflated_addr
))
2664 if (inflated_addr
& ~PAGE_MASK
)
2667 inflated_offset
= inflated_addr
& (hpage_size
- 1);
2668 inflated_addr
+= offset
- inflated_offset
;
2669 if (inflated_offset
> offset
)
2670 inflated_addr
+= hpage_size
;
2672 if (inflated_addr
> TASK_SIZE
- len
)
2674 return inflated_addr
;
2678 static int shmem_set_policy(struct vm_area_struct
*vma
, struct mempolicy
*mpol
)
2680 struct inode
*inode
= file_inode(vma
->vm_file
);
2681 return mpol_set_shared_policy(&SHMEM_I(inode
)->policy
, vma
, mpol
);
2684 static struct mempolicy
*shmem_get_policy(struct vm_area_struct
*vma
,
2685 unsigned long addr
, pgoff_t
*ilx
)
2687 struct inode
*inode
= file_inode(vma
->vm_file
);
2691 * Bias interleave by inode number to distribute better across nodes;
2692 * but this interface is independent of which page order is used, so
2693 * supplies only that bias, letting caller apply the offset (adjusted
2694 * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()).
2696 *ilx
= inode
->i_ino
;
2697 index
= ((addr
- vma
->vm_start
) >> PAGE_SHIFT
) + vma
->vm_pgoff
;
2698 return mpol_shared_policy_lookup(&SHMEM_I(inode
)->policy
, index
);
2701 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
2702 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
)
2704 struct mempolicy
*mpol
;
2706 /* Bias interleave by inode number to distribute better across nodes */
2707 *ilx
= info
->vfs_inode
.i_ino
+ (index
>> order
);
2709 mpol
= mpol_shared_policy_lookup(&info
->policy
, index
);
2710 return mpol
? mpol
: get_task_policy(current
);
2713 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
2714 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
)
2719 #endif /* CONFIG_NUMA */
2721 int shmem_lock(struct file
*file
, int lock
, struct ucounts
*ucounts
)
2723 struct inode
*inode
= file_inode(file
);
2724 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2725 int retval
= -ENOMEM
;
2728 * What serializes the accesses to info->flags?
2729 * ipc_lock_object() when called from shmctl_do_lock(),
2730 * no serialization needed when called from shm_destroy().
2732 if (lock
&& !(info
->flags
& VM_LOCKED
)) {
2733 if (!user_shm_lock(inode
->i_size
, ucounts
))
2735 info
->flags
|= VM_LOCKED
;
2736 mapping_set_unevictable(file
->f_mapping
);
2738 if (!lock
&& (info
->flags
& VM_LOCKED
) && ucounts
) {
2739 user_shm_unlock(inode
->i_size
, ucounts
);
2740 info
->flags
&= ~VM_LOCKED
;
2741 mapping_clear_unevictable(file
->f_mapping
);
2749 static int shmem_mmap(struct file
*file
, struct vm_area_struct
*vma
)
2751 struct inode
*inode
= file_inode(file
);
2752 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2755 ret
= seal_check_write(info
->seals
, vma
);
2759 file_accessed(file
);
2760 /* This is anonymous shared memory if it is unlinked at the time of mmap */
2762 vma
->vm_ops
= &shmem_vm_ops
;
2764 vma
->vm_ops
= &shmem_anon_vm_ops
;
2768 static int shmem_file_open(struct inode
*inode
, struct file
*file
)
2770 file
->f_mode
|= FMODE_CAN_ODIRECT
;
2771 return generic_file_open(inode
, file
);
2774 #ifdef CONFIG_TMPFS_XATTR
2775 static int shmem_initxattrs(struct inode
*, const struct xattr
*, void *);
2777 #if IS_ENABLED(CONFIG_UNICODE)
2779 * shmem_inode_casefold_flags - Deal with casefold file attribute flag
2781 * The casefold file attribute needs some special checks. I can just be added to
2782 * an empty dir, and can't be removed from a non-empty dir.
2784 static int shmem_inode_casefold_flags(struct inode
*inode
, unsigned int fsflags
,
2785 struct dentry
*dentry
, unsigned int *i_flags
)
2787 unsigned int old
= inode
->i_flags
;
2788 struct super_block
*sb
= inode
->i_sb
;
2790 if (fsflags
& FS_CASEFOLD_FL
) {
2791 if (!(old
& S_CASEFOLD
)) {
2792 if (!sb
->s_encoding
)
2795 if (!S_ISDIR(inode
->i_mode
))
2798 if (dentry
&& !simple_empty(dentry
))
2802 *i_flags
= *i_flags
| S_CASEFOLD
;
2803 } else if (old
& S_CASEFOLD
) {
2804 if (dentry
&& !simple_empty(dentry
))
2811 static int shmem_inode_casefold_flags(struct inode
*inode
, unsigned int fsflags
,
2812 struct dentry
*dentry
, unsigned int *i_flags
)
2814 if (fsflags
& FS_CASEFOLD_FL
)
2822 * chattr's fsflags are unrelated to extended attributes,
2823 * but tmpfs has chosen to enable them under the same config option.
2825 static int shmem_set_inode_flags(struct inode
*inode
, unsigned int fsflags
, struct dentry
*dentry
)
2827 unsigned int i_flags
= 0;
2830 ret
= shmem_inode_casefold_flags(inode
, fsflags
, dentry
, &i_flags
);
2834 if (fsflags
& FS_NOATIME_FL
)
2835 i_flags
|= S_NOATIME
;
2836 if (fsflags
& FS_APPEND_FL
)
2837 i_flags
|= S_APPEND
;
2838 if (fsflags
& FS_IMMUTABLE_FL
)
2839 i_flags
|= S_IMMUTABLE
;
2841 * But FS_NODUMP_FL does not require any action in i_flags.
2843 inode_set_flags(inode
, i_flags
, S_NOATIME
| S_APPEND
| S_IMMUTABLE
| S_CASEFOLD
);
2848 static void shmem_set_inode_flags(struct inode
*inode
, unsigned int fsflags
, struct dentry
*dentry
)
2851 #define shmem_initxattrs NULL
2854 static struct offset_ctx
*shmem_get_offset_ctx(struct inode
*inode
)
2856 return &SHMEM_I(inode
)->dir_offsets
;
2859 static struct inode
*__shmem_get_inode(struct mnt_idmap
*idmap
,
2860 struct super_block
*sb
,
2861 struct inode
*dir
, umode_t mode
,
2862 dev_t dev
, unsigned long flags
)
2864 struct inode
*inode
;
2865 struct shmem_inode_info
*info
;
2866 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
2870 err
= shmem_reserve_inode(sb
, &ino
);
2872 return ERR_PTR(err
);
2874 inode
= new_inode(sb
);
2876 shmem_free_inode(sb
, 0);
2877 return ERR_PTR(-ENOSPC
);
2881 inode_init_owner(idmap
, inode
, dir
, mode
);
2882 inode
->i_blocks
= 0;
2883 simple_inode_init_ts(inode
);
2884 inode
->i_generation
= get_random_u32();
2885 info
= SHMEM_I(inode
);
2886 memset(info
, 0, (char *)inode
- (char *)info
);
2887 spin_lock_init(&info
->lock
);
2888 atomic_set(&info
->stop_eviction
, 0);
2889 info
->seals
= F_SEAL_SEAL
;
2890 info
->flags
= flags
& VM_NORESERVE
;
2891 info
->i_crtime
= inode_get_mtime(inode
);
2892 info
->fsflags
= (dir
== NULL
) ? 0 :
2893 SHMEM_I(dir
)->fsflags
& SHMEM_FL_INHERITED
;
2895 shmem_set_inode_flags(inode
, info
->fsflags
, NULL
);
2896 INIT_LIST_HEAD(&info
->shrinklist
);
2897 INIT_LIST_HEAD(&info
->swaplist
);
2898 simple_xattrs_init(&info
->xattrs
);
2899 cache_no_acl(inode
);
2901 mapping_set_unevictable(inode
->i_mapping
);
2903 /* Don't consider 'deny' for emergencies and 'force' for testing */
2905 mapping_set_large_folios(inode
->i_mapping
);
2907 switch (mode
& S_IFMT
) {
2909 inode
->i_op
= &shmem_special_inode_operations
;
2910 init_special_inode(inode
, mode
, dev
);
2913 inode
->i_mapping
->a_ops
= &shmem_aops
;
2914 inode
->i_op
= &shmem_inode_operations
;
2915 inode
->i_fop
= &shmem_file_operations
;
2916 mpol_shared_policy_init(&info
->policy
,
2917 shmem_get_sbmpol(sbinfo
));
2921 /* Some things misbehave if size == 0 on a directory */
2922 inode
->i_size
= 2 * BOGO_DIRENT_SIZE
;
2923 inode
->i_op
= &shmem_dir_inode_operations
;
2924 inode
->i_fop
= &simple_offset_dir_operations
;
2925 simple_offset_init(shmem_get_offset_ctx(inode
));
2929 * Must not load anything in the rbtree,
2930 * mpol_free_shared_policy will not be called.
2932 mpol_shared_policy_init(&info
->policy
, NULL
);
2936 lockdep_annotate_inode_mutex_key(inode
);
2940 #ifdef CONFIG_TMPFS_QUOTA
2941 static struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
2942 struct super_block
*sb
, struct inode
*dir
,
2943 umode_t mode
, dev_t dev
, unsigned long flags
)
2946 struct inode
*inode
;
2948 inode
= __shmem_get_inode(idmap
, sb
, dir
, mode
, dev
, flags
);
2952 err
= dquot_initialize(inode
);
2956 err
= dquot_alloc_inode(inode
);
2964 inode
->i_flags
|= S_NOQUOTA
;
2966 return ERR_PTR(err
);
2969 static inline struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
2970 struct super_block
*sb
, struct inode
*dir
,
2971 umode_t mode
, dev_t dev
, unsigned long flags
)
2973 return __shmem_get_inode(idmap
, sb
, dir
, mode
, dev
, flags
);
2975 #endif /* CONFIG_TMPFS_QUOTA */
2977 #ifdef CONFIG_USERFAULTFD
2978 int shmem_mfill_atomic_pte(pmd_t
*dst_pmd
,
2979 struct vm_area_struct
*dst_vma
,
2980 unsigned long dst_addr
,
2981 unsigned long src_addr
,
2983 struct folio
**foliop
)
2985 struct inode
*inode
= file_inode(dst_vma
->vm_file
);
2986 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2987 struct address_space
*mapping
= inode
->i_mapping
;
2988 gfp_t gfp
= mapping_gfp_mask(mapping
);
2989 pgoff_t pgoff
= linear_page_index(dst_vma
, dst_addr
);
2991 struct folio
*folio
;
2995 if (shmem_inode_acct_blocks(inode
, 1)) {
2997 * We may have got a page, returned -ENOENT triggering a retry,
2998 * and now we find ourselves with -ENOMEM. Release the page, to
2999 * avoid a BUG_ON in our caller.
3001 if (unlikely(*foliop
)) {
3010 folio
= shmem_alloc_folio(gfp
, 0, info
, pgoff
);
3012 goto out_unacct_blocks
;
3014 if (uffd_flags_mode_is(flags
, MFILL_ATOMIC_COPY
)) {
3015 page_kaddr
= kmap_local_folio(folio
, 0);
3017 * The read mmap_lock is held here. Despite the
3018 * mmap_lock being read recursive a deadlock is still
3019 * possible if a writer has taken a lock. For example:
3021 * process A thread 1 takes read lock on own mmap_lock
3022 * process A thread 2 calls mmap, blocks taking write lock
3023 * process B thread 1 takes page fault, read lock on own mmap lock
3024 * process B thread 2 calls mmap, blocks taking write lock
3025 * process A thread 1 blocks taking read lock on process B
3026 * process B thread 1 blocks taking read lock on process A
3028 * Disable page faults to prevent potential deadlock
3029 * and retry the copy outside the mmap_lock.
3031 pagefault_disable();
3032 ret
= copy_from_user(page_kaddr
,
3033 (const void __user
*)src_addr
,
3036 kunmap_local(page_kaddr
);
3038 /* fallback to copy_from_user outside mmap_lock */
3039 if (unlikely(ret
)) {
3042 /* don't free the page */
3043 goto out_unacct_blocks
;
3046 flush_dcache_folio(folio
);
3047 } else { /* ZEROPAGE */
3048 clear_user_highpage(&folio
->page
, dst_addr
);
3052 VM_BUG_ON_FOLIO(folio_test_large(folio
), folio
);
3056 VM_BUG_ON(folio_test_locked(folio
));
3057 VM_BUG_ON(folio_test_swapbacked(folio
));
3058 __folio_set_locked(folio
);
3059 __folio_set_swapbacked(folio
);
3060 __folio_mark_uptodate(folio
);
3063 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
3064 if (unlikely(pgoff
>= max_off
))
3067 ret
= mem_cgroup_charge(folio
, dst_vma
->vm_mm
, gfp
);
3070 ret
= shmem_add_to_page_cache(folio
, mapping
, pgoff
, NULL
, gfp
);
3074 ret
= mfill_atomic_install_pte(dst_pmd
, dst_vma
, dst_addr
,
3075 &folio
->page
, true, flags
);
3077 goto out_delete_from_cache
;
3079 shmem_recalc_inode(inode
, 1, 0);
3080 folio_unlock(folio
);
3082 out_delete_from_cache
:
3083 filemap_remove_folio(folio
);
3085 folio_unlock(folio
);
3088 shmem_inode_unacct_blocks(inode
, 1);
3091 #endif /* CONFIG_USERFAULTFD */
3094 static const struct inode_operations shmem_symlink_inode_operations
;
3095 static const struct inode_operations shmem_short_symlink_operations
;
3098 shmem_write_begin(struct file
*file
, struct address_space
*mapping
,
3099 loff_t pos
, unsigned len
,
3100 struct folio
**foliop
, void **fsdata
)
3102 struct inode
*inode
= mapping
->host
;
3103 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3104 pgoff_t index
= pos
>> PAGE_SHIFT
;
3105 struct folio
*folio
;
3108 /* i_rwsem is held by caller */
3109 if (unlikely(info
->seals
& (F_SEAL_GROW
|
3110 F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
))) {
3111 if (info
->seals
& (F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
))
3113 if ((info
->seals
& F_SEAL_GROW
) && pos
+ len
> inode
->i_size
)
3117 ret
= shmem_get_folio(inode
, index
, pos
+ len
, &folio
, SGP_WRITE
);
3121 if (folio_test_hwpoison(folio
) ||
3122 (folio_test_large(folio
) && folio_test_has_hwpoisoned(folio
))) {
3123 folio_unlock(folio
);
3133 shmem_write_end(struct file
*file
, struct address_space
*mapping
,
3134 loff_t pos
, unsigned len
, unsigned copied
,
3135 struct folio
*folio
, void *fsdata
)
3137 struct inode
*inode
= mapping
->host
;
3139 if (pos
+ copied
> inode
->i_size
)
3140 i_size_write(inode
, pos
+ copied
);
3142 if (!folio_test_uptodate(folio
)) {
3143 if (copied
< folio_size(folio
)) {
3144 size_t from
= offset_in_folio(folio
, pos
);
3145 folio_zero_segments(folio
, 0, from
,
3146 from
+ copied
, folio_size(folio
));
3148 folio_mark_uptodate(folio
);
3150 folio_mark_dirty(folio
);
3151 folio_unlock(folio
);
3157 static ssize_t
shmem_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*to
)
3159 struct file
*file
= iocb
->ki_filp
;
3160 struct inode
*inode
= file_inode(file
);
3161 struct address_space
*mapping
= inode
->i_mapping
;
3163 unsigned long offset
;
3168 struct folio
*folio
= NULL
;
3169 struct page
*page
= NULL
;
3170 unsigned long nr
, ret
;
3171 loff_t end_offset
, i_size
= i_size_read(inode
);
3172 bool fallback_page_copy
= false;
3175 if (unlikely(iocb
->ki_pos
>= i_size
))
3178 index
= iocb
->ki_pos
>> PAGE_SHIFT
;
3179 error
= shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
3181 if (error
== -EINVAL
)
3186 folio_unlock(folio
);
3188 page
= folio_file_page(folio
, index
);
3189 if (PageHWPoison(page
)) {
3195 if (folio_test_large(folio
) &&
3196 folio_test_has_hwpoisoned(folio
))
3197 fallback_page_copy
= true;
3201 * We must evaluate after, since reads (unlike writes)
3202 * are called without i_rwsem protection against truncate
3204 i_size
= i_size_read(inode
);
3205 if (unlikely(iocb
->ki_pos
>= i_size
)) {
3210 end_offset
= min_t(loff_t
, i_size
, iocb
->ki_pos
+ to
->count
);
3211 if (folio
&& likely(!fallback_page_copy
))
3212 fsize
= folio_size(folio
);
3215 offset
= iocb
->ki_pos
& (fsize
- 1);
3216 nr
= min_t(loff_t
, end_offset
- iocb
->ki_pos
, fsize
- offset
);
3220 * If users can be writing to this page using arbitrary
3221 * virtual addresses, take care about potential aliasing
3222 * before reading the page on the kernel side.
3224 if (mapping_writably_mapped(mapping
)) {
3225 if (likely(!fallback_page_copy
))
3226 flush_dcache_folio(folio
);
3228 flush_dcache_page(page
);
3232 * Mark the folio accessed if we read the beginning.
3235 folio_mark_accessed(folio
);
3237 * Ok, we have the page, and it's up-to-date, so
3238 * now we can copy it to user space...
3240 if (likely(!fallback_page_copy
))
3241 ret
= copy_folio_to_iter(folio
, offset
, nr
, to
);
3243 ret
= copy_page_to_iter(page
, offset
, nr
, to
);
3245 } else if (user_backed_iter(to
)) {
3247 * Copy to user tends to be so well optimized, but
3248 * clear_user() not so much, that it is noticeably
3249 * faster to copy the zero page instead of clearing.
3251 ret
= copy_page_to_iter(ZERO_PAGE(0), offset
, nr
, to
);
3254 * But submitting the same page twice in a row to
3255 * splice() - or others? - can result in confusion:
3256 * so don't attempt that optimization on pipes etc.
3258 ret
= iov_iter_zero(nr
, to
);
3262 iocb
->ki_pos
+= ret
;
3264 if (!iov_iter_count(to
))
3273 file_accessed(file
);
3274 return retval
? retval
: error
;
3277 static ssize_t
shmem_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
3279 struct file
*file
= iocb
->ki_filp
;
3280 struct inode
*inode
= file
->f_mapping
->host
;
3284 ret
= generic_write_checks(iocb
, from
);
3287 ret
= file_remove_privs(file
);
3290 ret
= file_update_time(file
);
3293 ret
= generic_perform_write(iocb
, from
);
3295 inode_unlock(inode
);
3299 static bool zero_pipe_buf_get(struct pipe_inode_info
*pipe
,
3300 struct pipe_buffer
*buf
)
3305 static void zero_pipe_buf_release(struct pipe_inode_info
*pipe
,
3306 struct pipe_buffer
*buf
)
3310 static bool zero_pipe_buf_try_steal(struct pipe_inode_info
*pipe
,
3311 struct pipe_buffer
*buf
)
3316 static const struct pipe_buf_operations zero_pipe_buf_ops
= {
3317 .release
= zero_pipe_buf_release
,
3318 .try_steal
= zero_pipe_buf_try_steal
,
3319 .get
= zero_pipe_buf_get
,
3322 static size_t splice_zeropage_into_pipe(struct pipe_inode_info
*pipe
,
3323 loff_t fpos
, size_t size
)
3325 size_t offset
= fpos
& ~PAGE_MASK
;
3327 size
= min_t(size_t, size
, PAGE_SIZE
- offset
);
3329 if (!pipe_full(pipe
->head
, pipe
->tail
, pipe
->max_usage
)) {
3330 struct pipe_buffer
*buf
= pipe_head_buf(pipe
);
3332 *buf
= (struct pipe_buffer
) {
3333 .ops
= &zero_pipe_buf_ops
,
3334 .page
= ZERO_PAGE(0),
3344 static ssize_t
shmem_file_splice_read(struct file
*in
, loff_t
*ppos
,
3345 struct pipe_inode_info
*pipe
,
3346 size_t len
, unsigned int flags
)
3348 struct inode
*inode
= file_inode(in
);
3349 struct address_space
*mapping
= inode
->i_mapping
;
3350 struct folio
*folio
= NULL
;
3351 size_t total_spliced
= 0, used
, npages
, n
, part
;
3355 /* Work out how much data we can actually add into the pipe */
3356 used
= pipe_occupancy(pipe
->head
, pipe
->tail
);
3357 npages
= max_t(ssize_t
, pipe
->max_usage
- used
, 0);
3358 len
= min_t(size_t, len
, npages
* PAGE_SIZE
);
3361 bool fallback_page_splice
= false;
3362 struct page
*page
= NULL
;
3366 if (*ppos
>= i_size_read(inode
))
3369 index
= *ppos
>> PAGE_SHIFT
;
3370 error
= shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
3372 if (error
== -EINVAL
)
3377 folio_unlock(folio
);
3379 page
= folio_file_page(folio
, index
);
3380 if (PageHWPoison(page
)) {
3385 if (folio_test_large(folio
) &&
3386 folio_test_has_hwpoisoned(folio
))
3387 fallback_page_splice
= true;
3391 * i_size must be checked after we know the pages are Uptodate.
3393 * Checking i_size after the check allows us to calculate
3394 * the correct value for "nr", which means the zero-filled
3395 * part of the page is not copied back to userspace (unless
3396 * another truncate extends the file - this is desired though).
3398 isize
= i_size_read(inode
);
3399 if (unlikely(*ppos
>= isize
))
3402 * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned
3406 if (unlikely(fallback_page_splice
)) {
3407 size_t offset
= *ppos
& ~PAGE_MASK
;
3409 size
= umin(size
, PAGE_SIZE
- offset
);
3411 part
= min_t(loff_t
, isize
- *ppos
, size
);
3415 * If users can be writing to this page using arbitrary
3416 * virtual addresses, take care about potential aliasing
3417 * before reading the page on the kernel side.
3419 if (mapping_writably_mapped(mapping
)) {
3420 if (likely(!fallback_page_splice
))
3421 flush_dcache_folio(folio
);
3423 flush_dcache_page(page
);
3425 folio_mark_accessed(folio
);
3427 * Ok, we have the page, and it's up-to-date, so we can
3428 * now splice it into the pipe.
3430 n
= splice_folio_into_pipe(pipe
, folio
, *ppos
, part
);
3434 n
= splice_zeropage_into_pipe(pipe
, *ppos
, part
);
3442 in
->f_ra
.prev_pos
= *ppos
;
3443 if (pipe_full(pipe
->head
, pipe
->tail
, pipe
->max_usage
))
3453 return total_spliced
? total_spliced
: error
;
3456 static loff_t
shmem_file_llseek(struct file
*file
, loff_t offset
, int whence
)
3458 struct address_space
*mapping
= file
->f_mapping
;
3459 struct inode
*inode
= mapping
->host
;
3461 if (whence
!= SEEK_DATA
&& whence
!= SEEK_HOLE
)
3462 return generic_file_llseek_size(file
, offset
, whence
,
3463 MAX_LFS_FILESIZE
, i_size_read(inode
));
3468 /* We're holding i_rwsem so we can access i_size directly */
3469 offset
= mapping_seek_hole_data(mapping
, offset
, inode
->i_size
, whence
);
3471 offset
= vfs_setpos(file
, offset
, MAX_LFS_FILESIZE
);
3472 inode_unlock(inode
);
3476 static long shmem_fallocate(struct file
*file
, int mode
, loff_t offset
,
3479 struct inode
*inode
= file_inode(file
);
3480 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
3481 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3482 struct shmem_falloc shmem_falloc
;
3483 pgoff_t start
, index
, end
, undo_fallocend
;
3486 if (mode
& ~(FALLOC_FL_KEEP_SIZE
| FALLOC_FL_PUNCH_HOLE
))
3491 if (mode
& FALLOC_FL_PUNCH_HOLE
) {
3492 struct address_space
*mapping
= file
->f_mapping
;
3493 loff_t unmap_start
= round_up(offset
, PAGE_SIZE
);
3494 loff_t unmap_end
= round_down(offset
+ len
, PAGE_SIZE
) - 1;
3495 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq
);
3497 /* protected by i_rwsem */
3498 if (info
->seals
& (F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
)) {
3503 shmem_falloc
.waitq
= &shmem_falloc_waitq
;
3504 shmem_falloc
.start
= (u64
)unmap_start
>> PAGE_SHIFT
;
3505 shmem_falloc
.next
= (unmap_end
+ 1) >> PAGE_SHIFT
;
3506 spin_lock(&inode
->i_lock
);
3507 inode
->i_private
= &shmem_falloc
;
3508 spin_unlock(&inode
->i_lock
);
3510 if ((u64
)unmap_end
> (u64
)unmap_start
)
3511 unmap_mapping_range(mapping
, unmap_start
,
3512 1 + unmap_end
- unmap_start
, 0);
3513 shmem_truncate_range(inode
, offset
, offset
+ len
- 1);
3514 /* No need to unmap again: hole-punching leaves COWed pages */
3516 spin_lock(&inode
->i_lock
);
3517 inode
->i_private
= NULL
;
3518 wake_up_all(&shmem_falloc_waitq
);
3519 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq
.head
));
3520 spin_unlock(&inode
->i_lock
);
3525 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
3526 error
= inode_newsize_ok(inode
, offset
+ len
);
3530 if ((info
->seals
& F_SEAL_GROW
) && offset
+ len
> inode
->i_size
) {
3535 start
= offset
>> PAGE_SHIFT
;
3536 end
= (offset
+ len
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
3537 /* Try to avoid a swapstorm if len is impossible to satisfy */
3538 if (sbinfo
->max_blocks
&& end
- start
> sbinfo
->max_blocks
) {
3543 shmem_falloc
.waitq
= NULL
;
3544 shmem_falloc
.start
= start
;
3545 shmem_falloc
.next
= start
;
3546 shmem_falloc
.nr_falloced
= 0;
3547 shmem_falloc
.nr_unswapped
= 0;
3548 spin_lock(&inode
->i_lock
);
3549 inode
->i_private
= &shmem_falloc
;
3550 spin_unlock(&inode
->i_lock
);
3553 * info->fallocend is only relevant when huge pages might be
3554 * involved: to prevent split_huge_page() freeing fallocated
3555 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
3557 undo_fallocend
= info
->fallocend
;
3558 if (info
->fallocend
< end
)
3559 info
->fallocend
= end
;
3561 for (index
= start
; index
< end
; ) {
3562 struct folio
*folio
;
3565 * Check for fatal signal so that we abort early in OOM
3566 * situations. We don't want to abort in case of non-fatal
3567 * signals as large fallocate can take noticeable time and
3568 * e.g. periodic timers may result in fallocate constantly
3571 if (fatal_signal_pending(current
))
3573 else if (shmem_falloc
.nr_unswapped
> shmem_falloc
.nr_falloced
)
3576 error
= shmem_get_folio(inode
, index
, offset
+ len
,
3577 &folio
, SGP_FALLOC
);
3579 info
->fallocend
= undo_fallocend
;
3580 /* Remove the !uptodate folios we added */
3581 if (index
> start
) {
3582 shmem_undo_range(inode
,
3583 (loff_t
)start
<< PAGE_SHIFT
,
3584 ((loff_t
)index
<< PAGE_SHIFT
) - 1, true);
3590 * Here is a more important optimization than it appears:
3591 * a second SGP_FALLOC on the same large folio will clear it,
3592 * making it uptodate and un-undoable if we fail later.
3594 index
= folio_next_index(folio
);
3595 /* Beware 32-bit wraparound */
3600 * Inform shmem_writepage() how far we have reached.
3601 * No need for lock or barrier: we have the page lock.
3603 if (!folio_test_uptodate(folio
))
3604 shmem_falloc
.nr_falloced
+= index
- shmem_falloc
.next
;
3605 shmem_falloc
.next
= index
;
3608 * If !uptodate, leave it that way so that freeable folios
3609 * can be recognized if we need to rollback on error later.
3610 * But mark it dirty so that memory pressure will swap rather
3611 * than free the folios we are allocating (and SGP_CACHE folios
3612 * might still be clean: we now need to mark those dirty too).
3614 folio_mark_dirty(folio
);
3615 folio_unlock(folio
);
3620 if (!(mode
& FALLOC_FL_KEEP_SIZE
) && offset
+ len
> inode
->i_size
)
3621 i_size_write(inode
, offset
+ len
);
3623 spin_lock(&inode
->i_lock
);
3624 inode
->i_private
= NULL
;
3625 spin_unlock(&inode
->i_lock
);
3628 file_modified(file
);
3629 inode_unlock(inode
);
3633 static int shmem_statfs(struct dentry
*dentry
, struct kstatfs
*buf
)
3635 struct shmem_sb_info
*sbinfo
= SHMEM_SB(dentry
->d_sb
);
3637 buf
->f_type
= TMPFS_MAGIC
;
3638 buf
->f_bsize
= PAGE_SIZE
;
3639 buf
->f_namelen
= NAME_MAX
;
3640 if (sbinfo
->max_blocks
) {
3641 buf
->f_blocks
= sbinfo
->max_blocks
;
3643 buf
->f_bfree
= sbinfo
->max_blocks
-
3644 percpu_counter_sum(&sbinfo
->used_blocks
);
3646 if (sbinfo
->max_inodes
) {
3647 buf
->f_files
= sbinfo
->max_inodes
;
3648 buf
->f_ffree
= sbinfo
->free_ispace
/ BOGO_INODE_SIZE
;
3650 /* else leave those fields 0 like simple_statfs */
3652 buf
->f_fsid
= uuid_to_fsid(dentry
->d_sb
->s_uuid
.b
);
3658 * File creation. Allocate an inode, and we're done..
3661 shmem_mknod(struct mnt_idmap
*idmap
, struct inode
*dir
,
3662 struct dentry
*dentry
, umode_t mode
, dev_t dev
)
3664 struct inode
*inode
;
3667 if (!generic_ci_validate_strict_name(dir
, &dentry
->d_name
))
3670 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, mode
, dev
, VM_NORESERVE
);
3672 return PTR_ERR(inode
);
3674 error
= simple_acl_create(dir
, inode
);
3677 error
= security_inode_init_security(inode
, dir
, &dentry
->d_name
,
3678 shmem_initxattrs
, NULL
);
3679 if (error
&& error
!= -EOPNOTSUPP
)
3682 error
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3686 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3687 inode_set_mtime_to_ts(dir
, inode_set_ctime_current(dir
));
3688 inode_inc_iversion(dir
);
3690 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3691 d_add(dentry
, inode
);
3693 d_instantiate(dentry
, inode
);
3695 dget(dentry
); /* Extra count - pin the dentry in core */
3704 shmem_tmpfile(struct mnt_idmap
*idmap
, struct inode
*dir
,
3705 struct file
*file
, umode_t mode
)
3707 struct inode
*inode
;
3710 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, mode
, 0, VM_NORESERVE
);
3711 if (IS_ERR(inode
)) {
3712 error
= PTR_ERR(inode
);
3715 error
= security_inode_init_security(inode
, dir
, NULL
,
3716 shmem_initxattrs
, NULL
);
3717 if (error
&& error
!= -EOPNOTSUPP
)
3719 error
= simple_acl_create(dir
, inode
);
3722 d_tmpfile(file
, inode
);
3725 return finish_open_simple(file
, error
);
3731 static int shmem_mkdir(struct mnt_idmap
*idmap
, struct inode
*dir
,
3732 struct dentry
*dentry
, umode_t mode
)
3736 error
= shmem_mknod(idmap
, dir
, dentry
, mode
| S_IFDIR
, 0);
3743 static int shmem_create(struct mnt_idmap
*idmap
, struct inode
*dir
,
3744 struct dentry
*dentry
, umode_t mode
, bool excl
)
3746 return shmem_mknod(idmap
, dir
, dentry
, mode
| S_IFREG
, 0);
3752 static int shmem_link(struct dentry
*old_dentry
, struct inode
*dir
,
3753 struct dentry
*dentry
)
3755 struct inode
*inode
= d_inode(old_dentry
);
3759 * No ordinary (disk based) filesystem counts links as inodes;
3760 * but each new link needs a new dentry, pinning lowmem, and
3761 * tmpfs dentries cannot be pruned until they are unlinked.
3762 * But if an O_TMPFILE file is linked into the tmpfs, the
3763 * first link must skip that, to get the accounting right.
3765 if (inode
->i_nlink
) {
3766 ret
= shmem_reserve_inode(inode
->i_sb
, NULL
);
3771 ret
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3774 shmem_free_inode(inode
->i_sb
, 0);
3778 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3779 inode_set_mtime_to_ts(dir
,
3780 inode_set_ctime_to_ts(dir
, inode_set_ctime_current(inode
)));
3781 inode_inc_iversion(dir
);
3783 ihold(inode
); /* New dentry reference */
3784 dget(dentry
); /* Extra pinning count for the created dentry */
3785 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3786 d_add(dentry
, inode
);
3788 d_instantiate(dentry
, inode
);
3793 static int shmem_unlink(struct inode
*dir
, struct dentry
*dentry
)
3795 struct inode
*inode
= d_inode(dentry
);
3797 if (inode
->i_nlink
> 1 && !S_ISDIR(inode
->i_mode
))
3798 shmem_free_inode(inode
->i_sb
, 0);
3800 simple_offset_remove(shmem_get_offset_ctx(dir
), dentry
);
3802 dir
->i_size
-= BOGO_DIRENT_SIZE
;
3803 inode_set_mtime_to_ts(dir
,
3804 inode_set_ctime_to_ts(dir
, inode_set_ctime_current(inode
)));
3805 inode_inc_iversion(dir
);
3807 dput(dentry
); /* Undo the count from "create" - does all the work */
3810 * For now, VFS can't deal with case-insensitive negative dentries, so
3811 * we invalidate them
3813 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3814 d_invalidate(dentry
);
3819 static int shmem_rmdir(struct inode
*dir
, struct dentry
*dentry
)
3821 if (!simple_offset_empty(dentry
))
3824 drop_nlink(d_inode(dentry
));
3826 return shmem_unlink(dir
, dentry
);
3829 static int shmem_whiteout(struct mnt_idmap
*idmap
,
3830 struct inode
*old_dir
, struct dentry
*old_dentry
)
3832 struct dentry
*whiteout
;
3835 whiteout
= d_alloc(old_dentry
->d_parent
, &old_dentry
->d_name
);
3839 error
= shmem_mknod(idmap
, old_dir
, whiteout
,
3840 S_IFCHR
| WHITEOUT_MODE
, WHITEOUT_DEV
);
3846 * Cheat and hash the whiteout while the old dentry is still in
3847 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3849 * d_lookup() will consistently find one of them at this point,
3850 * not sure which one, but that isn't even important.
3857 * The VFS layer already does all the dentry stuff for rename,
3858 * we just have to decrement the usage count for the target if
3859 * it exists so that the VFS layer correctly free's it when it
3862 static int shmem_rename2(struct mnt_idmap
*idmap
,
3863 struct inode
*old_dir
, struct dentry
*old_dentry
,
3864 struct inode
*new_dir
, struct dentry
*new_dentry
,
3867 struct inode
*inode
= d_inode(old_dentry
);
3868 int they_are_dirs
= S_ISDIR(inode
->i_mode
);
3871 if (flags
& ~(RENAME_NOREPLACE
| RENAME_EXCHANGE
| RENAME_WHITEOUT
))
3874 if (flags
& RENAME_EXCHANGE
)
3875 return simple_offset_rename_exchange(old_dir
, old_dentry
,
3876 new_dir
, new_dentry
);
3878 if (!simple_offset_empty(new_dentry
))
3881 if (flags
& RENAME_WHITEOUT
) {
3882 error
= shmem_whiteout(idmap
, old_dir
, old_dentry
);
3887 error
= simple_offset_rename(old_dir
, old_dentry
, new_dir
, new_dentry
);
3891 if (d_really_is_positive(new_dentry
)) {
3892 (void) shmem_unlink(new_dir
, new_dentry
);
3893 if (they_are_dirs
) {
3894 drop_nlink(d_inode(new_dentry
));
3895 drop_nlink(old_dir
);
3897 } else if (they_are_dirs
) {
3898 drop_nlink(old_dir
);
3902 old_dir
->i_size
-= BOGO_DIRENT_SIZE
;
3903 new_dir
->i_size
+= BOGO_DIRENT_SIZE
;
3904 simple_rename_timestamp(old_dir
, old_dentry
, new_dir
, new_dentry
);
3905 inode_inc_iversion(old_dir
);
3906 inode_inc_iversion(new_dir
);
3910 static int shmem_symlink(struct mnt_idmap
*idmap
, struct inode
*dir
,
3911 struct dentry
*dentry
, const char *symname
)
3915 struct inode
*inode
;
3916 struct folio
*folio
;
3918 len
= strlen(symname
) + 1;
3919 if (len
> PAGE_SIZE
)
3920 return -ENAMETOOLONG
;
3922 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, S_IFLNK
| 0777, 0,
3925 return PTR_ERR(inode
);
3927 error
= security_inode_init_security(inode
, dir
, &dentry
->d_name
,
3928 shmem_initxattrs
, NULL
);
3929 if (error
&& error
!= -EOPNOTSUPP
)
3932 error
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3936 inode
->i_size
= len
-1;
3937 if (len
<= SHORT_SYMLINK_LEN
) {
3938 inode
->i_link
= kmemdup(symname
, len
, GFP_KERNEL
);
3939 if (!inode
->i_link
) {
3941 goto out_remove_offset
;
3943 inode
->i_op
= &shmem_short_symlink_operations
;
3945 inode_nohighmem(inode
);
3946 inode
->i_mapping
->a_ops
= &shmem_aops
;
3947 error
= shmem_get_folio(inode
, 0, 0, &folio
, SGP_WRITE
);
3949 goto out_remove_offset
;
3950 inode
->i_op
= &shmem_symlink_inode_operations
;
3951 memcpy(folio_address(folio
), symname
, len
);
3952 folio_mark_uptodate(folio
);
3953 folio_mark_dirty(folio
);
3954 folio_unlock(folio
);
3957 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3958 inode_set_mtime_to_ts(dir
, inode_set_ctime_current(dir
));
3959 inode_inc_iversion(dir
);
3960 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3961 d_add(dentry
, inode
);
3963 d_instantiate(dentry
, inode
);
3968 simple_offset_remove(shmem_get_offset_ctx(dir
), dentry
);
3974 static void shmem_put_link(void *arg
)
3976 folio_mark_accessed(arg
);
3980 static const char *shmem_get_link(struct dentry
*dentry
, struct inode
*inode
,
3981 struct delayed_call
*done
)
3983 struct folio
*folio
= NULL
;
3987 folio
= filemap_get_folio(inode
->i_mapping
, 0);
3989 return ERR_PTR(-ECHILD
);
3990 if (PageHWPoison(folio_page(folio
, 0)) ||
3991 !folio_test_uptodate(folio
)) {
3993 return ERR_PTR(-ECHILD
);
3996 error
= shmem_get_folio(inode
, 0, 0, &folio
, SGP_READ
);
3998 return ERR_PTR(error
);
4000 return ERR_PTR(-ECHILD
);
4001 if (PageHWPoison(folio_page(folio
, 0))) {
4002 folio_unlock(folio
);
4004 return ERR_PTR(-ECHILD
);
4006 folio_unlock(folio
);
4008 set_delayed_call(done
, shmem_put_link
, folio
);
4009 return folio_address(folio
);
4012 #ifdef CONFIG_TMPFS_XATTR
4014 static int shmem_fileattr_get(struct dentry
*dentry
, struct fileattr
*fa
)
4016 struct shmem_inode_info
*info
= SHMEM_I(d_inode(dentry
));
4018 fileattr_fill_flags(fa
, info
->fsflags
& SHMEM_FL_USER_VISIBLE
);
4023 static int shmem_fileattr_set(struct mnt_idmap
*idmap
,
4024 struct dentry
*dentry
, struct fileattr
*fa
)
4026 struct inode
*inode
= d_inode(dentry
);
4027 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4030 if (fileattr_has_fsx(fa
))
4032 if (fa
->flags
& ~SHMEM_FL_USER_MODIFIABLE
)
4035 flags
= (info
->fsflags
& ~SHMEM_FL_USER_MODIFIABLE
) |
4036 (fa
->flags
& SHMEM_FL_USER_MODIFIABLE
);
4038 ret
= shmem_set_inode_flags(inode
, flags
, dentry
);
4043 info
->fsflags
= flags
;
4045 inode_set_ctime_current(inode
);
4046 inode_inc_iversion(inode
);
4051 * Superblocks without xattr inode operations may get some security.* xattr
4052 * support from the LSM "for free". As soon as we have any other xattrs
4053 * like ACLs, we also need to implement the security.* handlers at
4054 * filesystem level, though.
4058 * Callback for security_inode_init_security() for acquiring xattrs.
4060 static int shmem_initxattrs(struct inode
*inode
,
4061 const struct xattr
*xattr_array
, void *fs_info
)
4063 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4064 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
4065 const struct xattr
*xattr
;
4066 struct simple_xattr
*new_xattr
;
4070 if (sbinfo
->max_inodes
) {
4071 for (xattr
= xattr_array
; xattr
->name
!= NULL
; xattr
++) {
4072 ispace
+= simple_xattr_space(xattr
->name
,
4073 xattr
->value_len
+ XATTR_SECURITY_PREFIX_LEN
);
4076 raw_spin_lock(&sbinfo
->stat_lock
);
4077 if (sbinfo
->free_ispace
< ispace
)
4080 sbinfo
->free_ispace
-= ispace
;
4081 raw_spin_unlock(&sbinfo
->stat_lock
);
4087 for (xattr
= xattr_array
; xattr
->name
!= NULL
; xattr
++) {
4088 new_xattr
= simple_xattr_alloc(xattr
->value
, xattr
->value_len
);
4092 len
= strlen(xattr
->name
) + 1;
4093 new_xattr
->name
= kmalloc(XATTR_SECURITY_PREFIX_LEN
+ len
,
4094 GFP_KERNEL_ACCOUNT
);
4095 if (!new_xattr
->name
) {
4100 memcpy(new_xattr
->name
, XATTR_SECURITY_PREFIX
,
4101 XATTR_SECURITY_PREFIX_LEN
);
4102 memcpy(new_xattr
->name
+ XATTR_SECURITY_PREFIX_LEN
,
4105 simple_xattr_add(&info
->xattrs
, new_xattr
);
4108 if (xattr
->name
!= NULL
) {
4110 raw_spin_lock(&sbinfo
->stat_lock
);
4111 sbinfo
->free_ispace
+= ispace
;
4112 raw_spin_unlock(&sbinfo
->stat_lock
);
4114 simple_xattrs_free(&info
->xattrs
, NULL
);
4121 static int shmem_xattr_handler_get(const struct xattr_handler
*handler
,
4122 struct dentry
*unused
, struct inode
*inode
,
4123 const char *name
, void *buffer
, size_t size
)
4125 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4127 name
= xattr_full_name(handler
, name
);
4128 return simple_xattr_get(&info
->xattrs
, name
, buffer
, size
);
4131 static int shmem_xattr_handler_set(const struct xattr_handler
*handler
,
4132 struct mnt_idmap
*idmap
,
4133 struct dentry
*unused
, struct inode
*inode
,
4134 const char *name
, const void *value
,
4135 size_t size
, int flags
)
4137 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4138 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
4139 struct simple_xattr
*old_xattr
;
4142 name
= xattr_full_name(handler
, name
);
4143 if (value
&& sbinfo
->max_inodes
) {
4144 ispace
= simple_xattr_space(name
, size
);
4145 raw_spin_lock(&sbinfo
->stat_lock
);
4146 if (sbinfo
->free_ispace
< ispace
)
4149 sbinfo
->free_ispace
-= ispace
;
4150 raw_spin_unlock(&sbinfo
->stat_lock
);
4155 old_xattr
= simple_xattr_set(&info
->xattrs
, name
, value
, size
, flags
);
4156 if (!IS_ERR(old_xattr
)) {
4158 if (old_xattr
&& sbinfo
->max_inodes
)
4159 ispace
= simple_xattr_space(old_xattr
->name
,
4161 simple_xattr_free(old_xattr
);
4163 inode_set_ctime_current(inode
);
4164 inode_inc_iversion(inode
);
4167 raw_spin_lock(&sbinfo
->stat_lock
);
4168 sbinfo
->free_ispace
+= ispace
;
4169 raw_spin_unlock(&sbinfo
->stat_lock
);
4171 return PTR_ERR(old_xattr
);
4174 static const struct xattr_handler shmem_security_xattr_handler
= {
4175 .prefix
= XATTR_SECURITY_PREFIX
,
4176 .get
= shmem_xattr_handler_get
,
4177 .set
= shmem_xattr_handler_set
,
4180 static const struct xattr_handler shmem_trusted_xattr_handler
= {
4181 .prefix
= XATTR_TRUSTED_PREFIX
,
4182 .get
= shmem_xattr_handler_get
,
4183 .set
= shmem_xattr_handler_set
,
4186 static const struct xattr_handler shmem_user_xattr_handler
= {
4187 .prefix
= XATTR_USER_PREFIX
,
4188 .get
= shmem_xattr_handler_get
,
4189 .set
= shmem_xattr_handler_set
,
4192 static const struct xattr_handler
* const shmem_xattr_handlers
[] = {
4193 &shmem_security_xattr_handler
,
4194 &shmem_trusted_xattr_handler
,
4195 &shmem_user_xattr_handler
,
4199 static ssize_t
shmem_listxattr(struct dentry
*dentry
, char *buffer
, size_t size
)
4201 struct shmem_inode_info
*info
= SHMEM_I(d_inode(dentry
));
4202 return simple_xattr_list(d_inode(dentry
), &info
->xattrs
, buffer
, size
);
4204 #endif /* CONFIG_TMPFS_XATTR */
4206 static const struct inode_operations shmem_short_symlink_operations
= {
4207 .getattr
= shmem_getattr
,
4208 .setattr
= shmem_setattr
,
4209 .get_link
= simple_get_link
,
4210 #ifdef CONFIG_TMPFS_XATTR
4211 .listxattr
= shmem_listxattr
,
4215 static const struct inode_operations shmem_symlink_inode_operations
= {
4216 .getattr
= shmem_getattr
,
4217 .setattr
= shmem_setattr
,
4218 .get_link
= shmem_get_link
,
4219 #ifdef CONFIG_TMPFS_XATTR
4220 .listxattr
= shmem_listxattr
,
4224 static struct dentry
*shmem_get_parent(struct dentry
*child
)
4226 return ERR_PTR(-ESTALE
);
4229 static int shmem_match(struct inode
*ino
, void *vfh
)
4233 inum
= (inum
<< 32) | fh
[1];
4234 return ino
->i_ino
== inum
&& fh
[0] == ino
->i_generation
;
4237 /* Find any alias of inode, but prefer a hashed alias */
4238 static struct dentry
*shmem_find_alias(struct inode
*inode
)
4240 struct dentry
*alias
= d_find_alias(inode
);
4242 return alias
?: d_find_any_alias(inode
);
4245 static struct dentry
*shmem_fh_to_dentry(struct super_block
*sb
,
4246 struct fid
*fid
, int fh_len
, int fh_type
)
4248 struct inode
*inode
;
4249 struct dentry
*dentry
= NULL
;
4256 inum
= (inum
<< 32) | fid
->raw
[1];
4258 inode
= ilookup5(sb
, (unsigned long)(inum
+ fid
->raw
[0]),
4259 shmem_match
, fid
->raw
);
4261 dentry
= shmem_find_alias(inode
);
4268 static int shmem_encode_fh(struct inode
*inode
, __u32
*fh
, int *len
,
4269 struct inode
*parent
)
4273 return FILEID_INVALID
;
4276 if (inode_unhashed(inode
)) {
4277 /* Unfortunately insert_inode_hash is not idempotent,
4278 * so as we hash inodes here rather than at creation
4279 * time, we need a lock to ensure we only try
4282 static DEFINE_SPINLOCK(lock
);
4284 if (inode_unhashed(inode
))
4285 __insert_inode_hash(inode
,
4286 inode
->i_ino
+ inode
->i_generation
);
4290 fh
[0] = inode
->i_generation
;
4291 fh
[1] = inode
->i_ino
;
4292 fh
[2] = ((__u64
)inode
->i_ino
) >> 32;
4298 static const struct export_operations shmem_export_ops
= {
4299 .get_parent
= shmem_get_parent
,
4300 .encode_fh
= shmem_encode_fh
,
4301 .fh_to_dentry
= shmem_fh_to_dentry
,
4319 Opt_usrquota_block_hardlimit
,
4320 Opt_usrquota_inode_hardlimit
,
4321 Opt_grpquota_block_hardlimit
,
4322 Opt_grpquota_inode_hardlimit
,
4323 Opt_casefold_version
,
4325 Opt_strict_encoding
,
4328 static const struct constant_table shmem_param_enums_huge
[] = {
4329 {"never", SHMEM_HUGE_NEVER
},
4330 {"always", SHMEM_HUGE_ALWAYS
},
4331 {"within_size", SHMEM_HUGE_WITHIN_SIZE
},
4332 {"advise", SHMEM_HUGE_ADVISE
},
4336 const struct fs_parameter_spec shmem_fs_parameters
[] = {
4337 fsparam_gid ("gid", Opt_gid
),
4338 fsparam_enum ("huge", Opt_huge
, shmem_param_enums_huge
),
4339 fsparam_u32oct("mode", Opt_mode
),
4340 fsparam_string("mpol", Opt_mpol
),
4341 fsparam_string("nr_blocks", Opt_nr_blocks
),
4342 fsparam_string("nr_inodes", Opt_nr_inodes
),
4343 fsparam_string("size", Opt_size
),
4344 fsparam_uid ("uid", Opt_uid
),
4345 fsparam_flag ("inode32", Opt_inode32
),
4346 fsparam_flag ("inode64", Opt_inode64
),
4347 fsparam_flag ("noswap", Opt_noswap
),
4348 #ifdef CONFIG_TMPFS_QUOTA
4349 fsparam_flag ("quota", Opt_quota
),
4350 fsparam_flag ("usrquota", Opt_usrquota
),
4351 fsparam_flag ("grpquota", Opt_grpquota
),
4352 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit
),
4353 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit
),
4354 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit
),
4355 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit
),
4357 fsparam_string("casefold", Opt_casefold_version
),
4358 fsparam_flag ("casefold", Opt_casefold
),
4359 fsparam_flag ("strict_encoding", Opt_strict_encoding
),
4363 #if IS_ENABLED(CONFIG_UNICODE)
4364 static int shmem_parse_opt_casefold(struct fs_context
*fc
, struct fs_parameter
*param
,
4365 bool latest_version
)
4367 struct shmem_options
*ctx
= fc
->fs_private
;
4368 unsigned int version
= UTF8_LATEST
;
4369 struct unicode_map
*encoding
;
4370 char *version_str
= param
->string
+ 5;
4372 if (!latest_version
) {
4373 if (strncmp(param
->string
, "utf8-", 5))
4374 return invalfc(fc
, "Only UTF-8 encodings are supported "
4375 "in the format: utf8-<version number>");
4377 version
= utf8_parse_version(version_str
);
4379 return invalfc(fc
, "Invalid UTF-8 version: %s", version_str
);
4382 encoding
= utf8_load(version
);
4384 if (IS_ERR(encoding
)) {
4385 return invalfc(fc
, "Failed loading UTF-8 version: utf8-%u.%u.%u\n",
4386 unicode_major(version
), unicode_minor(version
),
4387 unicode_rev(version
));
4390 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n",
4391 unicode_major(version
), unicode_minor(version
), unicode_rev(version
));
4393 ctx
->encoding
= encoding
;
4398 static int shmem_parse_opt_casefold(struct fs_context
*fc
, struct fs_parameter
*param
,
4399 bool latest_version
)
4401 return invalfc(fc
, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4405 static int shmem_parse_one(struct fs_context
*fc
, struct fs_parameter
*param
)
4407 struct shmem_options
*ctx
= fc
->fs_private
;
4408 struct fs_parse_result result
;
4409 unsigned long long size
;
4415 opt
= fs_parse(fc
, shmem_fs_parameters
, param
, &result
);
4421 size
= memparse(param
->string
, &rest
);
4423 size
<<= PAGE_SHIFT
;
4424 size
*= totalram_pages();
4430 ctx
->blocks
= DIV_ROUND_UP(size
, PAGE_SIZE
);
4431 ctx
->seen
|= SHMEM_SEEN_BLOCKS
;
4434 ctx
->blocks
= memparse(param
->string
, &rest
);
4435 if (*rest
|| ctx
->blocks
> LONG_MAX
)
4437 ctx
->seen
|= SHMEM_SEEN_BLOCKS
;
4440 ctx
->inodes
= memparse(param
->string
, &rest
);
4441 if (*rest
|| ctx
->inodes
> ULONG_MAX
/ BOGO_INODE_SIZE
)
4443 ctx
->seen
|= SHMEM_SEEN_INODES
;
4446 ctx
->mode
= result
.uint_32
& 07777;
4452 * The requested uid must be representable in the
4453 * filesystem's idmapping.
4455 if (!kuid_has_mapping(fc
->user_ns
, kuid
))
4464 * The requested gid must be representable in the
4465 * filesystem's idmapping.
4467 if (!kgid_has_mapping(fc
->user_ns
, kgid
))
4473 ctx
->huge
= result
.uint_32
;
4474 if (ctx
->huge
!= SHMEM_HUGE_NEVER
&&
4475 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
) &&
4476 has_transparent_hugepage()))
4477 goto unsupported_parameter
;
4478 ctx
->seen
|= SHMEM_SEEN_HUGE
;
4481 if (IS_ENABLED(CONFIG_NUMA
)) {
4482 mpol_put(ctx
->mpol
);
4484 if (mpol_parse_str(param
->string
, &ctx
->mpol
))
4488 goto unsupported_parameter
;
4490 ctx
->full_inums
= false;
4491 ctx
->seen
|= SHMEM_SEEN_INUMS
;
4494 if (sizeof(ino_t
) < 8) {
4496 "Cannot use inode64 with <64bit inums in kernel\n");
4498 ctx
->full_inums
= true;
4499 ctx
->seen
|= SHMEM_SEEN_INUMS
;
4502 if ((fc
->user_ns
!= &init_user_ns
) || !capable(CAP_SYS_ADMIN
)) {
4504 "Turning off swap in unprivileged tmpfs mounts unsupported");
4507 ctx
->seen
|= SHMEM_SEEN_NOSWAP
;
4510 if (fc
->user_ns
!= &init_user_ns
)
4511 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4512 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4513 ctx
->quota_types
|= (QTYPE_MASK_USR
| QTYPE_MASK_GRP
);
4516 if (fc
->user_ns
!= &init_user_ns
)
4517 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4518 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4519 ctx
->quota_types
|= QTYPE_MASK_USR
;
4522 if (fc
->user_ns
!= &init_user_ns
)
4523 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4524 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4525 ctx
->quota_types
|= QTYPE_MASK_GRP
;
4527 case Opt_usrquota_block_hardlimit
:
4528 size
= memparse(param
->string
, &rest
);
4531 if (size
> SHMEM_QUOTA_MAX_SPC_LIMIT
)
4533 "User quota block hardlimit too large.");
4534 ctx
->qlimits
.usrquota_bhardlimit
= size
;
4536 case Opt_grpquota_block_hardlimit
:
4537 size
= memparse(param
->string
, &rest
);
4540 if (size
> SHMEM_QUOTA_MAX_SPC_LIMIT
)
4542 "Group quota block hardlimit too large.");
4543 ctx
->qlimits
.grpquota_bhardlimit
= size
;
4545 case Opt_usrquota_inode_hardlimit
:
4546 size
= memparse(param
->string
, &rest
);
4549 if (size
> SHMEM_QUOTA_MAX_INO_LIMIT
)
4551 "User quota inode hardlimit too large.");
4552 ctx
->qlimits
.usrquota_ihardlimit
= size
;
4554 case Opt_grpquota_inode_hardlimit
:
4555 size
= memparse(param
->string
, &rest
);
4558 if (size
> SHMEM_QUOTA_MAX_INO_LIMIT
)
4560 "Group quota inode hardlimit too large.");
4561 ctx
->qlimits
.grpquota_ihardlimit
= size
;
4563 case Opt_casefold_version
:
4564 return shmem_parse_opt_casefold(fc
, param
, false);
4566 return shmem_parse_opt_casefold(fc
, param
, true);
4567 case Opt_strict_encoding
:
4568 #if IS_ENABLED(CONFIG_UNICODE)
4569 ctx
->strict_encoding
= true;
4572 return invalfc(fc
, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4577 unsupported_parameter
:
4578 return invalfc(fc
, "Unsupported parameter '%s'", param
->key
);
4580 return invalfc(fc
, "Bad value for '%s'", param
->key
);
4583 static int shmem_parse_options(struct fs_context
*fc
, void *data
)
4585 char *options
= data
;
4588 int err
= security_sb_eat_lsm_opts(options
, &fc
->security
);
4593 while (options
!= NULL
) {
4594 char *this_char
= options
;
4597 * NUL-terminate this option: unfortunately,
4598 * mount options form a comma-separated list,
4599 * but mpol's nodelist may also contain commas.
4601 options
= strchr(options
, ',');
4602 if (options
== NULL
)
4605 if (!isdigit(*options
)) {
4611 char *value
= strchr(this_char
, '=');
4617 len
= strlen(value
);
4619 err
= vfs_parse_fs_string(fc
, this_char
, value
, len
);
4628 * Reconfigure a shmem filesystem.
4630 static int shmem_reconfigure(struct fs_context
*fc
)
4632 struct shmem_options
*ctx
= fc
->fs_private
;
4633 struct shmem_sb_info
*sbinfo
= SHMEM_SB(fc
->root
->d_sb
);
4634 unsigned long used_isp
;
4635 struct mempolicy
*mpol
= NULL
;
4638 raw_spin_lock(&sbinfo
->stat_lock
);
4639 used_isp
= sbinfo
->max_inodes
* BOGO_INODE_SIZE
- sbinfo
->free_ispace
;
4641 if ((ctx
->seen
& SHMEM_SEEN_BLOCKS
) && ctx
->blocks
) {
4642 if (!sbinfo
->max_blocks
) {
4643 err
= "Cannot retroactively limit size";
4646 if (percpu_counter_compare(&sbinfo
->used_blocks
,
4648 err
= "Too small a size for current use";
4652 if ((ctx
->seen
& SHMEM_SEEN_INODES
) && ctx
->inodes
) {
4653 if (!sbinfo
->max_inodes
) {
4654 err
= "Cannot retroactively limit inodes";
4657 if (ctx
->inodes
* BOGO_INODE_SIZE
< used_isp
) {
4658 err
= "Too few inodes for current use";
4663 if ((ctx
->seen
& SHMEM_SEEN_INUMS
) && !ctx
->full_inums
&&
4664 sbinfo
->next_ino
> UINT_MAX
) {
4665 err
= "Current inum too high to switch to 32-bit inums";
4668 if ((ctx
->seen
& SHMEM_SEEN_NOSWAP
) && ctx
->noswap
&& !sbinfo
->noswap
) {
4669 err
= "Cannot disable swap on remount";
4672 if (!(ctx
->seen
& SHMEM_SEEN_NOSWAP
) && !ctx
->noswap
&& sbinfo
->noswap
) {
4673 err
= "Cannot enable swap on remount if it was disabled on first mount";
4677 if (ctx
->seen
& SHMEM_SEEN_QUOTA
&&
4678 !sb_any_quota_loaded(fc
->root
->d_sb
)) {
4679 err
= "Cannot enable quota on remount";
4683 #ifdef CONFIG_TMPFS_QUOTA
4684 #define CHANGED_LIMIT(name) \
4685 (ctx->qlimits.name## hardlimit && \
4686 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit))
4688 if (CHANGED_LIMIT(usrquota_b
) || CHANGED_LIMIT(usrquota_i
) ||
4689 CHANGED_LIMIT(grpquota_b
) || CHANGED_LIMIT(grpquota_i
)) {
4690 err
= "Cannot change global quota limit on remount";
4693 #endif /* CONFIG_TMPFS_QUOTA */
4695 if (ctx
->seen
& SHMEM_SEEN_HUGE
)
4696 sbinfo
->huge
= ctx
->huge
;
4697 if (ctx
->seen
& SHMEM_SEEN_INUMS
)
4698 sbinfo
->full_inums
= ctx
->full_inums
;
4699 if (ctx
->seen
& SHMEM_SEEN_BLOCKS
)
4700 sbinfo
->max_blocks
= ctx
->blocks
;
4701 if (ctx
->seen
& SHMEM_SEEN_INODES
) {
4702 sbinfo
->max_inodes
= ctx
->inodes
;
4703 sbinfo
->free_ispace
= ctx
->inodes
* BOGO_INODE_SIZE
- used_isp
;
4707 * Preserve previous mempolicy unless mpol remount option was specified.
4710 mpol
= sbinfo
->mpol
;
4711 sbinfo
->mpol
= ctx
->mpol
; /* transfers initial ref */
4716 sbinfo
->noswap
= true;
4718 raw_spin_unlock(&sbinfo
->stat_lock
);
4722 raw_spin_unlock(&sbinfo
->stat_lock
);
4723 return invalfc(fc
, "%s", err
);
4726 static int shmem_show_options(struct seq_file
*seq
, struct dentry
*root
)
4728 struct shmem_sb_info
*sbinfo
= SHMEM_SB(root
->d_sb
);
4729 struct mempolicy
*mpol
;
4731 if (sbinfo
->max_blocks
!= shmem_default_max_blocks())
4732 seq_printf(seq
, ",size=%luk", K(sbinfo
->max_blocks
));
4733 if (sbinfo
->max_inodes
!= shmem_default_max_inodes())
4734 seq_printf(seq
, ",nr_inodes=%lu", sbinfo
->max_inodes
);
4735 if (sbinfo
->mode
!= (0777 | S_ISVTX
))
4736 seq_printf(seq
, ",mode=%03ho", sbinfo
->mode
);
4737 if (!uid_eq(sbinfo
->uid
, GLOBAL_ROOT_UID
))
4738 seq_printf(seq
, ",uid=%u",
4739 from_kuid_munged(&init_user_ns
, sbinfo
->uid
));
4740 if (!gid_eq(sbinfo
->gid
, GLOBAL_ROOT_GID
))
4741 seq_printf(seq
, ",gid=%u",
4742 from_kgid_munged(&init_user_ns
, sbinfo
->gid
));
4745 * Showing inode{64,32} might be useful even if it's the system default,
4746 * since then people don't have to resort to checking both here and
4747 * /proc/config.gz to confirm 64-bit inums were successfully applied
4748 * (which may not even exist if IKCONFIG_PROC isn't enabled).
4750 * We hide it when inode64 isn't the default and we are using 32-bit
4751 * inodes, since that probably just means the feature isn't even under
4756 * +-----------------+-----------------+
4757 * | TMPFS_INODE64=y | TMPFS_INODE64=n |
4758 * +------------------+-----------------+-----------------+
4759 * | full_inums=true | show | show |
4760 * | full_inums=false | show | hide |
4761 * +------------------+-----------------+-----------------+
4764 if (IS_ENABLED(CONFIG_TMPFS_INODE64
) || sbinfo
->full_inums
)
4765 seq_printf(seq
, ",inode%d", (sbinfo
->full_inums
? 64 : 32));
4766 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4767 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
4769 seq_printf(seq
, ",huge=%s", shmem_format_huge(sbinfo
->huge
));
4771 mpol
= shmem_get_sbmpol(sbinfo
);
4772 shmem_show_mpol(seq
, mpol
);
4775 seq_printf(seq
, ",noswap");
4776 #ifdef CONFIG_TMPFS_QUOTA
4777 if (sb_has_quota_active(root
->d_sb
, USRQUOTA
))
4778 seq_printf(seq
, ",usrquota");
4779 if (sb_has_quota_active(root
->d_sb
, GRPQUOTA
))
4780 seq_printf(seq
, ",grpquota");
4781 if (sbinfo
->qlimits
.usrquota_bhardlimit
)
4782 seq_printf(seq
, ",usrquota_block_hardlimit=%lld",
4783 sbinfo
->qlimits
.usrquota_bhardlimit
);
4784 if (sbinfo
->qlimits
.grpquota_bhardlimit
)
4785 seq_printf(seq
, ",grpquota_block_hardlimit=%lld",
4786 sbinfo
->qlimits
.grpquota_bhardlimit
);
4787 if (sbinfo
->qlimits
.usrquota_ihardlimit
)
4788 seq_printf(seq
, ",usrquota_inode_hardlimit=%lld",
4789 sbinfo
->qlimits
.usrquota_ihardlimit
);
4790 if (sbinfo
->qlimits
.grpquota_ihardlimit
)
4791 seq_printf(seq
, ",grpquota_inode_hardlimit=%lld",
4792 sbinfo
->qlimits
.grpquota_ihardlimit
);
4797 #endif /* CONFIG_TMPFS */
4799 static void shmem_put_super(struct super_block
*sb
)
4801 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
4803 #if IS_ENABLED(CONFIG_UNICODE)
4805 utf8_unload(sb
->s_encoding
);
4808 #ifdef CONFIG_TMPFS_QUOTA
4809 shmem_disable_quotas(sb
);
4811 free_percpu(sbinfo
->ino_batch
);
4812 percpu_counter_destroy(&sbinfo
->used_blocks
);
4813 mpol_put(sbinfo
->mpol
);
4815 sb
->s_fs_info
= NULL
;
4818 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS)
4819 static const struct dentry_operations shmem_ci_dentry_ops
= {
4820 .d_hash
= generic_ci_d_hash
,
4821 .d_compare
= generic_ci_d_compare
,
4822 .d_delete
= always_delete_dentry
,
4826 static int shmem_fill_super(struct super_block
*sb
, struct fs_context
*fc
)
4828 struct shmem_options
*ctx
= fc
->fs_private
;
4829 struct inode
*inode
;
4830 struct shmem_sb_info
*sbinfo
;
4831 int error
= -ENOMEM
;
4833 /* Round up to L1_CACHE_BYTES to resist false sharing */
4834 sbinfo
= kzalloc(max((int)sizeof(struct shmem_sb_info
),
4835 L1_CACHE_BYTES
), GFP_KERNEL
);
4839 sb
->s_fs_info
= sbinfo
;
4843 * Per default we only allow half of the physical ram per
4844 * tmpfs instance, limiting inodes to one per page of lowmem;
4845 * but the internal instance is left unlimited.
4847 if (!(sb
->s_flags
& SB_KERNMOUNT
)) {
4848 if (!(ctx
->seen
& SHMEM_SEEN_BLOCKS
))
4849 ctx
->blocks
= shmem_default_max_blocks();
4850 if (!(ctx
->seen
& SHMEM_SEEN_INODES
))
4851 ctx
->inodes
= shmem_default_max_inodes();
4852 if (!(ctx
->seen
& SHMEM_SEEN_INUMS
))
4853 ctx
->full_inums
= IS_ENABLED(CONFIG_TMPFS_INODE64
);
4854 sbinfo
->noswap
= ctx
->noswap
;
4856 sb
->s_flags
|= SB_NOUSER
;
4858 sb
->s_export_op
= &shmem_export_ops
;
4859 sb
->s_flags
|= SB_NOSEC
| SB_I_VERSION
;
4861 #if IS_ENABLED(CONFIG_UNICODE)
4862 if (!ctx
->encoding
&& ctx
->strict_encoding
) {
4863 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n");
4868 if (ctx
->encoding
) {
4869 sb
->s_encoding
= ctx
->encoding
;
4870 sb
->s_d_op
= &shmem_ci_dentry_ops
;
4871 if (ctx
->strict_encoding
)
4872 sb
->s_encoding_flags
= SB_ENC_STRICT_MODE_FL
;
4877 sb
->s_flags
|= SB_NOUSER
;
4878 #endif /* CONFIG_TMPFS */
4879 sbinfo
->max_blocks
= ctx
->blocks
;
4880 sbinfo
->max_inodes
= ctx
->inodes
;
4881 sbinfo
->free_ispace
= sbinfo
->max_inodes
* BOGO_INODE_SIZE
;
4882 if (sb
->s_flags
& SB_KERNMOUNT
) {
4883 sbinfo
->ino_batch
= alloc_percpu(ino_t
);
4884 if (!sbinfo
->ino_batch
)
4887 sbinfo
->uid
= ctx
->uid
;
4888 sbinfo
->gid
= ctx
->gid
;
4889 sbinfo
->full_inums
= ctx
->full_inums
;
4890 sbinfo
->mode
= ctx
->mode
;
4891 sbinfo
->huge
= ctx
->huge
;
4892 sbinfo
->mpol
= ctx
->mpol
;
4895 raw_spin_lock_init(&sbinfo
->stat_lock
);
4896 if (percpu_counter_init(&sbinfo
->used_blocks
, 0, GFP_KERNEL
))
4898 spin_lock_init(&sbinfo
->shrinklist_lock
);
4899 INIT_LIST_HEAD(&sbinfo
->shrinklist
);
4901 sb
->s_maxbytes
= MAX_LFS_FILESIZE
;
4902 sb
->s_blocksize
= PAGE_SIZE
;
4903 sb
->s_blocksize_bits
= PAGE_SHIFT
;
4904 sb
->s_magic
= TMPFS_MAGIC
;
4905 sb
->s_op
= &shmem_ops
;
4906 sb
->s_time_gran
= 1;
4907 #ifdef CONFIG_TMPFS_XATTR
4908 sb
->s_xattr
= shmem_xattr_handlers
;
4910 #ifdef CONFIG_TMPFS_POSIX_ACL
4911 sb
->s_flags
|= SB_POSIXACL
;
4915 super_set_uuid(sb
, uuid
.b
, sizeof(uuid
));
4917 #ifdef CONFIG_TMPFS_QUOTA
4918 if (ctx
->seen
& SHMEM_SEEN_QUOTA
) {
4919 sb
->dq_op
= &shmem_quota_operations
;
4920 sb
->s_qcop
= &dquot_quotactl_sysfile_ops
;
4921 sb
->s_quota_types
= QTYPE_MASK_USR
| QTYPE_MASK_GRP
;
4923 /* Copy the default limits from ctx into sbinfo */
4924 memcpy(&sbinfo
->qlimits
, &ctx
->qlimits
,
4925 sizeof(struct shmem_quota_limits
));
4927 if (shmem_enable_quotas(sb
, ctx
->quota_types
))
4930 #endif /* CONFIG_TMPFS_QUOTA */
4932 inode
= shmem_get_inode(&nop_mnt_idmap
, sb
, NULL
,
4933 S_IFDIR
| sbinfo
->mode
, 0, VM_NORESERVE
);
4934 if (IS_ERR(inode
)) {
4935 error
= PTR_ERR(inode
);
4938 inode
->i_uid
= sbinfo
->uid
;
4939 inode
->i_gid
= sbinfo
->gid
;
4940 sb
->s_root
= d_make_root(inode
);
4946 shmem_put_super(sb
);
4950 static int shmem_get_tree(struct fs_context
*fc
)
4952 return get_tree_nodev(fc
, shmem_fill_super
);
4955 static void shmem_free_fc(struct fs_context
*fc
)
4957 struct shmem_options
*ctx
= fc
->fs_private
;
4960 mpol_put(ctx
->mpol
);
4965 static const struct fs_context_operations shmem_fs_context_ops
= {
4966 .free
= shmem_free_fc
,
4967 .get_tree
= shmem_get_tree
,
4969 .parse_monolithic
= shmem_parse_options
,
4970 .parse_param
= shmem_parse_one
,
4971 .reconfigure
= shmem_reconfigure
,
4975 static struct kmem_cache
*shmem_inode_cachep __ro_after_init
;
4977 static struct inode
*shmem_alloc_inode(struct super_block
*sb
)
4979 struct shmem_inode_info
*info
;
4980 info
= alloc_inode_sb(sb
, shmem_inode_cachep
, GFP_KERNEL
);
4983 return &info
->vfs_inode
;
4986 static void shmem_free_in_core_inode(struct inode
*inode
)
4988 if (S_ISLNK(inode
->i_mode
))
4989 kfree(inode
->i_link
);
4990 kmem_cache_free(shmem_inode_cachep
, SHMEM_I(inode
));
4993 static void shmem_destroy_inode(struct inode
*inode
)
4995 if (S_ISREG(inode
->i_mode
))
4996 mpol_free_shared_policy(&SHMEM_I(inode
)->policy
);
4997 if (S_ISDIR(inode
->i_mode
))
4998 simple_offset_destroy(shmem_get_offset_ctx(inode
));
5001 static void shmem_init_inode(void *foo
)
5003 struct shmem_inode_info
*info
= foo
;
5004 inode_init_once(&info
->vfs_inode
);
5007 static void __init
shmem_init_inodecache(void)
5009 shmem_inode_cachep
= kmem_cache_create("shmem_inode_cache",
5010 sizeof(struct shmem_inode_info
),
5011 0, SLAB_PANIC
|SLAB_ACCOUNT
, shmem_init_inode
);
5014 static void __init
shmem_destroy_inodecache(void)
5016 kmem_cache_destroy(shmem_inode_cachep
);
5019 /* Keep the page in page cache instead of truncating it */
5020 static int shmem_error_remove_folio(struct address_space
*mapping
,
5021 struct folio
*folio
)
5026 static const struct address_space_operations shmem_aops
= {
5027 .writepage
= shmem_writepage
,
5028 .dirty_folio
= noop_dirty_folio
,
5030 .write_begin
= shmem_write_begin
,
5031 .write_end
= shmem_write_end
,
5033 #ifdef CONFIG_MIGRATION
5034 .migrate_folio
= migrate_folio
,
5036 .error_remove_folio
= shmem_error_remove_folio
,
5039 static const struct file_operations shmem_file_operations
= {
5041 .open
= shmem_file_open
,
5042 .get_unmapped_area
= shmem_get_unmapped_area
,
5044 .llseek
= shmem_file_llseek
,
5045 .read_iter
= shmem_file_read_iter
,
5046 .write_iter
= shmem_file_write_iter
,
5047 .fsync
= noop_fsync
,
5048 .splice_read
= shmem_file_splice_read
,
5049 .splice_write
= iter_file_splice_write
,
5050 .fallocate
= shmem_fallocate
,
5054 static const struct inode_operations shmem_inode_operations
= {
5055 .getattr
= shmem_getattr
,
5056 .setattr
= shmem_setattr
,
5057 #ifdef CONFIG_TMPFS_XATTR
5058 .listxattr
= shmem_listxattr
,
5059 .set_acl
= simple_set_acl
,
5060 .fileattr_get
= shmem_fileattr_get
,
5061 .fileattr_set
= shmem_fileattr_set
,
5065 static const struct inode_operations shmem_dir_inode_operations
= {
5067 .getattr
= shmem_getattr
,
5068 .create
= shmem_create
,
5069 .lookup
= simple_lookup
,
5071 .unlink
= shmem_unlink
,
5072 .symlink
= shmem_symlink
,
5073 .mkdir
= shmem_mkdir
,
5074 .rmdir
= shmem_rmdir
,
5075 .mknod
= shmem_mknod
,
5076 .rename
= shmem_rename2
,
5077 .tmpfile
= shmem_tmpfile
,
5078 .get_offset_ctx
= shmem_get_offset_ctx
,
5080 #ifdef CONFIG_TMPFS_XATTR
5081 .listxattr
= shmem_listxattr
,
5082 .fileattr_get
= shmem_fileattr_get
,
5083 .fileattr_set
= shmem_fileattr_set
,
5085 #ifdef CONFIG_TMPFS_POSIX_ACL
5086 .setattr
= shmem_setattr
,
5087 .set_acl
= simple_set_acl
,
5091 static const struct inode_operations shmem_special_inode_operations
= {
5092 .getattr
= shmem_getattr
,
5093 #ifdef CONFIG_TMPFS_XATTR
5094 .listxattr
= shmem_listxattr
,
5096 #ifdef CONFIG_TMPFS_POSIX_ACL
5097 .setattr
= shmem_setattr
,
5098 .set_acl
= simple_set_acl
,
5102 static const struct super_operations shmem_ops
= {
5103 .alloc_inode
= shmem_alloc_inode
,
5104 .free_inode
= shmem_free_in_core_inode
,
5105 .destroy_inode
= shmem_destroy_inode
,
5107 .statfs
= shmem_statfs
,
5108 .show_options
= shmem_show_options
,
5110 #ifdef CONFIG_TMPFS_QUOTA
5111 .get_dquots
= shmem_get_dquots
,
5113 .evict_inode
= shmem_evict_inode
,
5114 .drop_inode
= generic_delete_inode
,
5115 .put_super
= shmem_put_super
,
5116 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5117 .nr_cached_objects
= shmem_unused_huge_count
,
5118 .free_cached_objects
= shmem_unused_huge_scan
,
5122 static const struct vm_operations_struct shmem_vm_ops
= {
5123 .fault
= shmem_fault
,
5124 .map_pages
= filemap_map_pages
,
5126 .set_policy
= shmem_set_policy
,
5127 .get_policy
= shmem_get_policy
,
5131 static const struct vm_operations_struct shmem_anon_vm_ops
= {
5132 .fault
= shmem_fault
,
5133 .map_pages
= filemap_map_pages
,
5135 .set_policy
= shmem_set_policy
,
5136 .get_policy
= shmem_get_policy
,
5140 int shmem_init_fs_context(struct fs_context
*fc
)
5142 struct shmem_options
*ctx
;
5144 ctx
= kzalloc(sizeof(struct shmem_options
), GFP_KERNEL
);
5148 ctx
->mode
= 0777 | S_ISVTX
;
5149 ctx
->uid
= current_fsuid();
5150 ctx
->gid
= current_fsgid();
5152 #if IS_ENABLED(CONFIG_UNICODE)
5153 ctx
->encoding
= NULL
;
5156 fc
->fs_private
= ctx
;
5157 fc
->ops
= &shmem_fs_context_ops
;
5161 static struct file_system_type shmem_fs_type
= {
5162 .owner
= THIS_MODULE
,
5164 .init_fs_context
= shmem_init_fs_context
,
5166 .parameters
= shmem_fs_parameters
,
5168 .kill_sb
= kill_litter_super
,
5169 .fs_flags
= FS_USERNS_MOUNT
| FS_ALLOW_IDMAP
| FS_MGTIME
,
5172 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5174 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \
5176 .attr = { .name = __stringify(_name), .mode = _mode }, \
5181 #define TMPFS_ATTR_W(_name, _store) \
5182 static struct kobj_attribute tmpfs_attr_##_name = \
5183 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store)
5185 #define TMPFS_ATTR_RW(_name, _show, _store) \
5186 static struct kobj_attribute tmpfs_attr_##_name = \
5187 __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
5189 #define TMPFS_ATTR_RO(_name, _show) \
5190 static struct kobj_attribute tmpfs_attr_##_name = \
5191 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL)
5193 #if IS_ENABLED(CONFIG_UNICODE)
5194 static ssize_t
casefold_show(struct kobject
*kobj
, struct kobj_attribute
*a
,
5197 return sysfs_emit(buf
, "supported\n");
5199 TMPFS_ATTR_RO(casefold
, casefold_show
);
5202 static struct attribute
*tmpfs_attributes
[] = {
5203 #if IS_ENABLED(CONFIG_UNICODE)
5204 &tmpfs_attr_casefold
.attr
,
5209 static const struct attribute_group tmpfs_attribute_group
= {
5210 .attrs
= tmpfs_attributes
,
5214 static struct kobject
*tmpfs_kobj
;
5216 static int __init
tmpfs_sysfs_init(void)
5220 tmpfs_kobj
= kobject_create_and_add("tmpfs", fs_kobj
);
5224 ret
= sysfs_create_group(tmpfs_kobj
, &tmpfs_attribute_group
);
5226 kobject_put(tmpfs_kobj
);
5230 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */
5232 void __init
shmem_init(void)
5236 shmem_init_inodecache();
5238 #ifdef CONFIG_TMPFS_QUOTA
5239 register_quota_format(&shmem_quota_format
);
5242 error
= register_filesystem(&shmem_fs_type
);
5244 pr_err("Could not register tmpfs\n");
5248 shm_mnt
= kern_mount(&shmem_fs_type
);
5249 if (IS_ERR(shm_mnt
)) {
5250 error
= PTR_ERR(shm_mnt
);
5251 pr_err("Could not kern_mount tmpfs\n");
5255 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5256 error
= tmpfs_sysfs_init();
5258 pr_err("Could not init tmpfs sysfs\n");
5263 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5264 if (has_transparent_hugepage() && shmem_huge
> SHMEM_HUGE_DENY
)
5265 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
5267 shmem_huge
= SHMEM_HUGE_NEVER
; /* just in case it was patched */
5270 * Default to setting PMD-sized THP to inherit the global setting and
5271 * disable all other multi-size THPs.
5273 if (!shmem_orders_configured
)
5274 huge_shmem_orders_inherit
= BIT(HPAGE_PMD_ORDER
);
5279 unregister_filesystem(&shmem_fs_type
);
5281 #ifdef CONFIG_TMPFS_QUOTA
5282 unregister_quota_format(&shmem_quota_format
);
5284 shmem_destroy_inodecache();
5285 shm_mnt
= ERR_PTR(error
);
5288 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
5289 static ssize_t
shmem_enabled_show(struct kobject
*kobj
,
5290 struct kobj_attribute
*attr
, char *buf
)
5292 static const int values
[] = {
5294 SHMEM_HUGE_WITHIN_SIZE
,
5303 for (i
= 0; i
< ARRAY_SIZE(values
); i
++) {
5304 len
+= sysfs_emit_at(buf
, len
,
5305 shmem_huge
== values
[i
] ? "%s[%s]" : "%s%s",
5306 i
? " " : "", shmem_format_huge(values
[i
]));
5308 len
+= sysfs_emit_at(buf
, len
, "\n");
5313 static ssize_t
shmem_enabled_store(struct kobject
*kobj
,
5314 struct kobj_attribute
*attr
, const char *buf
, size_t count
)
5319 if (count
+ 1 > sizeof(tmp
))
5321 memcpy(tmp
, buf
, count
);
5323 if (count
&& tmp
[count
- 1] == '\n')
5324 tmp
[count
- 1] = '\0';
5326 huge
= shmem_parse_huge(tmp
);
5327 if (huge
== -EINVAL
)
5331 if (shmem_huge
> SHMEM_HUGE_DENY
)
5332 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
5334 err
= start_stop_khugepaged();
5335 return err
? err
: count
;
5338 struct kobj_attribute shmem_enabled_attr
= __ATTR_RW(shmem_enabled
);
5339 static DEFINE_SPINLOCK(huge_shmem_orders_lock
);
5341 static ssize_t
thpsize_shmem_enabled_show(struct kobject
*kobj
,
5342 struct kobj_attribute
*attr
, char *buf
)
5344 int order
= to_thpsize(kobj
)->order
;
5347 if (test_bit(order
, &huge_shmem_orders_always
))
5348 output
= "[always] inherit within_size advise never";
5349 else if (test_bit(order
, &huge_shmem_orders_inherit
))
5350 output
= "always [inherit] within_size advise never";
5351 else if (test_bit(order
, &huge_shmem_orders_within_size
))
5352 output
= "always inherit [within_size] advise never";
5353 else if (test_bit(order
, &huge_shmem_orders_madvise
))
5354 output
= "always inherit within_size [advise] never";
5356 output
= "always inherit within_size advise [never]";
5358 return sysfs_emit(buf
, "%s\n", output
);
5361 static ssize_t
thpsize_shmem_enabled_store(struct kobject
*kobj
,
5362 struct kobj_attribute
*attr
,
5363 const char *buf
, size_t count
)
5365 int order
= to_thpsize(kobj
)->order
;
5366 ssize_t ret
= count
;
5368 if (sysfs_streq(buf
, "always")) {
5369 spin_lock(&huge_shmem_orders_lock
);
5370 clear_bit(order
, &huge_shmem_orders_inherit
);
5371 clear_bit(order
, &huge_shmem_orders_madvise
);
5372 clear_bit(order
, &huge_shmem_orders_within_size
);
5373 set_bit(order
, &huge_shmem_orders_always
);
5374 spin_unlock(&huge_shmem_orders_lock
);
5375 } else if (sysfs_streq(buf
, "inherit")) {
5376 /* Do not override huge allocation policy with non-PMD sized mTHP */
5377 if (shmem_huge
== SHMEM_HUGE_FORCE
&&
5378 order
!= HPAGE_PMD_ORDER
)
5381 spin_lock(&huge_shmem_orders_lock
);
5382 clear_bit(order
, &huge_shmem_orders_always
);
5383 clear_bit(order
, &huge_shmem_orders_madvise
);
5384 clear_bit(order
, &huge_shmem_orders_within_size
);
5385 set_bit(order
, &huge_shmem_orders_inherit
);
5386 spin_unlock(&huge_shmem_orders_lock
);
5387 } else if (sysfs_streq(buf
, "within_size")) {
5388 spin_lock(&huge_shmem_orders_lock
);
5389 clear_bit(order
, &huge_shmem_orders_always
);
5390 clear_bit(order
, &huge_shmem_orders_inherit
);
5391 clear_bit(order
, &huge_shmem_orders_madvise
);
5392 set_bit(order
, &huge_shmem_orders_within_size
);
5393 spin_unlock(&huge_shmem_orders_lock
);
5394 } else if (sysfs_streq(buf
, "advise")) {
5395 spin_lock(&huge_shmem_orders_lock
);
5396 clear_bit(order
, &huge_shmem_orders_always
);
5397 clear_bit(order
, &huge_shmem_orders_inherit
);
5398 clear_bit(order
, &huge_shmem_orders_within_size
);
5399 set_bit(order
, &huge_shmem_orders_madvise
);
5400 spin_unlock(&huge_shmem_orders_lock
);
5401 } else if (sysfs_streq(buf
, "never")) {
5402 spin_lock(&huge_shmem_orders_lock
);
5403 clear_bit(order
, &huge_shmem_orders_always
);
5404 clear_bit(order
, &huge_shmem_orders_inherit
);
5405 clear_bit(order
, &huge_shmem_orders_within_size
);
5406 clear_bit(order
, &huge_shmem_orders_madvise
);
5407 spin_unlock(&huge_shmem_orders_lock
);
5413 int err
= start_stop_khugepaged();
5421 struct kobj_attribute thpsize_shmem_enabled_attr
=
5422 __ATTR(shmem_enabled
, 0644, thpsize_shmem_enabled_show
, thpsize_shmem_enabled_store
);
5423 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
5425 #if defined(CONFIG_TRANSPARENT_HUGEPAGE)
5427 static int __init
setup_transparent_hugepage_shmem(char *str
)
5431 huge
= shmem_parse_huge(str
);
5432 if (huge
== -EINVAL
) {
5433 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
5440 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem
);
5442 static char str_dup
[PAGE_SIZE
] __initdata
;
5443 static int __init
setup_thp_shmem(char *str
)
5445 char *token
, *range
, *policy
, *subtoken
;
5446 unsigned long always
, inherit
, madvise
, within_size
;
5447 char *start_size
, *end_size
;
5451 if (!str
|| strlen(str
) + 1 > PAGE_SIZE
)
5453 strscpy(str_dup
, str
);
5455 always
= huge_shmem_orders_always
;
5456 inherit
= huge_shmem_orders_inherit
;
5457 madvise
= huge_shmem_orders_madvise
;
5458 within_size
= huge_shmem_orders_within_size
;
5460 while ((token
= strsep(&p
, ";")) != NULL
) {
5461 range
= strsep(&token
, ":");
5467 while ((subtoken
= strsep(&range
, ",")) != NULL
) {
5468 if (strchr(subtoken
, '-')) {
5469 start_size
= strsep(&subtoken
, "-");
5470 end_size
= subtoken
;
5472 start
= get_order_from_str(start_size
,
5473 THP_ORDERS_ALL_FILE_DEFAULT
);
5474 end
= get_order_from_str(end_size
,
5475 THP_ORDERS_ALL_FILE_DEFAULT
);
5477 start_size
= end_size
= subtoken
;
5478 start
= end
= get_order_from_str(subtoken
,
5479 THP_ORDERS_ALL_FILE_DEFAULT
);
5482 if (start
== -EINVAL
) {
5483 pr_err("invalid size %s in thp_shmem boot parameter\n",
5488 if (end
== -EINVAL
) {
5489 pr_err("invalid size %s in thp_shmem boot parameter\n",
5494 if (start
< 0 || end
< 0 || start
> end
)
5497 nr
= end
- start
+ 1;
5498 if (!strcmp(policy
, "always")) {
5499 bitmap_set(&always
, start
, nr
);
5500 bitmap_clear(&inherit
, start
, nr
);
5501 bitmap_clear(&madvise
, start
, nr
);
5502 bitmap_clear(&within_size
, start
, nr
);
5503 } else if (!strcmp(policy
, "advise")) {
5504 bitmap_set(&madvise
, start
, nr
);
5505 bitmap_clear(&inherit
, start
, nr
);
5506 bitmap_clear(&always
, start
, nr
);
5507 bitmap_clear(&within_size
, start
, nr
);
5508 } else if (!strcmp(policy
, "inherit")) {
5509 bitmap_set(&inherit
, start
, nr
);
5510 bitmap_clear(&madvise
, start
, nr
);
5511 bitmap_clear(&always
, start
, nr
);
5512 bitmap_clear(&within_size
, start
, nr
);
5513 } else if (!strcmp(policy
, "within_size")) {
5514 bitmap_set(&within_size
, start
, nr
);
5515 bitmap_clear(&inherit
, start
, nr
);
5516 bitmap_clear(&madvise
, start
, nr
);
5517 bitmap_clear(&always
, start
, nr
);
5518 } else if (!strcmp(policy
, "never")) {
5519 bitmap_clear(&inherit
, start
, nr
);
5520 bitmap_clear(&madvise
, start
, nr
);
5521 bitmap_clear(&always
, start
, nr
);
5522 bitmap_clear(&within_size
, start
, nr
);
5524 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy
);
5530 huge_shmem_orders_always
= always
;
5531 huge_shmem_orders_madvise
= madvise
;
5532 huge_shmem_orders_inherit
= inherit
;
5533 huge_shmem_orders_within_size
= within_size
;
5534 shmem_orders_configured
= true;
5538 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str
);
5541 __setup("thp_shmem=", setup_thp_shmem
);
5543 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5545 #else /* !CONFIG_SHMEM */
5548 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
5550 * This is intended for small system where the benefits of the full
5551 * shmem code (swap-backed and resource-limited) are outweighed by
5552 * their complexity. On systems without swap this code should be
5553 * effectively equivalent, but much lighter weight.
5556 static struct file_system_type shmem_fs_type
= {
5558 .init_fs_context
= ramfs_init_fs_context
,
5559 .parameters
= ramfs_fs_parameters
,
5560 .kill_sb
= ramfs_kill_sb
,
5561 .fs_flags
= FS_USERNS_MOUNT
,
5564 void __init
shmem_init(void)
5566 BUG_ON(register_filesystem(&shmem_fs_type
) != 0);
5568 shm_mnt
= kern_mount(&shmem_fs_type
);
5569 BUG_ON(IS_ERR(shm_mnt
));
5572 int shmem_unuse(unsigned int type
)
5577 int shmem_lock(struct file
*file
, int lock
, struct ucounts
*ucounts
)
5582 void shmem_unlock_mapping(struct address_space
*mapping
)
5587 unsigned long shmem_get_unmapped_area(struct file
*file
,
5588 unsigned long addr
, unsigned long len
,
5589 unsigned long pgoff
, unsigned long flags
)
5591 return mm_get_unmapped_area(current
->mm
, file
, addr
, len
, pgoff
, flags
);
5595 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
5597 truncate_inode_pages_range(inode
->i_mapping
, lstart
, lend
);
5599 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
5601 #define shmem_vm_ops generic_file_vm_ops
5602 #define shmem_anon_vm_ops generic_file_vm_ops
5603 #define shmem_file_operations ramfs_file_operations
5604 #define shmem_acct_size(flags, size) 0
5605 #define shmem_unacct_size(flags, size) do {} while (0)
5607 static inline struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
5608 struct super_block
*sb
, struct inode
*dir
,
5609 umode_t mode
, dev_t dev
, unsigned long flags
)
5611 struct inode
*inode
= ramfs_get_inode(sb
, dir
, mode
, dev
);
5612 return inode
? inode
: ERR_PTR(-ENOSPC
);
5615 #endif /* CONFIG_SHMEM */
5619 static struct file
*__shmem_file_setup(struct vfsmount
*mnt
, const char *name
,
5620 loff_t size
, unsigned long flags
, unsigned int i_flags
)
5622 struct inode
*inode
;
5626 return ERR_CAST(mnt
);
5628 if (size
< 0 || size
> MAX_LFS_FILESIZE
)
5629 return ERR_PTR(-EINVAL
);
5631 if (shmem_acct_size(flags
, size
))
5632 return ERR_PTR(-ENOMEM
);
5634 if (is_idmapped_mnt(mnt
))
5635 return ERR_PTR(-EINVAL
);
5637 inode
= shmem_get_inode(&nop_mnt_idmap
, mnt
->mnt_sb
, NULL
,
5638 S_IFREG
| S_IRWXUGO
, 0, flags
);
5639 if (IS_ERR(inode
)) {
5640 shmem_unacct_size(flags
, size
);
5641 return ERR_CAST(inode
);
5643 inode
->i_flags
|= i_flags
;
5644 inode
->i_size
= size
;
5645 clear_nlink(inode
); /* It is unlinked */
5646 res
= ERR_PTR(ramfs_nommu_expand_for_mapping(inode
, size
));
5648 res
= alloc_file_pseudo(inode
, mnt
, name
, O_RDWR
,
5649 &shmem_file_operations
);
5656 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
5657 * kernel internal. There will be NO LSM permission checks against the
5658 * underlying inode. So users of this interface must do LSM checks at a
5659 * higher layer. The users are the big_key and shm implementations. LSM
5660 * checks are provided at the key or shm level rather than the inode.
5661 * @name: name for dentry (to be seen in /proc/<pid>/maps
5662 * @size: size to be set for the file
5663 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5665 struct file
*shmem_kernel_file_setup(const char *name
, loff_t size
, unsigned long flags
)
5667 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, S_PRIVATE
);
5669 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup
);
5672 * shmem_file_setup - get an unlinked file living in tmpfs
5673 * @name: name for dentry (to be seen in /proc/<pid>/maps
5674 * @size: size to be set for the file
5675 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5677 struct file
*shmem_file_setup(const char *name
, loff_t size
, unsigned long flags
)
5679 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, 0);
5681 EXPORT_SYMBOL_GPL(shmem_file_setup
);
5684 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
5685 * @mnt: the tmpfs mount where the file will be created
5686 * @name: name for dentry (to be seen in /proc/<pid>/maps
5687 * @size: size to be set for the file
5688 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5690 struct file
*shmem_file_setup_with_mnt(struct vfsmount
*mnt
, const char *name
,
5691 loff_t size
, unsigned long flags
)
5693 return __shmem_file_setup(mnt
, name
, size
, flags
, 0);
5695 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt
);
5698 * shmem_zero_setup - setup a shared anonymous mapping
5699 * @vma: the vma to be mmapped is prepared by do_mmap
5701 int shmem_zero_setup(struct vm_area_struct
*vma
)
5704 loff_t size
= vma
->vm_end
- vma
->vm_start
;
5707 * Cloning a new file under mmap_lock leads to a lock ordering conflict
5708 * between XFS directory reading and selinux: since this file is only
5709 * accessible to the user through its mapping, use S_PRIVATE flag to
5710 * bypass file security, in the same way as shmem_kernel_file_setup().
5712 file
= shmem_kernel_file_setup("dev/zero", size
, vma
->vm_flags
);
5714 return PTR_ERR(file
);
5718 vma
->vm_file
= file
;
5719 vma
->vm_ops
= &shmem_anon_vm_ops
;
5725 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags.
5726 * @mapping: the folio's address_space
5727 * @index: the folio index
5728 * @gfp: the page allocator flags to use if allocating
5730 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
5731 * with any new page allocations done using the specified allocation flags.
5732 * But read_cache_page_gfp() uses the ->read_folio() method: which does not
5733 * suit tmpfs, since it may have pages in swapcache, and needs to find those
5734 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
5736 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
5737 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
5739 struct folio
*shmem_read_folio_gfp(struct address_space
*mapping
,
5740 pgoff_t index
, gfp_t gfp
)
5743 struct inode
*inode
= mapping
->host
;
5744 struct folio
*folio
;
5747 error
= shmem_get_folio_gfp(inode
, index
, 0, &folio
, SGP_CACHE
,
5750 return ERR_PTR(error
);
5752 folio_unlock(folio
);
5756 * The tiny !SHMEM case uses ramfs without swap
5758 return mapping_read_folio_gfp(mapping
, index
, gfp
);
5761 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp
);
5763 struct page
*shmem_read_mapping_page_gfp(struct address_space
*mapping
,
5764 pgoff_t index
, gfp_t gfp
)
5766 struct folio
*folio
= shmem_read_folio_gfp(mapping
, index
, gfp
);
5770 return &folio
->page
;
5772 page
= folio_file_page(folio
, index
);
5773 if (PageHWPoison(page
)) {
5775 return ERR_PTR(-EIO
);
5780 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp
);