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 */
790 static void shmem_update_stats(struct folio
*folio
, int nr_pages
)
792 if (folio_test_pmd_mappable(folio
))
793 __lruvec_stat_mod_folio(folio
, NR_SHMEM_THPS
, nr_pages
);
794 __lruvec_stat_mod_folio(folio
, NR_FILE_PAGES
, nr_pages
);
795 __lruvec_stat_mod_folio(folio
, NR_SHMEM
, nr_pages
);
799 * Somewhat like filemap_add_folio, but error if expected item has gone.
801 static int shmem_add_to_page_cache(struct folio
*folio
,
802 struct address_space
*mapping
,
803 pgoff_t index
, void *expected
, gfp_t gfp
)
805 XA_STATE_ORDER(xas
, &mapping
->i_pages
, index
, folio_order(folio
));
806 long nr
= folio_nr_pages(folio
);
808 VM_BUG_ON_FOLIO(index
!= round_down(index
, nr
), folio
);
809 VM_BUG_ON_FOLIO(!folio_test_locked(folio
), folio
);
810 VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio
), folio
);
812 folio_ref_add(folio
, nr
);
813 folio
->mapping
= mapping
;
814 folio
->index
= index
;
816 gfp
&= GFP_RECLAIM_MASK
;
817 folio_throttle_swaprate(folio
, gfp
);
821 if (expected
!= xas_find_conflict(&xas
)) {
822 xas_set_err(&xas
, -EEXIST
);
825 if (expected
&& xas_find_conflict(&xas
)) {
826 xas_set_err(&xas
, -EEXIST
);
829 xas_store(&xas
, folio
);
832 shmem_update_stats(folio
, nr
);
833 mapping
->nrpages
+= nr
;
835 xas_unlock_irq(&xas
);
836 } while (xas_nomem(&xas
, gfp
));
838 if (xas_error(&xas
)) {
839 folio
->mapping
= NULL
;
840 folio_ref_sub(folio
, nr
);
841 return xas_error(&xas
);
848 * Somewhat like filemap_remove_folio, but substitutes swap for @folio.
850 static void shmem_delete_from_page_cache(struct folio
*folio
, void *radswap
)
852 struct address_space
*mapping
= folio
->mapping
;
853 long nr
= folio_nr_pages(folio
);
856 xa_lock_irq(&mapping
->i_pages
);
857 error
= shmem_replace_entry(mapping
, folio
->index
, folio
, radswap
);
858 folio
->mapping
= NULL
;
859 mapping
->nrpages
-= nr
;
860 shmem_update_stats(folio
, -nr
);
861 xa_unlock_irq(&mapping
->i_pages
);
862 folio_put_refs(folio
, nr
);
867 * Remove swap entry from page cache, free the swap and its page cache. Returns
868 * the number of pages being freed. 0 means entry not found in XArray (0 pages
871 static long shmem_free_swap(struct address_space
*mapping
,
872 pgoff_t index
, void *radswap
)
874 int order
= xa_get_order(&mapping
->i_pages
, index
);
877 old
= xa_cmpxchg_irq(&mapping
->i_pages
, index
, radswap
, NULL
, 0);
880 free_swap_and_cache_nr(radix_to_swp_entry(radswap
), 1 << order
);
886 * Determine (in bytes) how many of the shmem object's pages mapped by the
887 * given offsets are swapped out.
889 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
890 * as long as the inode doesn't go away and racy results are not a problem.
892 unsigned long shmem_partial_swap_usage(struct address_space
*mapping
,
893 pgoff_t start
, pgoff_t end
)
895 XA_STATE(xas
, &mapping
->i_pages
, start
);
897 unsigned long swapped
= 0;
898 unsigned long max
= end
- 1;
901 xas_for_each(&xas
, page
, max
) {
902 if (xas_retry(&xas
, page
))
904 if (xa_is_value(page
))
905 swapped
+= 1 << xas_get_order(&xas
);
906 if (xas
.xa_index
== max
)
908 if (need_resched()) {
915 return swapped
<< PAGE_SHIFT
;
919 * Determine (in bytes) how many of the shmem object's pages mapped by the
920 * given vma is swapped out.
922 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
923 * as long as the inode doesn't go away and racy results are not a problem.
925 unsigned long shmem_swap_usage(struct vm_area_struct
*vma
)
927 struct inode
*inode
= file_inode(vma
->vm_file
);
928 struct shmem_inode_info
*info
= SHMEM_I(inode
);
929 struct address_space
*mapping
= inode
->i_mapping
;
930 unsigned long swapped
;
932 /* Be careful as we don't hold info->lock */
933 swapped
= READ_ONCE(info
->swapped
);
936 * The easier cases are when the shmem object has nothing in swap, or
937 * the vma maps it whole. Then we can simply use the stats that we
943 if (!vma
->vm_pgoff
&& vma
->vm_end
- vma
->vm_start
>= inode
->i_size
)
944 return swapped
<< PAGE_SHIFT
;
946 /* Here comes the more involved part */
947 return shmem_partial_swap_usage(mapping
, vma
->vm_pgoff
,
948 vma
->vm_pgoff
+ vma_pages(vma
));
952 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
954 void shmem_unlock_mapping(struct address_space
*mapping
)
956 struct folio_batch fbatch
;
959 folio_batch_init(&fbatch
);
961 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
963 while (!mapping_unevictable(mapping
) &&
964 filemap_get_folios(mapping
, &index
, ~0UL, &fbatch
)) {
965 check_move_unevictable_folios(&fbatch
);
966 folio_batch_release(&fbatch
);
971 static struct folio
*shmem_get_partial_folio(struct inode
*inode
, pgoff_t index
)
976 * At first avoid shmem_get_folio(,,,SGP_READ): that fails
977 * beyond i_size, and reports fallocated folios as holes.
979 folio
= filemap_get_entry(inode
->i_mapping
, index
);
982 if (!xa_is_value(folio
)) {
984 if (folio
->mapping
== inode
->i_mapping
)
986 /* The folio has been swapped out */
991 * But read a folio back from swap if any of it is within i_size
992 * (although in some cases this is just a waste of time).
995 shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
1000 * Remove range of pages and swap entries from page cache, and free them.
1001 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
1003 static void shmem_undo_range(struct inode
*inode
, loff_t lstart
, loff_t lend
,
1006 struct address_space
*mapping
= inode
->i_mapping
;
1007 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1008 pgoff_t start
= (lstart
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
1009 pgoff_t end
= (lend
+ 1) >> PAGE_SHIFT
;
1010 struct folio_batch fbatch
;
1011 pgoff_t indices
[PAGEVEC_SIZE
];
1012 struct folio
*folio
;
1014 long nr_swaps_freed
= 0;
1019 end
= -1; /* unsigned, so actually very big */
1021 if (info
->fallocend
> start
&& info
->fallocend
<= end
&& !unfalloc
)
1022 info
->fallocend
= start
;
1024 folio_batch_init(&fbatch
);
1026 while (index
< end
&& find_lock_entries(mapping
, &index
, end
- 1,
1027 &fbatch
, indices
)) {
1028 for (i
= 0; i
< folio_batch_count(&fbatch
); i
++) {
1029 folio
= fbatch
.folios
[i
];
1031 if (xa_is_value(folio
)) {
1034 nr_swaps_freed
+= shmem_free_swap(mapping
,
1039 if (!unfalloc
|| !folio_test_uptodate(folio
))
1040 truncate_inode_folio(mapping
, folio
);
1041 folio_unlock(folio
);
1043 folio_batch_remove_exceptionals(&fbatch
);
1044 folio_batch_release(&fbatch
);
1049 * When undoing a failed fallocate, we want none of the partial folio
1050 * zeroing and splitting below, but shall want to truncate the whole
1051 * folio when !uptodate indicates that it was added by this fallocate,
1052 * even when [lstart, lend] covers only a part of the folio.
1057 same_folio
= (lstart
>> PAGE_SHIFT
) == (lend
>> PAGE_SHIFT
);
1058 folio
= shmem_get_partial_folio(inode
, lstart
>> PAGE_SHIFT
);
1060 same_folio
= lend
< folio_pos(folio
) + folio_size(folio
);
1061 folio_mark_dirty(folio
);
1062 if (!truncate_inode_partial_folio(folio
, lstart
, lend
)) {
1063 start
= folio_next_index(folio
);
1067 folio_unlock(folio
);
1073 folio
= shmem_get_partial_folio(inode
, lend
>> PAGE_SHIFT
);
1075 folio_mark_dirty(folio
);
1076 if (!truncate_inode_partial_folio(folio
, lstart
, lend
))
1078 folio_unlock(folio
);
1085 while (index
< end
) {
1088 if (!find_get_entries(mapping
, &index
, end
- 1, &fbatch
,
1090 /* If all gone or hole-punch or unfalloc, we're done */
1091 if (index
== start
|| end
!= -1)
1093 /* But if truncating, restart to make sure all gone */
1097 for (i
= 0; i
< folio_batch_count(&fbatch
); i
++) {
1098 folio
= fbatch
.folios
[i
];
1100 if (xa_is_value(folio
)) {
1105 swaps_freed
= shmem_free_swap(mapping
, indices
[i
], folio
);
1107 /* Swap was replaced by page: retry */
1111 nr_swaps_freed
+= swaps_freed
;
1117 if (!unfalloc
|| !folio_test_uptodate(folio
)) {
1118 if (folio_mapping(folio
) != mapping
) {
1119 /* Page was replaced by swap: retry */
1120 folio_unlock(folio
);
1124 VM_BUG_ON_FOLIO(folio_test_writeback(folio
),
1127 if (!folio_test_large(folio
)) {
1128 truncate_inode_folio(mapping
, folio
);
1129 } else if (truncate_inode_partial_folio(folio
, lstart
, lend
)) {
1131 * If we split a page, reset the loop so
1132 * that we pick up the new sub pages.
1133 * Otherwise the THP was entirely
1134 * dropped or the target range was
1135 * zeroed, so just continue the loop as
1138 if (!folio_test_large(folio
)) {
1139 folio_unlock(folio
);
1145 folio_unlock(folio
);
1147 folio_batch_remove_exceptionals(&fbatch
);
1148 folio_batch_release(&fbatch
);
1151 shmem_recalc_inode(inode
, 0, -nr_swaps_freed
);
1154 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
1156 shmem_undo_range(inode
, lstart
, lend
, false);
1157 inode_set_mtime_to_ts(inode
, inode_set_ctime_current(inode
));
1158 inode_inc_iversion(inode
);
1160 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
1162 static int shmem_getattr(struct mnt_idmap
*idmap
,
1163 const struct path
*path
, struct kstat
*stat
,
1164 u32 request_mask
, unsigned int query_flags
)
1166 struct inode
*inode
= path
->dentry
->d_inode
;
1167 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1169 if (info
->alloced
- info
->swapped
!= inode
->i_mapping
->nrpages
)
1170 shmem_recalc_inode(inode
, 0, 0);
1172 if (info
->fsflags
& FS_APPEND_FL
)
1173 stat
->attributes
|= STATX_ATTR_APPEND
;
1174 if (info
->fsflags
& FS_IMMUTABLE_FL
)
1175 stat
->attributes
|= STATX_ATTR_IMMUTABLE
;
1176 if (info
->fsflags
& FS_NODUMP_FL
)
1177 stat
->attributes
|= STATX_ATTR_NODUMP
;
1178 stat
->attributes_mask
|= (STATX_ATTR_APPEND
|
1179 STATX_ATTR_IMMUTABLE
|
1181 generic_fillattr(idmap
, request_mask
, inode
, stat
);
1183 if (shmem_huge_global_enabled(inode
, 0, 0, false, 0))
1184 stat
->blksize
= HPAGE_PMD_SIZE
;
1186 if (request_mask
& STATX_BTIME
) {
1187 stat
->result_mask
|= STATX_BTIME
;
1188 stat
->btime
.tv_sec
= info
->i_crtime
.tv_sec
;
1189 stat
->btime
.tv_nsec
= info
->i_crtime
.tv_nsec
;
1195 static int shmem_setattr(struct mnt_idmap
*idmap
,
1196 struct dentry
*dentry
, struct iattr
*attr
)
1198 struct inode
*inode
= d_inode(dentry
);
1199 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1201 bool update_mtime
= false;
1202 bool update_ctime
= true;
1204 error
= setattr_prepare(idmap
, dentry
, attr
);
1208 if ((info
->seals
& F_SEAL_EXEC
) && (attr
->ia_valid
& ATTR_MODE
)) {
1209 if ((inode
->i_mode
^ attr
->ia_mode
) & 0111) {
1214 if (S_ISREG(inode
->i_mode
) && (attr
->ia_valid
& ATTR_SIZE
)) {
1215 loff_t oldsize
= inode
->i_size
;
1216 loff_t newsize
= attr
->ia_size
;
1218 /* protected by i_rwsem */
1219 if ((newsize
< oldsize
&& (info
->seals
& F_SEAL_SHRINK
)) ||
1220 (newsize
> oldsize
&& (info
->seals
& F_SEAL_GROW
)))
1223 if (newsize
!= oldsize
) {
1224 error
= shmem_reacct_size(SHMEM_I(inode
)->flags
,
1228 i_size_write(inode
, newsize
);
1229 update_mtime
= true;
1231 update_ctime
= false;
1233 if (newsize
<= oldsize
) {
1234 loff_t holebegin
= round_up(newsize
, PAGE_SIZE
);
1235 if (oldsize
> holebegin
)
1236 unmap_mapping_range(inode
->i_mapping
,
1239 shmem_truncate_range(inode
,
1240 newsize
, (loff_t
)-1);
1241 /* unmap again to remove racily COWed private pages */
1242 if (oldsize
> holebegin
)
1243 unmap_mapping_range(inode
->i_mapping
,
1248 if (is_quota_modification(idmap
, inode
, attr
)) {
1249 error
= dquot_initialize(inode
);
1254 /* Transfer quota accounting */
1255 if (i_uid_needs_update(idmap
, attr
, inode
) ||
1256 i_gid_needs_update(idmap
, attr
, inode
)) {
1257 error
= dquot_transfer(idmap
, inode
, attr
);
1262 setattr_copy(idmap
, inode
, attr
);
1263 if (attr
->ia_valid
& ATTR_MODE
)
1264 error
= posix_acl_chmod(idmap
, dentry
, inode
->i_mode
);
1265 if (!error
&& update_ctime
) {
1266 inode_set_ctime_current(inode
);
1268 inode_set_mtime_to_ts(inode
, inode_get_ctime(inode
));
1269 inode_inc_iversion(inode
);
1274 static void shmem_evict_inode(struct inode
*inode
)
1276 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1277 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1280 if (shmem_mapping(inode
->i_mapping
)) {
1281 shmem_unacct_size(info
->flags
, inode
->i_size
);
1283 mapping_set_exiting(inode
->i_mapping
);
1284 shmem_truncate_range(inode
, 0, (loff_t
)-1);
1285 if (!list_empty(&info
->shrinklist
)) {
1286 spin_lock(&sbinfo
->shrinklist_lock
);
1287 if (!list_empty(&info
->shrinklist
)) {
1288 list_del_init(&info
->shrinklist
);
1289 sbinfo
->shrinklist_len
--;
1291 spin_unlock(&sbinfo
->shrinklist_lock
);
1293 while (!list_empty(&info
->swaplist
)) {
1294 /* Wait while shmem_unuse() is scanning this inode... */
1295 wait_var_event(&info
->stop_eviction
,
1296 !atomic_read(&info
->stop_eviction
));
1297 mutex_lock(&shmem_swaplist_mutex
);
1298 /* ...but beware of the race if we peeked too early */
1299 if (!atomic_read(&info
->stop_eviction
))
1300 list_del_init(&info
->swaplist
);
1301 mutex_unlock(&shmem_swaplist_mutex
);
1305 simple_xattrs_free(&info
->xattrs
, sbinfo
->max_inodes
? &freed
: NULL
);
1306 shmem_free_inode(inode
->i_sb
, freed
);
1307 WARN_ON(inode
->i_blocks
);
1309 #ifdef CONFIG_TMPFS_QUOTA
1310 dquot_free_inode(inode
);
1315 static int shmem_find_swap_entries(struct address_space
*mapping
,
1316 pgoff_t start
, struct folio_batch
*fbatch
,
1317 pgoff_t
*indices
, unsigned int type
)
1319 XA_STATE(xas
, &mapping
->i_pages
, start
);
1320 struct folio
*folio
;
1324 xas_for_each(&xas
, folio
, ULONG_MAX
) {
1325 if (xas_retry(&xas
, folio
))
1328 if (!xa_is_value(folio
))
1331 entry
= radix_to_swp_entry(folio
);
1333 * swapin error entries can be found in the mapping. But they're
1334 * deliberately ignored here as we've done everything we can do.
1336 if (swp_type(entry
) != type
)
1339 indices
[folio_batch_count(fbatch
)] = xas
.xa_index
;
1340 if (!folio_batch_add(fbatch
, folio
))
1343 if (need_resched()) {
1350 return xas
.xa_index
;
1354 * Move the swapped pages for an inode to page cache. Returns the count
1355 * of pages swapped in, or the error in case of failure.
1357 static int shmem_unuse_swap_entries(struct inode
*inode
,
1358 struct folio_batch
*fbatch
, pgoff_t
*indices
)
1363 struct address_space
*mapping
= inode
->i_mapping
;
1365 for (i
= 0; i
< folio_batch_count(fbatch
); i
++) {
1366 struct folio
*folio
= fbatch
->folios
[i
];
1368 if (!xa_is_value(folio
))
1370 error
= shmem_swapin_folio(inode
, indices
[i
], &folio
, SGP_CACHE
,
1371 mapping_gfp_mask(mapping
), NULL
, NULL
);
1373 folio_unlock(folio
);
1377 if (error
== -ENOMEM
)
1381 return error
? error
: ret
;
1385 * If swap found in inode, free it and move page from swapcache to filecache.
1387 static int shmem_unuse_inode(struct inode
*inode
, unsigned int type
)
1389 struct address_space
*mapping
= inode
->i_mapping
;
1391 struct folio_batch fbatch
;
1392 pgoff_t indices
[PAGEVEC_SIZE
];
1396 folio_batch_init(&fbatch
);
1397 shmem_find_swap_entries(mapping
, start
, &fbatch
, indices
, type
);
1398 if (folio_batch_count(&fbatch
) == 0) {
1403 ret
= shmem_unuse_swap_entries(inode
, &fbatch
, indices
);
1407 start
= indices
[folio_batch_count(&fbatch
) - 1];
1414 * Read all the shared memory data that resides in the swap
1415 * device 'type' back into memory, so the swap device can be
1418 int shmem_unuse(unsigned int type
)
1420 struct shmem_inode_info
*info
, *next
;
1423 if (list_empty(&shmem_swaplist
))
1426 mutex_lock(&shmem_swaplist_mutex
);
1427 list_for_each_entry_safe(info
, next
, &shmem_swaplist
, swaplist
) {
1428 if (!info
->swapped
) {
1429 list_del_init(&info
->swaplist
);
1433 * Drop the swaplist mutex while searching the inode for swap;
1434 * but before doing so, make sure shmem_evict_inode() will not
1435 * remove placeholder inode from swaplist, nor let it be freed
1436 * (igrab() would protect from unlink, but not from unmount).
1438 atomic_inc(&info
->stop_eviction
);
1439 mutex_unlock(&shmem_swaplist_mutex
);
1441 error
= shmem_unuse_inode(&info
->vfs_inode
, type
);
1444 mutex_lock(&shmem_swaplist_mutex
);
1445 next
= list_next_entry(info
, swaplist
);
1447 list_del_init(&info
->swaplist
);
1448 if (atomic_dec_and_test(&info
->stop_eviction
))
1449 wake_up_var(&info
->stop_eviction
);
1453 mutex_unlock(&shmem_swaplist_mutex
);
1459 * Move the page from the page cache to the swap cache.
1461 static int shmem_writepage(struct page
*page
, struct writeback_control
*wbc
)
1463 struct folio
*folio
= page_folio(page
);
1464 struct address_space
*mapping
= folio
->mapping
;
1465 struct inode
*inode
= mapping
->host
;
1466 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1467 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1474 * Our capabilities prevent regular writeback or sync from ever calling
1475 * shmem_writepage; but a stacking filesystem might use ->writepage of
1476 * its underlying filesystem, in which case tmpfs should write out to
1477 * swap only in response to memory pressure, and not for the writeback
1480 if (WARN_ON_ONCE(!wbc
->for_reclaim
))
1483 if (WARN_ON_ONCE((info
->flags
& VM_LOCKED
) || sbinfo
->noswap
))
1486 if (!total_swap_pages
)
1490 * If CONFIG_THP_SWAP is not enabled, the large folio should be
1491 * split when swapping.
1493 * And shrinkage of pages beyond i_size does not split swap, so
1494 * swapout of a large folio crossing i_size needs to split too
1495 * (unless fallocate has been used to preallocate beyond EOF).
1497 if (folio_test_large(folio
)) {
1498 index
= shmem_fallocend(inode
,
1499 DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
));
1500 if ((index
> folio
->index
&& index
< folio_next_index(folio
)) ||
1501 !IS_ENABLED(CONFIG_THP_SWAP
))
1507 /* Ensure the subpages are still dirty */
1508 folio_test_set_dirty(folio
);
1509 if (split_huge_page_to_list_to_order(page
, wbc
->list
, 0))
1511 folio
= page_folio(page
);
1512 folio_clear_dirty(folio
);
1515 index
= folio
->index
;
1516 nr_pages
= folio_nr_pages(folio
);
1519 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1520 * value into swapfile.c, the only way we can correctly account for a
1521 * fallocated folio arriving here is now to initialize it and write it.
1523 * That's okay for a folio already fallocated earlier, but if we have
1524 * not yet completed the fallocation, then (a) we want to keep track
1525 * of this folio in case we have to undo it, and (b) it may not be a
1526 * good idea to continue anyway, once we're pushing into swap. So
1527 * reactivate the folio, and let shmem_fallocate() quit when too many.
1529 if (!folio_test_uptodate(folio
)) {
1530 if (inode
->i_private
) {
1531 struct shmem_falloc
*shmem_falloc
;
1532 spin_lock(&inode
->i_lock
);
1533 shmem_falloc
= inode
->i_private
;
1535 !shmem_falloc
->waitq
&&
1536 index
>= shmem_falloc
->start
&&
1537 index
< shmem_falloc
->next
)
1538 shmem_falloc
->nr_unswapped
++;
1540 shmem_falloc
= NULL
;
1541 spin_unlock(&inode
->i_lock
);
1545 folio_zero_range(folio
, 0, folio_size(folio
));
1546 flush_dcache_folio(folio
);
1547 folio_mark_uptodate(folio
);
1550 swap
= folio_alloc_swap(folio
);
1559 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1560 * if it's not already there. Do it now before the folio is
1561 * moved to swap cache, when its pagelock no longer protects
1562 * the inode from eviction. But don't unlock the mutex until
1563 * we've incremented swapped, because shmem_unuse_inode() will
1564 * prune a !swapped inode from the swaplist under this mutex.
1566 mutex_lock(&shmem_swaplist_mutex
);
1567 if (list_empty(&info
->swaplist
))
1568 list_add(&info
->swaplist
, &shmem_swaplist
);
1570 if (add_to_swap_cache(folio
, swap
,
1571 __GFP_HIGH
| __GFP_NOMEMALLOC
| __GFP_NOWARN
,
1573 shmem_recalc_inode(inode
, 0, nr_pages
);
1574 swap_shmem_alloc(swap
, nr_pages
);
1575 shmem_delete_from_page_cache(folio
, swp_to_radix_entry(swap
));
1577 mutex_unlock(&shmem_swaplist_mutex
);
1578 BUG_ON(folio_mapped(folio
));
1579 return swap_writepage(&folio
->page
, wbc
);
1582 mutex_unlock(&shmem_swaplist_mutex
);
1583 put_swap_folio(folio
, swap
);
1585 folio_mark_dirty(folio
);
1586 if (wbc
->for_reclaim
)
1587 return AOP_WRITEPAGE_ACTIVATE
; /* Return with folio locked */
1588 folio_unlock(folio
);
1592 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1593 static void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1597 if (!mpol
|| mpol
->mode
== MPOL_DEFAULT
)
1598 return; /* show nothing */
1600 mpol_to_str(buffer
, sizeof(buffer
), mpol
);
1602 seq_printf(seq
, ",mpol=%s", buffer
);
1605 static struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1607 struct mempolicy
*mpol
= NULL
;
1609 raw_spin_lock(&sbinfo
->stat_lock
); /* prevent replace/use races */
1610 mpol
= sbinfo
->mpol
;
1612 raw_spin_unlock(&sbinfo
->stat_lock
);
1616 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1617 static inline void shmem_show_mpol(struct seq_file
*seq
, struct mempolicy
*mpol
)
1620 static inline struct mempolicy
*shmem_get_sbmpol(struct shmem_sb_info
*sbinfo
)
1624 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1626 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
1627 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
);
1629 static struct folio
*shmem_swapin_cluster(swp_entry_t swap
, gfp_t gfp
,
1630 struct shmem_inode_info
*info
, pgoff_t index
)
1632 struct mempolicy
*mpol
;
1634 struct folio
*folio
;
1636 mpol
= shmem_get_pgoff_policy(info
, index
, 0, &ilx
);
1637 folio
= swap_cluster_readahead(swap
, gfp
, mpol
, ilx
);
1638 mpol_cond_put(mpol
);
1644 * Make sure huge_gfp is always more limited than limit_gfp.
1645 * Some of the flags set permissions, while others set limitations.
1647 static gfp_t
limit_gfp_mask(gfp_t huge_gfp
, gfp_t limit_gfp
)
1649 gfp_t allowflags
= __GFP_IO
| __GFP_FS
| __GFP_RECLAIM
;
1650 gfp_t denyflags
= __GFP_NOWARN
| __GFP_NORETRY
;
1651 gfp_t zoneflags
= limit_gfp
& GFP_ZONEMASK
;
1652 gfp_t result
= huge_gfp
& ~(allowflags
| GFP_ZONEMASK
);
1654 /* Allow allocations only from the originally specified zones. */
1655 result
|= zoneflags
;
1658 * Minimize the result gfp by taking the union with the deny flags,
1659 * and the intersection of the allow flags.
1661 result
|= (limit_gfp
& denyflags
);
1662 result
|= (huge_gfp
& limit_gfp
) & allowflags
;
1667 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1668 bool shmem_hpage_pmd_enabled(void)
1670 if (shmem_huge
== SHMEM_HUGE_DENY
)
1672 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_always
))
1674 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_madvise
))
1676 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_within_size
))
1678 if (test_bit(HPAGE_PMD_ORDER
, &huge_shmem_orders_inherit
) &&
1679 shmem_huge
!= SHMEM_HUGE_NEVER
)
1685 unsigned long shmem_allowable_huge_orders(struct inode
*inode
,
1686 struct vm_area_struct
*vma
, pgoff_t index
,
1687 loff_t write_end
, bool shmem_huge_force
)
1689 unsigned long mask
= READ_ONCE(huge_shmem_orders_always
);
1690 unsigned long within_size_orders
= READ_ONCE(huge_shmem_orders_within_size
);
1691 unsigned long vm_flags
= vma
? vma
->vm_flags
: 0;
1696 if (thp_disabled_by_hw() || (vma
&& vma_thp_disabled(vma
, vm_flags
)))
1699 global_huge
= shmem_huge_global_enabled(inode
, index
, write_end
,
1700 shmem_huge_force
, vm_flags
);
1701 if (!vma
|| !vma_is_anon_shmem(vma
)) {
1703 * For tmpfs, we now only support PMD sized THP if huge page
1704 * is enabled, otherwise fallback to order 0.
1706 return global_huge
? BIT(HPAGE_PMD_ORDER
) : 0;
1710 * Following the 'deny' semantics of the top level, force the huge
1711 * option off from all mounts.
1713 if (shmem_huge
== SHMEM_HUGE_DENY
)
1717 * Only allow inherit orders if the top-level value is 'force', which
1718 * means non-PMD sized THP can not override 'huge' mount option now.
1720 if (shmem_huge
== SHMEM_HUGE_FORCE
)
1721 return READ_ONCE(huge_shmem_orders_inherit
);
1723 /* Allow mTHP that will be fully within i_size. */
1724 order
= highest_order(within_size_orders
);
1725 while (within_size_orders
) {
1726 index
= round_up(index
+ 1, order
);
1727 i_size
= round_up(i_size_read(inode
), PAGE_SIZE
);
1728 if (i_size
>> PAGE_SHIFT
>= index
) {
1729 mask
|= within_size_orders
;
1733 order
= next_order(&within_size_orders
, order
);
1736 if (vm_flags
& VM_HUGEPAGE
)
1737 mask
|= READ_ONCE(huge_shmem_orders_madvise
);
1740 mask
|= READ_ONCE(huge_shmem_orders_inherit
);
1742 return THP_ORDERS_ALL_FILE_DEFAULT
& mask
;
1745 static unsigned long shmem_suitable_orders(struct inode
*inode
, struct vm_fault
*vmf
,
1746 struct address_space
*mapping
, pgoff_t index
,
1747 unsigned long orders
)
1749 struct vm_area_struct
*vma
= vmf
? vmf
->vma
: NULL
;
1750 pgoff_t aligned_index
;
1751 unsigned long pages
;
1755 orders
= thp_vma_suitable_orders(vma
, vmf
->address
, orders
);
1760 /* Find the highest order that can add into the page cache */
1761 order
= highest_order(orders
);
1763 pages
= 1UL << order
;
1764 aligned_index
= round_down(index
, pages
);
1766 * Check for conflict before waiting on a huge allocation.
1767 * Conflict might be that a huge page has just been allocated
1768 * and added to page cache by a racing thread, or that there
1769 * is already at least one small page in the huge extent.
1770 * Be careful to retry when appropriate, but not forever!
1771 * Elsewhere -EEXIST would be the right code, but not here.
1773 if (!xa_find(&mapping
->i_pages
, &aligned_index
,
1774 aligned_index
+ pages
- 1, XA_PRESENT
))
1776 order
= next_order(&orders
, order
);
1782 static unsigned long shmem_suitable_orders(struct inode
*inode
, struct vm_fault
*vmf
,
1783 struct address_space
*mapping
, pgoff_t index
,
1784 unsigned long orders
)
1788 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1790 static struct folio
*shmem_alloc_folio(gfp_t gfp
, int order
,
1791 struct shmem_inode_info
*info
, pgoff_t index
)
1793 struct mempolicy
*mpol
;
1795 struct folio
*folio
;
1797 mpol
= shmem_get_pgoff_policy(info
, index
, order
, &ilx
);
1798 folio
= folio_alloc_mpol(gfp
, order
, mpol
, ilx
, numa_node_id());
1799 mpol_cond_put(mpol
);
1804 static struct folio
*shmem_alloc_and_add_folio(struct vm_fault
*vmf
,
1805 gfp_t gfp
, struct inode
*inode
, pgoff_t index
,
1806 struct mm_struct
*fault_mm
, unsigned long orders
)
1808 struct address_space
*mapping
= inode
->i_mapping
;
1809 struct shmem_inode_info
*info
= SHMEM_I(inode
);
1810 unsigned long suitable_orders
= 0;
1811 struct folio
*folio
= NULL
;
1815 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
))
1819 suitable_orders
= shmem_suitable_orders(inode
, vmf
,
1820 mapping
, index
, orders
);
1822 order
= highest_order(suitable_orders
);
1823 while (suitable_orders
) {
1824 pages
= 1UL << order
;
1825 index
= round_down(index
, pages
);
1826 folio
= shmem_alloc_folio(gfp
, order
, info
, index
);
1830 if (pages
== HPAGE_PMD_NR
)
1831 count_vm_event(THP_FILE_FALLBACK
);
1832 count_mthp_stat(order
, MTHP_STAT_SHMEM_FALLBACK
);
1833 order
= next_order(&suitable_orders
, order
);
1837 folio
= shmem_alloc_folio(gfp
, 0, info
, index
);
1840 return ERR_PTR(-ENOMEM
);
1843 __folio_set_locked(folio
);
1844 __folio_set_swapbacked(folio
);
1846 gfp
&= GFP_RECLAIM_MASK
;
1847 error
= mem_cgroup_charge(folio
, fault_mm
, gfp
);
1849 if (xa_find(&mapping
->i_pages
, &index
,
1850 index
+ pages
- 1, XA_PRESENT
)) {
1852 } else if (pages
> 1) {
1853 if (pages
== HPAGE_PMD_NR
) {
1854 count_vm_event(THP_FILE_FALLBACK
);
1855 count_vm_event(THP_FILE_FALLBACK_CHARGE
);
1857 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_FALLBACK
);
1858 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_FALLBACK_CHARGE
);
1863 error
= shmem_add_to_page_cache(folio
, mapping
, index
, NULL
, gfp
);
1867 error
= shmem_inode_acct_blocks(inode
, pages
);
1869 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
1872 * Try to reclaim some space by splitting a few
1873 * large folios beyond i_size on the filesystem.
1875 shmem_unused_huge_shrink(sbinfo
, NULL
, pages
);
1877 * And do a shmem_recalc_inode() to account for freed pages:
1878 * except our folio is there in cache, so not quite balanced.
1880 spin_lock(&info
->lock
);
1881 freed
= pages
+ info
->alloced
- info
->swapped
-
1882 READ_ONCE(mapping
->nrpages
);
1884 info
->alloced
-= freed
;
1885 spin_unlock(&info
->lock
);
1887 shmem_inode_unacct_blocks(inode
, freed
);
1888 error
= shmem_inode_acct_blocks(inode
, pages
);
1890 filemap_remove_folio(folio
);
1895 shmem_recalc_inode(inode
, pages
, 0);
1896 folio_add_lru(folio
);
1900 folio_unlock(folio
);
1902 return ERR_PTR(error
);
1906 * When a page is moved from swapcache to shmem filecache (either by the
1907 * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
1908 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1909 * ignorance of the mapping it belongs to. If that mapping has special
1910 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1911 * we may need to copy to a suitable page before moving to filecache.
1913 * In a future release, this may well be extended to respect cpuset and
1914 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1915 * but for now it is a simple matter of zone.
1917 static bool shmem_should_replace_folio(struct folio
*folio
, gfp_t gfp
)
1919 return folio_zonenum(folio
) > gfp_zone(gfp
);
1922 static int shmem_replace_folio(struct folio
**foliop
, gfp_t gfp
,
1923 struct shmem_inode_info
*info
, pgoff_t index
,
1924 struct vm_area_struct
*vma
)
1926 struct folio
*new, *old
= *foliop
;
1927 swp_entry_t entry
= old
->swap
;
1928 struct address_space
*swap_mapping
= swap_address_space(entry
);
1929 pgoff_t swap_index
= swap_cache_index(entry
);
1930 XA_STATE(xas
, &swap_mapping
->i_pages
, swap_index
);
1931 int nr_pages
= folio_nr_pages(old
);
1935 * We have arrived here because our zones are constrained, so don't
1936 * limit chance of success by further cpuset and node constraints.
1938 gfp
&= ~GFP_CONSTRAINT_MASK
;
1939 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1941 gfp_t huge_gfp
= vma_thp_gfp_mask(vma
);
1943 gfp
= limit_gfp_mask(huge_gfp
, gfp
);
1947 new = shmem_alloc_folio(gfp
, folio_order(old
), info
, index
);
1951 folio_ref_add(new, nr_pages
);
1952 folio_copy(new, old
);
1953 flush_dcache_folio(new);
1955 __folio_set_locked(new);
1956 __folio_set_swapbacked(new);
1957 folio_mark_uptodate(new);
1959 folio_set_swapcache(new);
1961 /* Swap cache still stores N entries instead of a high-order entry */
1962 xa_lock_irq(&swap_mapping
->i_pages
);
1963 for (i
= 0; i
< nr_pages
; i
++) {
1964 void *item
= xas_load(&xas
);
1971 xas_store(&xas
, new);
1975 mem_cgroup_replace_folio(old
, new);
1976 shmem_update_stats(new, nr_pages
);
1977 shmem_update_stats(old
, -nr_pages
);
1979 xa_unlock_irq(&swap_mapping
->i_pages
);
1981 if (unlikely(error
)) {
1983 * Is this possible? I think not, now that our callers
1984 * check both the swapcache flag and folio->private
1985 * after getting the folio lock; but be defensive.
1986 * Reverse old to newpage for clear and free.
1994 folio_clear_swapcache(old
);
1995 old
->private = NULL
;
1999 * The old folio are removed from swap cache, drop the 'nr_pages'
2000 * reference, as well as one temporary reference getting from swap
2003 folio_put_refs(old
, nr_pages
+ 1);
2007 static void shmem_set_folio_swapin_error(struct inode
*inode
, pgoff_t index
,
2008 struct folio
*folio
, swp_entry_t swap
)
2010 struct address_space
*mapping
= inode
->i_mapping
;
2011 swp_entry_t swapin_error
;
2015 swapin_error
= make_poisoned_swp_entry();
2016 old
= xa_cmpxchg_irq(&mapping
->i_pages
, index
,
2017 swp_to_radix_entry(swap
),
2018 swp_to_radix_entry(swapin_error
), 0);
2019 if (old
!= swp_to_radix_entry(swap
))
2022 nr_pages
= folio_nr_pages(folio
);
2023 folio_wait_writeback(folio
);
2024 delete_from_swap_cache(folio
);
2026 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks
2027 * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks)
2028 * in shmem_evict_inode().
2030 shmem_recalc_inode(inode
, -nr_pages
, -nr_pages
);
2031 swap_free_nr(swap
, nr_pages
);
2034 static int shmem_split_large_entry(struct inode
*inode
, pgoff_t index
,
2035 swp_entry_t swap
, gfp_t gfp
)
2037 struct address_space
*mapping
= inode
->i_mapping
;
2038 XA_STATE_ORDER(xas
, &mapping
->i_pages
, index
, 0);
2039 void *alloced_shadow
= NULL
;
2040 int alloced_order
= 0, i
;
2042 /* Convert user data gfp flags to xarray node gfp flags */
2043 gfp
&= GFP_RECLAIM_MASK
;
2046 int order
= -1, split_order
= 0;
2050 old
= xas_load(&xas
);
2051 if (!xa_is_value(old
) || swp_to_radix_entry(swap
) != old
) {
2052 xas_set_err(&xas
, -EEXIST
);
2056 order
= xas_get_order(&xas
);
2058 /* Swap entry may have changed before we re-acquire the lock */
2059 if (alloced_order
&&
2060 (old
!= alloced_shadow
|| order
!= alloced_order
)) {
2065 /* Try to split large swap entry in pagecache */
2067 if (!alloced_order
) {
2068 split_order
= order
;
2071 xas_split(&xas
, old
, order
);
2074 * Re-set the swap entry after splitting, and the swap
2075 * offset of the original large entry must be continuous.
2077 for (i
= 0; i
< 1 << order
; i
++) {
2078 pgoff_t aligned_index
= round_down(index
, 1 << order
);
2081 tmp
= swp_entry(swp_type(swap
), swp_offset(swap
) + i
);
2082 __xa_store(&mapping
->i_pages
, aligned_index
+ i
,
2083 swp_to_radix_entry(tmp
), 0);
2088 xas_unlock_irq(&xas
);
2090 /* split needed, alloc here and retry. */
2092 xas_split_alloc(&xas
, old
, split_order
, gfp
);
2093 if (xas_error(&xas
))
2095 alloced_shadow
= old
;
2096 alloced_order
= split_order
;
2101 if (!xas_nomem(&xas
, gfp
))
2106 if (xas_error(&xas
))
2107 return xas_error(&xas
);
2109 return alloced_order
;
2113 * Swap in the folio pointed to by *foliop.
2114 * Caller has to make sure that *foliop contains a valid swapped folio.
2115 * Returns 0 and the folio in foliop if success. On failure, returns the
2116 * error code and NULL in *foliop.
2118 static int shmem_swapin_folio(struct inode
*inode
, pgoff_t index
,
2119 struct folio
**foliop
, enum sgp_type sgp
,
2120 gfp_t gfp
, struct vm_area_struct
*vma
,
2121 vm_fault_t
*fault_type
)
2123 struct address_space
*mapping
= inode
->i_mapping
;
2124 struct mm_struct
*fault_mm
= vma
? vma
->vm_mm
: NULL
;
2125 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2126 struct swap_info_struct
*si
;
2127 struct folio
*folio
= NULL
;
2129 int error
, nr_pages
;
2131 VM_BUG_ON(!*foliop
|| !xa_is_value(*foliop
));
2132 swap
= radix_to_swp_entry(*foliop
);
2135 if (is_poisoned_swp_entry(swap
))
2138 si
= get_swap_device(swap
);
2140 if (!shmem_confirm_swap(mapping
, index
, swap
))
2146 /* Look it up and read it in.. */
2147 folio
= swap_cache_get_folio(swap
, NULL
, 0);
2151 /* Or update major stats only when swapin succeeds?? */
2153 *fault_type
|= VM_FAULT_MAJOR
;
2154 count_vm_event(PGMAJFAULT
);
2155 count_memcg_event_mm(fault_mm
, PGMAJFAULT
);
2159 * Now swap device can only swap in order 0 folio, then we
2160 * should split the large swap entry stored in the pagecache
2163 split_order
= shmem_split_large_entry(inode
, index
, swap
, gfp
);
2164 if (split_order
< 0) {
2165 error
= split_order
;
2170 * If the large swap entry has already been split, it is
2171 * necessary to recalculate the new swap entry based on
2172 * the old order alignment.
2174 if (split_order
> 0) {
2175 pgoff_t offset
= index
- round_down(index
, 1 << split_order
);
2177 swap
= swp_entry(swp_type(swap
), swp_offset(swap
) + offset
);
2180 /* Here we actually start the io */
2181 folio
= shmem_swapin_cluster(swap
, gfp
, info
, index
);
2188 /* We have to do this with folio locked to prevent races */
2190 if (!folio_test_swapcache(folio
) ||
2191 folio
->swap
.val
!= swap
.val
||
2192 !shmem_confirm_swap(mapping
, index
, swap
)) {
2196 if (!folio_test_uptodate(folio
)) {
2200 folio_wait_writeback(folio
);
2201 nr_pages
= folio_nr_pages(folio
);
2204 * Some architectures may have to restore extra metadata to the
2205 * folio after reading from swap.
2207 arch_swap_restore(folio_swap(swap
, folio
), folio
);
2209 if (shmem_should_replace_folio(folio
, gfp
)) {
2210 error
= shmem_replace_folio(&folio
, gfp
, info
, index
, vma
);
2215 error
= shmem_add_to_page_cache(folio
, mapping
,
2216 round_down(index
, nr_pages
),
2217 swp_to_radix_entry(swap
), gfp
);
2221 shmem_recalc_inode(inode
, 0, -nr_pages
);
2223 if (sgp
== SGP_WRITE
)
2224 folio_mark_accessed(folio
);
2226 delete_from_swap_cache(folio
);
2227 folio_mark_dirty(folio
);
2228 swap_free_nr(swap
, nr_pages
);
2229 put_swap_device(si
);
2234 if (!shmem_confirm_swap(mapping
, index
, swap
))
2237 shmem_set_folio_swapin_error(inode
, index
, folio
, swap
);
2240 folio_unlock(folio
);
2243 put_swap_device(si
);
2249 * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
2251 * If we allocate a new one we do not mark it dirty. That's up to the
2252 * vm. If we swap it in we mark it dirty since we also free the swap
2253 * entry since a page cannot live in both the swap and page cache.
2255 * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL.
2257 static int shmem_get_folio_gfp(struct inode
*inode
, pgoff_t index
,
2258 loff_t write_end
, struct folio
**foliop
, enum sgp_type sgp
,
2259 gfp_t gfp
, struct vm_fault
*vmf
, vm_fault_t
*fault_type
)
2261 struct vm_area_struct
*vma
= vmf
? vmf
->vma
: NULL
;
2262 struct mm_struct
*fault_mm
;
2263 struct folio
*folio
;
2266 unsigned long orders
= 0;
2268 if (WARN_ON_ONCE(!shmem_mapping(inode
->i_mapping
)))
2271 if (index
> (MAX_LFS_FILESIZE
>> PAGE_SHIFT
))
2274 if (sgp
<= SGP_CACHE
&&
2275 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
))
2279 fault_mm
= vma
? vma
->vm_mm
: NULL
;
2281 folio
= filemap_get_entry(inode
->i_mapping
, index
);
2282 if (folio
&& vma
&& userfaultfd_minor(vma
)) {
2283 if (!xa_is_value(folio
))
2285 *fault_type
= handle_userfault(vmf
, VM_UFFD_MINOR
);
2289 if (xa_is_value(folio
)) {
2290 error
= shmem_swapin_folio(inode
, index
, &folio
,
2291 sgp
, gfp
, vma
, fault_type
);
2292 if (error
== -EEXIST
)
2302 /* Has the folio been truncated or swapped out? */
2303 if (unlikely(folio
->mapping
!= inode
->i_mapping
)) {
2304 folio_unlock(folio
);
2308 if (sgp
== SGP_WRITE
)
2309 folio_mark_accessed(folio
);
2310 if (folio_test_uptodate(folio
))
2312 /* fallocated folio */
2313 if (sgp
!= SGP_READ
)
2315 folio_unlock(folio
);
2320 * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
2321 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
2324 if (sgp
== SGP_READ
)
2326 if (sgp
== SGP_NOALLOC
)
2330 * Fast cache lookup and swap lookup did not find it: allocate.
2333 if (vma
&& userfaultfd_missing(vma
)) {
2334 *fault_type
= handle_userfault(vmf
, VM_UFFD_MISSING
);
2338 /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */
2339 orders
= shmem_allowable_huge_orders(inode
, vma
, index
, write_end
, false);
2343 huge_gfp
= vma_thp_gfp_mask(vma
);
2344 huge_gfp
= limit_gfp_mask(huge_gfp
, gfp
);
2345 folio
= shmem_alloc_and_add_folio(vmf
, huge_gfp
,
2346 inode
, index
, fault_mm
, orders
);
2347 if (!IS_ERR(folio
)) {
2348 if (folio_test_pmd_mappable(folio
))
2349 count_vm_event(THP_FILE_ALLOC
);
2350 count_mthp_stat(folio_order(folio
), MTHP_STAT_SHMEM_ALLOC
);
2353 if (PTR_ERR(folio
) == -EEXIST
)
2357 folio
= shmem_alloc_and_add_folio(vmf
, gfp
, inode
, index
, fault_mm
, 0);
2358 if (IS_ERR(folio
)) {
2359 error
= PTR_ERR(folio
);
2360 if (error
== -EEXIST
)
2368 if (folio_test_large(folio
) &&
2369 DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
) <
2370 folio_next_index(folio
)) {
2371 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
2372 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2374 * Part of the large folio is beyond i_size: subject
2375 * to shrink under memory pressure.
2377 spin_lock(&sbinfo
->shrinklist_lock
);
2379 * _careful to defend against unlocked access to
2380 * ->shrink_list in shmem_unused_huge_shrink()
2382 if (list_empty_careful(&info
->shrinklist
)) {
2383 list_add_tail(&info
->shrinklist
,
2384 &sbinfo
->shrinklist
);
2385 sbinfo
->shrinklist_len
++;
2387 spin_unlock(&sbinfo
->shrinklist_lock
);
2390 if (sgp
== SGP_WRITE
)
2391 folio_set_referenced(folio
);
2393 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
2395 if (sgp
== SGP_FALLOC
)
2399 * Let SGP_WRITE caller clear ends if write does not fill folio;
2400 * but SGP_FALLOC on a folio fallocated earlier must initialize
2401 * it now, lest undo on failure cancel our earlier guarantee.
2403 if (sgp
!= SGP_WRITE
&& !folio_test_uptodate(folio
)) {
2404 long i
, n
= folio_nr_pages(folio
);
2406 for (i
= 0; i
< n
; i
++)
2407 clear_highpage(folio_page(folio
, i
));
2408 flush_dcache_folio(folio
);
2409 folio_mark_uptodate(folio
);
2412 /* Perhaps the file has been truncated since we checked */
2413 if (sgp
<= SGP_CACHE
&&
2414 ((loff_t
)index
<< PAGE_SHIFT
) >= i_size_read(inode
)) {
2427 filemap_remove_folio(folio
);
2428 shmem_recalc_inode(inode
, 0, 0);
2430 folio_unlock(folio
);
2437 * shmem_get_folio - find, and lock a shmem folio.
2438 * @inode: inode to search
2439 * @index: the page index.
2440 * @write_end: end of a write, could extend inode size
2441 * @foliop: pointer to the folio if found
2442 * @sgp: SGP_* flags to control behavior
2444 * Looks up the page cache entry at @inode & @index. If a folio is
2445 * present, it is returned locked with an increased refcount.
2447 * If the caller modifies data in the folio, it must call folio_mark_dirty()
2448 * before unlocking the folio to ensure that the folio is not reclaimed.
2449 * There is no need to reserve space before calling folio_mark_dirty().
2451 * When no folio is found, the behavior depends on @sgp:
2452 * - for SGP_READ, *@foliop is %NULL and 0 is returned
2453 * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned
2454 * - for all other flags a new folio is allocated, inserted into the
2455 * page cache and returned locked in @foliop.
2457 * Context: May sleep.
2458 * Return: 0 if successful, else a negative error code.
2460 int shmem_get_folio(struct inode
*inode
, pgoff_t index
, loff_t write_end
,
2461 struct folio
**foliop
, enum sgp_type sgp
)
2463 return shmem_get_folio_gfp(inode
, index
, write_end
, foliop
, sgp
,
2464 mapping_gfp_mask(inode
->i_mapping
), NULL
, NULL
);
2466 EXPORT_SYMBOL_GPL(shmem_get_folio
);
2469 * This is like autoremove_wake_function, but it removes the wait queue
2470 * entry unconditionally - even if something else had already woken the
2473 static int synchronous_wake_function(wait_queue_entry_t
*wait
,
2474 unsigned int mode
, int sync
, void *key
)
2476 int ret
= default_wake_function(wait
, mode
, sync
, key
);
2477 list_del_init(&wait
->entry
);
2482 * Trinity finds that probing a hole which tmpfs is punching can
2483 * prevent the hole-punch from ever completing: which in turn
2484 * locks writers out with its hold on i_rwsem. So refrain from
2485 * faulting pages into the hole while it's being punched. Although
2486 * shmem_undo_range() does remove the additions, it may be unable to
2487 * keep up, as each new page needs its own unmap_mapping_range() call,
2488 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2490 * It does not matter if we sometimes reach this check just before the
2491 * hole-punch begins, so that one fault then races with the punch:
2492 * we just need to make racing faults a rare case.
2494 * The implementation below would be much simpler if we just used a
2495 * standard mutex or completion: but we cannot take i_rwsem in fault,
2496 * and bloating every shmem inode for this unlikely case would be sad.
2498 static vm_fault_t
shmem_falloc_wait(struct vm_fault
*vmf
, struct inode
*inode
)
2500 struct shmem_falloc
*shmem_falloc
;
2501 struct file
*fpin
= NULL
;
2504 spin_lock(&inode
->i_lock
);
2505 shmem_falloc
= inode
->i_private
;
2507 shmem_falloc
->waitq
&&
2508 vmf
->pgoff
>= shmem_falloc
->start
&&
2509 vmf
->pgoff
< shmem_falloc
->next
) {
2510 wait_queue_head_t
*shmem_falloc_waitq
;
2511 DEFINE_WAIT_FUNC(shmem_fault_wait
, synchronous_wake_function
);
2513 ret
= VM_FAULT_NOPAGE
;
2514 fpin
= maybe_unlock_mmap_for_io(vmf
, NULL
);
2515 shmem_falloc_waitq
= shmem_falloc
->waitq
;
2516 prepare_to_wait(shmem_falloc_waitq
, &shmem_fault_wait
,
2517 TASK_UNINTERRUPTIBLE
);
2518 spin_unlock(&inode
->i_lock
);
2522 * shmem_falloc_waitq points into the shmem_fallocate()
2523 * stack of the hole-punching task: shmem_falloc_waitq
2524 * is usually invalid by the time we reach here, but
2525 * finish_wait() does not dereference it in that case;
2526 * though i_lock needed lest racing with wake_up_all().
2528 spin_lock(&inode
->i_lock
);
2529 finish_wait(shmem_falloc_waitq
, &shmem_fault_wait
);
2531 spin_unlock(&inode
->i_lock
);
2534 ret
= VM_FAULT_RETRY
;
2539 static vm_fault_t
shmem_fault(struct vm_fault
*vmf
)
2541 struct inode
*inode
= file_inode(vmf
->vma
->vm_file
);
2542 gfp_t gfp
= mapping_gfp_mask(inode
->i_mapping
);
2543 struct folio
*folio
= NULL
;
2548 * Trinity finds that probing a hole which tmpfs is punching can
2549 * prevent the hole-punch from ever completing: noted in i_private.
2551 if (unlikely(inode
->i_private
)) {
2552 ret
= shmem_falloc_wait(vmf
, inode
);
2557 WARN_ON_ONCE(vmf
->page
!= NULL
);
2558 err
= shmem_get_folio_gfp(inode
, vmf
->pgoff
, 0, &folio
, SGP_CACHE
,
2561 return vmf_error(err
);
2563 vmf
->page
= folio_file_page(folio
, vmf
->pgoff
);
2564 ret
|= VM_FAULT_LOCKED
;
2569 unsigned long shmem_get_unmapped_area(struct file
*file
,
2570 unsigned long uaddr
, unsigned long len
,
2571 unsigned long pgoff
, unsigned long flags
)
2574 unsigned long offset
;
2575 unsigned long inflated_len
;
2576 unsigned long inflated_addr
;
2577 unsigned long inflated_offset
;
2578 unsigned long hpage_size
;
2580 if (len
> TASK_SIZE
)
2583 addr
= mm_get_unmapped_area(current
->mm
, file
, uaddr
, len
, pgoff
,
2586 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
))
2588 if (IS_ERR_VALUE(addr
))
2590 if (addr
& ~PAGE_MASK
)
2592 if (addr
> TASK_SIZE
- len
)
2595 if (shmem_huge
== SHMEM_HUGE_DENY
)
2597 if (flags
& MAP_FIXED
)
2600 * Our priority is to support MAP_SHARED mapped hugely;
2601 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2602 * But if caller specified an address hint and we allocated area there
2603 * successfully, respect that as before.
2608 hpage_size
= HPAGE_PMD_SIZE
;
2609 if (shmem_huge
!= SHMEM_HUGE_FORCE
) {
2610 struct super_block
*sb
;
2611 unsigned long __maybe_unused hpage_orders
;
2615 VM_BUG_ON(file
->f_op
!= &shmem_file_operations
);
2616 sb
= file_inode(file
)->i_sb
;
2619 * Called directly from mm/mmap.c, or drivers/char/mem.c
2620 * for "/dev/zero", to create a shared anonymous object.
2622 if (IS_ERR(shm_mnt
))
2624 sb
= shm_mnt
->mnt_sb
;
2627 * Find the highest mTHP order used for anonymous shmem to
2628 * provide a suitable alignment address.
2630 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2631 hpage_orders
= READ_ONCE(huge_shmem_orders_always
);
2632 hpage_orders
|= READ_ONCE(huge_shmem_orders_within_size
);
2633 hpage_orders
|= READ_ONCE(huge_shmem_orders_madvise
);
2634 if (SHMEM_SB(sb
)->huge
!= SHMEM_HUGE_NEVER
)
2635 hpage_orders
|= READ_ONCE(huge_shmem_orders_inherit
);
2637 if (hpage_orders
> 0) {
2638 order
= highest_order(hpage_orders
);
2639 hpage_size
= PAGE_SIZE
<< order
;
2643 if (SHMEM_SB(sb
)->huge
== SHMEM_HUGE_NEVER
&& !order
)
2647 if (len
< hpage_size
)
2650 offset
= (pgoff
<< PAGE_SHIFT
) & (hpage_size
- 1);
2651 if (offset
&& offset
+ len
< 2 * hpage_size
)
2653 if ((addr
& (hpage_size
- 1)) == offset
)
2656 inflated_len
= len
+ hpage_size
- PAGE_SIZE
;
2657 if (inflated_len
> TASK_SIZE
)
2659 if (inflated_len
< len
)
2662 inflated_addr
= mm_get_unmapped_area(current
->mm
, NULL
, uaddr
,
2663 inflated_len
, 0, flags
);
2664 if (IS_ERR_VALUE(inflated_addr
))
2666 if (inflated_addr
& ~PAGE_MASK
)
2669 inflated_offset
= inflated_addr
& (hpage_size
- 1);
2670 inflated_addr
+= offset
- inflated_offset
;
2671 if (inflated_offset
> offset
)
2672 inflated_addr
+= hpage_size
;
2674 if (inflated_addr
> TASK_SIZE
- len
)
2676 return inflated_addr
;
2680 static int shmem_set_policy(struct vm_area_struct
*vma
, struct mempolicy
*mpol
)
2682 struct inode
*inode
= file_inode(vma
->vm_file
);
2683 return mpol_set_shared_policy(&SHMEM_I(inode
)->policy
, vma
, mpol
);
2686 static struct mempolicy
*shmem_get_policy(struct vm_area_struct
*vma
,
2687 unsigned long addr
, pgoff_t
*ilx
)
2689 struct inode
*inode
= file_inode(vma
->vm_file
);
2693 * Bias interleave by inode number to distribute better across nodes;
2694 * but this interface is independent of which page order is used, so
2695 * supplies only that bias, letting caller apply the offset (adjusted
2696 * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()).
2698 *ilx
= inode
->i_ino
;
2699 index
= ((addr
- vma
->vm_start
) >> PAGE_SHIFT
) + vma
->vm_pgoff
;
2700 return mpol_shared_policy_lookup(&SHMEM_I(inode
)->policy
, index
);
2703 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
2704 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
)
2706 struct mempolicy
*mpol
;
2708 /* Bias interleave by inode number to distribute better across nodes */
2709 *ilx
= info
->vfs_inode
.i_ino
+ (index
>> order
);
2711 mpol
= mpol_shared_policy_lookup(&info
->policy
, index
);
2712 return mpol
? mpol
: get_task_policy(current
);
2715 static struct mempolicy
*shmem_get_pgoff_policy(struct shmem_inode_info
*info
,
2716 pgoff_t index
, unsigned int order
, pgoff_t
*ilx
)
2721 #endif /* CONFIG_NUMA */
2723 int shmem_lock(struct file
*file
, int lock
, struct ucounts
*ucounts
)
2725 struct inode
*inode
= file_inode(file
);
2726 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2727 int retval
= -ENOMEM
;
2730 * What serializes the accesses to info->flags?
2731 * ipc_lock_object() when called from shmctl_do_lock(),
2732 * no serialization needed when called from shm_destroy().
2734 if (lock
&& !(info
->flags
& VM_LOCKED
)) {
2735 if (!user_shm_lock(inode
->i_size
, ucounts
))
2737 info
->flags
|= VM_LOCKED
;
2738 mapping_set_unevictable(file
->f_mapping
);
2740 if (!lock
&& (info
->flags
& VM_LOCKED
) && ucounts
) {
2741 user_shm_unlock(inode
->i_size
, ucounts
);
2742 info
->flags
&= ~VM_LOCKED
;
2743 mapping_clear_unevictable(file
->f_mapping
);
2751 static int shmem_mmap(struct file
*file
, struct vm_area_struct
*vma
)
2753 struct inode
*inode
= file_inode(file
);
2754 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2757 ret
= seal_check_write(info
->seals
, vma
);
2761 file_accessed(file
);
2762 /* This is anonymous shared memory if it is unlinked at the time of mmap */
2764 vma
->vm_ops
= &shmem_vm_ops
;
2766 vma
->vm_ops
= &shmem_anon_vm_ops
;
2770 static int shmem_file_open(struct inode
*inode
, struct file
*file
)
2772 file
->f_mode
|= FMODE_CAN_ODIRECT
;
2773 return generic_file_open(inode
, file
);
2776 #ifdef CONFIG_TMPFS_XATTR
2777 static int shmem_initxattrs(struct inode
*, const struct xattr
*, void *);
2779 #if IS_ENABLED(CONFIG_UNICODE)
2781 * shmem_inode_casefold_flags - Deal with casefold file attribute flag
2783 * The casefold file attribute needs some special checks. I can just be added to
2784 * an empty dir, and can't be removed from a non-empty dir.
2786 static int shmem_inode_casefold_flags(struct inode
*inode
, unsigned int fsflags
,
2787 struct dentry
*dentry
, unsigned int *i_flags
)
2789 unsigned int old
= inode
->i_flags
;
2790 struct super_block
*sb
= inode
->i_sb
;
2792 if (fsflags
& FS_CASEFOLD_FL
) {
2793 if (!(old
& S_CASEFOLD
)) {
2794 if (!sb
->s_encoding
)
2797 if (!S_ISDIR(inode
->i_mode
))
2800 if (dentry
&& !simple_empty(dentry
))
2804 *i_flags
= *i_flags
| S_CASEFOLD
;
2805 } else if (old
& S_CASEFOLD
) {
2806 if (dentry
&& !simple_empty(dentry
))
2813 static int shmem_inode_casefold_flags(struct inode
*inode
, unsigned int fsflags
,
2814 struct dentry
*dentry
, unsigned int *i_flags
)
2816 if (fsflags
& FS_CASEFOLD_FL
)
2824 * chattr's fsflags are unrelated to extended attributes,
2825 * but tmpfs has chosen to enable them under the same config option.
2827 static int shmem_set_inode_flags(struct inode
*inode
, unsigned int fsflags
, struct dentry
*dentry
)
2829 unsigned int i_flags
= 0;
2832 ret
= shmem_inode_casefold_flags(inode
, fsflags
, dentry
, &i_flags
);
2836 if (fsflags
& FS_NOATIME_FL
)
2837 i_flags
|= S_NOATIME
;
2838 if (fsflags
& FS_APPEND_FL
)
2839 i_flags
|= S_APPEND
;
2840 if (fsflags
& FS_IMMUTABLE_FL
)
2841 i_flags
|= S_IMMUTABLE
;
2843 * But FS_NODUMP_FL does not require any action in i_flags.
2845 inode_set_flags(inode
, i_flags
, S_NOATIME
| S_APPEND
| S_IMMUTABLE
| S_CASEFOLD
);
2850 static void shmem_set_inode_flags(struct inode
*inode
, unsigned int fsflags
, struct dentry
*dentry
)
2853 #define shmem_initxattrs NULL
2856 static struct offset_ctx
*shmem_get_offset_ctx(struct inode
*inode
)
2858 return &SHMEM_I(inode
)->dir_offsets
;
2861 static struct inode
*__shmem_get_inode(struct mnt_idmap
*idmap
,
2862 struct super_block
*sb
,
2863 struct inode
*dir
, umode_t mode
,
2864 dev_t dev
, unsigned long flags
)
2866 struct inode
*inode
;
2867 struct shmem_inode_info
*info
;
2868 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
2872 err
= shmem_reserve_inode(sb
, &ino
);
2874 return ERR_PTR(err
);
2876 inode
= new_inode(sb
);
2878 shmem_free_inode(sb
, 0);
2879 return ERR_PTR(-ENOSPC
);
2883 inode_init_owner(idmap
, inode
, dir
, mode
);
2884 inode
->i_blocks
= 0;
2885 simple_inode_init_ts(inode
);
2886 inode
->i_generation
= get_random_u32();
2887 info
= SHMEM_I(inode
);
2888 memset(info
, 0, (char *)inode
- (char *)info
);
2889 spin_lock_init(&info
->lock
);
2890 atomic_set(&info
->stop_eviction
, 0);
2891 info
->seals
= F_SEAL_SEAL
;
2892 info
->flags
= flags
& VM_NORESERVE
;
2893 info
->i_crtime
= inode_get_mtime(inode
);
2894 info
->fsflags
= (dir
== NULL
) ? 0 :
2895 SHMEM_I(dir
)->fsflags
& SHMEM_FL_INHERITED
;
2897 shmem_set_inode_flags(inode
, info
->fsflags
, NULL
);
2898 INIT_LIST_HEAD(&info
->shrinklist
);
2899 INIT_LIST_HEAD(&info
->swaplist
);
2900 simple_xattrs_init(&info
->xattrs
);
2901 cache_no_acl(inode
);
2903 mapping_set_unevictable(inode
->i_mapping
);
2905 /* Don't consider 'deny' for emergencies and 'force' for testing */
2907 mapping_set_large_folios(inode
->i_mapping
);
2909 switch (mode
& S_IFMT
) {
2911 inode
->i_op
= &shmem_special_inode_operations
;
2912 init_special_inode(inode
, mode
, dev
);
2915 inode
->i_mapping
->a_ops
= &shmem_aops
;
2916 inode
->i_op
= &shmem_inode_operations
;
2917 inode
->i_fop
= &shmem_file_operations
;
2918 mpol_shared_policy_init(&info
->policy
,
2919 shmem_get_sbmpol(sbinfo
));
2923 /* Some things misbehave if size == 0 on a directory */
2924 inode
->i_size
= 2 * BOGO_DIRENT_SIZE
;
2925 inode
->i_op
= &shmem_dir_inode_operations
;
2926 inode
->i_fop
= &simple_offset_dir_operations
;
2927 simple_offset_init(shmem_get_offset_ctx(inode
));
2931 * Must not load anything in the rbtree,
2932 * mpol_free_shared_policy will not be called.
2934 mpol_shared_policy_init(&info
->policy
, NULL
);
2938 lockdep_annotate_inode_mutex_key(inode
);
2942 #ifdef CONFIG_TMPFS_QUOTA
2943 static struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
2944 struct super_block
*sb
, struct inode
*dir
,
2945 umode_t mode
, dev_t dev
, unsigned long flags
)
2948 struct inode
*inode
;
2950 inode
= __shmem_get_inode(idmap
, sb
, dir
, mode
, dev
, flags
);
2954 err
= dquot_initialize(inode
);
2958 err
= dquot_alloc_inode(inode
);
2966 inode
->i_flags
|= S_NOQUOTA
;
2968 return ERR_PTR(err
);
2971 static inline struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
2972 struct super_block
*sb
, struct inode
*dir
,
2973 umode_t mode
, dev_t dev
, unsigned long flags
)
2975 return __shmem_get_inode(idmap
, sb
, dir
, mode
, dev
, flags
);
2977 #endif /* CONFIG_TMPFS_QUOTA */
2979 #ifdef CONFIG_USERFAULTFD
2980 int shmem_mfill_atomic_pte(pmd_t
*dst_pmd
,
2981 struct vm_area_struct
*dst_vma
,
2982 unsigned long dst_addr
,
2983 unsigned long src_addr
,
2985 struct folio
**foliop
)
2987 struct inode
*inode
= file_inode(dst_vma
->vm_file
);
2988 struct shmem_inode_info
*info
= SHMEM_I(inode
);
2989 struct address_space
*mapping
= inode
->i_mapping
;
2990 gfp_t gfp
= mapping_gfp_mask(mapping
);
2991 pgoff_t pgoff
= linear_page_index(dst_vma
, dst_addr
);
2993 struct folio
*folio
;
2997 if (shmem_inode_acct_blocks(inode
, 1)) {
2999 * We may have got a page, returned -ENOENT triggering a retry,
3000 * and now we find ourselves with -ENOMEM. Release the page, to
3001 * avoid a BUG_ON in our caller.
3003 if (unlikely(*foliop
)) {
3012 folio
= shmem_alloc_folio(gfp
, 0, info
, pgoff
);
3014 goto out_unacct_blocks
;
3016 if (uffd_flags_mode_is(flags
, MFILL_ATOMIC_COPY
)) {
3017 page_kaddr
= kmap_local_folio(folio
, 0);
3019 * The read mmap_lock is held here. Despite the
3020 * mmap_lock being read recursive a deadlock is still
3021 * possible if a writer has taken a lock. For example:
3023 * process A thread 1 takes read lock on own mmap_lock
3024 * process A thread 2 calls mmap, blocks taking write lock
3025 * process B thread 1 takes page fault, read lock on own mmap lock
3026 * process B thread 2 calls mmap, blocks taking write lock
3027 * process A thread 1 blocks taking read lock on process B
3028 * process B thread 1 blocks taking read lock on process A
3030 * Disable page faults to prevent potential deadlock
3031 * and retry the copy outside the mmap_lock.
3033 pagefault_disable();
3034 ret
= copy_from_user(page_kaddr
,
3035 (const void __user
*)src_addr
,
3038 kunmap_local(page_kaddr
);
3040 /* fallback to copy_from_user outside mmap_lock */
3041 if (unlikely(ret
)) {
3044 /* don't free the page */
3045 goto out_unacct_blocks
;
3048 flush_dcache_folio(folio
);
3049 } else { /* ZEROPAGE */
3050 clear_user_highpage(&folio
->page
, dst_addr
);
3054 VM_BUG_ON_FOLIO(folio_test_large(folio
), folio
);
3058 VM_BUG_ON(folio_test_locked(folio
));
3059 VM_BUG_ON(folio_test_swapbacked(folio
));
3060 __folio_set_locked(folio
);
3061 __folio_set_swapbacked(folio
);
3062 __folio_mark_uptodate(folio
);
3065 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
3066 if (unlikely(pgoff
>= max_off
))
3069 ret
= mem_cgroup_charge(folio
, dst_vma
->vm_mm
, gfp
);
3072 ret
= shmem_add_to_page_cache(folio
, mapping
, pgoff
, NULL
, gfp
);
3076 ret
= mfill_atomic_install_pte(dst_pmd
, dst_vma
, dst_addr
,
3077 &folio
->page
, true, flags
);
3079 goto out_delete_from_cache
;
3081 shmem_recalc_inode(inode
, 1, 0);
3082 folio_unlock(folio
);
3084 out_delete_from_cache
:
3085 filemap_remove_folio(folio
);
3087 folio_unlock(folio
);
3090 shmem_inode_unacct_blocks(inode
, 1);
3093 #endif /* CONFIG_USERFAULTFD */
3096 static const struct inode_operations shmem_symlink_inode_operations
;
3097 static const struct inode_operations shmem_short_symlink_operations
;
3100 shmem_write_begin(struct file
*file
, struct address_space
*mapping
,
3101 loff_t pos
, unsigned len
,
3102 struct folio
**foliop
, void **fsdata
)
3104 struct inode
*inode
= mapping
->host
;
3105 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3106 pgoff_t index
= pos
>> PAGE_SHIFT
;
3107 struct folio
*folio
;
3110 /* i_rwsem is held by caller */
3111 if (unlikely(info
->seals
& (F_SEAL_GROW
|
3112 F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
))) {
3113 if (info
->seals
& (F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
))
3115 if ((info
->seals
& F_SEAL_GROW
) && pos
+ len
> inode
->i_size
)
3119 ret
= shmem_get_folio(inode
, index
, pos
+ len
, &folio
, SGP_WRITE
);
3123 if (folio_test_hwpoison(folio
) ||
3124 (folio_test_large(folio
) && folio_test_has_hwpoisoned(folio
))) {
3125 folio_unlock(folio
);
3135 shmem_write_end(struct file
*file
, struct address_space
*mapping
,
3136 loff_t pos
, unsigned len
, unsigned copied
,
3137 struct folio
*folio
, void *fsdata
)
3139 struct inode
*inode
= mapping
->host
;
3141 if (pos
+ copied
> inode
->i_size
)
3142 i_size_write(inode
, pos
+ copied
);
3144 if (!folio_test_uptodate(folio
)) {
3145 if (copied
< folio_size(folio
)) {
3146 size_t from
= offset_in_folio(folio
, pos
);
3147 folio_zero_segments(folio
, 0, from
,
3148 from
+ copied
, folio_size(folio
));
3150 folio_mark_uptodate(folio
);
3152 folio_mark_dirty(folio
);
3153 folio_unlock(folio
);
3159 static ssize_t
shmem_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*to
)
3161 struct file
*file
= iocb
->ki_filp
;
3162 struct inode
*inode
= file_inode(file
);
3163 struct address_space
*mapping
= inode
->i_mapping
;
3165 unsigned long offset
;
3170 struct folio
*folio
= NULL
;
3171 struct page
*page
= NULL
;
3172 unsigned long nr
, ret
;
3173 loff_t end_offset
, i_size
= i_size_read(inode
);
3174 bool fallback_page_copy
= false;
3177 if (unlikely(iocb
->ki_pos
>= i_size
))
3180 index
= iocb
->ki_pos
>> PAGE_SHIFT
;
3181 error
= shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
3183 if (error
== -EINVAL
)
3188 folio_unlock(folio
);
3190 page
= folio_file_page(folio
, index
);
3191 if (PageHWPoison(page
)) {
3197 if (folio_test_large(folio
) &&
3198 folio_test_has_hwpoisoned(folio
))
3199 fallback_page_copy
= true;
3203 * We must evaluate after, since reads (unlike writes)
3204 * are called without i_rwsem protection against truncate
3206 i_size
= i_size_read(inode
);
3207 if (unlikely(iocb
->ki_pos
>= i_size
)) {
3212 end_offset
= min_t(loff_t
, i_size
, iocb
->ki_pos
+ to
->count
);
3213 if (folio
&& likely(!fallback_page_copy
))
3214 fsize
= folio_size(folio
);
3217 offset
= iocb
->ki_pos
& (fsize
- 1);
3218 nr
= min_t(loff_t
, end_offset
- iocb
->ki_pos
, fsize
- offset
);
3222 * If users can be writing to this page using arbitrary
3223 * virtual addresses, take care about potential aliasing
3224 * before reading the page on the kernel side.
3226 if (mapping_writably_mapped(mapping
)) {
3227 if (likely(!fallback_page_copy
))
3228 flush_dcache_folio(folio
);
3230 flush_dcache_page(page
);
3234 * Mark the folio accessed if we read the beginning.
3237 folio_mark_accessed(folio
);
3239 * Ok, we have the page, and it's up-to-date, so
3240 * now we can copy it to user space...
3242 if (likely(!fallback_page_copy
))
3243 ret
= copy_folio_to_iter(folio
, offset
, nr
, to
);
3245 ret
= copy_page_to_iter(page
, offset
, nr
, to
);
3247 } else if (user_backed_iter(to
)) {
3249 * Copy to user tends to be so well optimized, but
3250 * clear_user() not so much, that it is noticeably
3251 * faster to copy the zero page instead of clearing.
3253 ret
= copy_page_to_iter(ZERO_PAGE(0), offset
, nr
, to
);
3256 * But submitting the same page twice in a row to
3257 * splice() - or others? - can result in confusion:
3258 * so don't attempt that optimization on pipes etc.
3260 ret
= iov_iter_zero(nr
, to
);
3264 iocb
->ki_pos
+= ret
;
3266 if (!iov_iter_count(to
))
3275 file_accessed(file
);
3276 return retval
? retval
: error
;
3279 static ssize_t
shmem_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
3281 struct file
*file
= iocb
->ki_filp
;
3282 struct inode
*inode
= file
->f_mapping
->host
;
3286 ret
= generic_write_checks(iocb
, from
);
3289 ret
= file_remove_privs(file
);
3292 ret
= file_update_time(file
);
3295 ret
= generic_perform_write(iocb
, from
);
3297 inode_unlock(inode
);
3301 static bool zero_pipe_buf_get(struct pipe_inode_info
*pipe
,
3302 struct pipe_buffer
*buf
)
3307 static void zero_pipe_buf_release(struct pipe_inode_info
*pipe
,
3308 struct pipe_buffer
*buf
)
3312 static bool zero_pipe_buf_try_steal(struct pipe_inode_info
*pipe
,
3313 struct pipe_buffer
*buf
)
3318 static const struct pipe_buf_operations zero_pipe_buf_ops
= {
3319 .release
= zero_pipe_buf_release
,
3320 .try_steal
= zero_pipe_buf_try_steal
,
3321 .get
= zero_pipe_buf_get
,
3324 static size_t splice_zeropage_into_pipe(struct pipe_inode_info
*pipe
,
3325 loff_t fpos
, size_t size
)
3327 size_t offset
= fpos
& ~PAGE_MASK
;
3329 size
= min_t(size_t, size
, PAGE_SIZE
- offset
);
3331 if (!pipe_full(pipe
->head
, pipe
->tail
, pipe
->max_usage
)) {
3332 struct pipe_buffer
*buf
= pipe_head_buf(pipe
);
3334 *buf
= (struct pipe_buffer
) {
3335 .ops
= &zero_pipe_buf_ops
,
3336 .page
= ZERO_PAGE(0),
3346 static ssize_t
shmem_file_splice_read(struct file
*in
, loff_t
*ppos
,
3347 struct pipe_inode_info
*pipe
,
3348 size_t len
, unsigned int flags
)
3350 struct inode
*inode
= file_inode(in
);
3351 struct address_space
*mapping
= inode
->i_mapping
;
3352 struct folio
*folio
= NULL
;
3353 size_t total_spliced
= 0, used
, npages
, n
, part
;
3357 /* Work out how much data we can actually add into the pipe */
3358 used
= pipe_occupancy(pipe
->head
, pipe
->tail
);
3359 npages
= max_t(ssize_t
, pipe
->max_usage
- used
, 0);
3360 len
= min_t(size_t, len
, npages
* PAGE_SIZE
);
3363 bool fallback_page_splice
= false;
3364 struct page
*page
= NULL
;
3368 if (*ppos
>= i_size_read(inode
))
3371 index
= *ppos
>> PAGE_SHIFT
;
3372 error
= shmem_get_folio(inode
, index
, 0, &folio
, SGP_READ
);
3374 if (error
== -EINVAL
)
3379 folio_unlock(folio
);
3381 page
= folio_file_page(folio
, index
);
3382 if (PageHWPoison(page
)) {
3387 if (folio_test_large(folio
) &&
3388 folio_test_has_hwpoisoned(folio
))
3389 fallback_page_splice
= true;
3393 * i_size must be checked after we know the pages are Uptodate.
3395 * Checking i_size after the check allows us to calculate
3396 * the correct value for "nr", which means the zero-filled
3397 * part of the page is not copied back to userspace (unless
3398 * another truncate extends the file - this is desired though).
3400 isize
= i_size_read(inode
);
3401 if (unlikely(*ppos
>= isize
))
3404 * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned
3408 if (unlikely(fallback_page_splice
)) {
3409 size_t offset
= *ppos
& ~PAGE_MASK
;
3411 size
= umin(size
, PAGE_SIZE
- offset
);
3413 part
= min_t(loff_t
, isize
- *ppos
, size
);
3417 * If users can be writing to this page using arbitrary
3418 * virtual addresses, take care about potential aliasing
3419 * before reading the page on the kernel side.
3421 if (mapping_writably_mapped(mapping
)) {
3422 if (likely(!fallback_page_splice
))
3423 flush_dcache_folio(folio
);
3425 flush_dcache_page(page
);
3427 folio_mark_accessed(folio
);
3429 * Ok, we have the page, and it's up-to-date, so we can
3430 * now splice it into the pipe.
3432 n
= splice_folio_into_pipe(pipe
, folio
, *ppos
, part
);
3436 n
= splice_zeropage_into_pipe(pipe
, *ppos
, part
);
3444 in
->f_ra
.prev_pos
= *ppos
;
3445 if (pipe_full(pipe
->head
, pipe
->tail
, pipe
->max_usage
))
3455 return total_spliced
? total_spliced
: error
;
3458 static loff_t
shmem_file_llseek(struct file
*file
, loff_t offset
, int whence
)
3460 struct address_space
*mapping
= file
->f_mapping
;
3461 struct inode
*inode
= mapping
->host
;
3463 if (whence
!= SEEK_DATA
&& whence
!= SEEK_HOLE
)
3464 return generic_file_llseek_size(file
, offset
, whence
,
3465 MAX_LFS_FILESIZE
, i_size_read(inode
));
3470 /* We're holding i_rwsem so we can access i_size directly */
3471 offset
= mapping_seek_hole_data(mapping
, offset
, inode
->i_size
, whence
);
3473 offset
= vfs_setpos(file
, offset
, MAX_LFS_FILESIZE
);
3474 inode_unlock(inode
);
3478 static long shmem_fallocate(struct file
*file
, int mode
, loff_t offset
,
3481 struct inode
*inode
= file_inode(file
);
3482 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
3483 struct shmem_inode_info
*info
= SHMEM_I(inode
);
3484 struct shmem_falloc shmem_falloc
;
3485 pgoff_t start
, index
, end
, undo_fallocend
;
3488 if (mode
& ~(FALLOC_FL_KEEP_SIZE
| FALLOC_FL_PUNCH_HOLE
))
3493 if (mode
& FALLOC_FL_PUNCH_HOLE
) {
3494 struct address_space
*mapping
= file
->f_mapping
;
3495 loff_t unmap_start
= round_up(offset
, PAGE_SIZE
);
3496 loff_t unmap_end
= round_down(offset
+ len
, PAGE_SIZE
) - 1;
3497 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq
);
3499 /* protected by i_rwsem */
3500 if (info
->seals
& (F_SEAL_WRITE
| F_SEAL_FUTURE_WRITE
)) {
3505 shmem_falloc
.waitq
= &shmem_falloc_waitq
;
3506 shmem_falloc
.start
= (u64
)unmap_start
>> PAGE_SHIFT
;
3507 shmem_falloc
.next
= (unmap_end
+ 1) >> PAGE_SHIFT
;
3508 spin_lock(&inode
->i_lock
);
3509 inode
->i_private
= &shmem_falloc
;
3510 spin_unlock(&inode
->i_lock
);
3512 if ((u64
)unmap_end
> (u64
)unmap_start
)
3513 unmap_mapping_range(mapping
, unmap_start
,
3514 1 + unmap_end
- unmap_start
, 0);
3515 shmem_truncate_range(inode
, offset
, offset
+ len
- 1);
3516 /* No need to unmap again: hole-punching leaves COWed pages */
3518 spin_lock(&inode
->i_lock
);
3519 inode
->i_private
= NULL
;
3520 wake_up_all(&shmem_falloc_waitq
);
3521 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq
.head
));
3522 spin_unlock(&inode
->i_lock
);
3527 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
3528 error
= inode_newsize_ok(inode
, offset
+ len
);
3532 if ((info
->seals
& F_SEAL_GROW
) && offset
+ len
> inode
->i_size
) {
3537 start
= offset
>> PAGE_SHIFT
;
3538 end
= (offset
+ len
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
3539 /* Try to avoid a swapstorm if len is impossible to satisfy */
3540 if (sbinfo
->max_blocks
&& end
- start
> sbinfo
->max_blocks
) {
3545 shmem_falloc
.waitq
= NULL
;
3546 shmem_falloc
.start
= start
;
3547 shmem_falloc
.next
= start
;
3548 shmem_falloc
.nr_falloced
= 0;
3549 shmem_falloc
.nr_unswapped
= 0;
3550 spin_lock(&inode
->i_lock
);
3551 inode
->i_private
= &shmem_falloc
;
3552 spin_unlock(&inode
->i_lock
);
3555 * info->fallocend is only relevant when huge pages might be
3556 * involved: to prevent split_huge_page() freeing fallocated
3557 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
3559 undo_fallocend
= info
->fallocend
;
3560 if (info
->fallocend
< end
)
3561 info
->fallocend
= end
;
3563 for (index
= start
; index
< end
; ) {
3564 struct folio
*folio
;
3567 * Check for fatal signal so that we abort early in OOM
3568 * situations. We don't want to abort in case of non-fatal
3569 * signals as large fallocate can take noticeable time and
3570 * e.g. periodic timers may result in fallocate constantly
3573 if (fatal_signal_pending(current
))
3575 else if (shmem_falloc
.nr_unswapped
> shmem_falloc
.nr_falloced
)
3578 error
= shmem_get_folio(inode
, index
, offset
+ len
,
3579 &folio
, SGP_FALLOC
);
3581 info
->fallocend
= undo_fallocend
;
3582 /* Remove the !uptodate folios we added */
3583 if (index
> start
) {
3584 shmem_undo_range(inode
,
3585 (loff_t
)start
<< PAGE_SHIFT
,
3586 ((loff_t
)index
<< PAGE_SHIFT
) - 1, true);
3592 * Here is a more important optimization than it appears:
3593 * a second SGP_FALLOC on the same large folio will clear it,
3594 * making it uptodate and un-undoable if we fail later.
3596 index
= folio_next_index(folio
);
3597 /* Beware 32-bit wraparound */
3602 * Inform shmem_writepage() how far we have reached.
3603 * No need for lock or barrier: we have the page lock.
3605 if (!folio_test_uptodate(folio
))
3606 shmem_falloc
.nr_falloced
+= index
- shmem_falloc
.next
;
3607 shmem_falloc
.next
= index
;
3610 * If !uptodate, leave it that way so that freeable folios
3611 * can be recognized if we need to rollback on error later.
3612 * But mark it dirty so that memory pressure will swap rather
3613 * than free the folios we are allocating (and SGP_CACHE folios
3614 * might still be clean: we now need to mark those dirty too).
3616 folio_mark_dirty(folio
);
3617 folio_unlock(folio
);
3622 if (!(mode
& FALLOC_FL_KEEP_SIZE
) && offset
+ len
> inode
->i_size
)
3623 i_size_write(inode
, offset
+ len
);
3625 spin_lock(&inode
->i_lock
);
3626 inode
->i_private
= NULL
;
3627 spin_unlock(&inode
->i_lock
);
3630 file_modified(file
);
3631 inode_unlock(inode
);
3635 static int shmem_statfs(struct dentry
*dentry
, struct kstatfs
*buf
)
3637 struct shmem_sb_info
*sbinfo
= SHMEM_SB(dentry
->d_sb
);
3639 buf
->f_type
= TMPFS_MAGIC
;
3640 buf
->f_bsize
= PAGE_SIZE
;
3641 buf
->f_namelen
= NAME_MAX
;
3642 if (sbinfo
->max_blocks
) {
3643 buf
->f_blocks
= sbinfo
->max_blocks
;
3645 buf
->f_bfree
= sbinfo
->max_blocks
-
3646 percpu_counter_sum(&sbinfo
->used_blocks
);
3648 if (sbinfo
->max_inodes
) {
3649 buf
->f_files
= sbinfo
->max_inodes
;
3650 buf
->f_ffree
= sbinfo
->free_ispace
/ BOGO_INODE_SIZE
;
3652 /* else leave those fields 0 like simple_statfs */
3654 buf
->f_fsid
= uuid_to_fsid(dentry
->d_sb
->s_uuid
.b
);
3660 * File creation. Allocate an inode, and we're done..
3663 shmem_mknod(struct mnt_idmap
*idmap
, struct inode
*dir
,
3664 struct dentry
*dentry
, umode_t mode
, dev_t dev
)
3666 struct inode
*inode
;
3669 if (!generic_ci_validate_strict_name(dir
, &dentry
->d_name
))
3672 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, mode
, dev
, VM_NORESERVE
);
3674 return PTR_ERR(inode
);
3676 error
= simple_acl_create(dir
, inode
);
3679 error
= security_inode_init_security(inode
, dir
, &dentry
->d_name
,
3680 shmem_initxattrs
, NULL
);
3681 if (error
&& error
!= -EOPNOTSUPP
)
3684 error
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3688 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3689 inode_set_mtime_to_ts(dir
, inode_set_ctime_current(dir
));
3690 inode_inc_iversion(dir
);
3692 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3693 d_add(dentry
, inode
);
3695 d_instantiate(dentry
, inode
);
3697 dget(dentry
); /* Extra count - pin the dentry in core */
3706 shmem_tmpfile(struct mnt_idmap
*idmap
, struct inode
*dir
,
3707 struct file
*file
, umode_t mode
)
3709 struct inode
*inode
;
3712 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, mode
, 0, VM_NORESERVE
);
3713 if (IS_ERR(inode
)) {
3714 error
= PTR_ERR(inode
);
3717 error
= security_inode_init_security(inode
, dir
, NULL
,
3718 shmem_initxattrs
, NULL
);
3719 if (error
&& error
!= -EOPNOTSUPP
)
3721 error
= simple_acl_create(dir
, inode
);
3724 d_tmpfile(file
, inode
);
3727 return finish_open_simple(file
, error
);
3733 static int shmem_mkdir(struct mnt_idmap
*idmap
, struct inode
*dir
,
3734 struct dentry
*dentry
, umode_t mode
)
3738 error
= shmem_mknod(idmap
, dir
, dentry
, mode
| S_IFDIR
, 0);
3745 static int shmem_create(struct mnt_idmap
*idmap
, struct inode
*dir
,
3746 struct dentry
*dentry
, umode_t mode
, bool excl
)
3748 return shmem_mknod(idmap
, dir
, dentry
, mode
| S_IFREG
, 0);
3754 static int shmem_link(struct dentry
*old_dentry
, struct inode
*dir
,
3755 struct dentry
*dentry
)
3757 struct inode
*inode
= d_inode(old_dentry
);
3761 * No ordinary (disk based) filesystem counts links as inodes;
3762 * but each new link needs a new dentry, pinning lowmem, and
3763 * tmpfs dentries cannot be pruned until they are unlinked.
3764 * But if an O_TMPFILE file is linked into the tmpfs, the
3765 * first link must skip that, to get the accounting right.
3767 if (inode
->i_nlink
) {
3768 ret
= shmem_reserve_inode(inode
->i_sb
, NULL
);
3773 ret
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3776 shmem_free_inode(inode
->i_sb
, 0);
3780 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3781 inode_set_mtime_to_ts(dir
,
3782 inode_set_ctime_to_ts(dir
, inode_set_ctime_current(inode
)));
3783 inode_inc_iversion(dir
);
3785 ihold(inode
); /* New dentry reference */
3786 dget(dentry
); /* Extra pinning count for the created dentry */
3787 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3788 d_add(dentry
, inode
);
3790 d_instantiate(dentry
, inode
);
3795 static int shmem_unlink(struct inode
*dir
, struct dentry
*dentry
)
3797 struct inode
*inode
= d_inode(dentry
);
3799 if (inode
->i_nlink
> 1 && !S_ISDIR(inode
->i_mode
))
3800 shmem_free_inode(inode
->i_sb
, 0);
3802 simple_offset_remove(shmem_get_offset_ctx(dir
), dentry
);
3804 dir
->i_size
-= BOGO_DIRENT_SIZE
;
3805 inode_set_mtime_to_ts(dir
,
3806 inode_set_ctime_to_ts(dir
, inode_set_ctime_current(inode
)));
3807 inode_inc_iversion(dir
);
3809 dput(dentry
); /* Undo the count from "create" - does all the work */
3812 * For now, VFS can't deal with case-insensitive negative dentries, so
3813 * we invalidate them
3815 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3816 d_invalidate(dentry
);
3821 static int shmem_rmdir(struct inode
*dir
, struct dentry
*dentry
)
3823 if (!simple_offset_empty(dentry
))
3826 drop_nlink(d_inode(dentry
));
3828 return shmem_unlink(dir
, dentry
);
3831 static int shmem_whiteout(struct mnt_idmap
*idmap
,
3832 struct inode
*old_dir
, struct dentry
*old_dentry
)
3834 struct dentry
*whiteout
;
3837 whiteout
= d_alloc(old_dentry
->d_parent
, &old_dentry
->d_name
);
3841 error
= shmem_mknod(idmap
, old_dir
, whiteout
,
3842 S_IFCHR
| WHITEOUT_MODE
, WHITEOUT_DEV
);
3848 * Cheat and hash the whiteout while the old dentry is still in
3849 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
3851 * d_lookup() will consistently find one of them at this point,
3852 * not sure which one, but that isn't even important.
3859 * The VFS layer already does all the dentry stuff for rename,
3860 * we just have to decrement the usage count for the target if
3861 * it exists so that the VFS layer correctly free's it when it
3864 static int shmem_rename2(struct mnt_idmap
*idmap
,
3865 struct inode
*old_dir
, struct dentry
*old_dentry
,
3866 struct inode
*new_dir
, struct dentry
*new_dentry
,
3869 struct inode
*inode
= d_inode(old_dentry
);
3870 int they_are_dirs
= S_ISDIR(inode
->i_mode
);
3873 if (flags
& ~(RENAME_NOREPLACE
| RENAME_EXCHANGE
| RENAME_WHITEOUT
))
3876 if (flags
& RENAME_EXCHANGE
)
3877 return simple_offset_rename_exchange(old_dir
, old_dentry
,
3878 new_dir
, new_dentry
);
3880 if (!simple_offset_empty(new_dentry
))
3883 if (flags
& RENAME_WHITEOUT
) {
3884 error
= shmem_whiteout(idmap
, old_dir
, old_dentry
);
3889 error
= simple_offset_rename(old_dir
, old_dentry
, new_dir
, new_dentry
);
3893 if (d_really_is_positive(new_dentry
)) {
3894 (void) shmem_unlink(new_dir
, new_dentry
);
3895 if (they_are_dirs
) {
3896 drop_nlink(d_inode(new_dentry
));
3897 drop_nlink(old_dir
);
3899 } else if (they_are_dirs
) {
3900 drop_nlink(old_dir
);
3904 old_dir
->i_size
-= BOGO_DIRENT_SIZE
;
3905 new_dir
->i_size
+= BOGO_DIRENT_SIZE
;
3906 simple_rename_timestamp(old_dir
, old_dentry
, new_dir
, new_dentry
);
3907 inode_inc_iversion(old_dir
);
3908 inode_inc_iversion(new_dir
);
3912 static int shmem_symlink(struct mnt_idmap
*idmap
, struct inode
*dir
,
3913 struct dentry
*dentry
, const char *symname
)
3917 struct inode
*inode
;
3918 struct folio
*folio
;
3920 len
= strlen(symname
) + 1;
3921 if (len
> PAGE_SIZE
)
3922 return -ENAMETOOLONG
;
3924 inode
= shmem_get_inode(idmap
, dir
->i_sb
, dir
, S_IFLNK
| 0777, 0,
3927 return PTR_ERR(inode
);
3929 error
= security_inode_init_security(inode
, dir
, &dentry
->d_name
,
3930 shmem_initxattrs
, NULL
);
3931 if (error
&& error
!= -EOPNOTSUPP
)
3934 error
= simple_offset_add(shmem_get_offset_ctx(dir
), dentry
);
3938 inode
->i_size
= len
-1;
3939 if (len
<= SHORT_SYMLINK_LEN
) {
3940 inode
->i_link
= kmemdup(symname
, len
, GFP_KERNEL
);
3941 if (!inode
->i_link
) {
3943 goto out_remove_offset
;
3945 inode
->i_op
= &shmem_short_symlink_operations
;
3947 inode_nohighmem(inode
);
3948 inode
->i_mapping
->a_ops
= &shmem_aops
;
3949 error
= shmem_get_folio(inode
, 0, 0, &folio
, SGP_WRITE
);
3951 goto out_remove_offset
;
3952 inode
->i_op
= &shmem_symlink_inode_operations
;
3953 memcpy(folio_address(folio
), symname
, len
);
3954 folio_mark_uptodate(folio
);
3955 folio_mark_dirty(folio
);
3956 folio_unlock(folio
);
3959 dir
->i_size
+= BOGO_DIRENT_SIZE
;
3960 inode_set_mtime_to_ts(dir
, inode_set_ctime_current(dir
));
3961 inode_inc_iversion(dir
);
3962 if (IS_ENABLED(CONFIG_UNICODE
) && IS_CASEFOLDED(dir
))
3963 d_add(dentry
, inode
);
3965 d_instantiate(dentry
, inode
);
3970 simple_offset_remove(shmem_get_offset_ctx(dir
), dentry
);
3976 static void shmem_put_link(void *arg
)
3978 folio_mark_accessed(arg
);
3982 static const char *shmem_get_link(struct dentry
*dentry
, struct inode
*inode
,
3983 struct delayed_call
*done
)
3985 struct folio
*folio
= NULL
;
3989 folio
= filemap_get_folio(inode
->i_mapping
, 0);
3991 return ERR_PTR(-ECHILD
);
3992 if (PageHWPoison(folio_page(folio
, 0)) ||
3993 !folio_test_uptodate(folio
)) {
3995 return ERR_PTR(-ECHILD
);
3998 error
= shmem_get_folio(inode
, 0, 0, &folio
, SGP_READ
);
4000 return ERR_PTR(error
);
4002 return ERR_PTR(-ECHILD
);
4003 if (PageHWPoison(folio_page(folio
, 0))) {
4004 folio_unlock(folio
);
4006 return ERR_PTR(-ECHILD
);
4008 folio_unlock(folio
);
4010 set_delayed_call(done
, shmem_put_link
, folio
);
4011 return folio_address(folio
);
4014 #ifdef CONFIG_TMPFS_XATTR
4016 static int shmem_fileattr_get(struct dentry
*dentry
, struct fileattr
*fa
)
4018 struct shmem_inode_info
*info
= SHMEM_I(d_inode(dentry
));
4020 fileattr_fill_flags(fa
, info
->fsflags
& SHMEM_FL_USER_VISIBLE
);
4025 static int shmem_fileattr_set(struct mnt_idmap
*idmap
,
4026 struct dentry
*dentry
, struct fileattr
*fa
)
4028 struct inode
*inode
= d_inode(dentry
);
4029 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4032 if (fileattr_has_fsx(fa
))
4034 if (fa
->flags
& ~SHMEM_FL_USER_MODIFIABLE
)
4037 flags
= (info
->fsflags
& ~SHMEM_FL_USER_MODIFIABLE
) |
4038 (fa
->flags
& SHMEM_FL_USER_MODIFIABLE
);
4040 ret
= shmem_set_inode_flags(inode
, flags
, dentry
);
4045 info
->fsflags
= flags
;
4047 inode_set_ctime_current(inode
);
4048 inode_inc_iversion(inode
);
4053 * Superblocks without xattr inode operations may get some security.* xattr
4054 * support from the LSM "for free". As soon as we have any other xattrs
4055 * like ACLs, we also need to implement the security.* handlers at
4056 * filesystem level, though.
4060 * Callback for security_inode_init_security() for acquiring xattrs.
4062 static int shmem_initxattrs(struct inode
*inode
,
4063 const struct xattr
*xattr_array
, void *fs_info
)
4065 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4066 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
4067 const struct xattr
*xattr
;
4068 struct simple_xattr
*new_xattr
;
4072 if (sbinfo
->max_inodes
) {
4073 for (xattr
= xattr_array
; xattr
->name
!= NULL
; xattr
++) {
4074 ispace
+= simple_xattr_space(xattr
->name
,
4075 xattr
->value_len
+ XATTR_SECURITY_PREFIX_LEN
);
4078 raw_spin_lock(&sbinfo
->stat_lock
);
4079 if (sbinfo
->free_ispace
< ispace
)
4082 sbinfo
->free_ispace
-= ispace
;
4083 raw_spin_unlock(&sbinfo
->stat_lock
);
4089 for (xattr
= xattr_array
; xattr
->name
!= NULL
; xattr
++) {
4090 new_xattr
= simple_xattr_alloc(xattr
->value
, xattr
->value_len
);
4094 len
= strlen(xattr
->name
) + 1;
4095 new_xattr
->name
= kmalloc(XATTR_SECURITY_PREFIX_LEN
+ len
,
4096 GFP_KERNEL_ACCOUNT
);
4097 if (!new_xattr
->name
) {
4102 memcpy(new_xattr
->name
, XATTR_SECURITY_PREFIX
,
4103 XATTR_SECURITY_PREFIX_LEN
);
4104 memcpy(new_xattr
->name
+ XATTR_SECURITY_PREFIX_LEN
,
4107 simple_xattr_add(&info
->xattrs
, new_xattr
);
4110 if (xattr
->name
!= NULL
) {
4112 raw_spin_lock(&sbinfo
->stat_lock
);
4113 sbinfo
->free_ispace
+= ispace
;
4114 raw_spin_unlock(&sbinfo
->stat_lock
);
4116 simple_xattrs_free(&info
->xattrs
, NULL
);
4123 static int shmem_xattr_handler_get(const struct xattr_handler
*handler
,
4124 struct dentry
*unused
, struct inode
*inode
,
4125 const char *name
, void *buffer
, size_t size
)
4127 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4129 name
= xattr_full_name(handler
, name
);
4130 return simple_xattr_get(&info
->xattrs
, name
, buffer
, size
);
4133 static int shmem_xattr_handler_set(const struct xattr_handler
*handler
,
4134 struct mnt_idmap
*idmap
,
4135 struct dentry
*unused
, struct inode
*inode
,
4136 const char *name
, const void *value
,
4137 size_t size
, int flags
)
4139 struct shmem_inode_info
*info
= SHMEM_I(inode
);
4140 struct shmem_sb_info
*sbinfo
= SHMEM_SB(inode
->i_sb
);
4141 struct simple_xattr
*old_xattr
;
4144 name
= xattr_full_name(handler
, name
);
4145 if (value
&& sbinfo
->max_inodes
) {
4146 ispace
= simple_xattr_space(name
, size
);
4147 raw_spin_lock(&sbinfo
->stat_lock
);
4148 if (sbinfo
->free_ispace
< ispace
)
4151 sbinfo
->free_ispace
-= ispace
;
4152 raw_spin_unlock(&sbinfo
->stat_lock
);
4157 old_xattr
= simple_xattr_set(&info
->xattrs
, name
, value
, size
, flags
);
4158 if (!IS_ERR(old_xattr
)) {
4160 if (old_xattr
&& sbinfo
->max_inodes
)
4161 ispace
= simple_xattr_space(old_xattr
->name
,
4163 simple_xattr_free(old_xattr
);
4165 inode_set_ctime_current(inode
);
4166 inode_inc_iversion(inode
);
4169 raw_spin_lock(&sbinfo
->stat_lock
);
4170 sbinfo
->free_ispace
+= ispace
;
4171 raw_spin_unlock(&sbinfo
->stat_lock
);
4173 return PTR_ERR(old_xattr
);
4176 static const struct xattr_handler shmem_security_xattr_handler
= {
4177 .prefix
= XATTR_SECURITY_PREFIX
,
4178 .get
= shmem_xattr_handler_get
,
4179 .set
= shmem_xattr_handler_set
,
4182 static const struct xattr_handler shmem_trusted_xattr_handler
= {
4183 .prefix
= XATTR_TRUSTED_PREFIX
,
4184 .get
= shmem_xattr_handler_get
,
4185 .set
= shmem_xattr_handler_set
,
4188 static const struct xattr_handler shmem_user_xattr_handler
= {
4189 .prefix
= XATTR_USER_PREFIX
,
4190 .get
= shmem_xattr_handler_get
,
4191 .set
= shmem_xattr_handler_set
,
4194 static const struct xattr_handler
* const shmem_xattr_handlers
[] = {
4195 &shmem_security_xattr_handler
,
4196 &shmem_trusted_xattr_handler
,
4197 &shmem_user_xattr_handler
,
4201 static ssize_t
shmem_listxattr(struct dentry
*dentry
, char *buffer
, size_t size
)
4203 struct shmem_inode_info
*info
= SHMEM_I(d_inode(dentry
));
4204 return simple_xattr_list(d_inode(dentry
), &info
->xattrs
, buffer
, size
);
4206 #endif /* CONFIG_TMPFS_XATTR */
4208 static const struct inode_operations shmem_short_symlink_operations
= {
4209 .getattr
= shmem_getattr
,
4210 .setattr
= shmem_setattr
,
4211 .get_link
= simple_get_link
,
4212 #ifdef CONFIG_TMPFS_XATTR
4213 .listxattr
= shmem_listxattr
,
4217 static const struct inode_operations shmem_symlink_inode_operations
= {
4218 .getattr
= shmem_getattr
,
4219 .setattr
= shmem_setattr
,
4220 .get_link
= shmem_get_link
,
4221 #ifdef CONFIG_TMPFS_XATTR
4222 .listxattr
= shmem_listxattr
,
4226 static struct dentry
*shmem_get_parent(struct dentry
*child
)
4228 return ERR_PTR(-ESTALE
);
4231 static int shmem_match(struct inode
*ino
, void *vfh
)
4235 inum
= (inum
<< 32) | fh
[1];
4236 return ino
->i_ino
== inum
&& fh
[0] == ino
->i_generation
;
4239 /* Find any alias of inode, but prefer a hashed alias */
4240 static struct dentry
*shmem_find_alias(struct inode
*inode
)
4242 struct dentry
*alias
= d_find_alias(inode
);
4244 return alias
?: d_find_any_alias(inode
);
4247 static struct dentry
*shmem_fh_to_dentry(struct super_block
*sb
,
4248 struct fid
*fid
, int fh_len
, int fh_type
)
4250 struct inode
*inode
;
4251 struct dentry
*dentry
= NULL
;
4258 inum
= (inum
<< 32) | fid
->raw
[1];
4260 inode
= ilookup5(sb
, (unsigned long)(inum
+ fid
->raw
[0]),
4261 shmem_match
, fid
->raw
);
4263 dentry
= shmem_find_alias(inode
);
4270 static int shmem_encode_fh(struct inode
*inode
, __u32
*fh
, int *len
,
4271 struct inode
*parent
)
4275 return FILEID_INVALID
;
4278 if (inode_unhashed(inode
)) {
4279 /* Unfortunately insert_inode_hash is not idempotent,
4280 * so as we hash inodes here rather than at creation
4281 * time, we need a lock to ensure we only try
4284 static DEFINE_SPINLOCK(lock
);
4286 if (inode_unhashed(inode
))
4287 __insert_inode_hash(inode
,
4288 inode
->i_ino
+ inode
->i_generation
);
4292 fh
[0] = inode
->i_generation
;
4293 fh
[1] = inode
->i_ino
;
4294 fh
[2] = ((__u64
)inode
->i_ino
) >> 32;
4300 static const struct export_operations shmem_export_ops
= {
4301 .get_parent
= shmem_get_parent
,
4302 .encode_fh
= shmem_encode_fh
,
4303 .fh_to_dentry
= shmem_fh_to_dentry
,
4321 Opt_usrquota_block_hardlimit
,
4322 Opt_usrquota_inode_hardlimit
,
4323 Opt_grpquota_block_hardlimit
,
4324 Opt_grpquota_inode_hardlimit
,
4325 Opt_casefold_version
,
4327 Opt_strict_encoding
,
4330 static const struct constant_table shmem_param_enums_huge
[] = {
4331 {"never", SHMEM_HUGE_NEVER
},
4332 {"always", SHMEM_HUGE_ALWAYS
},
4333 {"within_size", SHMEM_HUGE_WITHIN_SIZE
},
4334 {"advise", SHMEM_HUGE_ADVISE
},
4338 const struct fs_parameter_spec shmem_fs_parameters
[] = {
4339 fsparam_gid ("gid", Opt_gid
),
4340 fsparam_enum ("huge", Opt_huge
, shmem_param_enums_huge
),
4341 fsparam_u32oct("mode", Opt_mode
),
4342 fsparam_string("mpol", Opt_mpol
),
4343 fsparam_string("nr_blocks", Opt_nr_blocks
),
4344 fsparam_string("nr_inodes", Opt_nr_inodes
),
4345 fsparam_string("size", Opt_size
),
4346 fsparam_uid ("uid", Opt_uid
),
4347 fsparam_flag ("inode32", Opt_inode32
),
4348 fsparam_flag ("inode64", Opt_inode64
),
4349 fsparam_flag ("noswap", Opt_noswap
),
4350 #ifdef CONFIG_TMPFS_QUOTA
4351 fsparam_flag ("quota", Opt_quota
),
4352 fsparam_flag ("usrquota", Opt_usrquota
),
4353 fsparam_flag ("grpquota", Opt_grpquota
),
4354 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit
),
4355 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit
),
4356 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit
),
4357 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit
),
4359 fsparam_string("casefold", Opt_casefold_version
),
4360 fsparam_flag ("casefold", Opt_casefold
),
4361 fsparam_flag ("strict_encoding", Opt_strict_encoding
),
4365 #if IS_ENABLED(CONFIG_UNICODE)
4366 static int shmem_parse_opt_casefold(struct fs_context
*fc
, struct fs_parameter
*param
,
4367 bool latest_version
)
4369 struct shmem_options
*ctx
= fc
->fs_private
;
4370 unsigned int version
= UTF8_LATEST
;
4371 struct unicode_map
*encoding
;
4372 char *version_str
= param
->string
+ 5;
4374 if (!latest_version
) {
4375 if (strncmp(param
->string
, "utf8-", 5))
4376 return invalfc(fc
, "Only UTF-8 encodings are supported "
4377 "in the format: utf8-<version number>");
4379 version
= utf8_parse_version(version_str
);
4381 return invalfc(fc
, "Invalid UTF-8 version: %s", version_str
);
4384 encoding
= utf8_load(version
);
4386 if (IS_ERR(encoding
)) {
4387 return invalfc(fc
, "Failed loading UTF-8 version: utf8-%u.%u.%u\n",
4388 unicode_major(version
), unicode_minor(version
),
4389 unicode_rev(version
));
4392 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n",
4393 unicode_major(version
), unicode_minor(version
), unicode_rev(version
));
4395 ctx
->encoding
= encoding
;
4400 static int shmem_parse_opt_casefold(struct fs_context
*fc
, struct fs_parameter
*param
,
4401 bool latest_version
)
4403 return invalfc(fc
, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4407 static int shmem_parse_one(struct fs_context
*fc
, struct fs_parameter
*param
)
4409 struct shmem_options
*ctx
= fc
->fs_private
;
4410 struct fs_parse_result result
;
4411 unsigned long long size
;
4417 opt
= fs_parse(fc
, shmem_fs_parameters
, param
, &result
);
4423 size
= memparse(param
->string
, &rest
);
4425 size
<<= PAGE_SHIFT
;
4426 size
*= totalram_pages();
4432 ctx
->blocks
= DIV_ROUND_UP(size
, PAGE_SIZE
);
4433 ctx
->seen
|= SHMEM_SEEN_BLOCKS
;
4436 ctx
->blocks
= memparse(param
->string
, &rest
);
4437 if (*rest
|| ctx
->blocks
> LONG_MAX
)
4439 ctx
->seen
|= SHMEM_SEEN_BLOCKS
;
4442 ctx
->inodes
= memparse(param
->string
, &rest
);
4443 if (*rest
|| ctx
->inodes
> ULONG_MAX
/ BOGO_INODE_SIZE
)
4445 ctx
->seen
|= SHMEM_SEEN_INODES
;
4448 ctx
->mode
= result
.uint_32
& 07777;
4454 * The requested uid must be representable in the
4455 * filesystem's idmapping.
4457 if (!kuid_has_mapping(fc
->user_ns
, kuid
))
4466 * The requested gid must be representable in the
4467 * filesystem's idmapping.
4469 if (!kgid_has_mapping(fc
->user_ns
, kgid
))
4475 ctx
->huge
= result
.uint_32
;
4476 if (ctx
->huge
!= SHMEM_HUGE_NEVER
&&
4477 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE
) &&
4478 has_transparent_hugepage()))
4479 goto unsupported_parameter
;
4480 ctx
->seen
|= SHMEM_SEEN_HUGE
;
4483 if (IS_ENABLED(CONFIG_NUMA
)) {
4484 mpol_put(ctx
->mpol
);
4486 if (mpol_parse_str(param
->string
, &ctx
->mpol
))
4490 goto unsupported_parameter
;
4492 ctx
->full_inums
= false;
4493 ctx
->seen
|= SHMEM_SEEN_INUMS
;
4496 if (sizeof(ino_t
) < 8) {
4498 "Cannot use inode64 with <64bit inums in kernel\n");
4500 ctx
->full_inums
= true;
4501 ctx
->seen
|= SHMEM_SEEN_INUMS
;
4504 if ((fc
->user_ns
!= &init_user_ns
) || !capable(CAP_SYS_ADMIN
)) {
4506 "Turning off swap in unprivileged tmpfs mounts unsupported");
4509 ctx
->seen
|= SHMEM_SEEN_NOSWAP
;
4512 if (fc
->user_ns
!= &init_user_ns
)
4513 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4514 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4515 ctx
->quota_types
|= (QTYPE_MASK_USR
| QTYPE_MASK_GRP
);
4518 if (fc
->user_ns
!= &init_user_ns
)
4519 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4520 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4521 ctx
->quota_types
|= QTYPE_MASK_USR
;
4524 if (fc
->user_ns
!= &init_user_ns
)
4525 return invalfc(fc
, "Quotas in unprivileged tmpfs mounts are unsupported");
4526 ctx
->seen
|= SHMEM_SEEN_QUOTA
;
4527 ctx
->quota_types
|= QTYPE_MASK_GRP
;
4529 case Opt_usrquota_block_hardlimit
:
4530 size
= memparse(param
->string
, &rest
);
4533 if (size
> SHMEM_QUOTA_MAX_SPC_LIMIT
)
4535 "User quota block hardlimit too large.");
4536 ctx
->qlimits
.usrquota_bhardlimit
= size
;
4538 case Opt_grpquota_block_hardlimit
:
4539 size
= memparse(param
->string
, &rest
);
4542 if (size
> SHMEM_QUOTA_MAX_SPC_LIMIT
)
4544 "Group quota block hardlimit too large.");
4545 ctx
->qlimits
.grpquota_bhardlimit
= size
;
4547 case Opt_usrquota_inode_hardlimit
:
4548 size
= memparse(param
->string
, &rest
);
4551 if (size
> SHMEM_QUOTA_MAX_INO_LIMIT
)
4553 "User quota inode hardlimit too large.");
4554 ctx
->qlimits
.usrquota_ihardlimit
= size
;
4556 case Opt_grpquota_inode_hardlimit
:
4557 size
= memparse(param
->string
, &rest
);
4560 if (size
> SHMEM_QUOTA_MAX_INO_LIMIT
)
4562 "Group quota inode hardlimit too large.");
4563 ctx
->qlimits
.grpquota_ihardlimit
= size
;
4565 case Opt_casefold_version
:
4566 return shmem_parse_opt_casefold(fc
, param
, false);
4568 return shmem_parse_opt_casefold(fc
, param
, true);
4569 case Opt_strict_encoding
:
4570 #if IS_ENABLED(CONFIG_UNICODE)
4571 ctx
->strict_encoding
= true;
4574 return invalfc(fc
, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4579 unsupported_parameter
:
4580 return invalfc(fc
, "Unsupported parameter '%s'", param
->key
);
4582 return invalfc(fc
, "Bad value for '%s'", param
->key
);
4585 static int shmem_parse_options(struct fs_context
*fc
, void *data
)
4587 char *options
= data
;
4590 int err
= security_sb_eat_lsm_opts(options
, &fc
->security
);
4595 while (options
!= NULL
) {
4596 char *this_char
= options
;
4599 * NUL-terminate this option: unfortunately,
4600 * mount options form a comma-separated list,
4601 * but mpol's nodelist may also contain commas.
4603 options
= strchr(options
, ',');
4604 if (options
== NULL
)
4607 if (!isdigit(*options
)) {
4613 char *value
= strchr(this_char
, '=');
4619 len
= strlen(value
);
4621 err
= vfs_parse_fs_string(fc
, this_char
, value
, len
);
4630 * Reconfigure a shmem filesystem.
4632 static int shmem_reconfigure(struct fs_context
*fc
)
4634 struct shmem_options
*ctx
= fc
->fs_private
;
4635 struct shmem_sb_info
*sbinfo
= SHMEM_SB(fc
->root
->d_sb
);
4636 unsigned long used_isp
;
4637 struct mempolicy
*mpol
= NULL
;
4640 raw_spin_lock(&sbinfo
->stat_lock
);
4641 used_isp
= sbinfo
->max_inodes
* BOGO_INODE_SIZE
- sbinfo
->free_ispace
;
4643 if ((ctx
->seen
& SHMEM_SEEN_BLOCKS
) && ctx
->blocks
) {
4644 if (!sbinfo
->max_blocks
) {
4645 err
= "Cannot retroactively limit size";
4648 if (percpu_counter_compare(&sbinfo
->used_blocks
,
4650 err
= "Too small a size for current use";
4654 if ((ctx
->seen
& SHMEM_SEEN_INODES
) && ctx
->inodes
) {
4655 if (!sbinfo
->max_inodes
) {
4656 err
= "Cannot retroactively limit inodes";
4659 if (ctx
->inodes
* BOGO_INODE_SIZE
< used_isp
) {
4660 err
= "Too few inodes for current use";
4665 if ((ctx
->seen
& SHMEM_SEEN_INUMS
) && !ctx
->full_inums
&&
4666 sbinfo
->next_ino
> UINT_MAX
) {
4667 err
= "Current inum too high to switch to 32-bit inums";
4670 if ((ctx
->seen
& SHMEM_SEEN_NOSWAP
) && ctx
->noswap
&& !sbinfo
->noswap
) {
4671 err
= "Cannot disable swap on remount";
4674 if (!(ctx
->seen
& SHMEM_SEEN_NOSWAP
) && !ctx
->noswap
&& sbinfo
->noswap
) {
4675 err
= "Cannot enable swap on remount if it was disabled on first mount";
4679 if (ctx
->seen
& SHMEM_SEEN_QUOTA
&&
4680 !sb_any_quota_loaded(fc
->root
->d_sb
)) {
4681 err
= "Cannot enable quota on remount";
4685 #ifdef CONFIG_TMPFS_QUOTA
4686 #define CHANGED_LIMIT(name) \
4687 (ctx->qlimits.name## hardlimit && \
4688 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit))
4690 if (CHANGED_LIMIT(usrquota_b
) || CHANGED_LIMIT(usrquota_i
) ||
4691 CHANGED_LIMIT(grpquota_b
) || CHANGED_LIMIT(grpquota_i
)) {
4692 err
= "Cannot change global quota limit on remount";
4695 #endif /* CONFIG_TMPFS_QUOTA */
4697 if (ctx
->seen
& SHMEM_SEEN_HUGE
)
4698 sbinfo
->huge
= ctx
->huge
;
4699 if (ctx
->seen
& SHMEM_SEEN_INUMS
)
4700 sbinfo
->full_inums
= ctx
->full_inums
;
4701 if (ctx
->seen
& SHMEM_SEEN_BLOCKS
)
4702 sbinfo
->max_blocks
= ctx
->blocks
;
4703 if (ctx
->seen
& SHMEM_SEEN_INODES
) {
4704 sbinfo
->max_inodes
= ctx
->inodes
;
4705 sbinfo
->free_ispace
= ctx
->inodes
* BOGO_INODE_SIZE
- used_isp
;
4709 * Preserve previous mempolicy unless mpol remount option was specified.
4712 mpol
= sbinfo
->mpol
;
4713 sbinfo
->mpol
= ctx
->mpol
; /* transfers initial ref */
4718 sbinfo
->noswap
= true;
4720 raw_spin_unlock(&sbinfo
->stat_lock
);
4724 raw_spin_unlock(&sbinfo
->stat_lock
);
4725 return invalfc(fc
, "%s", err
);
4728 static int shmem_show_options(struct seq_file
*seq
, struct dentry
*root
)
4730 struct shmem_sb_info
*sbinfo
= SHMEM_SB(root
->d_sb
);
4731 struct mempolicy
*mpol
;
4733 if (sbinfo
->max_blocks
!= shmem_default_max_blocks())
4734 seq_printf(seq
, ",size=%luk", K(sbinfo
->max_blocks
));
4735 if (sbinfo
->max_inodes
!= shmem_default_max_inodes())
4736 seq_printf(seq
, ",nr_inodes=%lu", sbinfo
->max_inodes
);
4737 if (sbinfo
->mode
!= (0777 | S_ISVTX
))
4738 seq_printf(seq
, ",mode=%03ho", sbinfo
->mode
);
4739 if (!uid_eq(sbinfo
->uid
, GLOBAL_ROOT_UID
))
4740 seq_printf(seq
, ",uid=%u",
4741 from_kuid_munged(&init_user_ns
, sbinfo
->uid
));
4742 if (!gid_eq(sbinfo
->gid
, GLOBAL_ROOT_GID
))
4743 seq_printf(seq
, ",gid=%u",
4744 from_kgid_munged(&init_user_ns
, sbinfo
->gid
));
4747 * Showing inode{64,32} might be useful even if it's the system default,
4748 * since then people don't have to resort to checking both here and
4749 * /proc/config.gz to confirm 64-bit inums were successfully applied
4750 * (which may not even exist if IKCONFIG_PROC isn't enabled).
4752 * We hide it when inode64 isn't the default and we are using 32-bit
4753 * inodes, since that probably just means the feature isn't even under
4758 * +-----------------+-----------------+
4759 * | TMPFS_INODE64=y | TMPFS_INODE64=n |
4760 * +------------------+-----------------+-----------------+
4761 * | full_inums=true | show | show |
4762 * | full_inums=false | show | hide |
4763 * +------------------+-----------------+-----------------+
4766 if (IS_ENABLED(CONFIG_TMPFS_INODE64
) || sbinfo
->full_inums
)
4767 seq_printf(seq
, ",inode%d", (sbinfo
->full_inums
? 64 : 32));
4768 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4769 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
4771 seq_printf(seq
, ",huge=%s", shmem_format_huge(sbinfo
->huge
));
4773 mpol
= shmem_get_sbmpol(sbinfo
);
4774 shmem_show_mpol(seq
, mpol
);
4777 seq_printf(seq
, ",noswap");
4778 #ifdef CONFIG_TMPFS_QUOTA
4779 if (sb_has_quota_active(root
->d_sb
, USRQUOTA
))
4780 seq_printf(seq
, ",usrquota");
4781 if (sb_has_quota_active(root
->d_sb
, GRPQUOTA
))
4782 seq_printf(seq
, ",grpquota");
4783 if (sbinfo
->qlimits
.usrquota_bhardlimit
)
4784 seq_printf(seq
, ",usrquota_block_hardlimit=%lld",
4785 sbinfo
->qlimits
.usrquota_bhardlimit
);
4786 if (sbinfo
->qlimits
.grpquota_bhardlimit
)
4787 seq_printf(seq
, ",grpquota_block_hardlimit=%lld",
4788 sbinfo
->qlimits
.grpquota_bhardlimit
);
4789 if (sbinfo
->qlimits
.usrquota_ihardlimit
)
4790 seq_printf(seq
, ",usrquota_inode_hardlimit=%lld",
4791 sbinfo
->qlimits
.usrquota_ihardlimit
);
4792 if (sbinfo
->qlimits
.grpquota_ihardlimit
)
4793 seq_printf(seq
, ",grpquota_inode_hardlimit=%lld",
4794 sbinfo
->qlimits
.grpquota_ihardlimit
);
4799 #endif /* CONFIG_TMPFS */
4801 static void shmem_put_super(struct super_block
*sb
)
4803 struct shmem_sb_info
*sbinfo
= SHMEM_SB(sb
);
4805 #if IS_ENABLED(CONFIG_UNICODE)
4807 utf8_unload(sb
->s_encoding
);
4810 #ifdef CONFIG_TMPFS_QUOTA
4811 shmem_disable_quotas(sb
);
4813 free_percpu(sbinfo
->ino_batch
);
4814 percpu_counter_destroy(&sbinfo
->used_blocks
);
4815 mpol_put(sbinfo
->mpol
);
4817 sb
->s_fs_info
= NULL
;
4820 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS)
4821 static const struct dentry_operations shmem_ci_dentry_ops
= {
4822 .d_hash
= generic_ci_d_hash
,
4823 .d_compare
= generic_ci_d_compare
,
4824 .d_delete
= always_delete_dentry
,
4828 static int shmem_fill_super(struct super_block
*sb
, struct fs_context
*fc
)
4830 struct shmem_options
*ctx
= fc
->fs_private
;
4831 struct inode
*inode
;
4832 struct shmem_sb_info
*sbinfo
;
4833 int error
= -ENOMEM
;
4835 /* Round up to L1_CACHE_BYTES to resist false sharing */
4836 sbinfo
= kzalloc(max((int)sizeof(struct shmem_sb_info
),
4837 L1_CACHE_BYTES
), GFP_KERNEL
);
4841 sb
->s_fs_info
= sbinfo
;
4845 * Per default we only allow half of the physical ram per
4846 * tmpfs instance, limiting inodes to one per page of lowmem;
4847 * but the internal instance is left unlimited.
4849 if (!(sb
->s_flags
& SB_KERNMOUNT
)) {
4850 if (!(ctx
->seen
& SHMEM_SEEN_BLOCKS
))
4851 ctx
->blocks
= shmem_default_max_blocks();
4852 if (!(ctx
->seen
& SHMEM_SEEN_INODES
))
4853 ctx
->inodes
= shmem_default_max_inodes();
4854 if (!(ctx
->seen
& SHMEM_SEEN_INUMS
))
4855 ctx
->full_inums
= IS_ENABLED(CONFIG_TMPFS_INODE64
);
4856 sbinfo
->noswap
= ctx
->noswap
;
4858 sb
->s_flags
|= SB_NOUSER
;
4860 sb
->s_export_op
= &shmem_export_ops
;
4861 sb
->s_flags
|= SB_NOSEC
| SB_I_VERSION
;
4863 #if IS_ENABLED(CONFIG_UNICODE)
4864 if (!ctx
->encoding
&& ctx
->strict_encoding
) {
4865 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n");
4870 if (ctx
->encoding
) {
4871 sb
->s_encoding
= ctx
->encoding
;
4872 sb
->s_d_op
= &shmem_ci_dentry_ops
;
4873 if (ctx
->strict_encoding
)
4874 sb
->s_encoding_flags
= SB_ENC_STRICT_MODE_FL
;
4879 sb
->s_flags
|= SB_NOUSER
;
4880 #endif /* CONFIG_TMPFS */
4881 sbinfo
->max_blocks
= ctx
->blocks
;
4882 sbinfo
->max_inodes
= ctx
->inodes
;
4883 sbinfo
->free_ispace
= sbinfo
->max_inodes
* BOGO_INODE_SIZE
;
4884 if (sb
->s_flags
& SB_KERNMOUNT
) {
4885 sbinfo
->ino_batch
= alloc_percpu(ino_t
);
4886 if (!sbinfo
->ino_batch
)
4889 sbinfo
->uid
= ctx
->uid
;
4890 sbinfo
->gid
= ctx
->gid
;
4891 sbinfo
->full_inums
= ctx
->full_inums
;
4892 sbinfo
->mode
= ctx
->mode
;
4893 sbinfo
->huge
= ctx
->huge
;
4894 sbinfo
->mpol
= ctx
->mpol
;
4897 raw_spin_lock_init(&sbinfo
->stat_lock
);
4898 if (percpu_counter_init(&sbinfo
->used_blocks
, 0, GFP_KERNEL
))
4900 spin_lock_init(&sbinfo
->shrinklist_lock
);
4901 INIT_LIST_HEAD(&sbinfo
->shrinklist
);
4903 sb
->s_maxbytes
= MAX_LFS_FILESIZE
;
4904 sb
->s_blocksize
= PAGE_SIZE
;
4905 sb
->s_blocksize_bits
= PAGE_SHIFT
;
4906 sb
->s_magic
= TMPFS_MAGIC
;
4907 sb
->s_op
= &shmem_ops
;
4908 sb
->s_time_gran
= 1;
4909 #ifdef CONFIG_TMPFS_XATTR
4910 sb
->s_xattr
= shmem_xattr_handlers
;
4912 #ifdef CONFIG_TMPFS_POSIX_ACL
4913 sb
->s_flags
|= SB_POSIXACL
;
4917 super_set_uuid(sb
, uuid
.b
, sizeof(uuid
));
4919 #ifdef CONFIG_TMPFS_QUOTA
4920 if (ctx
->seen
& SHMEM_SEEN_QUOTA
) {
4921 sb
->dq_op
= &shmem_quota_operations
;
4922 sb
->s_qcop
= &dquot_quotactl_sysfile_ops
;
4923 sb
->s_quota_types
= QTYPE_MASK_USR
| QTYPE_MASK_GRP
;
4925 /* Copy the default limits from ctx into sbinfo */
4926 memcpy(&sbinfo
->qlimits
, &ctx
->qlimits
,
4927 sizeof(struct shmem_quota_limits
));
4929 if (shmem_enable_quotas(sb
, ctx
->quota_types
))
4932 #endif /* CONFIG_TMPFS_QUOTA */
4934 inode
= shmem_get_inode(&nop_mnt_idmap
, sb
, NULL
,
4935 S_IFDIR
| sbinfo
->mode
, 0, VM_NORESERVE
);
4936 if (IS_ERR(inode
)) {
4937 error
= PTR_ERR(inode
);
4940 inode
->i_uid
= sbinfo
->uid
;
4941 inode
->i_gid
= sbinfo
->gid
;
4942 sb
->s_root
= d_make_root(inode
);
4948 shmem_put_super(sb
);
4952 static int shmem_get_tree(struct fs_context
*fc
)
4954 return get_tree_nodev(fc
, shmem_fill_super
);
4957 static void shmem_free_fc(struct fs_context
*fc
)
4959 struct shmem_options
*ctx
= fc
->fs_private
;
4962 mpol_put(ctx
->mpol
);
4967 static const struct fs_context_operations shmem_fs_context_ops
= {
4968 .free
= shmem_free_fc
,
4969 .get_tree
= shmem_get_tree
,
4971 .parse_monolithic
= shmem_parse_options
,
4972 .parse_param
= shmem_parse_one
,
4973 .reconfigure
= shmem_reconfigure
,
4977 static struct kmem_cache
*shmem_inode_cachep __ro_after_init
;
4979 static struct inode
*shmem_alloc_inode(struct super_block
*sb
)
4981 struct shmem_inode_info
*info
;
4982 info
= alloc_inode_sb(sb
, shmem_inode_cachep
, GFP_KERNEL
);
4985 return &info
->vfs_inode
;
4988 static void shmem_free_in_core_inode(struct inode
*inode
)
4990 if (S_ISLNK(inode
->i_mode
))
4991 kfree(inode
->i_link
);
4992 kmem_cache_free(shmem_inode_cachep
, SHMEM_I(inode
));
4995 static void shmem_destroy_inode(struct inode
*inode
)
4997 if (S_ISREG(inode
->i_mode
))
4998 mpol_free_shared_policy(&SHMEM_I(inode
)->policy
);
4999 if (S_ISDIR(inode
->i_mode
))
5000 simple_offset_destroy(shmem_get_offset_ctx(inode
));
5003 static void shmem_init_inode(void *foo
)
5005 struct shmem_inode_info
*info
= foo
;
5006 inode_init_once(&info
->vfs_inode
);
5009 static void __init
shmem_init_inodecache(void)
5011 shmem_inode_cachep
= kmem_cache_create("shmem_inode_cache",
5012 sizeof(struct shmem_inode_info
),
5013 0, SLAB_PANIC
|SLAB_ACCOUNT
, shmem_init_inode
);
5016 static void __init
shmem_destroy_inodecache(void)
5018 kmem_cache_destroy(shmem_inode_cachep
);
5021 /* Keep the page in page cache instead of truncating it */
5022 static int shmem_error_remove_folio(struct address_space
*mapping
,
5023 struct folio
*folio
)
5028 static const struct address_space_operations shmem_aops
= {
5029 .writepage
= shmem_writepage
,
5030 .dirty_folio
= noop_dirty_folio
,
5032 .write_begin
= shmem_write_begin
,
5033 .write_end
= shmem_write_end
,
5035 #ifdef CONFIG_MIGRATION
5036 .migrate_folio
= migrate_folio
,
5038 .error_remove_folio
= shmem_error_remove_folio
,
5041 static const struct file_operations shmem_file_operations
= {
5043 .open
= shmem_file_open
,
5044 .get_unmapped_area
= shmem_get_unmapped_area
,
5046 .llseek
= shmem_file_llseek
,
5047 .read_iter
= shmem_file_read_iter
,
5048 .write_iter
= shmem_file_write_iter
,
5049 .fsync
= noop_fsync
,
5050 .splice_read
= shmem_file_splice_read
,
5051 .splice_write
= iter_file_splice_write
,
5052 .fallocate
= shmem_fallocate
,
5056 static const struct inode_operations shmem_inode_operations
= {
5057 .getattr
= shmem_getattr
,
5058 .setattr
= shmem_setattr
,
5059 #ifdef CONFIG_TMPFS_XATTR
5060 .listxattr
= shmem_listxattr
,
5061 .set_acl
= simple_set_acl
,
5062 .fileattr_get
= shmem_fileattr_get
,
5063 .fileattr_set
= shmem_fileattr_set
,
5067 static const struct inode_operations shmem_dir_inode_operations
= {
5069 .getattr
= shmem_getattr
,
5070 .create
= shmem_create
,
5071 .lookup
= simple_lookup
,
5073 .unlink
= shmem_unlink
,
5074 .symlink
= shmem_symlink
,
5075 .mkdir
= shmem_mkdir
,
5076 .rmdir
= shmem_rmdir
,
5077 .mknod
= shmem_mknod
,
5078 .rename
= shmem_rename2
,
5079 .tmpfile
= shmem_tmpfile
,
5080 .get_offset_ctx
= shmem_get_offset_ctx
,
5082 #ifdef CONFIG_TMPFS_XATTR
5083 .listxattr
= shmem_listxattr
,
5084 .fileattr_get
= shmem_fileattr_get
,
5085 .fileattr_set
= shmem_fileattr_set
,
5087 #ifdef CONFIG_TMPFS_POSIX_ACL
5088 .setattr
= shmem_setattr
,
5089 .set_acl
= simple_set_acl
,
5093 static const struct inode_operations shmem_special_inode_operations
= {
5094 .getattr
= shmem_getattr
,
5095 #ifdef CONFIG_TMPFS_XATTR
5096 .listxattr
= shmem_listxattr
,
5098 #ifdef CONFIG_TMPFS_POSIX_ACL
5099 .setattr
= shmem_setattr
,
5100 .set_acl
= simple_set_acl
,
5104 static const struct super_operations shmem_ops
= {
5105 .alloc_inode
= shmem_alloc_inode
,
5106 .free_inode
= shmem_free_in_core_inode
,
5107 .destroy_inode
= shmem_destroy_inode
,
5109 .statfs
= shmem_statfs
,
5110 .show_options
= shmem_show_options
,
5112 #ifdef CONFIG_TMPFS_QUOTA
5113 .get_dquots
= shmem_get_dquots
,
5115 .evict_inode
= shmem_evict_inode
,
5116 .drop_inode
= generic_delete_inode
,
5117 .put_super
= shmem_put_super
,
5118 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5119 .nr_cached_objects
= shmem_unused_huge_count
,
5120 .free_cached_objects
= shmem_unused_huge_scan
,
5124 static const struct vm_operations_struct shmem_vm_ops
= {
5125 .fault
= shmem_fault
,
5126 .map_pages
= filemap_map_pages
,
5128 .set_policy
= shmem_set_policy
,
5129 .get_policy
= shmem_get_policy
,
5133 static const struct vm_operations_struct shmem_anon_vm_ops
= {
5134 .fault
= shmem_fault
,
5135 .map_pages
= filemap_map_pages
,
5137 .set_policy
= shmem_set_policy
,
5138 .get_policy
= shmem_get_policy
,
5142 int shmem_init_fs_context(struct fs_context
*fc
)
5144 struct shmem_options
*ctx
;
5146 ctx
= kzalloc(sizeof(struct shmem_options
), GFP_KERNEL
);
5150 ctx
->mode
= 0777 | S_ISVTX
;
5151 ctx
->uid
= current_fsuid();
5152 ctx
->gid
= current_fsgid();
5154 #if IS_ENABLED(CONFIG_UNICODE)
5155 ctx
->encoding
= NULL
;
5158 fc
->fs_private
= ctx
;
5159 fc
->ops
= &shmem_fs_context_ops
;
5163 static struct file_system_type shmem_fs_type
= {
5164 .owner
= THIS_MODULE
,
5166 .init_fs_context
= shmem_init_fs_context
,
5168 .parameters
= shmem_fs_parameters
,
5170 .kill_sb
= kill_litter_super
,
5171 .fs_flags
= FS_USERNS_MOUNT
| FS_ALLOW_IDMAP
| FS_MGTIME
,
5174 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5176 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \
5178 .attr = { .name = __stringify(_name), .mode = _mode }, \
5183 #define TMPFS_ATTR_W(_name, _store) \
5184 static struct kobj_attribute tmpfs_attr_##_name = \
5185 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store)
5187 #define TMPFS_ATTR_RW(_name, _show, _store) \
5188 static struct kobj_attribute tmpfs_attr_##_name = \
5189 __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
5191 #define TMPFS_ATTR_RO(_name, _show) \
5192 static struct kobj_attribute tmpfs_attr_##_name = \
5193 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL)
5195 #if IS_ENABLED(CONFIG_UNICODE)
5196 static ssize_t
casefold_show(struct kobject
*kobj
, struct kobj_attribute
*a
,
5199 return sysfs_emit(buf
, "supported\n");
5201 TMPFS_ATTR_RO(casefold
, casefold_show
);
5204 static struct attribute
*tmpfs_attributes
[] = {
5205 #if IS_ENABLED(CONFIG_UNICODE)
5206 &tmpfs_attr_casefold
.attr
,
5211 static const struct attribute_group tmpfs_attribute_group
= {
5212 .attrs
= tmpfs_attributes
,
5216 static struct kobject
*tmpfs_kobj
;
5218 static int __init
tmpfs_sysfs_init(void)
5222 tmpfs_kobj
= kobject_create_and_add("tmpfs", fs_kobj
);
5226 ret
= sysfs_create_group(tmpfs_kobj
, &tmpfs_attribute_group
);
5228 kobject_put(tmpfs_kobj
);
5232 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */
5234 void __init
shmem_init(void)
5238 shmem_init_inodecache();
5240 #ifdef CONFIG_TMPFS_QUOTA
5241 register_quota_format(&shmem_quota_format
);
5244 error
= register_filesystem(&shmem_fs_type
);
5246 pr_err("Could not register tmpfs\n");
5250 shm_mnt
= kern_mount(&shmem_fs_type
);
5251 if (IS_ERR(shm_mnt
)) {
5252 error
= PTR_ERR(shm_mnt
);
5253 pr_err("Could not kern_mount tmpfs\n");
5257 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5258 error
= tmpfs_sysfs_init();
5260 pr_err("Could not init tmpfs sysfs\n");
5265 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5266 if (has_transparent_hugepage() && shmem_huge
> SHMEM_HUGE_DENY
)
5267 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
5269 shmem_huge
= SHMEM_HUGE_NEVER
; /* just in case it was patched */
5272 * Default to setting PMD-sized THP to inherit the global setting and
5273 * disable all other multi-size THPs.
5275 if (!shmem_orders_configured
)
5276 huge_shmem_orders_inherit
= BIT(HPAGE_PMD_ORDER
);
5281 unregister_filesystem(&shmem_fs_type
);
5283 #ifdef CONFIG_TMPFS_QUOTA
5284 unregister_quota_format(&shmem_quota_format
);
5286 shmem_destroy_inodecache();
5287 shm_mnt
= ERR_PTR(error
);
5290 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
5291 static ssize_t
shmem_enabled_show(struct kobject
*kobj
,
5292 struct kobj_attribute
*attr
, char *buf
)
5294 static const int values
[] = {
5296 SHMEM_HUGE_WITHIN_SIZE
,
5305 for (i
= 0; i
< ARRAY_SIZE(values
); i
++) {
5306 len
+= sysfs_emit_at(buf
, len
,
5307 shmem_huge
== values
[i
] ? "%s[%s]" : "%s%s",
5308 i
? " " : "", shmem_format_huge(values
[i
]));
5310 len
+= sysfs_emit_at(buf
, len
, "\n");
5315 static ssize_t
shmem_enabled_store(struct kobject
*kobj
,
5316 struct kobj_attribute
*attr
, const char *buf
, size_t count
)
5321 if (count
+ 1 > sizeof(tmp
))
5323 memcpy(tmp
, buf
, count
);
5325 if (count
&& tmp
[count
- 1] == '\n')
5326 tmp
[count
- 1] = '\0';
5328 huge
= shmem_parse_huge(tmp
);
5329 if (huge
== -EINVAL
)
5333 if (shmem_huge
> SHMEM_HUGE_DENY
)
5334 SHMEM_SB(shm_mnt
->mnt_sb
)->huge
= shmem_huge
;
5336 err
= start_stop_khugepaged();
5337 return err
? err
: count
;
5340 struct kobj_attribute shmem_enabled_attr
= __ATTR_RW(shmem_enabled
);
5341 static DEFINE_SPINLOCK(huge_shmem_orders_lock
);
5343 static ssize_t
thpsize_shmem_enabled_show(struct kobject
*kobj
,
5344 struct kobj_attribute
*attr
, char *buf
)
5346 int order
= to_thpsize(kobj
)->order
;
5349 if (test_bit(order
, &huge_shmem_orders_always
))
5350 output
= "[always] inherit within_size advise never";
5351 else if (test_bit(order
, &huge_shmem_orders_inherit
))
5352 output
= "always [inherit] within_size advise never";
5353 else if (test_bit(order
, &huge_shmem_orders_within_size
))
5354 output
= "always inherit [within_size] advise never";
5355 else if (test_bit(order
, &huge_shmem_orders_madvise
))
5356 output
= "always inherit within_size [advise] never";
5358 output
= "always inherit within_size advise [never]";
5360 return sysfs_emit(buf
, "%s\n", output
);
5363 static ssize_t
thpsize_shmem_enabled_store(struct kobject
*kobj
,
5364 struct kobj_attribute
*attr
,
5365 const char *buf
, size_t count
)
5367 int order
= to_thpsize(kobj
)->order
;
5368 ssize_t ret
= count
;
5370 if (sysfs_streq(buf
, "always")) {
5371 spin_lock(&huge_shmem_orders_lock
);
5372 clear_bit(order
, &huge_shmem_orders_inherit
);
5373 clear_bit(order
, &huge_shmem_orders_madvise
);
5374 clear_bit(order
, &huge_shmem_orders_within_size
);
5375 set_bit(order
, &huge_shmem_orders_always
);
5376 spin_unlock(&huge_shmem_orders_lock
);
5377 } else if (sysfs_streq(buf
, "inherit")) {
5378 /* Do not override huge allocation policy with non-PMD sized mTHP */
5379 if (shmem_huge
== SHMEM_HUGE_FORCE
&&
5380 order
!= HPAGE_PMD_ORDER
)
5383 spin_lock(&huge_shmem_orders_lock
);
5384 clear_bit(order
, &huge_shmem_orders_always
);
5385 clear_bit(order
, &huge_shmem_orders_madvise
);
5386 clear_bit(order
, &huge_shmem_orders_within_size
);
5387 set_bit(order
, &huge_shmem_orders_inherit
);
5388 spin_unlock(&huge_shmem_orders_lock
);
5389 } else if (sysfs_streq(buf
, "within_size")) {
5390 spin_lock(&huge_shmem_orders_lock
);
5391 clear_bit(order
, &huge_shmem_orders_always
);
5392 clear_bit(order
, &huge_shmem_orders_inherit
);
5393 clear_bit(order
, &huge_shmem_orders_madvise
);
5394 set_bit(order
, &huge_shmem_orders_within_size
);
5395 spin_unlock(&huge_shmem_orders_lock
);
5396 } else if (sysfs_streq(buf
, "advise")) {
5397 spin_lock(&huge_shmem_orders_lock
);
5398 clear_bit(order
, &huge_shmem_orders_always
);
5399 clear_bit(order
, &huge_shmem_orders_inherit
);
5400 clear_bit(order
, &huge_shmem_orders_within_size
);
5401 set_bit(order
, &huge_shmem_orders_madvise
);
5402 spin_unlock(&huge_shmem_orders_lock
);
5403 } else if (sysfs_streq(buf
, "never")) {
5404 spin_lock(&huge_shmem_orders_lock
);
5405 clear_bit(order
, &huge_shmem_orders_always
);
5406 clear_bit(order
, &huge_shmem_orders_inherit
);
5407 clear_bit(order
, &huge_shmem_orders_within_size
);
5408 clear_bit(order
, &huge_shmem_orders_madvise
);
5409 spin_unlock(&huge_shmem_orders_lock
);
5415 int err
= start_stop_khugepaged();
5423 struct kobj_attribute thpsize_shmem_enabled_attr
=
5424 __ATTR(shmem_enabled
, 0644, thpsize_shmem_enabled_show
, thpsize_shmem_enabled_store
);
5425 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
5427 #if defined(CONFIG_TRANSPARENT_HUGEPAGE)
5429 static int __init
setup_transparent_hugepage_shmem(char *str
)
5433 huge
= shmem_parse_huge(str
);
5434 if (huge
== -EINVAL
) {
5435 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
5442 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem
);
5444 static char str_dup
[PAGE_SIZE
] __initdata
;
5445 static int __init
setup_thp_shmem(char *str
)
5447 char *token
, *range
, *policy
, *subtoken
;
5448 unsigned long always
, inherit
, madvise
, within_size
;
5449 char *start_size
, *end_size
;
5453 if (!str
|| strlen(str
) + 1 > PAGE_SIZE
)
5455 strscpy(str_dup
, str
);
5457 always
= huge_shmem_orders_always
;
5458 inherit
= huge_shmem_orders_inherit
;
5459 madvise
= huge_shmem_orders_madvise
;
5460 within_size
= huge_shmem_orders_within_size
;
5462 while ((token
= strsep(&p
, ";")) != NULL
) {
5463 range
= strsep(&token
, ":");
5469 while ((subtoken
= strsep(&range
, ",")) != NULL
) {
5470 if (strchr(subtoken
, '-')) {
5471 start_size
= strsep(&subtoken
, "-");
5472 end_size
= subtoken
;
5474 start
= get_order_from_str(start_size
,
5475 THP_ORDERS_ALL_FILE_DEFAULT
);
5476 end
= get_order_from_str(end_size
,
5477 THP_ORDERS_ALL_FILE_DEFAULT
);
5479 start_size
= end_size
= subtoken
;
5480 start
= end
= get_order_from_str(subtoken
,
5481 THP_ORDERS_ALL_FILE_DEFAULT
);
5484 if (start
== -EINVAL
) {
5485 pr_err("invalid size %s in thp_shmem boot parameter\n",
5490 if (end
== -EINVAL
) {
5491 pr_err("invalid size %s in thp_shmem boot parameter\n",
5496 if (start
< 0 || end
< 0 || start
> end
)
5499 nr
= end
- start
+ 1;
5500 if (!strcmp(policy
, "always")) {
5501 bitmap_set(&always
, start
, nr
);
5502 bitmap_clear(&inherit
, start
, nr
);
5503 bitmap_clear(&madvise
, start
, nr
);
5504 bitmap_clear(&within_size
, start
, nr
);
5505 } else if (!strcmp(policy
, "advise")) {
5506 bitmap_set(&madvise
, start
, nr
);
5507 bitmap_clear(&inherit
, start
, nr
);
5508 bitmap_clear(&always
, start
, nr
);
5509 bitmap_clear(&within_size
, start
, nr
);
5510 } else if (!strcmp(policy
, "inherit")) {
5511 bitmap_set(&inherit
, start
, nr
);
5512 bitmap_clear(&madvise
, start
, nr
);
5513 bitmap_clear(&always
, start
, nr
);
5514 bitmap_clear(&within_size
, start
, nr
);
5515 } else if (!strcmp(policy
, "within_size")) {
5516 bitmap_set(&within_size
, start
, nr
);
5517 bitmap_clear(&inherit
, start
, nr
);
5518 bitmap_clear(&madvise
, start
, nr
);
5519 bitmap_clear(&always
, start
, nr
);
5520 } else if (!strcmp(policy
, "never")) {
5521 bitmap_clear(&inherit
, start
, nr
);
5522 bitmap_clear(&madvise
, start
, nr
);
5523 bitmap_clear(&always
, start
, nr
);
5524 bitmap_clear(&within_size
, start
, nr
);
5526 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy
);
5532 huge_shmem_orders_always
= always
;
5533 huge_shmem_orders_madvise
= madvise
;
5534 huge_shmem_orders_inherit
= inherit
;
5535 huge_shmem_orders_within_size
= within_size
;
5536 shmem_orders_configured
= true;
5540 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str
);
5543 __setup("thp_shmem=", setup_thp_shmem
);
5545 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5547 #else /* !CONFIG_SHMEM */
5550 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
5552 * This is intended for small system where the benefits of the full
5553 * shmem code (swap-backed and resource-limited) are outweighed by
5554 * their complexity. On systems without swap this code should be
5555 * effectively equivalent, but much lighter weight.
5558 static struct file_system_type shmem_fs_type
= {
5560 .init_fs_context
= ramfs_init_fs_context
,
5561 .parameters
= ramfs_fs_parameters
,
5562 .kill_sb
= ramfs_kill_sb
,
5563 .fs_flags
= FS_USERNS_MOUNT
,
5566 void __init
shmem_init(void)
5568 BUG_ON(register_filesystem(&shmem_fs_type
) != 0);
5570 shm_mnt
= kern_mount(&shmem_fs_type
);
5571 BUG_ON(IS_ERR(shm_mnt
));
5574 int shmem_unuse(unsigned int type
)
5579 int shmem_lock(struct file
*file
, int lock
, struct ucounts
*ucounts
)
5584 void shmem_unlock_mapping(struct address_space
*mapping
)
5589 unsigned long shmem_get_unmapped_area(struct file
*file
,
5590 unsigned long addr
, unsigned long len
,
5591 unsigned long pgoff
, unsigned long flags
)
5593 return mm_get_unmapped_area(current
->mm
, file
, addr
, len
, pgoff
, flags
);
5597 void shmem_truncate_range(struct inode
*inode
, loff_t lstart
, loff_t lend
)
5599 truncate_inode_pages_range(inode
->i_mapping
, lstart
, lend
);
5601 EXPORT_SYMBOL_GPL(shmem_truncate_range
);
5603 #define shmem_vm_ops generic_file_vm_ops
5604 #define shmem_anon_vm_ops generic_file_vm_ops
5605 #define shmem_file_operations ramfs_file_operations
5606 #define shmem_acct_size(flags, size) 0
5607 #define shmem_unacct_size(flags, size) do {} while (0)
5609 static inline struct inode
*shmem_get_inode(struct mnt_idmap
*idmap
,
5610 struct super_block
*sb
, struct inode
*dir
,
5611 umode_t mode
, dev_t dev
, unsigned long flags
)
5613 struct inode
*inode
= ramfs_get_inode(sb
, dir
, mode
, dev
);
5614 return inode
? inode
: ERR_PTR(-ENOSPC
);
5617 #endif /* CONFIG_SHMEM */
5621 static struct file
*__shmem_file_setup(struct vfsmount
*mnt
, const char *name
,
5622 loff_t size
, unsigned long flags
, unsigned int i_flags
)
5624 struct inode
*inode
;
5628 return ERR_CAST(mnt
);
5630 if (size
< 0 || size
> MAX_LFS_FILESIZE
)
5631 return ERR_PTR(-EINVAL
);
5633 if (shmem_acct_size(flags
, size
))
5634 return ERR_PTR(-ENOMEM
);
5636 if (is_idmapped_mnt(mnt
))
5637 return ERR_PTR(-EINVAL
);
5639 inode
= shmem_get_inode(&nop_mnt_idmap
, mnt
->mnt_sb
, NULL
,
5640 S_IFREG
| S_IRWXUGO
, 0, flags
);
5641 if (IS_ERR(inode
)) {
5642 shmem_unacct_size(flags
, size
);
5643 return ERR_CAST(inode
);
5645 inode
->i_flags
|= i_flags
;
5646 inode
->i_size
= size
;
5647 clear_nlink(inode
); /* It is unlinked */
5648 res
= ERR_PTR(ramfs_nommu_expand_for_mapping(inode
, size
));
5650 res
= alloc_file_pseudo(inode
, mnt
, name
, O_RDWR
,
5651 &shmem_file_operations
);
5658 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
5659 * kernel internal. There will be NO LSM permission checks against the
5660 * underlying inode. So users of this interface must do LSM checks at a
5661 * higher layer. The users are the big_key and shm implementations. LSM
5662 * checks are provided at the key or shm level rather than the inode.
5663 * @name: name for dentry (to be seen in /proc/<pid>/maps
5664 * @size: size to be set for the file
5665 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5667 struct file
*shmem_kernel_file_setup(const char *name
, loff_t size
, unsigned long flags
)
5669 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, S_PRIVATE
);
5671 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup
);
5674 * shmem_file_setup - get an unlinked file living in tmpfs
5675 * @name: name for dentry (to be seen in /proc/<pid>/maps
5676 * @size: size to be set for the file
5677 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5679 struct file
*shmem_file_setup(const char *name
, loff_t size
, unsigned long flags
)
5681 return __shmem_file_setup(shm_mnt
, name
, size
, flags
, 0);
5683 EXPORT_SYMBOL_GPL(shmem_file_setup
);
5686 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
5687 * @mnt: the tmpfs mount where the file will be created
5688 * @name: name for dentry (to be seen in /proc/<pid>/maps
5689 * @size: size to be set for the file
5690 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
5692 struct file
*shmem_file_setup_with_mnt(struct vfsmount
*mnt
, const char *name
,
5693 loff_t size
, unsigned long flags
)
5695 return __shmem_file_setup(mnt
, name
, size
, flags
, 0);
5697 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt
);
5700 * shmem_zero_setup - setup a shared anonymous mapping
5701 * @vma: the vma to be mmapped is prepared by do_mmap
5703 int shmem_zero_setup(struct vm_area_struct
*vma
)
5706 loff_t size
= vma
->vm_end
- vma
->vm_start
;
5709 * Cloning a new file under mmap_lock leads to a lock ordering conflict
5710 * between XFS directory reading and selinux: since this file is only
5711 * accessible to the user through its mapping, use S_PRIVATE flag to
5712 * bypass file security, in the same way as shmem_kernel_file_setup().
5714 file
= shmem_kernel_file_setup("dev/zero", size
, vma
->vm_flags
);
5716 return PTR_ERR(file
);
5720 vma
->vm_file
= file
;
5721 vma
->vm_ops
= &shmem_anon_vm_ops
;
5727 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags.
5728 * @mapping: the folio's address_space
5729 * @index: the folio index
5730 * @gfp: the page allocator flags to use if allocating
5732 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
5733 * with any new page allocations done using the specified allocation flags.
5734 * But read_cache_page_gfp() uses the ->read_folio() method: which does not
5735 * suit tmpfs, since it may have pages in swapcache, and needs to find those
5736 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
5738 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
5739 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
5741 struct folio
*shmem_read_folio_gfp(struct address_space
*mapping
,
5742 pgoff_t index
, gfp_t gfp
)
5745 struct inode
*inode
= mapping
->host
;
5746 struct folio
*folio
;
5749 error
= shmem_get_folio_gfp(inode
, index
, 0, &folio
, SGP_CACHE
,
5752 return ERR_PTR(error
);
5754 folio_unlock(folio
);
5758 * The tiny !SHMEM case uses ramfs without swap
5760 return mapping_read_folio_gfp(mapping
, index
, gfp
);
5763 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp
);
5765 struct page
*shmem_read_mapping_page_gfp(struct address_space
*mapping
,
5766 pgoff_t index
, gfp_t gfp
)
5768 struct folio
*folio
= shmem_read_folio_gfp(mapping
, index
, gfp
);
5772 return &folio
->page
;
5774 page
= folio_file_page(folio
, index
);
5775 if (PageHWPoison(page
)) {
5777 return ERR_PTR(-EIO
);
5782 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp
);