1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Resizable virtual memory filesystem for Linux.
4 *
5 * Copyright (C) 2000 Linus Torvalds.
6 * 2000 Transmeta Corp.
7 * 2000-2001 Christoph Rohland
8 * 2000-2001 SAP AG
9 * 2002 Red Hat Inc.
10 * Copyright (C) 2002-2011 Hugh Dickins.
11 * Copyright (C) 2011 Google Inc.
12 * Copyright (C) 2002-2005 VERITAS Software Corporation.
13 * Copyright (C) 2004 Andi Kleen, SuSE Labs
14 *
15 * Extended attribute support for tmpfs:
16 * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
17 * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
18 *
19 * tiny-shmem:
20 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
21 */
22
23 #include <linux/fs.h>
24 #include <linux/init.h>
25 #include <linux/vfs.h>
26 #include <linux/mount.h>
27 #include <linux/ramfs.h>
28 #include <linux/pagemap.h>
29 #include <linux/file.h>
30 #include <linux/fileattr.h>
31 #include <linux/filelock.h>
32 #include <linux/mm.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>
44 #include "swap.h"
45
46 static struct vfsmount *shm_mnt __ro_after_init;
47
48 #ifdef CONFIG_SHMEM
49 /*
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.
53 */
54
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/leafops.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>
84
85 #include <linux/uaccess.h>
86
87 #include "internal.h"
88
89 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
90
91 /* Pretend that each entry is of this size in directory's i_size */
92 #define BOGO_DIRENT_SIZE 20
93
94 /* Pretend that one inode + its dentry occupy this much memory */
95 #define BOGO_INODE_SIZE 1024
96
97 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
98 #define SHORT_SYMLINK_LEN 128
99
100 /*
101 * shmem_fallocate communicates with shmem_fault or shmem_writeout via
102 * inode->i_private (with i_rwsem making sure that it has only one user at
103 * a time): we would prefer not to enlarge the shmem inode just for that.
104 */
105 struct shmem_falloc {
106 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
107 pgoff_t start; /* start of range currently being fallocated */
108 pgoff_t next; /* the next page offset to be fallocated */
109 pgoff_t nr_falloced; /* how many new pages have been fallocated */
110 pgoff_t nr_unswapped; /* how often writeout refused to swap out */
111 };
112
113 struct shmem_options {
114 unsigned long long blocks;
115 unsigned long long inodes;
116 struct mempolicy *mpol;
117 kuid_t uid;
118 kgid_t gid;
119 umode_t mode;
120 bool full_inums;
121 int huge;
122 int seen;
123 bool noswap;
124 unsigned short quota_types;
125 struct shmem_quota_limits qlimits;
126 #if IS_ENABLED(CONFIG_UNICODE)
127 struct unicode_map *encoding;
128 bool strict_encoding;
129 #endif
130 #define SHMEM_SEEN_BLOCKS 1
131 #define SHMEM_SEEN_INODES 2
132 #define SHMEM_SEEN_HUGE 4
133 #define SHMEM_SEEN_INUMS 8
134 #define SHMEM_SEEN_QUOTA 16
135 };
136
137 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
138 static unsigned long huge_shmem_orders_always __read_mostly;
139 static unsigned long huge_shmem_orders_madvise __read_mostly;
140 static unsigned long huge_shmem_orders_inherit __read_mostly;
141 static unsigned long huge_shmem_orders_within_size __read_mostly;
142 static bool shmem_orders_configured __initdata;
143 #endif
144
145 #ifdef CONFIG_TMPFS
shmem_default_max_blocks(void)146 static unsigned long shmem_default_max_blocks(void)
147 {
148 return totalram_pages() / 2;
149 }
150
shmem_default_max_inodes(void)151 static unsigned long shmem_default_max_inodes(void)
152 {
153 unsigned long nr_pages = totalram_pages();
154
155 return min3(nr_pages - totalhigh_pages(), nr_pages / 2,
156 ULONG_MAX / BOGO_INODE_SIZE);
157 }
158 #endif
159
160 static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
161 struct folio **foliop, enum sgp_type sgp, gfp_t gfp,
162 struct vm_area_struct *vma, vm_fault_t *fault_type);
163
SHMEM_SB(struct super_block * sb)164 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
165 {
166 return sb->s_fs_info;
167 }
168
169 /*
170 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
171 * for shared memory and for shared anonymous (/dev/zero) mappings
172 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
173 * consistent with the pre-accounting of private mappings ...
174 */
shmem_acct_size(unsigned long flags,loff_t size)175 static inline int shmem_acct_size(unsigned long flags, loff_t size)
176 {
177 return (flags & SHMEM_F_NORESERVE) ?
178 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
179 }
180
shmem_unacct_size(unsigned long flags,loff_t size)181 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
182 {
183 if (!(flags & SHMEM_F_NORESERVE))
184 vm_unacct_memory(VM_ACCT(size));
185 }
186
shmem_reacct_size(unsigned long flags,loff_t oldsize,loff_t newsize)187 static inline int shmem_reacct_size(unsigned long flags,
188 loff_t oldsize, loff_t newsize)
189 {
190 if (!(flags & SHMEM_F_NORESERVE)) {
191 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
192 return security_vm_enough_memory_mm(current->mm,
193 VM_ACCT(newsize) - VM_ACCT(oldsize));
194 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
195 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
196 }
197 return 0;
198 }
199
200 /*
201 * ... whereas tmpfs objects are accounted incrementally as
202 * pages are allocated, in order to allow large sparse files.
203 * shmem_get_folio reports shmem_acct_blocks failure as -ENOSPC not -ENOMEM,
204 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
205 */
shmem_acct_blocks(unsigned long flags,long pages)206 static inline int shmem_acct_blocks(unsigned long flags, long pages)
207 {
208 if (!(flags & SHMEM_F_NORESERVE))
209 return 0;
210
211 return security_vm_enough_memory_mm(current->mm,
212 pages * VM_ACCT(PAGE_SIZE));
213 }
214
shmem_unacct_blocks(unsigned long flags,long pages)215 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
216 {
217 if (flags & SHMEM_F_NORESERVE)
218 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
219 }
220
shmem_inode_acct_blocks(struct inode * inode,long pages)221 int shmem_inode_acct_blocks(struct inode *inode, long pages)
222 {
223 struct shmem_inode_info *info = SHMEM_I(inode);
224 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
225 int err = -ENOSPC;
226
227 if (shmem_acct_blocks(info->flags, pages))
228 return err;
229
230 might_sleep(); /* when quotas */
231 if (sbinfo->max_blocks) {
232 if (!percpu_counter_limited_add(&sbinfo->used_blocks,
233 sbinfo->max_blocks, pages))
234 goto unacct;
235
236 err = dquot_alloc_block_nodirty(inode, pages);
237 if (err) {
238 percpu_counter_sub(&sbinfo->used_blocks, pages);
239 goto unacct;
240 }
241 } else {
242 err = dquot_alloc_block_nodirty(inode, pages);
243 if (err)
244 goto unacct;
245 }
246
247 return 0;
248
249 unacct:
250 shmem_unacct_blocks(info->flags, pages);
251 return err;
252 }
253
shmem_inode_unacct_blocks(struct inode * inode,long pages)254 static void shmem_inode_unacct_blocks(struct inode *inode, long pages)
255 {
256 struct shmem_inode_info *info = SHMEM_I(inode);
257 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
258
259 might_sleep(); /* when quotas */
260 dquot_free_block_nodirty(inode, pages);
261
262 if (sbinfo->max_blocks)
263 percpu_counter_sub(&sbinfo->used_blocks, pages);
264 shmem_unacct_blocks(info->flags, pages);
265 }
266
267 static const struct super_operations shmem_ops;
268 static const struct address_space_operations shmem_aops;
269 static const struct file_operations shmem_file_operations;
270 static const struct inode_operations shmem_inode_operations;
271 static const struct inode_operations shmem_dir_inode_operations;
272 static const struct inode_operations shmem_special_inode_operations;
273 static const struct vm_operations_struct shmem_vm_ops;
274 static const struct vm_operations_struct shmem_anon_vm_ops;
275 static struct file_system_type shmem_fs_type;
276
shmem_mapping(const struct address_space * mapping)277 bool shmem_mapping(const struct address_space *mapping)
278 {
279 return mapping->a_ops == &shmem_aops;
280 }
281 EXPORT_SYMBOL_GPL(shmem_mapping);
282
vma_is_anon_shmem(const struct vm_area_struct * vma)283 bool vma_is_anon_shmem(const struct vm_area_struct *vma)
284 {
285 return vma->vm_ops == &shmem_anon_vm_ops;
286 }
287
vma_is_shmem(const struct vm_area_struct * vma)288 bool vma_is_shmem(const struct vm_area_struct *vma)
289 {
290 return vma_is_anon_shmem(vma) || vma->vm_ops == &shmem_vm_ops;
291 }
292
293 static LIST_HEAD(shmem_swaplist);
294 static DEFINE_SPINLOCK(shmem_swaplist_lock);
295
296 #ifdef CONFIG_TMPFS_QUOTA
297
shmem_enable_quotas(struct super_block * sb,unsigned short quota_types)298 static int shmem_enable_quotas(struct super_block *sb,
299 unsigned short quota_types)
300 {
301 int type, err = 0;
302
303 sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
304 for (type = 0; type < SHMEM_MAXQUOTAS; type++) {
305 if (!(quota_types & (1 << type)))
306 continue;
307 err = dquot_load_quota_sb(sb, type, QFMT_SHMEM,
308 DQUOT_USAGE_ENABLED |
309 DQUOT_LIMITS_ENABLED);
310 if (err)
311 goto out_err;
312 }
313 return 0;
314
315 out_err:
316 pr_warn("tmpfs: failed to enable quota tracking (type=%d, err=%d)\n",
317 type, err);
318 for (type--; type >= 0; type--)
319 dquot_quota_off(sb, type);
320 return err;
321 }
322
shmem_disable_quotas(struct super_block * sb)323 static void shmem_disable_quotas(struct super_block *sb)
324 {
325 int type;
326
327 for (type = 0; type < SHMEM_MAXQUOTAS; type++)
328 dquot_quota_off(sb, type);
329 }
330
shmem_get_dquots(struct inode * inode)331 static struct dquot __rcu **shmem_get_dquots(struct inode *inode)
332 {
333 return SHMEM_I(inode)->i_dquot;
334 }
335 #endif /* CONFIG_TMPFS_QUOTA */
336
337 /*
338 * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
339 * produces a novel ino for the newly allocated inode.
340 *
341 * It may also be called when making a hard link to permit the space needed by
342 * each dentry. However, in that case, no new inode number is needed since that
343 * internally draws from another pool of inode numbers (currently global
344 * get_next_ino()). This case is indicated by passing NULL as inop.
345 */
346 #define SHMEM_INO_BATCH 1024
shmem_reserve_inode(struct super_block * sb,ino_t * inop)347 static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
348 {
349 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
350 ino_t ino;
351
352 if (!(sb->s_flags & SB_KERNMOUNT)) {
353 raw_spin_lock(&sbinfo->stat_lock);
354 if (sbinfo->max_inodes) {
355 if (sbinfo->free_ispace < BOGO_INODE_SIZE) {
356 raw_spin_unlock(&sbinfo->stat_lock);
357 return -ENOSPC;
358 }
359 sbinfo->free_ispace -= BOGO_INODE_SIZE;
360 }
361 if (inop) {
362 ino = sbinfo->next_ino++;
363 if (unlikely(is_zero_ino(ino)))
364 ino = sbinfo->next_ino++;
365 if (unlikely(!sbinfo->full_inums &&
366 ino > UINT_MAX)) {
367 /*
368 * Emulate get_next_ino uint wraparound for
369 * compatibility
370 */
371 if (IS_ENABLED(CONFIG_64BIT))
372 pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
373 __func__, MINOR(sb->s_dev));
374 sbinfo->next_ino = 1;
375 ino = sbinfo->next_ino++;
376 }
377 *inop = ino;
378 }
379 raw_spin_unlock(&sbinfo->stat_lock);
380 } else if (inop) {
381 /*
382 * __shmem_file_setup, one of our callers, is lock-free: it
383 * doesn't hold stat_lock in shmem_reserve_inode since
384 * max_inodes is always 0, and is called from potentially
385 * unknown contexts. As such, use a per-cpu batched allocator
386 * which doesn't require the per-sb stat_lock unless we are at
387 * the batch boundary.
388 *
389 * We don't need to worry about inode{32,64} since SB_KERNMOUNT
390 * shmem mounts are not exposed to userspace, so we don't need
391 * to worry about things like glibc compatibility.
392 */
393 ino_t *next_ino;
394
395 next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
396 ino = *next_ino;
397 if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
398 raw_spin_lock(&sbinfo->stat_lock);
399 ino = sbinfo->next_ino;
400 sbinfo->next_ino += SHMEM_INO_BATCH;
401 raw_spin_unlock(&sbinfo->stat_lock);
402 if (unlikely(is_zero_ino(ino)))
403 ino++;
404 }
405 *inop = ino;
406 *next_ino = ++ino;
407 put_cpu();
408 }
409
410 return 0;
411 }
412
shmem_free_inode(struct super_block * sb,size_t freed_ispace)413 static void shmem_free_inode(struct super_block *sb, size_t freed_ispace)
414 {
415 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
416 if (sbinfo->max_inodes) {
417 raw_spin_lock(&sbinfo->stat_lock);
418 sbinfo->free_ispace += BOGO_INODE_SIZE + freed_ispace;
419 raw_spin_unlock(&sbinfo->stat_lock);
420 }
421 }
422
423 /**
424 * shmem_recalc_inode - recalculate the block usage of an inode
425 * @inode: inode to recalc
426 * @alloced: the change in number of pages allocated to inode
427 * @swapped: the change in number of pages swapped from inode
428 *
429 * We have to calculate the free blocks since the mm can drop
430 * undirtied hole pages behind our back.
431 *
432 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
433 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
434 *
435 * Return: true if swapped was incremented from 0, for shmem_writeout().
436 */
shmem_recalc_inode(struct inode * inode,long alloced,long swapped)437 bool shmem_recalc_inode(struct inode *inode, long alloced, long swapped)
438 {
439 struct shmem_inode_info *info = SHMEM_I(inode);
440 bool first_swapped = false;
441 long freed;
442
443 spin_lock(&info->lock);
444 info->alloced += alloced;
445 info->swapped += swapped;
446 freed = info->alloced - info->swapped -
447 READ_ONCE(inode->i_mapping->nrpages);
448 /*
449 * Special case: whereas normally shmem_recalc_inode() is called
450 * after i_mapping->nrpages has already been adjusted (up or down),
451 * shmem_writeout() has to raise swapped before nrpages is lowered -
452 * to stop a racing shmem_recalc_inode() from thinking that a page has
453 * been freed. Compensate here, to avoid the need for a followup call.
454 */
455 if (swapped > 0) {
456 if (info->swapped == swapped)
457 first_swapped = true;
458 freed += swapped;
459 }
460 if (freed > 0)
461 info->alloced -= freed;
462 spin_unlock(&info->lock);
463
464 /* The quota case may block */
465 if (freed > 0)
466 shmem_inode_unacct_blocks(inode, freed);
467 return first_swapped;
468 }
469
shmem_charge(struct inode * inode,long pages)470 bool shmem_charge(struct inode *inode, long pages)
471 {
472 struct address_space *mapping = inode->i_mapping;
473
474 if (shmem_inode_acct_blocks(inode, pages))
475 return false;
476
477 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
478 xa_lock_irq(&mapping->i_pages);
479 mapping->nrpages += pages;
480 xa_unlock_irq(&mapping->i_pages);
481
482 shmem_recalc_inode(inode, pages, 0);
483 return true;
484 }
485
shmem_uncharge(struct inode * inode,long pages)486 void shmem_uncharge(struct inode *inode, long pages)
487 {
488 /* pages argument is currently unused: keep it to help debugging */
489 /* nrpages adjustment done by __filemap_remove_folio() or caller */
490
491 shmem_recalc_inode(inode, 0, 0);
492 }
493
494 /*
495 * Replace item expected in xarray by a new item, while holding xa_lock.
496 */
shmem_replace_entry(struct address_space * mapping,pgoff_t index,void * expected,void * replacement)497 static int shmem_replace_entry(struct address_space *mapping,
498 pgoff_t index, void *expected, void *replacement)
499 {
500 XA_STATE(xas, &mapping->i_pages, index);
501 void *item;
502
503 VM_BUG_ON(!expected);
504 VM_BUG_ON(!replacement);
505 item = xas_load(&xas);
506 if (item != expected)
507 return -ENOENT;
508 xas_store(&xas, replacement);
509 return 0;
510 }
511
512 /*
513 * Sometimes, before we decide whether to proceed or to fail, we must check
514 * that an entry was not already brought back or split by a racing thread.
515 *
516 * Checking folio is not enough: by the time a swapcache folio is locked, it
517 * might be reused, and again be swapcache, using the same swap as before.
518 * Returns the swap entry's order if it still presents, else returns -1.
519 */
shmem_confirm_swap(struct address_space * mapping,pgoff_t index,swp_entry_t swap)520 static int shmem_confirm_swap(struct address_space *mapping, pgoff_t index,
521 swp_entry_t swap)
522 {
523 XA_STATE(xas, &mapping->i_pages, index);
524 int ret = -1;
525 void *entry;
526
527 rcu_read_lock();
528 do {
529 entry = xas_load(&xas);
530 if (entry == swp_to_radix_entry(swap))
531 ret = xas_get_order(&xas);
532 } while (xas_retry(&xas, entry));
533 rcu_read_unlock();
534 return ret;
535 }
536
537 /*
538 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
539 *
540 * SHMEM_HUGE_NEVER:
541 * disables huge pages for the mount;
542 * SHMEM_HUGE_ALWAYS:
543 * enables huge pages for the mount;
544 * SHMEM_HUGE_WITHIN_SIZE:
545 * only allocate huge pages if the page will be fully within i_size,
546 * also respect madvise() hints;
547 * SHMEM_HUGE_ADVISE:
548 * only allocate huge pages if requested with madvise();
549 */
550
551 #define SHMEM_HUGE_NEVER 0
552 #define SHMEM_HUGE_ALWAYS 1
553 #define SHMEM_HUGE_WITHIN_SIZE 2
554 #define SHMEM_HUGE_ADVISE 3
555
556 /*
557 * Special values.
558 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
559 *
560 * SHMEM_HUGE_DENY:
561 * disables huge on shm_mnt and all mounts, for emergency use;
562 * SHMEM_HUGE_FORCE:
563 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
564 *
565 */
566 #define SHMEM_HUGE_DENY (-1)
567 #define SHMEM_HUGE_FORCE (-2)
568
569 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
570 /* ifdef here to avoid bloating shmem.o when not necessary */
571
572 #if defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER)
573 #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_NEVER
574 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ALWAYS)
575 #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_ALWAYS
576 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_WITHIN_SIZE)
577 #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_WITHIN_SIZE
578 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ADVISE)
579 #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_ADVISE
580 #else
581 #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_NEVER
582 #endif
583
584 static int shmem_huge __read_mostly = SHMEM_HUGE_DEFAULT;
585
586 #undef SHMEM_HUGE_DEFAULT
587
588 #if defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER)
589 #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_NEVER
590 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ALWAYS)
591 #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_ALWAYS
592 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_WITHIN_SIZE)
593 #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_WITHIN_SIZE
594 #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ADVISE)
595 #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_ADVISE
596 #else
597 #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_NEVER
598 #endif
599
600 static int tmpfs_huge __read_mostly = TMPFS_HUGE_DEFAULT;
601
602 #undef TMPFS_HUGE_DEFAULT
603
shmem_get_orders_within_size(struct inode * inode,unsigned long within_size_orders,pgoff_t index,loff_t write_end)604 static unsigned int shmem_get_orders_within_size(struct inode *inode,
605 unsigned long within_size_orders, pgoff_t index,
606 loff_t write_end)
607 {
608 pgoff_t aligned_index;
609 unsigned long order;
610 loff_t i_size;
611
612 order = highest_order(within_size_orders);
613 while (within_size_orders) {
614 aligned_index = round_up(index + 1, 1 << order);
615 i_size = max(write_end, i_size_read(inode));
616 i_size = round_up(i_size, PAGE_SIZE);
617 if (i_size >> PAGE_SHIFT >= aligned_index)
618 return within_size_orders;
619
620 order = next_order(&within_size_orders, order);
621 }
622
623 return 0;
624 }
625
shmem_huge_global_enabled(struct inode * inode,pgoff_t index,loff_t write_end,bool shmem_huge_force,struct vm_area_struct * vma,vm_flags_t vm_flags)626 static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index,
627 loff_t write_end, bool shmem_huge_force,
628 struct vm_area_struct *vma,
629 vm_flags_t vm_flags)
630 {
631 unsigned int maybe_pmd_order = HPAGE_PMD_ORDER > MAX_PAGECACHE_ORDER ?
632 0 : BIT(HPAGE_PMD_ORDER);
633 unsigned long within_size_orders;
634
635 if (!S_ISREG(inode->i_mode))
636 return 0;
637 if (shmem_huge == SHMEM_HUGE_DENY)
638 return 0;
639 if (shmem_huge_force || shmem_huge == SHMEM_HUGE_FORCE)
640 return maybe_pmd_order;
641
642 /*
643 * The huge order allocation for anon shmem is controlled through
644 * the mTHP interface, so we still use PMD-sized huge order to
645 * check whether global control is enabled.
646 *
647 * For tmpfs with 'huge=always' or 'huge=within_size' mount option,
648 * we will always try PMD-sized order first. If that failed, it will
649 * fall back to small large folios.
650 */
651 switch (SHMEM_SB(inode->i_sb)->huge) {
652 case SHMEM_HUGE_ALWAYS:
653 return THP_ORDERS_ALL_FILE_DEFAULT;
654 case SHMEM_HUGE_WITHIN_SIZE:
655 within_size_orders = shmem_get_orders_within_size(inode,
656 THP_ORDERS_ALL_FILE_DEFAULT, index, write_end);
657 if (within_size_orders > 0)
658 return within_size_orders;
659
660 fallthrough;
661 case SHMEM_HUGE_ADVISE:
662 if (vm_flags & VM_HUGEPAGE)
663 return THP_ORDERS_ALL_FILE_DEFAULT;
664 fallthrough;
665 default:
666 return 0;
667 }
668 }
669
shmem_parse_huge(const char * str)670 static int shmem_parse_huge(const char *str)
671 {
672 int huge;
673
674 if (!str)
675 return -EINVAL;
676
677 if (!strcmp(str, "never"))
678 huge = SHMEM_HUGE_NEVER;
679 else if (!strcmp(str, "always"))
680 huge = SHMEM_HUGE_ALWAYS;
681 else if (!strcmp(str, "within_size"))
682 huge = SHMEM_HUGE_WITHIN_SIZE;
683 else if (!strcmp(str, "advise"))
684 huge = SHMEM_HUGE_ADVISE;
685 else if (!strcmp(str, "deny"))
686 huge = SHMEM_HUGE_DENY;
687 else if (!strcmp(str, "force"))
688 huge = SHMEM_HUGE_FORCE;
689 else
690 return -EINVAL;
691
692 if (!has_transparent_hugepage() &&
693 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
694 return -EINVAL;
695
696 /* Do not override huge allocation policy with non-PMD sized mTHP */
697 if (huge == SHMEM_HUGE_FORCE &&
698 huge_shmem_orders_inherit != BIT(HPAGE_PMD_ORDER))
699 return -EINVAL;
700
701 return huge;
702 }
703
704 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
shmem_format_huge(int huge)705 static const char *shmem_format_huge(int huge)
706 {
707 switch (huge) {
708 case SHMEM_HUGE_NEVER:
709 return "never";
710 case SHMEM_HUGE_ALWAYS:
711 return "always";
712 case SHMEM_HUGE_WITHIN_SIZE:
713 return "within_size";
714 case SHMEM_HUGE_ADVISE:
715 return "advise";
716 case SHMEM_HUGE_DENY:
717 return "deny";
718 case SHMEM_HUGE_FORCE:
719 return "force";
720 default:
721 VM_BUG_ON(1);
722 return "bad_val";
723 }
724 }
725 #endif
726
shmem_unused_huge_shrink(struct shmem_sb_info * sbinfo,struct shrink_control * sc,unsigned long nr_to_free)727 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
728 struct shrink_control *sc, unsigned long nr_to_free)
729 {
730 LIST_HEAD(list), *pos, *next;
731 struct inode *inode;
732 struct shmem_inode_info *info;
733 struct folio *folio;
734 unsigned long batch = sc ? sc->nr_to_scan : 128;
735 unsigned long split = 0, freed = 0;
736
737 if (list_empty(&sbinfo->shrinklist))
738 return SHRINK_STOP;
739
740 spin_lock(&sbinfo->shrinklist_lock);
741 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
742 info = list_entry(pos, struct shmem_inode_info, shrinklist);
743
744 /* pin the inode */
745 inode = igrab(&info->vfs_inode);
746
747 /* inode is about to be evicted */
748 if (!inode) {
749 list_del_init(&info->shrinklist);
750 goto next;
751 }
752
753 list_move(&info->shrinklist, &list);
754 next:
755 sbinfo->shrinklist_len--;
756 if (!--batch)
757 break;
758 }
759 spin_unlock(&sbinfo->shrinklist_lock);
760
761 list_for_each_safe(pos, next, &list) {
762 pgoff_t next, end;
763 loff_t i_size;
764 int ret;
765
766 info = list_entry(pos, struct shmem_inode_info, shrinklist);
767 inode = &info->vfs_inode;
768
769 if (nr_to_free && freed >= nr_to_free)
770 goto move_back;
771
772 i_size = i_size_read(inode);
773 folio = filemap_get_entry(inode->i_mapping, i_size / PAGE_SIZE);
774 if (!folio || xa_is_value(folio))
775 goto drop;
776
777 /* No large folio at the end of the file: nothing to split */
778 if (!folio_test_large(folio)) {
779 folio_put(folio);
780 goto drop;
781 }
782
783 /* Check if there is anything to gain from splitting */
784 next = folio_next_index(folio);
785 end = shmem_fallocend(inode, DIV_ROUND_UP(i_size, PAGE_SIZE));
786 if (end <= folio->index || end >= next) {
787 folio_put(folio);
788 goto drop;
789 }
790
791 /*
792 * Move the inode on the list back to shrinklist if we failed
793 * to lock the page at this time.
794 *
795 * Waiting for the lock may lead to deadlock in the
796 * reclaim path.
797 */
798 if (!folio_trylock(folio)) {
799 folio_put(folio);
800 goto move_back;
801 }
802
803 ret = split_folio(folio);
804 folio_unlock(folio);
805 folio_put(folio);
806
807 /* If split failed move the inode on the list back to shrinklist */
808 if (ret)
809 goto move_back;
810
811 freed += next - end;
812 split++;
813 drop:
814 list_del_init(&info->shrinklist);
815 goto put;
816 move_back:
817 /*
818 * Make sure the inode is either on the global list or deleted
819 * from any local list before iput() since it could be deleted
820 * in another thread once we put the inode (then the local list
821 * is corrupted).
822 */
823 spin_lock(&sbinfo->shrinklist_lock);
824 list_move(&info->shrinklist, &sbinfo->shrinklist);
825 sbinfo->shrinklist_len++;
826 spin_unlock(&sbinfo->shrinklist_lock);
827 put:
828 iput(inode);
829 }
830
831 return split;
832 }
833
shmem_unused_huge_scan(struct super_block * sb,struct shrink_control * sc)834 static long shmem_unused_huge_scan(struct super_block *sb,
835 struct shrink_control *sc)
836 {
837 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
838
839 if (!READ_ONCE(sbinfo->shrinklist_len))
840 return SHRINK_STOP;
841
842 return shmem_unused_huge_shrink(sbinfo, sc, 0);
843 }
844
shmem_unused_huge_count(struct super_block * sb,struct shrink_control * sc)845 static long shmem_unused_huge_count(struct super_block *sb,
846 struct shrink_control *sc)
847 {
848 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
849 return READ_ONCE(sbinfo->shrinklist_len);
850 }
851 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
852
853 #define shmem_huge SHMEM_HUGE_DENY
854
shmem_unused_huge_shrink(struct shmem_sb_info * sbinfo,struct shrink_control * sc,unsigned long nr_to_free)855 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
856 struct shrink_control *sc, unsigned long nr_to_free)
857 {
858 return 0;
859 }
860
shmem_huge_global_enabled(struct inode * inode,pgoff_t index,loff_t write_end,bool shmem_huge_force,struct vm_area_struct * vma,vm_flags_t vm_flags)861 static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index,
862 loff_t write_end, bool shmem_huge_force,
863 struct vm_area_struct *vma,
864 vm_flags_t vm_flags)
865 {
866 return 0;
867 }
868 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
869
shmem_update_stats(struct folio * folio,int nr_pages)870 static void shmem_update_stats(struct folio *folio, int nr_pages)
871 {
872 if (folio_test_pmd_mappable(folio))
873 lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr_pages);
874 lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
875 lruvec_stat_mod_folio(folio, NR_SHMEM, nr_pages);
876 }
877
878 /*
879 * Somewhat like filemap_add_folio, but error if expected item has gone.
880 */
shmem_add_to_page_cache(struct folio * folio,struct address_space * mapping,pgoff_t index,void * expected,gfp_t gfp)881 int shmem_add_to_page_cache(struct folio *folio,
882 struct address_space *mapping,
883 pgoff_t index, void *expected, gfp_t gfp)
884 {
885 XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio));
886 unsigned long nr = folio_nr_pages(folio);
887 swp_entry_t iter, swap;
888 void *entry;
889
890 VM_BUG_ON_FOLIO(index != round_down(index, nr), folio);
891 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
892 VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio);
893
894 folio_ref_add(folio, nr);
895 folio->mapping = mapping;
896 folio->index = index;
897
898 gfp &= GFP_RECLAIM_MASK;
899 folio_throttle_swaprate(folio, gfp);
900 swap = radix_to_swp_entry(expected);
901
902 do {
903 iter = swap;
904 xas_lock_irq(&xas);
905 xas_for_each_conflict(&xas, entry) {
906 /*
907 * The range must either be empty, or filled with
908 * expected swap entries. Shmem swap entries are never
909 * partially freed without split of both entry and
910 * folio, so there shouldn't be any holes.
911 */
912 if (!expected || entry != swp_to_radix_entry(iter)) {
913 xas_set_err(&xas, -EEXIST);
914 goto unlock;
915 }
916 iter.val += 1 << xas_get_order(&xas);
917 }
918 if (expected && iter.val - nr != swap.val) {
919 xas_set_err(&xas, -EEXIST);
920 goto unlock;
921 }
922 xas_store(&xas, folio);
923 if (xas_error(&xas))
924 goto unlock;
925 shmem_update_stats(folio, nr);
926 mapping->nrpages += nr;
927 unlock:
928 xas_unlock_irq(&xas);
929 } while (xas_nomem(&xas, gfp));
930
931 if (xas_error(&xas)) {
932 folio->mapping = NULL;
933 folio_ref_sub(folio, nr);
934 return xas_error(&xas);
935 }
936
937 return 0;
938 }
939
940 /*
941 * Somewhat like filemap_remove_folio, but substitutes swap for @folio.
942 */
shmem_delete_from_page_cache(struct folio * folio,void * radswap)943 static void shmem_delete_from_page_cache(struct folio *folio, void *radswap)
944 {
945 struct address_space *mapping = folio->mapping;
946 long nr = folio_nr_pages(folio);
947 int error;
948
949 xa_lock_irq(&mapping->i_pages);
950 error = shmem_replace_entry(mapping, folio->index, folio, radswap);
951 folio->mapping = NULL;
952 mapping->nrpages -= nr;
953 shmem_update_stats(folio, -nr);
954 xa_unlock_irq(&mapping->i_pages);
955 folio_put_refs(folio, nr);
956 BUG_ON(error);
957 }
958
959 /*
960 * Remove swap entry from page cache, free the swap and its page cache. Returns
961 * the number of pages being freed. 0 means entry not found in XArray (0 pages
962 * being freed).
963 */
shmem_free_swap(struct address_space * mapping,pgoff_t index,pgoff_t end,void * radswap)964 static long shmem_free_swap(struct address_space *mapping,
965 pgoff_t index, pgoff_t end, void *radswap)
966 {
967 XA_STATE(xas, &mapping->i_pages, index);
968 unsigned int nr_pages = 0;
969 pgoff_t base;
970 void *entry;
971
972 xas_lock_irq(&xas);
973 entry = xas_load(&xas);
974 if (entry == radswap) {
975 nr_pages = 1 << xas_get_order(&xas);
976 base = round_down(xas.xa_index, nr_pages);
977 if (base < index || base + nr_pages - 1 > end)
978 nr_pages = 0;
979 else
980 xas_store(&xas, NULL);
981 }
982 xas_unlock_irq(&xas);
983
984 if (nr_pages)
985 swap_put_entries_direct(radix_to_swp_entry(radswap), nr_pages);
986
987 return nr_pages;
988 }
989
990 /*
991 * Determine (in bytes) how many of the shmem object's pages mapped by the
992 * given offsets are swapped out.
993 *
994 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
995 * as long as the inode doesn't go away and racy results are not a problem.
996 */
shmem_partial_swap_usage(struct address_space * mapping,pgoff_t start,pgoff_t end)997 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
998 pgoff_t start, pgoff_t end)
999 {
1000 XA_STATE(xas, &mapping->i_pages, start);
1001 struct folio *folio;
1002 unsigned long swapped = 0;
1003 unsigned long max = end - 1;
1004
1005 rcu_read_lock();
1006 xas_for_each(&xas, folio, max) {
1007 if (xas_retry(&xas, folio))
1008 continue;
1009 if (xa_is_value(folio))
1010 swapped += 1 << xas_get_order(&xas);
1011 if (xas.xa_index == max)
1012 break;
1013 if (need_resched()) {
1014 xas_pause(&xas);
1015 cond_resched_rcu();
1016 }
1017 }
1018 rcu_read_unlock();
1019
1020 return swapped << PAGE_SHIFT;
1021 }
1022
1023 /*
1024 * Determine (in bytes) how many of the shmem object's pages mapped by the
1025 * given vma is swapped out.
1026 *
1027 * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
1028 * as long as the inode doesn't go away and racy results are not a problem.
1029 */
shmem_swap_usage(struct vm_area_struct * vma)1030 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
1031 {
1032 struct inode *inode = file_inode(vma->vm_file);
1033 struct shmem_inode_info *info = SHMEM_I(inode);
1034 struct address_space *mapping = inode->i_mapping;
1035 unsigned long swapped;
1036
1037 /* Be careful as we don't hold info->lock */
1038 swapped = READ_ONCE(info->swapped);
1039
1040 /*
1041 * The easier cases are when the shmem object has nothing in swap, or
1042 * the vma maps it whole. Then we can simply use the stats that we
1043 * already track.
1044 */
1045 if (!swapped)
1046 return 0;
1047
1048 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
1049 return swapped << PAGE_SHIFT;
1050
1051 /* Here comes the more involved part */
1052 return shmem_partial_swap_usage(mapping, vma->vm_pgoff,
1053 vma->vm_pgoff + vma_pages(vma));
1054 }
1055
1056 /*
1057 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
1058 */
shmem_unlock_mapping(struct address_space * mapping)1059 void shmem_unlock_mapping(struct address_space *mapping)
1060 {
1061 struct folio_batch fbatch;
1062 pgoff_t index = 0;
1063
1064 folio_batch_init(&fbatch);
1065 /*
1066 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
1067 */
1068 while (!mapping_unevictable(mapping) &&
1069 filemap_get_folios(mapping, &index, ~0UL, &fbatch)) {
1070 check_move_unevictable_folios(&fbatch);
1071 folio_batch_release(&fbatch);
1072 cond_resched();
1073 }
1074 }
1075
shmem_get_partial_folio(struct inode * inode,pgoff_t index)1076 static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
1077 {
1078 struct folio *folio;
1079
1080 /*
1081 * At first avoid shmem_get_folio(,,,SGP_READ): that fails
1082 * beyond i_size, and reports fallocated folios as holes.
1083 */
1084 folio = filemap_get_entry(inode->i_mapping, index);
1085 if (!folio)
1086 return folio;
1087 if (!xa_is_value(folio)) {
1088 folio_lock(folio);
1089 if (folio->mapping == inode->i_mapping)
1090 return folio;
1091 /* The folio has been swapped out */
1092 folio_unlock(folio);
1093 folio_put(folio);
1094 }
1095 /*
1096 * But read a folio back from swap if any of it is within i_size
1097 * (although in some cases this is just a waste of time).
1098 */
1099 folio = NULL;
1100 shmem_get_folio(inode, index, 0, &folio, SGP_READ);
1101 return folio;
1102 }
1103
1104 /*
1105 * Remove range of pages and swap entries from page cache, and free them.
1106 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
1107 */
shmem_undo_range(struct inode * inode,loff_t lstart,uoff_t lend,bool unfalloc)1108 static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
1109 bool unfalloc)
1110 {
1111 struct address_space *mapping = inode->i_mapping;
1112 struct shmem_inode_info *info = SHMEM_I(inode);
1113 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
1114 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
1115 struct folio_batch fbatch;
1116 pgoff_t indices[PAGEVEC_SIZE];
1117 struct folio *folio;
1118 bool same_folio;
1119 long nr_swaps_freed = 0;
1120 pgoff_t index;
1121 int i;
1122
1123 if (lend == -1)
1124 end = -1; /* unsigned, so actually very big */
1125
1126 if (info->fallocend > start && info->fallocend <= end && !unfalloc)
1127 info->fallocend = start;
1128
1129 folio_batch_init(&fbatch);
1130 index = start;
1131 while (index < end && find_lock_entries(mapping, &index, end - 1,
1132 &fbatch, indices)) {
1133 for (i = 0; i < folio_batch_count(&fbatch); i++) {
1134 folio = fbatch.folios[i];
1135
1136 if (xa_is_value(folio)) {
1137 if (unfalloc)
1138 continue;
1139 nr_swaps_freed += shmem_free_swap(mapping, indices[i],
1140 end - 1, folio);
1141 continue;
1142 }
1143
1144 if (!unfalloc || !folio_test_uptodate(folio))
1145 truncate_inode_folio(mapping, folio);
1146 folio_unlock(folio);
1147 }
1148 folio_batch_remove_exceptionals(&fbatch);
1149 folio_batch_release(&fbatch);
1150 cond_resched();
1151 }
1152
1153 /*
1154 * When undoing a failed fallocate, we want none of the partial folio
1155 * zeroing and splitting below, but shall want to truncate the whole
1156 * folio when !uptodate indicates that it was added by this fallocate,
1157 * even when [lstart, lend] covers only a part of the folio.
1158 */
1159 if (unfalloc)
1160 goto whole_folios;
1161
1162 same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
1163 folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT);
1164 if (folio) {
1165 same_folio = lend < folio_next_pos(folio);
1166 folio_mark_dirty(folio);
1167 if (!truncate_inode_partial_folio(folio, lstart, lend)) {
1168 start = folio_next_index(folio);
1169 if (same_folio)
1170 end = folio->index;
1171 }
1172 folio_unlock(folio);
1173 folio_put(folio);
1174 folio = NULL;
1175 }
1176
1177 if (!same_folio)
1178 folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT);
1179 if (folio) {
1180 folio_mark_dirty(folio);
1181 if (!truncate_inode_partial_folio(folio, lstart, lend))
1182 end = folio->index;
1183 folio_unlock(folio);
1184 folio_put(folio);
1185 }
1186
1187 whole_folios:
1188
1189 index = start;
1190 while (index < end) {
1191 cond_resched();
1192
1193 if (!find_get_entries(mapping, &index, end - 1, &fbatch,
1194 indices)) {
1195 /* If all gone or hole-punch or unfalloc, we're done */
1196 if (index == start || end != -1)
1197 break;
1198 /* But if truncating, restart to make sure all gone */
1199 index = start;
1200 continue;
1201 }
1202 for (i = 0; i < folio_batch_count(&fbatch); i++) {
1203 folio = fbatch.folios[i];
1204
1205 if (xa_is_value(folio)) {
1206 int order;
1207 long swaps_freed;
1208
1209 if (unfalloc)
1210 continue;
1211 swaps_freed = shmem_free_swap(mapping, indices[i],
1212 end - 1, folio);
1213 if (!swaps_freed) {
1214 pgoff_t base = indices[i];
1215
1216 order = shmem_confirm_swap(mapping, indices[i],
1217 radix_to_swp_entry(folio));
1218 /*
1219 * If found a large swap entry cross the end or start
1220 * border, skip it as the truncate_inode_partial_folio
1221 * above should have at least zerod its content once.
1222 */
1223 if (order > 0) {
1224 base = round_down(base, 1 << order);
1225 if (base < start || base + (1 << order) > end)
1226 continue;
1227 }
1228 /* Swap was replaced by page or extended, retry */
1229 index = base;
1230 break;
1231 }
1232 nr_swaps_freed += swaps_freed;
1233 continue;
1234 }
1235
1236 folio_lock(folio);
1237
1238 if (!unfalloc || !folio_test_uptodate(folio)) {
1239 if (folio_mapping(folio) != mapping) {
1240 /* Page was replaced by swap: retry */
1241 folio_unlock(folio);
1242 index = indices[i];
1243 break;
1244 }
1245 VM_BUG_ON_FOLIO(folio_test_writeback(folio),
1246 folio);
1247
1248 if (!folio_test_large(folio)) {
1249 truncate_inode_folio(mapping, folio);
1250 } else if (truncate_inode_partial_folio(folio, lstart, lend)) {
1251 /*
1252 * If we split a page, reset the loop so
1253 * that we pick up the new sub pages.
1254 * Otherwise the THP was entirely
1255 * dropped or the target range was
1256 * zeroed, so just continue the loop as
1257 * is.
1258 */
1259 if (!folio_test_large(folio)) {
1260 folio_unlock(folio);
1261 index = start;
1262 break;
1263 }
1264 }
1265 }
1266 folio_unlock(folio);
1267 }
1268 folio_batch_remove_exceptionals(&fbatch);
1269 folio_batch_release(&fbatch);
1270 }
1271
1272 shmem_recalc_inode(inode, 0, -nr_swaps_freed);
1273 }
1274
shmem_truncate_range(struct inode * inode,loff_t lstart,uoff_t lend)1275 void shmem_truncate_range(struct inode *inode, loff_t lstart, uoff_t lend)
1276 {
1277 shmem_undo_range(inode, lstart, lend, false);
1278 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1279 inode_inc_iversion(inode);
1280 }
1281 EXPORT_SYMBOL_GPL(shmem_truncate_range);
1282
shmem_getattr(struct mnt_idmap * idmap,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)1283 static int shmem_getattr(struct mnt_idmap *idmap,
1284 const struct path *path, struct kstat *stat,
1285 u32 request_mask, unsigned int query_flags)
1286 {
1287 struct inode *inode = path->dentry->d_inode;
1288 struct shmem_inode_info *info = SHMEM_I(inode);
1289
1290 if (info->alloced - info->swapped != inode->i_mapping->nrpages)
1291 shmem_recalc_inode(inode, 0, 0);
1292
1293 if (info->fsflags & FS_APPEND_FL)
1294 stat->attributes |= STATX_ATTR_APPEND;
1295 if (info->fsflags & FS_IMMUTABLE_FL)
1296 stat->attributes |= STATX_ATTR_IMMUTABLE;
1297 if (info->fsflags & FS_NODUMP_FL)
1298 stat->attributes |= STATX_ATTR_NODUMP;
1299 stat->attributes_mask |= (STATX_ATTR_APPEND |
1300 STATX_ATTR_IMMUTABLE |
1301 STATX_ATTR_NODUMP);
1302 generic_fillattr(idmap, request_mask, inode, stat);
1303
1304 if (shmem_huge_global_enabled(inode, 0, 0, false, NULL, 0))
1305 stat->blksize = HPAGE_PMD_SIZE;
1306
1307 if (request_mask & STATX_BTIME) {
1308 stat->result_mask |= STATX_BTIME;
1309 stat->btime.tv_sec = info->i_crtime.tv_sec;
1310 stat->btime.tv_nsec = info->i_crtime.tv_nsec;
1311 }
1312
1313 return 0;
1314 }
1315
shmem_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * attr)1316 static int shmem_setattr(struct mnt_idmap *idmap,
1317 struct dentry *dentry, struct iattr *attr)
1318 {
1319 struct inode *inode = d_inode(dentry);
1320 struct shmem_inode_info *info = SHMEM_I(inode);
1321 int error;
1322 bool update_mtime = false;
1323 bool update_ctime = true;
1324
1325 error = setattr_prepare(idmap, dentry, attr);
1326 if (error)
1327 return error;
1328
1329 if ((info->seals & F_SEAL_EXEC) && (attr->ia_valid & ATTR_MODE)) {
1330 if ((inode->i_mode ^ attr->ia_mode) & 0111) {
1331 return -EPERM;
1332 }
1333 }
1334
1335 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1336 loff_t oldsize = inode->i_size;
1337 loff_t newsize = attr->ia_size;
1338
1339 /* protected by i_rwsem */
1340 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1341 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1342 return -EPERM;
1343
1344 if (newsize != oldsize) {
1345 if (info->flags & SHMEM_F_MAPPING_FROZEN)
1346 return -EPERM;
1347 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1348 oldsize, newsize);
1349 if (error)
1350 return error;
1351 i_size_write(inode, newsize);
1352 update_mtime = true;
1353 } else {
1354 update_ctime = false;
1355 }
1356 if (newsize <= oldsize) {
1357 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1358 if (oldsize > holebegin)
1359 unmap_mapping_range(inode->i_mapping,
1360 holebegin, 0, 1);
1361 if (info->alloced)
1362 shmem_truncate_range(inode,
1363 newsize, (loff_t)-1);
1364 /* unmap again to remove racily COWed private pages */
1365 if (oldsize > holebegin)
1366 unmap_mapping_range(inode->i_mapping,
1367 holebegin, 0, 1);
1368 }
1369 }
1370
1371 if (is_quota_modification(idmap, inode, attr)) {
1372 error = dquot_initialize(inode);
1373 if (error)
1374 return error;
1375 }
1376
1377 /* Transfer quota accounting */
1378 if (i_uid_needs_update(idmap, attr, inode) ||
1379 i_gid_needs_update(idmap, attr, inode)) {
1380 error = dquot_transfer(idmap, inode, attr);
1381 if (error)
1382 return error;
1383 }
1384
1385 setattr_copy(idmap, inode, attr);
1386 if (attr->ia_valid & ATTR_MODE)
1387 error = posix_acl_chmod(idmap, dentry, inode->i_mode);
1388 if (!error && update_ctime) {
1389 inode_set_ctime_current(inode);
1390 if (update_mtime)
1391 inode_set_mtime_to_ts(inode, inode_get_ctime(inode));
1392 inode_inc_iversion(inode);
1393 }
1394 return error;
1395 }
1396
shmem_evict_inode(struct inode * inode)1397 static void shmem_evict_inode(struct inode *inode)
1398 {
1399 struct shmem_inode_info *info = SHMEM_I(inode);
1400 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1401 size_t freed = 0;
1402
1403 if (shmem_mapping(inode->i_mapping)) {
1404 shmem_unacct_size(info->flags, inode->i_size);
1405 inode->i_size = 0;
1406 mapping_set_exiting(inode->i_mapping);
1407 shmem_truncate_range(inode, 0, (loff_t)-1);
1408 if (!list_empty(&info->shrinklist)) {
1409 spin_lock(&sbinfo->shrinklist_lock);
1410 if (!list_empty(&info->shrinklist)) {
1411 list_del_init(&info->shrinklist);
1412 sbinfo->shrinklist_len--;
1413 }
1414 spin_unlock(&sbinfo->shrinklist_lock);
1415 }
1416 while (!list_empty(&info->swaplist)) {
1417 /* Wait while shmem_unuse() is scanning this inode... */
1418 wait_var_event(&info->stop_eviction,
1419 !atomic_read(&info->stop_eviction));
1420 spin_lock(&shmem_swaplist_lock);
1421 /* ...but beware of the race if we peeked too early */
1422 if (!atomic_read(&info->stop_eviction))
1423 list_del_init(&info->swaplist);
1424 spin_unlock(&shmem_swaplist_lock);
1425 }
1426 }
1427
1428 if (info->xattrs) {
1429 simple_xattrs_free(info->xattrs, sbinfo->max_inodes ? &freed : NULL);
1430 kfree(info->xattrs);
1431 }
1432 shmem_free_inode(inode->i_sb, freed);
1433 WARN_ON(inode->i_blocks);
1434 clear_inode(inode);
1435 #ifdef CONFIG_TMPFS_QUOTA
1436 dquot_free_inode(inode);
1437 dquot_drop(inode);
1438 #endif
1439 }
1440
shmem_find_swap_entries(struct address_space * mapping,pgoff_t start,struct folio_batch * fbatch,pgoff_t * indices,unsigned int type)1441 static unsigned int shmem_find_swap_entries(struct address_space *mapping,
1442 pgoff_t start, struct folio_batch *fbatch,
1443 pgoff_t *indices, unsigned int type)
1444 {
1445 XA_STATE(xas, &mapping->i_pages, start);
1446 struct folio *folio;
1447 swp_entry_t entry;
1448
1449 rcu_read_lock();
1450 xas_for_each(&xas, folio, ULONG_MAX) {
1451 if (xas_retry(&xas, folio))
1452 continue;
1453
1454 if (!xa_is_value(folio))
1455 continue;
1456
1457 entry = radix_to_swp_entry(folio);
1458 /*
1459 * swapin error entries can be found in the mapping. But they're
1460 * deliberately ignored here as we've done everything we can do.
1461 */
1462 if (swp_type(entry) != type)
1463 continue;
1464
1465 indices[folio_batch_count(fbatch)] = xas.xa_index;
1466 if (!folio_batch_add(fbatch, folio))
1467 break;
1468
1469 if (need_resched()) {
1470 xas_pause(&xas);
1471 cond_resched_rcu();
1472 }
1473 }
1474 rcu_read_unlock();
1475
1476 return folio_batch_count(fbatch);
1477 }
1478
1479 /*
1480 * Move the swapped pages for an inode to page cache. Returns the count
1481 * of pages swapped in, or the error in case of failure.
1482 */
shmem_unuse_swap_entries(struct inode * inode,struct folio_batch * fbatch,pgoff_t * indices)1483 static int shmem_unuse_swap_entries(struct inode *inode,
1484 struct folio_batch *fbatch, pgoff_t *indices)
1485 {
1486 int i = 0;
1487 int ret = 0;
1488 int error = 0;
1489 struct address_space *mapping = inode->i_mapping;
1490
1491 for (i = 0; i < folio_batch_count(fbatch); i++) {
1492 struct folio *folio = fbatch->folios[i];
1493
1494 error = shmem_swapin_folio(inode, indices[i], &folio, SGP_CACHE,
1495 mapping_gfp_mask(mapping), NULL, NULL);
1496 if (error == 0) {
1497 folio_unlock(folio);
1498 folio_put(folio);
1499 ret++;
1500 }
1501 if (error == -ENOMEM)
1502 break;
1503 error = 0;
1504 }
1505 return error ? error : ret;
1506 }
1507
1508 /*
1509 * If swap found in inode, free it and move page from swapcache to filecache.
1510 */
shmem_unuse_inode(struct inode * inode,unsigned int type)1511 static int shmem_unuse_inode(struct inode *inode, unsigned int type)
1512 {
1513 struct address_space *mapping = inode->i_mapping;
1514 pgoff_t start = 0;
1515 struct folio_batch fbatch;
1516 pgoff_t indices[PAGEVEC_SIZE];
1517 int ret = 0;
1518
1519 do {
1520 folio_batch_init(&fbatch);
1521 if (!shmem_find_swap_entries(mapping, start, &fbatch,
1522 indices, type)) {
1523 ret = 0;
1524 break;
1525 }
1526
1527 ret = shmem_unuse_swap_entries(inode, &fbatch, indices);
1528 if (ret < 0)
1529 break;
1530
1531 start = indices[folio_batch_count(&fbatch) - 1];
1532 } while (true);
1533
1534 return ret;
1535 }
1536
1537 /*
1538 * Read all the shared memory data that resides in the swap
1539 * device 'type' back into memory, so the swap device can be
1540 * unused.
1541 */
shmem_unuse(unsigned int type)1542 int shmem_unuse(unsigned int type)
1543 {
1544 struct shmem_inode_info *info, *next;
1545 int error = 0;
1546
1547 if (list_empty(&shmem_swaplist))
1548 return 0;
1549
1550 spin_lock(&shmem_swaplist_lock);
1551 start_over:
1552 list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
1553 if (!info->swapped) {
1554 list_del_init(&info->swaplist);
1555 continue;
1556 }
1557 /*
1558 * Drop the swaplist mutex while searching the inode for swap;
1559 * but before doing so, make sure shmem_evict_inode() will not
1560 * remove placeholder inode from swaplist, nor let it be freed
1561 * (igrab() would protect from unlink, but not from unmount).
1562 */
1563 atomic_inc(&info->stop_eviction);
1564 spin_unlock(&shmem_swaplist_lock);
1565
1566 error = shmem_unuse_inode(&info->vfs_inode, type);
1567 cond_resched();
1568
1569 spin_lock(&shmem_swaplist_lock);
1570 if (atomic_dec_and_test(&info->stop_eviction))
1571 wake_up_var(&info->stop_eviction);
1572 if (error)
1573 break;
1574 if (list_empty(&info->swaplist))
1575 goto start_over;
1576 next = list_next_entry(info, swaplist);
1577 if (!info->swapped)
1578 list_del_init(&info->swaplist);
1579 }
1580 spin_unlock(&shmem_swaplist_lock);
1581
1582 return error;
1583 }
1584
1585 /**
1586 * shmem_writeout - Write the folio to swap
1587 * @folio: The folio to write
1588 * @plug: swap plug
1589 * @folio_list: list to put back folios on split
1590 *
1591 * Move the folio from the page cache to the swap cache.
1592 */
shmem_writeout(struct folio * folio,struct swap_iocb ** plug,struct list_head * folio_list)1593 int shmem_writeout(struct folio *folio, struct swap_iocb **plug,
1594 struct list_head *folio_list)
1595 {
1596 struct address_space *mapping = folio->mapping;
1597 struct inode *inode = mapping->host;
1598 struct shmem_inode_info *info = SHMEM_I(inode);
1599 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1600 pgoff_t index;
1601 int nr_pages;
1602 bool split = false;
1603
1604 if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap)
1605 goto redirty;
1606
1607 if (!total_swap_pages)
1608 goto redirty;
1609
1610 /*
1611 * If CONFIG_THP_SWAP is not enabled, the large folio should be
1612 * split when swapping.
1613 *
1614 * And shrinkage of pages beyond i_size does not split swap, so
1615 * swapout of a large folio crossing i_size needs to split too
1616 * (unless fallocate has been used to preallocate beyond EOF).
1617 */
1618 if (folio_test_large(folio)) {
1619 index = shmem_fallocend(inode,
1620 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE));
1621 if ((index > folio->index && index < folio_next_index(folio)) ||
1622 !IS_ENABLED(CONFIG_THP_SWAP))
1623 split = true;
1624 }
1625
1626 if (split) {
1627 int order;
1628
1629 try_split:
1630 order = folio_order(folio);
1631 /* Ensure the subpages are still dirty */
1632 folio_test_set_dirty(folio);
1633 if (split_folio_to_list(folio, folio_list))
1634 goto redirty;
1635
1636 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1637 if (order >= HPAGE_PMD_ORDER) {
1638 count_memcg_folio_events(folio, THP_SWPOUT_FALLBACK, 1);
1639 count_vm_event(THP_SWPOUT_FALLBACK);
1640 }
1641 #endif
1642 count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
1643
1644 folio_clear_dirty(folio);
1645 }
1646
1647 index = folio->index;
1648 nr_pages = folio_nr_pages(folio);
1649
1650 /*
1651 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1652 * value into swapfile.c, the only way we can correctly account for a
1653 * fallocated folio arriving here is now to initialize it and write it.
1654 *
1655 * That's okay for a folio already fallocated earlier, but if we have
1656 * not yet completed the fallocation, then (a) we want to keep track
1657 * of this folio in case we have to undo it, and (b) it may not be a
1658 * good idea to continue anyway, once we're pushing into swap. So
1659 * reactivate the folio, and let shmem_fallocate() quit when too many.
1660 */
1661 if (!folio_test_uptodate(folio)) {
1662 if (inode->i_private) {
1663 struct shmem_falloc *shmem_falloc;
1664 spin_lock(&inode->i_lock);
1665 shmem_falloc = inode->i_private;
1666 if (shmem_falloc &&
1667 !shmem_falloc->waitq &&
1668 index >= shmem_falloc->start &&
1669 index < shmem_falloc->next)
1670 shmem_falloc->nr_unswapped += nr_pages;
1671 else
1672 shmem_falloc = NULL;
1673 spin_unlock(&inode->i_lock);
1674 if (shmem_falloc)
1675 goto redirty;
1676 }
1677 folio_zero_range(folio, 0, folio_size(folio));
1678 flush_dcache_folio(folio);
1679 folio_mark_uptodate(folio);
1680 }
1681
1682 if (!folio_alloc_swap(folio)) {
1683 bool first_swapped = shmem_recalc_inode(inode, 0, nr_pages);
1684 int error;
1685
1686 /*
1687 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1688 * if it's not already there. Do it now before the folio is
1689 * removed from page cache, when its pagelock no longer
1690 * protects the inode from eviction. And do it now, after
1691 * we've incremented swapped, because shmem_unuse() will
1692 * prune a !swapped inode from the swaplist.
1693 */
1694 if (first_swapped) {
1695 spin_lock(&shmem_swaplist_lock);
1696 if (list_empty(&info->swaplist))
1697 list_add(&info->swaplist, &shmem_swaplist);
1698 spin_unlock(&shmem_swaplist_lock);
1699 }
1700
1701 folio_dup_swap(folio, NULL);
1702 shmem_delete_from_page_cache(folio, swp_to_radix_entry(folio->swap));
1703
1704 BUG_ON(folio_mapped(folio));
1705 error = swap_writeout(folio, plug);
1706 if (error != AOP_WRITEPAGE_ACTIVATE) {
1707 /* folio has been unlocked */
1708 return error;
1709 }
1710
1711 /*
1712 * The intention here is to avoid holding on to the swap when
1713 * zswap was unable to compress and unable to writeback; but
1714 * it will be appropriate if other reactivate cases are added.
1715 */
1716 error = shmem_add_to_page_cache(folio, mapping, index,
1717 swp_to_radix_entry(folio->swap),
1718 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
1719 /* Swap entry might be erased by racing shmem_free_swap() */
1720 if (!error) {
1721 shmem_recalc_inode(inode, 0, -nr_pages);
1722 folio_put_swap(folio, NULL);
1723 }
1724
1725 /*
1726 * The swap_cache_del_folio() below could be left for
1727 * shrink_folio_list()'s folio_free_swap() to dispose of;
1728 * but I'm a little nervous about letting this folio out of
1729 * shmem_writeout() in a hybrid half-tmpfs-half-swap state
1730 * e.g. folio_mapping(folio) might give an unexpected answer.
1731 */
1732 swap_cache_del_folio(folio);
1733 goto redirty;
1734 }
1735 if (nr_pages > 1)
1736 goto try_split;
1737 redirty:
1738 folio_mark_dirty(folio);
1739 return AOP_WRITEPAGE_ACTIVATE; /* Return with folio locked */
1740 }
1741 EXPORT_SYMBOL_GPL(shmem_writeout);
1742
1743 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
shmem_show_mpol(struct seq_file * seq,struct mempolicy * mpol)1744 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1745 {
1746 char buffer[64];
1747
1748 if (!mpol || mpol->mode == MPOL_DEFAULT)
1749 return; /* show nothing */
1750
1751 mpol_to_str(buffer, sizeof(buffer), mpol);
1752
1753 seq_printf(seq, ",mpol=%s", buffer);
1754 }
1755
shmem_get_sbmpol(struct shmem_sb_info * sbinfo)1756 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1757 {
1758 struct mempolicy *mpol = NULL;
1759 if (sbinfo->mpol) {
1760 raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1761 mpol = sbinfo->mpol;
1762 mpol_get(mpol);
1763 raw_spin_unlock(&sbinfo->stat_lock);
1764 }
1765 return mpol;
1766 }
1767 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
shmem_show_mpol(struct seq_file * seq,struct mempolicy * mpol)1768 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1769 {
1770 }
shmem_get_sbmpol(struct shmem_sb_info * sbinfo)1771 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1772 {
1773 return NULL;
1774 }
1775 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1776
1777 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
1778 pgoff_t index, unsigned int order, pgoff_t *ilx);
1779
shmem_swapin_cluster(swp_entry_t swap,gfp_t gfp,struct shmem_inode_info * info,pgoff_t index)1780 static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp,
1781 struct shmem_inode_info *info, pgoff_t index)
1782 {
1783 struct mempolicy *mpol;
1784 pgoff_t ilx;
1785 struct folio *folio;
1786
1787 mpol = shmem_get_pgoff_policy(info, index, 0, &ilx);
1788 folio = swap_cluster_readahead(swap, gfp, mpol, ilx);
1789 mpol_cond_put(mpol);
1790
1791 return folio;
1792 }
1793
1794 /*
1795 * Make sure huge_gfp is always more limited than limit_gfp.
1796 * Some of the flags set permissions, while others set limitations.
1797 */
limit_gfp_mask(gfp_t huge_gfp,gfp_t limit_gfp)1798 static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
1799 {
1800 gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
1801 gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
1802 gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
1803 gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
1804
1805 /* Allow allocations only from the originally specified zones. */
1806 result |= zoneflags;
1807
1808 /*
1809 * Minimize the result gfp by taking the union with the deny flags,
1810 * and the intersection of the allow flags.
1811 */
1812 result |= (limit_gfp & denyflags);
1813 result |= (huge_gfp & limit_gfp) & allowflags;
1814
1815 return result;
1816 }
1817
1818 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
shmem_hpage_pmd_enabled(void)1819 bool shmem_hpage_pmd_enabled(void)
1820 {
1821 if (shmem_huge == SHMEM_HUGE_DENY)
1822 return false;
1823 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always))
1824 return true;
1825 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise))
1826 return true;
1827 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size))
1828 return true;
1829 if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) &&
1830 shmem_huge != SHMEM_HUGE_NEVER)
1831 return true;
1832
1833 return false;
1834 }
1835
shmem_allowable_huge_orders(struct inode * inode,struct vm_area_struct * vma,pgoff_t index,loff_t write_end,bool shmem_huge_force)1836 unsigned long shmem_allowable_huge_orders(struct inode *inode,
1837 struct vm_area_struct *vma, pgoff_t index,
1838 loff_t write_end, bool shmem_huge_force)
1839 {
1840 unsigned long mask = READ_ONCE(huge_shmem_orders_always);
1841 unsigned long within_size_orders = READ_ONCE(huge_shmem_orders_within_size);
1842 vm_flags_t vm_flags = vma ? vma->vm_flags : 0;
1843 unsigned int global_orders;
1844
1845 if (thp_disabled_by_hw() || (vma && vma_thp_disabled(vma, vm_flags, shmem_huge_force)))
1846 return 0;
1847
1848 global_orders = shmem_huge_global_enabled(inode, index, write_end,
1849 shmem_huge_force, vma, vm_flags);
1850 /* Tmpfs huge pages allocation */
1851 if (!vma || !vma_is_anon_shmem(vma))
1852 return global_orders;
1853
1854 /*
1855 * Following the 'deny' semantics of the top level, force the huge
1856 * option off from all mounts.
1857 */
1858 if (shmem_huge == SHMEM_HUGE_DENY)
1859 return 0;
1860
1861 /*
1862 * Only allow inherit orders if the top-level value is 'force', which
1863 * means non-PMD sized THP can not override 'huge' mount option now.
1864 */
1865 if (shmem_huge == SHMEM_HUGE_FORCE)
1866 return READ_ONCE(huge_shmem_orders_inherit);
1867
1868 /* Allow mTHP that will be fully within i_size. */
1869 mask |= shmem_get_orders_within_size(inode, within_size_orders, index, 0);
1870
1871 if (vm_flags & VM_HUGEPAGE)
1872 mask |= READ_ONCE(huge_shmem_orders_madvise);
1873
1874 if (global_orders > 0)
1875 mask |= READ_ONCE(huge_shmem_orders_inherit);
1876
1877 return THP_ORDERS_ALL_FILE_DEFAULT & mask;
1878 }
1879
shmem_suitable_orders(struct inode * inode,struct vm_fault * vmf,struct address_space * mapping,pgoff_t index,unsigned long orders)1880 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf,
1881 struct address_space *mapping, pgoff_t index,
1882 unsigned long orders)
1883 {
1884 struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
1885 pgoff_t aligned_index;
1886 unsigned long pages;
1887 int order;
1888
1889 if (vma) {
1890 orders = thp_vma_suitable_orders(vma, vmf->address, orders);
1891 if (!orders)
1892 return 0;
1893 }
1894
1895 /* Find the highest order that can add into the page cache */
1896 order = highest_order(orders);
1897 while (orders) {
1898 pages = 1UL << order;
1899 aligned_index = round_down(index, pages);
1900 /*
1901 * Check for conflict before waiting on a huge allocation.
1902 * Conflict might be that a huge page has just been allocated
1903 * and added to page cache by a racing thread, or that there
1904 * is already at least one small page in the huge extent.
1905 * Be careful to retry when appropriate, but not forever!
1906 * Elsewhere -EEXIST would be the right code, but not here.
1907 */
1908 if (!xa_find(&mapping->i_pages, &aligned_index,
1909 aligned_index + pages - 1, XA_PRESENT))
1910 break;
1911 order = next_order(&orders, order);
1912 }
1913
1914 return orders;
1915 }
1916 #else
shmem_suitable_orders(struct inode * inode,struct vm_fault * vmf,struct address_space * mapping,pgoff_t index,unsigned long orders)1917 static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf,
1918 struct address_space *mapping, pgoff_t index,
1919 unsigned long orders)
1920 {
1921 return 0;
1922 }
1923 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1924
shmem_alloc_folio(gfp_t gfp,int order,struct shmem_inode_info * info,pgoff_t index)1925 static struct folio *shmem_alloc_folio(gfp_t gfp, int order,
1926 struct shmem_inode_info *info, pgoff_t index)
1927 {
1928 struct mempolicy *mpol;
1929 pgoff_t ilx;
1930 struct folio *folio;
1931
1932 mpol = shmem_get_pgoff_policy(info, index, order, &ilx);
1933 folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
1934 mpol_cond_put(mpol);
1935
1936 return folio;
1937 }
1938
shmem_alloc_and_add_folio(struct vm_fault * vmf,gfp_t gfp,struct inode * inode,pgoff_t index,struct mm_struct * fault_mm,unsigned long orders)1939 static struct folio *shmem_alloc_and_add_folio(struct vm_fault *vmf,
1940 gfp_t gfp, struct inode *inode, pgoff_t index,
1941 struct mm_struct *fault_mm, unsigned long orders)
1942 {
1943 struct address_space *mapping = inode->i_mapping;
1944 struct shmem_inode_info *info = SHMEM_I(inode);
1945 unsigned long suitable_orders = 0;
1946 struct folio *folio = NULL;
1947 pgoff_t aligned_index;
1948 long pages;
1949 int error, order;
1950
1951 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1952 orders = 0;
1953
1954 if (orders > 0) {
1955 suitable_orders = shmem_suitable_orders(inode, vmf,
1956 mapping, index, orders);
1957
1958 order = highest_order(suitable_orders);
1959 while (suitable_orders) {
1960 pages = 1UL << order;
1961 aligned_index = round_down(index, pages);
1962 folio = shmem_alloc_folio(gfp, order, info, aligned_index);
1963 if (folio) {
1964 index = aligned_index;
1965 goto allocated;
1966 }
1967
1968 if (pages == HPAGE_PMD_NR)
1969 count_vm_event(THP_FILE_FALLBACK);
1970 count_mthp_stat(order, MTHP_STAT_SHMEM_FALLBACK);
1971 order = next_order(&suitable_orders, order);
1972 }
1973 } else {
1974 pages = 1;
1975 folio = shmem_alloc_folio(gfp, 0, info, index);
1976 }
1977 if (!folio)
1978 return ERR_PTR(-ENOMEM);
1979
1980 allocated:
1981 __folio_set_locked(folio);
1982 __folio_set_swapbacked(folio);
1983
1984 gfp &= GFP_RECLAIM_MASK;
1985 error = mem_cgroup_charge(folio, fault_mm, gfp);
1986 if (error) {
1987 if (xa_find(&mapping->i_pages, &index,
1988 index + pages - 1, XA_PRESENT)) {
1989 error = -EEXIST;
1990 } else if (pages > 1) {
1991 if (pages == HPAGE_PMD_NR) {
1992 count_vm_event(THP_FILE_FALLBACK);
1993 count_vm_event(THP_FILE_FALLBACK_CHARGE);
1994 }
1995 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK);
1996 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK_CHARGE);
1997 }
1998 goto unlock;
1999 }
2000
2001 error = shmem_add_to_page_cache(folio, mapping, index, NULL, gfp);
2002 if (error)
2003 goto unlock;
2004
2005 error = shmem_inode_acct_blocks(inode, pages);
2006 if (error) {
2007 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2008 long freed;
2009 /*
2010 * Try to reclaim some space by splitting a few
2011 * large folios beyond i_size on the filesystem.
2012 */
2013 shmem_unused_huge_shrink(sbinfo, NULL, pages);
2014 /*
2015 * And do a shmem_recalc_inode() to account for freed pages:
2016 * except our folio is there in cache, so not quite balanced.
2017 */
2018 spin_lock(&info->lock);
2019 freed = pages + info->alloced - info->swapped -
2020 READ_ONCE(mapping->nrpages);
2021 if (freed > 0)
2022 info->alloced -= freed;
2023 spin_unlock(&info->lock);
2024 if (freed > 0)
2025 shmem_inode_unacct_blocks(inode, freed);
2026 error = shmem_inode_acct_blocks(inode, pages);
2027 if (error) {
2028 filemap_remove_folio(folio);
2029 goto unlock;
2030 }
2031 }
2032
2033 shmem_recalc_inode(inode, pages, 0);
2034 folio_add_lru(folio);
2035 return folio;
2036
2037 unlock:
2038 folio_unlock(folio);
2039 folio_put(folio);
2040 return ERR_PTR(error);
2041 }
2042
shmem_swap_alloc_folio(struct inode * inode,struct vm_area_struct * vma,pgoff_t index,swp_entry_t entry,int order,gfp_t gfp)2043 static struct folio *shmem_swap_alloc_folio(struct inode *inode,
2044 struct vm_area_struct *vma, pgoff_t index,
2045 swp_entry_t entry, int order, gfp_t gfp)
2046 {
2047 struct shmem_inode_info *info = SHMEM_I(inode);
2048 struct folio *new, *swapcache;
2049 int nr_pages = 1 << order;
2050 gfp_t alloc_gfp;
2051
2052 /*
2053 * We have arrived here because our zones are constrained, so don't
2054 * limit chance of success with further cpuset and node constraints.
2055 */
2056 gfp &= ~GFP_CONSTRAINT_MASK;
2057 alloc_gfp = gfp;
2058 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
2059 if (WARN_ON_ONCE(order))
2060 return ERR_PTR(-EINVAL);
2061 } else if (order) {
2062 /*
2063 * If uffd is active for the vma, we need per-page fault
2064 * fidelity to maintain the uffd semantics, then fallback
2065 * to swapin order-0 folio, as well as for zswap case.
2066 * Any existing sub folio in the swap cache also blocks
2067 * mTHP swapin.
2068 */
2069 if ((vma && unlikely(userfaultfd_armed(vma))) ||
2070 !zswap_never_enabled() ||
2071 non_swapcache_batch(entry, nr_pages) != nr_pages)
2072 goto fallback;
2073
2074 alloc_gfp = limit_gfp_mask(vma_thp_gfp_mask(vma), gfp);
2075 }
2076 retry:
2077 new = shmem_alloc_folio(alloc_gfp, order, info, index);
2078 if (!new) {
2079 new = ERR_PTR(-ENOMEM);
2080 goto fallback;
2081 }
2082
2083 if (mem_cgroup_swapin_charge_folio(new, vma ? vma->vm_mm : NULL,
2084 alloc_gfp, entry)) {
2085 folio_put(new);
2086 new = ERR_PTR(-ENOMEM);
2087 goto fallback;
2088 }
2089
2090 swapcache = swapin_folio(entry, new);
2091 if (swapcache != new) {
2092 folio_put(new);
2093 if (!swapcache) {
2094 /*
2095 * The new folio is charged already, swapin can
2096 * only fail due to another raced swapin.
2097 */
2098 new = ERR_PTR(-EEXIST);
2099 goto fallback;
2100 }
2101 }
2102 return swapcache;
2103 fallback:
2104 /* Order 0 swapin failed, nothing to fallback to, abort */
2105 if (!order)
2106 return new;
2107 entry.val += index - round_down(index, nr_pages);
2108 alloc_gfp = gfp;
2109 nr_pages = 1;
2110 order = 0;
2111 goto retry;
2112 }
2113
2114 /*
2115 * When a page is moved from swapcache to shmem filecache (either by the
2116 * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
2117 * shmem_unuse_inode()), it may have been read in earlier from swap, in
2118 * ignorance of the mapping it belongs to. If that mapping has special
2119 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
2120 * we may need to copy to a suitable page before moving to filecache.
2121 *
2122 * In a future release, this may well be extended to respect cpuset and
2123 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
2124 * but for now it is a simple matter of zone.
2125 */
shmem_should_replace_folio(struct folio * folio,gfp_t gfp)2126 static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp)
2127 {
2128 return folio_zonenum(folio) > gfp_zone(gfp);
2129 }
2130
shmem_replace_folio(struct folio ** foliop,gfp_t gfp,struct shmem_inode_info * info,pgoff_t index,struct vm_area_struct * vma)2131 static int shmem_replace_folio(struct folio **foliop, gfp_t gfp,
2132 struct shmem_inode_info *info, pgoff_t index,
2133 struct vm_area_struct *vma)
2134 {
2135 struct swap_cluster_info *ci;
2136 struct folio *new, *old = *foliop;
2137 swp_entry_t entry = old->swap;
2138 int nr_pages = folio_nr_pages(old);
2139 int error = 0;
2140
2141 /*
2142 * We have arrived here because our zones are constrained, so don't
2143 * limit chance of success by further cpuset and node constraints.
2144 */
2145 gfp &= ~GFP_CONSTRAINT_MASK;
2146 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2147 if (nr_pages > 1) {
2148 gfp_t huge_gfp = vma_thp_gfp_mask(vma);
2149
2150 gfp = limit_gfp_mask(huge_gfp, gfp);
2151 }
2152 #endif
2153
2154 new = shmem_alloc_folio(gfp, folio_order(old), info, index);
2155 if (!new)
2156 return -ENOMEM;
2157
2158 folio_ref_add(new, nr_pages);
2159 folio_copy(new, old);
2160 flush_dcache_folio(new);
2161
2162 __folio_set_locked(new);
2163 __folio_set_swapbacked(new);
2164 folio_mark_uptodate(new);
2165 new->swap = entry;
2166 folio_set_swapcache(new);
2167
2168 ci = swap_cluster_get_and_lock_irq(old);
2169 __swap_cache_replace_folio(ci, old, new);
2170 mem_cgroup_replace_folio(old, new);
2171 shmem_update_stats(new, nr_pages);
2172 shmem_update_stats(old, -nr_pages);
2173 swap_cluster_unlock_irq(ci);
2174
2175 folio_add_lru(new);
2176 *foliop = new;
2177
2178 folio_clear_swapcache(old);
2179 old->private = NULL;
2180
2181 folio_unlock(old);
2182 /*
2183 * The old folio are removed from swap cache, drop the 'nr_pages'
2184 * reference, as well as one temporary reference getting from swap
2185 * cache.
2186 */
2187 folio_put_refs(old, nr_pages + 1);
2188 return error;
2189 }
2190
shmem_set_folio_swapin_error(struct inode * inode,pgoff_t index,struct folio * folio,swp_entry_t swap)2191 static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,
2192 struct folio *folio, swp_entry_t swap)
2193 {
2194 struct address_space *mapping = inode->i_mapping;
2195 swp_entry_t swapin_error;
2196 void *old;
2197 int nr_pages;
2198
2199 swapin_error = make_poisoned_swp_entry();
2200 old = xa_cmpxchg_irq(&mapping->i_pages, index,
2201 swp_to_radix_entry(swap),
2202 swp_to_radix_entry(swapin_error), 0);
2203 if (old != swp_to_radix_entry(swap))
2204 return;
2205
2206 nr_pages = folio_nr_pages(folio);
2207 folio_wait_writeback(folio);
2208 folio_put_swap(folio, NULL);
2209 swap_cache_del_folio(folio);
2210 /*
2211 * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks
2212 * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks)
2213 * in shmem_evict_inode().
2214 */
2215 shmem_recalc_inode(inode, -nr_pages, -nr_pages);
2216 }
2217
shmem_split_large_entry(struct inode * inode,pgoff_t index,swp_entry_t swap,gfp_t gfp)2218 static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
2219 swp_entry_t swap, gfp_t gfp)
2220 {
2221 struct address_space *mapping = inode->i_mapping;
2222 XA_STATE_ORDER(xas, &mapping->i_pages, index, 0);
2223 int split_order = 0;
2224 int i;
2225
2226 /* Convert user data gfp flags to xarray node gfp flags */
2227 gfp &= GFP_RECLAIM_MASK;
2228
2229 for (;;) {
2230 void *old = NULL;
2231 int cur_order;
2232 pgoff_t swap_index;
2233
2234 xas_lock_irq(&xas);
2235 old = xas_load(&xas);
2236 if (!xa_is_value(old) || swp_to_radix_entry(swap) != old) {
2237 xas_set_err(&xas, -EEXIST);
2238 goto unlock;
2239 }
2240
2241 cur_order = xas_get_order(&xas);
2242 if (!cur_order)
2243 goto unlock;
2244
2245 /* Try to split large swap entry in pagecache */
2246 swap_index = round_down(index, 1 << cur_order);
2247 split_order = xas_try_split_min_order(cur_order);
2248
2249 while (cur_order > 0) {
2250 pgoff_t aligned_index =
2251 round_down(index, 1 << cur_order);
2252 pgoff_t swap_offset = aligned_index - swap_index;
2253
2254 xas_set_order(&xas, index, split_order);
2255 xas_try_split(&xas, old, cur_order);
2256 if (xas_error(&xas))
2257 goto unlock;
2258
2259 /*
2260 * Re-set the swap entry after splitting, and the swap
2261 * offset of the original large entry must be continuous.
2262 */
2263 for (i = 0; i < 1 << cur_order;
2264 i += (1 << split_order)) {
2265 swp_entry_t tmp;
2266
2267 tmp = swp_entry(swp_type(swap),
2268 swp_offset(swap) + swap_offset +
2269 i);
2270 __xa_store(&mapping->i_pages, aligned_index + i,
2271 swp_to_radix_entry(tmp), 0);
2272 }
2273 cur_order = split_order;
2274 split_order = xas_try_split_min_order(split_order);
2275 }
2276
2277 unlock:
2278 xas_unlock_irq(&xas);
2279
2280 if (!xas_nomem(&xas, gfp))
2281 break;
2282 }
2283
2284 if (xas_error(&xas))
2285 return xas_error(&xas);
2286
2287 return 0;
2288 }
2289
2290 /*
2291 * Swap in the folio pointed to by *foliop.
2292 * Caller has to make sure that *foliop contains a valid swapped folio.
2293 * Returns 0 and the folio in foliop if success. On failure, returns the
2294 * error code and NULL in *foliop.
2295 */
shmem_swapin_folio(struct inode * inode,pgoff_t index,struct folio ** foliop,enum sgp_type sgp,gfp_t gfp,struct vm_area_struct * vma,vm_fault_t * fault_type)2296 static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
2297 struct folio **foliop, enum sgp_type sgp,
2298 gfp_t gfp, struct vm_area_struct *vma,
2299 vm_fault_t *fault_type)
2300 {
2301 struct address_space *mapping = inode->i_mapping;
2302 struct mm_struct *fault_mm = vma ? vma->vm_mm : NULL;
2303 struct shmem_inode_info *info = SHMEM_I(inode);
2304 swp_entry_t swap;
2305 softleaf_t index_entry;
2306 struct swap_info_struct *si;
2307 struct folio *folio = NULL;
2308 int error, nr_pages, order;
2309 pgoff_t offset;
2310
2311 VM_BUG_ON(!*foliop || !xa_is_value(*foliop));
2312 index_entry = radix_to_swp_entry(*foliop);
2313 swap = index_entry;
2314 *foliop = NULL;
2315
2316 if (softleaf_is_poison_marker(index_entry))
2317 return -EIO;
2318
2319 si = get_swap_device(index_entry);
2320 order = shmem_confirm_swap(mapping, index, index_entry);
2321 if (unlikely(!si)) {
2322 if (order < 0)
2323 return -EEXIST;
2324 else
2325 return -EINVAL;
2326 }
2327 if (unlikely(order < 0)) {
2328 put_swap_device(si);
2329 return -EEXIST;
2330 }
2331
2332 /* index may point to the middle of a large entry, get the sub entry */
2333 if (order) {
2334 offset = index - round_down(index, 1 << order);
2335 swap = swp_entry(swp_type(swap), swp_offset(swap) + offset);
2336 }
2337
2338 /* Look it up and read it in.. */
2339 folio = swap_cache_get_folio(swap);
2340 if (!folio) {
2341 if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) {
2342 /* Direct swapin skipping swap cache & readahead */
2343 folio = shmem_swap_alloc_folio(inode, vma, index,
2344 index_entry, order, gfp);
2345 if (IS_ERR(folio)) {
2346 error = PTR_ERR(folio);
2347 folio = NULL;
2348 goto failed;
2349 }
2350 } else {
2351 /* Cached swapin only supports order 0 folio */
2352 folio = shmem_swapin_cluster(swap, gfp, info, index);
2353 if (!folio) {
2354 error = -ENOMEM;
2355 goto failed;
2356 }
2357 }
2358 if (fault_type) {
2359 *fault_type |= VM_FAULT_MAJOR;
2360 count_vm_event(PGMAJFAULT);
2361 count_memcg_event_mm(fault_mm, PGMAJFAULT);
2362 }
2363 } else {
2364 swap_update_readahead(folio, NULL, 0);
2365 }
2366
2367 if (order > folio_order(folio)) {
2368 /*
2369 * Swapin may get smaller folios due to various reasons:
2370 * It may fallback to order 0 due to memory pressure or race,
2371 * swap readahead may swap in order 0 folios into swapcache
2372 * asynchronously, while the shmem mapping can still stores
2373 * large swap entries. In such cases, we should split the
2374 * large swap entry to prevent possible data corruption.
2375 */
2376 error = shmem_split_large_entry(inode, index, index_entry, gfp);
2377 if (error)
2378 goto failed_nolock;
2379 }
2380
2381 /*
2382 * If the folio is large, round down swap and index by folio size.
2383 * No matter what race occurs, the swap layer ensures we either get
2384 * a valid folio that has its swap entry aligned by size, or a
2385 * temporarily invalid one which we'll abort very soon and retry.
2386 *
2387 * shmem_add_to_page_cache ensures the whole range contains expected
2388 * entries and prevents any corruption, so any race split is fine
2389 * too, it will succeed as long as the entries are still there.
2390 */
2391 nr_pages = folio_nr_pages(folio);
2392 if (nr_pages > 1) {
2393 swap.val = round_down(swap.val, nr_pages);
2394 index = round_down(index, nr_pages);
2395 }
2396
2397 /*
2398 * We have to do this with the folio locked to prevent races.
2399 * The shmem_confirm_swap below only checks if the first swap
2400 * entry matches the folio, that's enough to ensure the folio
2401 * is not used outside of shmem, as shmem swap entries
2402 * and swap cache folios are never partially freed.
2403 */
2404 folio_lock(folio);
2405 if (!folio_matches_swap_entry(folio, swap) ||
2406 shmem_confirm_swap(mapping, index, swap) < 0) {
2407 error = -EEXIST;
2408 goto unlock;
2409 }
2410 if (!folio_test_uptodate(folio)) {
2411 error = -EIO;
2412 goto failed;
2413 }
2414 folio_wait_writeback(folio);
2415
2416 /*
2417 * Some architectures may have to restore extra metadata to the
2418 * folio after reading from swap.
2419 */
2420 arch_swap_restore(folio_swap(swap, folio), folio);
2421
2422 if (shmem_should_replace_folio(folio, gfp)) {
2423 error = shmem_replace_folio(&folio, gfp, info, index, vma);
2424 if (error)
2425 goto failed;
2426 }
2427
2428 error = shmem_add_to_page_cache(folio, mapping, index,
2429 swp_to_radix_entry(swap), gfp);
2430 if (error)
2431 goto failed;
2432
2433 shmem_recalc_inode(inode, 0, -nr_pages);
2434
2435 if (sgp == SGP_WRITE)
2436 folio_mark_accessed(folio);
2437
2438 folio_put_swap(folio, NULL);
2439 swap_cache_del_folio(folio);
2440 folio_mark_dirty(folio);
2441 put_swap_device(si);
2442
2443 *foliop = folio;
2444 return 0;
2445 failed:
2446 if (shmem_confirm_swap(mapping, index, swap) < 0)
2447 error = -EEXIST;
2448 if (error == -EIO)
2449 shmem_set_folio_swapin_error(inode, index, folio, swap);
2450 unlock:
2451 if (folio)
2452 folio_unlock(folio);
2453 failed_nolock:
2454 if (folio)
2455 folio_put(folio);
2456 put_swap_device(si);
2457
2458 return error;
2459 }
2460
2461 /*
2462 * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
2463 *
2464 * If we allocate a new one we do not mark it dirty. That's up to the
2465 * vm. If we swap it in we mark it dirty since we also free the swap
2466 * entry since a page cannot live in both the swap and page cache.
2467 *
2468 * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL.
2469 */
shmem_get_folio_gfp(struct inode * inode,pgoff_t index,loff_t write_end,struct folio ** foliop,enum sgp_type sgp,gfp_t gfp,struct vm_fault * vmf,vm_fault_t * fault_type)2470 static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index,
2471 loff_t write_end, struct folio **foliop, enum sgp_type sgp,
2472 gfp_t gfp, struct vm_fault *vmf, vm_fault_t *fault_type)
2473 {
2474 struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
2475 struct mm_struct *fault_mm;
2476 struct folio *folio;
2477 int error;
2478 bool alloced;
2479 unsigned long orders = 0;
2480
2481 if (WARN_ON_ONCE(!shmem_mapping(inode->i_mapping)))
2482 return -EINVAL;
2483
2484 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
2485 return -EFBIG;
2486 repeat:
2487 if (sgp <= SGP_CACHE &&
2488 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode))
2489 return -EINVAL;
2490
2491 alloced = false;
2492 fault_mm = vma ? vma->vm_mm : NULL;
2493
2494 folio = filemap_get_entry(inode->i_mapping, index);
2495 if (folio && vma && userfaultfd_minor(vma)) {
2496 if (!xa_is_value(folio))
2497 folio_put(folio);
2498 *fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
2499 return 0;
2500 }
2501
2502 if (xa_is_value(folio)) {
2503 error = shmem_swapin_folio(inode, index, &folio,
2504 sgp, gfp, vma, fault_type);
2505 if (error == -EEXIST)
2506 goto repeat;
2507
2508 *foliop = folio;
2509 return error;
2510 }
2511
2512 if (folio) {
2513 folio_lock(folio);
2514
2515 /* Has the folio been truncated or swapped out? */
2516 if (unlikely(folio->mapping != inode->i_mapping)) {
2517 folio_unlock(folio);
2518 folio_put(folio);
2519 goto repeat;
2520 }
2521 if (sgp == SGP_WRITE)
2522 folio_mark_accessed(folio);
2523 if (folio_test_uptodate(folio))
2524 goto out;
2525 /* fallocated folio */
2526 if (sgp != SGP_READ)
2527 goto clear;
2528 folio_unlock(folio);
2529 folio_put(folio);
2530 }
2531
2532 /*
2533 * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
2534 * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
2535 */
2536 *foliop = NULL;
2537 if (sgp == SGP_READ)
2538 return 0;
2539 if (sgp == SGP_NOALLOC)
2540 return -ENOENT;
2541
2542 /*
2543 * Fast cache lookup and swap lookup did not find it: allocate.
2544 */
2545
2546 if (vma && userfaultfd_missing(vma)) {
2547 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
2548 return 0;
2549 }
2550
2551 /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */
2552 orders = shmem_allowable_huge_orders(inode, vma, index, write_end, false);
2553 if (orders > 0) {
2554 gfp_t huge_gfp;
2555
2556 huge_gfp = vma_thp_gfp_mask(vma);
2557 huge_gfp = limit_gfp_mask(huge_gfp, gfp);
2558 folio = shmem_alloc_and_add_folio(vmf, huge_gfp,
2559 inode, index, fault_mm, orders);
2560 if (!IS_ERR(folio)) {
2561 if (folio_test_pmd_mappable(folio))
2562 count_vm_event(THP_FILE_ALLOC);
2563 count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_ALLOC);
2564 goto alloced;
2565 }
2566 if (PTR_ERR(folio) == -EEXIST)
2567 goto repeat;
2568 }
2569
2570 folio = shmem_alloc_and_add_folio(vmf, gfp, inode, index, fault_mm, 0);
2571 if (IS_ERR(folio)) {
2572 error = PTR_ERR(folio);
2573 if (error == -EEXIST)
2574 goto repeat;
2575 folio = NULL;
2576 goto unlock;
2577 }
2578
2579 alloced:
2580 alloced = true;
2581 if (folio_test_large(folio) &&
2582 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
2583 folio_next_index(folio)) {
2584 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2585 struct shmem_inode_info *info = SHMEM_I(inode);
2586 /*
2587 * Part of the large folio is beyond i_size: subject
2588 * to shrink under memory pressure.
2589 */
2590 spin_lock(&sbinfo->shrinklist_lock);
2591 /*
2592 * _careful to defend against unlocked access to
2593 * ->shrink_list in shmem_unused_huge_shrink()
2594 */
2595 if (list_empty_careful(&info->shrinklist)) {
2596 list_add_tail(&info->shrinklist,
2597 &sbinfo->shrinklist);
2598 sbinfo->shrinklist_len++;
2599 }
2600 spin_unlock(&sbinfo->shrinklist_lock);
2601 }
2602
2603 if (sgp == SGP_WRITE)
2604 folio_set_referenced(folio);
2605 /*
2606 * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
2607 */
2608 if (sgp == SGP_FALLOC)
2609 sgp = SGP_WRITE;
2610 clear:
2611 /*
2612 * Let SGP_WRITE caller clear ends if write does not fill folio;
2613 * but SGP_FALLOC on a folio fallocated earlier must initialize
2614 * it now, lest undo on failure cancel our earlier guarantee.
2615 */
2616 if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) {
2617 long i, n = folio_nr_pages(folio);
2618
2619 for (i = 0; i < n; i++)
2620 clear_highpage(folio_page(folio, i));
2621 flush_dcache_folio(folio);
2622 folio_mark_uptodate(folio);
2623 }
2624
2625 /* Perhaps the file has been truncated since we checked */
2626 if (sgp <= SGP_CACHE &&
2627 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
2628 error = -EINVAL;
2629 goto unlock;
2630 }
2631 out:
2632 *foliop = folio;
2633 return 0;
2634
2635 /*
2636 * Error recovery.
2637 */
2638 unlock:
2639 if (alloced)
2640 filemap_remove_folio(folio);
2641 shmem_recalc_inode(inode, 0, 0);
2642 if (folio) {
2643 folio_unlock(folio);
2644 folio_put(folio);
2645 }
2646 return error;
2647 }
2648
2649 /**
2650 * shmem_get_folio - find, and lock a shmem folio.
2651 * @inode: inode to search
2652 * @index: the page index.
2653 * @write_end: end of a write, could extend inode size
2654 * @foliop: pointer to the folio if found
2655 * @sgp: SGP_* flags to control behavior
2656 *
2657 * Looks up the page cache entry at @inode & @index. If a folio is
2658 * present, it is returned locked with an increased refcount.
2659 *
2660 * If the caller modifies data in the folio, it must call folio_mark_dirty()
2661 * before unlocking the folio to ensure that the folio is not reclaimed.
2662 * There is no need to reserve space before calling folio_mark_dirty().
2663 *
2664 * When no folio is found, the behavior depends on @sgp:
2665 * - for SGP_READ, *@foliop is %NULL and 0 is returned
2666 * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned
2667 * - for all other flags a new folio is allocated, inserted into the
2668 * page cache and returned locked in @foliop.
2669 *
2670 * Context: May sleep.
2671 * Return: 0 if successful, else a negative error code.
2672 */
shmem_get_folio(struct inode * inode,pgoff_t index,loff_t write_end,struct folio ** foliop,enum sgp_type sgp)2673 int shmem_get_folio(struct inode *inode, pgoff_t index, loff_t write_end,
2674 struct folio **foliop, enum sgp_type sgp)
2675 {
2676 return shmem_get_folio_gfp(inode, index, write_end, foliop, sgp,
2677 mapping_gfp_mask(inode->i_mapping), NULL, NULL);
2678 }
2679 EXPORT_SYMBOL_GPL(shmem_get_folio);
2680
2681 /*
2682 * This is like autoremove_wake_function, but it removes the wait queue
2683 * entry unconditionally - even if something else had already woken the
2684 * target.
2685 */
synchronous_wake_function(wait_queue_entry_t * wait,unsigned int mode,int sync,void * key)2686 static int synchronous_wake_function(wait_queue_entry_t *wait,
2687 unsigned int mode, int sync, void *key)
2688 {
2689 int ret = default_wake_function(wait, mode, sync, key);
2690 list_del_init(&wait->entry);
2691 return ret;
2692 }
2693
2694 /*
2695 * Trinity finds that probing a hole which tmpfs is punching can
2696 * prevent the hole-punch from ever completing: which in turn
2697 * locks writers out with its hold on i_rwsem. So refrain from
2698 * faulting pages into the hole while it's being punched. Although
2699 * shmem_undo_range() does remove the additions, it may be unable to
2700 * keep up, as each new page needs its own unmap_mapping_range() call,
2701 * and the i_mmap tree grows ever slower to scan if new vmas are added.
2702 *
2703 * It does not matter if we sometimes reach this check just before the
2704 * hole-punch begins, so that one fault then races with the punch:
2705 * we just need to make racing faults a rare case.
2706 *
2707 * The implementation below would be much simpler if we just used a
2708 * standard mutex or completion: but we cannot take i_rwsem in fault,
2709 * and bloating every shmem inode for this unlikely case would be sad.
2710 */
shmem_falloc_wait(struct vm_fault * vmf,struct inode * inode)2711 static vm_fault_t shmem_falloc_wait(struct vm_fault *vmf, struct inode *inode)
2712 {
2713 struct shmem_falloc *shmem_falloc;
2714 struct file *fpin = NULL;
2715 vm_fault_t ret = 0;
2716
2717 spin_lock(&inode->i_lock);
2718 shmem_falloc = inode->i_private;
2719 if (shmem_falloc &&
2720 shmem_falloc->waitq &&
2721 vmf->pgoff >= shmem_falloc->start &&
2722 vmf->pgoff < shmem_falloc->next) {
2723 wait_queue_head_t *shmem_falloc_waitq;
2724 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
2725
2726 ret = VM_FAULT_NOPAGE;
2727 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2728 shmem_falloc_waitq = shmem_falloc->waitq;
2729 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
2730 TASK_UNINTERRUPTIBLE);
2731 spin_unlock(&inode->i_lock);
2732 schedule();
2733
2734 /*
2735 * shmem_falloc_waitq points into the shmem_fallocate()
2736 * stack of the hole-punching task: shmem_falloc_waitq
2737 * is usually invalid by the time we reach here, but
2738 * finish_wait() does not dereference it in that case;
2739 * though i_lock needed lest racing with wake_up_all().
2740 */
2741 spin_lock(&inode->i_lock);
2742 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
2743 }
2744 spin_unlock(&inode->i_lock);
2745 if (fpin) {
2746 fput(fpin);
2747 ret = VM_FAULT_RETRY;
2748 }
2749 return ret;
2750 }
2751
shmem_fault(struct vm_fault * vmf)2752 static vm_fault_t shmem_fault(struct vm_fault *vmf)
2753 {
2754 struct inode *inode = file_inode(vmf->vma->vm_file);
2755 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
2756 struct folio *folio = NULL;
2757 vm_fault_t ret = 0;
2758 int err;
2759
2760 /*
2761 * Trinity finds that probing a hole which tmpfs is punching can
2762 * prevent the hole-punch from ever completing: noted in i_private.
2763 */
2764 if (unlikely(inode->i_private)) {
2765 ret = shmem_falloc_wait(vmf, inode);
2766 if (ret)
2767 return ret;
2768 }
2769
2770 WARN_ON_ONCE(vmf->page != NULL);
2771 err = shmem_get_folio_gfp(inode, vmf->pgoff, 0, &folio, SGP_CACHE,
2772 gfp, vmf, &ret);
2773 if (err)
2774 return vmf_error(err);
2775 if (folio) {
2776 vmf->page = folio_file_page(folio, vmf->pgoff);
2777 ret |= VM_FAULT_LOCKED;
2778 }
2779 return ret;
2780 }
2781
shmem_get_unmapped_area(struct file * file,unsigned long uaddr,unsigned long len,unsigned long pgoff,unsigned long flags)2782 unsigned long shmem_get_unmapped_area(struct file *file,
2783 unsigned long uaddr, unsigned long len,
2784 unsigned long pgoff, unsigned long flags)
2785 {
2786 unsigned long addr;
2787 unsigned long offset;
2788 unsigned long inflated_len;
2789 unsigned long inflated_addr;
2790 unsigned long inflated_offset;
2791 unsigned long hpage_size;
2792
2793 if (len > TASK_SIZE)
2794 return -ENOMEM;
2795
2796 addr = mm_get_unmapped_area(file, uaddr, len, pgoff, flags);
2797
2798 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
2799 return addr;
2800 if (IS_ERR_VALUE(addr))
2801 return addr;
2802 if (addr & ~PAGE_MASK)
2803 return addr;
2804 if (addr > TASK_SIZE - len)
2805 return addr;
2806
2807 if (shmem_huge == SHMEM_HUGE_DENY)
2808 return addr;
2809 if (flags & MAP_FIXED)
2810 return addr;
2811 /*
2812 * Our priority is to support MAP_SHARED mapped hugely;
2813 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2814 * But if caller specified an address hint and we allocated area there
2815 * successfully, respect that as before.
2816 */
2817 if (uaddr == addr)
2818 return addr;
2819
2820 hpage_size = HPAGE_PMD_SIZE;
2821 if (shmem_huge != SHMEM_HUGE_FORCE) {
2822 struct super_block *sb;
2823 unsigned long __maybe_unused hpage_orders;
2824 int order = 0;
2825
2826 if (file) {
2827 VM_BUG_ON(file->f_op != &shmem_file_operations);
2828 sb = file_inode(file)->i_sb;
2829 } else {
2830 /*
2831 * Called directly from mm/mmap.c, or drivers/char/mem.c
2832 * for "/dev/zero", to create a shared anonymous object.
2833 */
2834 if (IS_ERR(shm_mnt))
2835 return addr;
2836 sb = shm_mnt->mnt_sb;
2837
2838 /*
2839 * Find the highest mTHP order used for anonymous shmem to
2840 * provide a suitable alignment address.
2841 */
2842 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2843 hpage_orders = READ_ONCE(huge_shmem_orders_always);
2844 hpage_orders |= READ_ONCE(huge_shmem_orders_within_size);
2845 hpage_orders |= READ_ONCE(huge_shmem_orders_madvise);
2846 if (SHMEM_SB(sb)->huge != SHMEM_HUGE_NEVER)
2847 hpage_orders |= READ_ONCE(huge_shmem_orders_inherit);
2848
2849 if (hpage_orders > 0) {
2850 order = highest_order(hpage_orders);
2851 hpage_size = PAGE_SIZE << order;
2852 }
2853 #endif
2854 }
2855 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER && !order)
2856 return addr;
2857 }
2858
2859 if (len < hpage_size)
2860 return addr;
2861
2862 offset = (pgoff << PAGE_SHIFT) & (hpage_size - 1);
2863 if (offset && offset + len < 2 * hpage_size)
2864 return addr;
2865 if ((addr & (hpage_size - 1)) == offset)
2866 return addr;
2867
2868 inflated_len = len + hpage_size - PAGE_SIZE;
2869 if (inflated_len > TASK_SIZE)
2870 return addr;
2871 if (inflated_len < len)
2872 return addr;
2873
2874 inflated_addr = mm_get_unmapped_area(NULL, uaddr, inflated_len, 0, flags);
2875 if (IS_ERR_VALUE(inflated_addr))
2876 return addr;
2877 if (inflated_addr & ~PAGE_MASK)
2878 return addr;
2879
2880 inflated_offset = inflated_addr & (hpage_size - 1);
2881 inflated_addr += offset - inflated_offset;
2882 if (inflated_offset > offset)
2883 inflated_addr += hpage_size;
2884
2885 if (inflated_addr > TASK_SIZE - len)
2886 return addr;
2887 return inflated_addr;
2888 }
2889
2890 #ifdef CONFIG_NUMA
shmem_set_policy(struct vm_area_struct * vma,struct mempolicy * mpol)2891 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2892 {
2893 struct inode *inode = file_inode(vma->vm_file);
2894 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2895 }
2896
shmem_get_policy(struct vm_area_struct * vma,unsigned long addr,pgoff_t * ilx)2897 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2898 unsigned long addr, pgoff_t *ilx)
2899 {
2900 struct inode *inode = file_inode(vma->vm_file);
2901 pgoff_t index;
2902
2903 /*
2904 * Bias interleave by inode number to distribute better across nodes;
2905 * but this interface is independent of which page order is used, so
2906 * supplies only that bias, letting caller apply the offset (adjusted
2907 * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()).
2908 */
2909 *ilx = inode->i_ino;
2910 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2911 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2912 }
2913
shmem_get_pgoff_policy(struct shmem_inode_info * info,pgoff_t index,unsigned int order,pgoff_t * ilx)2914 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
2915 pgoff_t index, unsigned int order, pgoff_t *ilx)
2916 {
2917 struct mempolicy *mpol;
2918
2919 /* Bias interleave by inode number to distribute better across nodes */
2920 *ilx = info->vfs_inode.i_ino + (index >> order);
2921
2922 mpol = mpol_shared_policy_lookup(&info->policy, index);
2923 return mpol ? mpol : get_task_policy(current);
2924 }
2925 #else
shmem_get_pgoff_policy(struct shmem_inode_info * info,pgoff_t index,unsigned int order,pgoff_t * ilx)2926 static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
2927 pgoff_t index, unsigned int order, pgoff_t *ilx)
2928 {
2929 *ilx = 0;
2930 return NULL;
2931 }
2932 #endif /* CONFIG_NUMA */
2933
shmem_lock(struct file * file,int lock,struct ucounts * ucounts)2934 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
2935 {
2936 struct inode *inode = file_inode(file);
2937 struct shmem_inode_info *info = SHMEM_I(inode);
2938 int retval = -ENOMEM;
2939
2940 /*
2941 * What serializes the accesses to info->flags?
2942 * ipc_lock_object() when called from shmctl_do_lock(),
2943 * no serialization needed when called from shm_destroy().
2944 */
2945 if (lock && !(info->flags & SHMEM_F_LOCKED)) {
2946 if (!user_shm_lock(inode->i_size, ucounts))
2947 goto out_nomem;
2948 info->flags |= SHMEM_F_LOCKED;
2949 mapping_set_unevictable(file->f_mapping);
2950 }
2951 if (!lock && (info->flags & SHMEM_F_LOCKED) && ucounts) {
2952 user_shm_unlock(inode->i_size, ucounts);
2953 info->flags &= ~SHMEM_F_LOCKED;
2954 mapping_clear_unevictable(file->f_mapping);
2955 }
2956 retval = 0;
2957
2958 out_nomem:
2959 return retval;
2960 }
2961
shmem_mmap_prepare(struct vm_area_desc * desc)2962 static int shmem_mmap_prepare(struct vm_area_desc *desc)
2963 {
2964 struct file *file = desc->file;
2965 struct inode *inode = file_inode(file);
2966
2967 file_accessed(file);
2968 /* This is anonymous shared memory if it is unlinked at the time of mmap */
2969 if (inode->i_nlink)
2970 desc->vm_ops = &shmem_vm_ops;
2971 else
2972 desc->vm_ops = &shmem_anon_vm_ops;
2973 return 0;
2974 }
2975
shmem_file_open(struct inode * inode,struct file * file)2976 static int shmem_file_open(struct inode *inode, struct file *file)
2977 {
2978 file->f_mode |= FMODE_CAN_ODIRECT;
2979 return generic_file_open(inode, file);
2980 }
2981
2982 #ifdef CONFIG_TMPFS_XATTR
2983 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2984
2985 #if IS_ENABLED(CONFIG_UNICODE)
2986 /*
2987 * shmem_inode_casefold_flags - Deal with casefold file attribute flag
2988 *
2989 * The casefold file attribute needs some special checks. I can just be added to
2990 * an empty dir, and can't be removed from a non-empty dir.
2991 */
shmem_inode_casefold_flags(struct inode * inode,unsigned int fsflags,struct dentry * dentry,unsigned int * i_flags)2992 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags,
2993 struct dentry *dentry, unsigned int *i_flags)
2994 {
2995 unsigned int old = inode->i_flags;
2996 struct super_block *sb = inode->i_sb;
2997
2998 if (fsflags & FS_CASEFOLD_FL) {
2999 if (!(old & S_CASEFOLD)) {
3000 if (!sb->s_encoding)
3001 return -EOPNOTSUPP;
3002
3003 if (!S_ISDIR(inode->i_mode))
3004 return -ENOTDIR;
3005
3006 if (dentry && !simple_empty(dentry))
3007 return -ENOTEMPTY;
3008 }
3009
3010 *i_flags = *i_flags | S_CASEFOLD;
3011 } else if (old & S_CASEFOLD) {
3012 if (dentry && !simple_empty(dentry))
3013 return -ENOTEMPTY;
3014 }
3015
3016 return 0;
3017 }
3018 #else
shmem_inode_casefold_flags(struct inode * inode,unsigned int fsflags,struct dentry * dentry,unsigned int * i_flags)3019 static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags,
3020 struct dentry *dentry, unsigned int *i_flags)
3021 {
3022 if (fsflags & FS_CASEFOLD_FL)
3023 return -EOPNOTSUPP;
3024
3025 return 0;
3026 }
3027 #endif
3028
3029 /*
3030 * chattr's fsflags are unrelated to extended attributes,
3031 * but tmpfs has chosen to enable them under the same config option.
3032 */
shmem_set_inode_flags(struct inode * inode,unsigned int fsflags,struct dentry * dentry)3033 static int shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry)
3034 {
3035 unsigned int i_flags = 0;
3036 int ret;
3037
3038 ret = shmem_inode_casefold_flags(inode, fsflags, dentry, &i_flags);
3039 if (ret)
3040 return ret;
3041
3042 if (fsflags & FS_NOATIME_FL)
3043 i_flags |= S_NOATIME;
3044 if (fsflags & FS_APPEND_FL)
3045 i_flags |= S_APPEND;
3046 if (fsflags & FS_IMMUTABLE_FL)
3047 i_flags |= S_IMMUTABLE;
3048 /*
3049 * But FS_NODUMP_FL does not require any action in i_flags.
3050 */
3051 inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE | S_CASEFOLD);
3052
3053 return 0;
3054 }
3055 #else
shmem_set_inode_flags(struct inode * inode,unsigned int fsflags,struct dentry * dentry)3056 static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry)
3057 {
3058 }
3059 #define shmem_initxattrs NULL
3060 #endif
3061
shmem_get_offset_ctx(struct inode * inode)3062 static struct offset_ctx *shmem_get_offset_ctx(struct inode *inode)
3063 {
3064 return &SHMEM_I(inode)->dir_offsets;
3065 }
3066
__shmem_get_inode(struct mnt_idmap * idmap,struct super_block * sb,struct inode * dir,umode_t mode,dev_t dev,vma_flags_t flags)3067 static struct inode *__shmem_get_inode(struct mnt_idmap *idmap,
3068 struct super_block *sb,
3069 struct inode *dir, umode_t mode,
3070 dev_t dev, vma_flags_t flags)
3071 {
3072 struct inode *inode;
3073 struct shmem_inode_info *info;
3074 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3075 ino_t ino;
3076 int err;
3077
3078 err = shmem_reserve_inode(sb, &ino);
3079 if (err)
3080 return ERR_PTR(err);
3081
3082 inode = new_inode(sb);
3083 if (!inode) {
3084 shmem_free_inode(sb, 0);
3085 return ERR_PTR(-ENOSPC);
3086 }
3087
3088 inode->i_ino = ino;
3089 inode_init_owner(idmap, inode, dir, mode);
3090 inode->i_blocks = 0;
3091 simple_inode_init_ts(inode);
3092 inode->i_generation = get_random_u32();
3093 info = SHMEM_I(inode);
3094 memset(info, 0, (char *)inode - (char *)info);
3095 spin_lock_init(&info->lock);
3096 atomic_set(&info->stop_eviction, 0);
3097 info->seals = F_SEAL_SEAL;
3098 info->flags = vma_flags_test(&flags, VMA_NORESERVE_BIT)
3099 ? SHMEM_F_NORESERVE : 0;
3100 info->i_crtime = inode_get_mtime(inode);
3101 info->fsflags = (dir == NULL) ? 0 :
3102 SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED;
3103 if (info->fsflags)
3104 shmem_set_inode_flags(inode, info->fsflags, NULL);
3105 INIT_LIST_HEAD(&info->shrinklist);
3106 INIT_LIST_HEAD(&info->swaplist);
3107 cache_no_acl(inode);
3108 if (sbinfo->noswap)
3109 mapping_set_unevictable(inode->i_mapping);
3110
3111 /* Don't consider 'deny' for emergencies and 'force' for testing */
3112 if (sbinfo->huge)
3113 mapping_set_large_folios(inode->i_mapping);
3114
3115 switch (mode & S_IFMT) {
3116 default:
3117 inode->i_op = &shmem_special_inode_operations;
3118 init_special_inode(inode, mode, dev);
3119 break;
3120 case S_IFREG:
3121 inode->i_mapping->a_ops = &shmem_aops;
3122 inode->i_op = &shmem_inode_operations;
3123 inode->i_fop = &shmem_file_operations;
3124 mpol_shared_policy_init(&info->policy,
3125 shmem_get_sbmpol(sbinfo));
3126 break;
3127 case S_IFDIR:
3128 inc_nlink(inode);
3129 /* Some things misbehave if size == 0 on a directory */
3130 inode->i_size = 2 * BOGO_DIRENT_SIZE;
3131 inode->i_op = &shmem_dir_inode_operations;
3132 inode->i_fop = &simple_offset_dir_operations;
3133 simple_offset_init(shmem_get_offset_ctx(inode));
3134 break;
3135 case S_IFLNK:
3136 /*
3137 * Must not load anything in the rbtree,
3138 * mpol_free_shared_policy will not be called.
3139 */
3140 mpol_shared_policy_init(&info->policy, NULL);
3141 break;
3142 }
3143
3144 lockdep_annotate_inode_mutex_key(inode);
3145 return inode;
3146 }
3147
3148 #ifdef CONFIG_TMPFS_QUOTA
shmem_get_inode(struct mnt_idmap * idmap,struct super_block * sb,struct inode * dir,umode_t mode,dev_t dev,vma_flags_t flags)3149 static struct inode *shmem_get_inode(struct mnt_idmap *idmap,
3150 struct super_block *sb, struct inode *dir,
3151 umode_t mode, dev_t dev, vma_flags_t flags)
3152 {
3153 int err;
3154 struct inode *inode;
3155
3156 inode = __shmem_get_inode(idmap, sb, dir, mode, dev, flags);
3157 if (IS_ERR(inode))
3158 return inode;
3159
3160 err = dquot_initialize(inode);
3161 if (err)
3162 goto errout;
3163
3164 err = dquot_alloc_inode(inode);
3165 if (err) {
3166 dquot_drop(inode);
3167 goto errout;
3168 }
3169 return inode;
3170
3171 errout:
3172 inode->i_flags |= S_NOQUOTA;
3173 iput(inode);
3174 return ERR_PTR(err);
3175 }
3176 #else
shmem_get_inode(struct mnt_idmap * idmap,struct super_block * sb,struct inode * dir,umode_t mode,dev_t dev,vma_flags_t flags)3177 static struct inode *shmem_get_inode(struct mnt_idmap *idmap,
3178 struct super_block *sb, struct inode *dir,
3179 umode_t mode, dev_t dev, vma_flags_t flags)
3180 {
3181 return __shmem_get_inode(idmap, sb, dir, mode, dev, flags);
3182 }
3183 #endif /* CONFIG_TMPFS_QUOTA */
3184
3185 #ifdef CONFIG_USERFAULTFD
shmem_mfill_atomic_pte(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,uffd_flags_t flags,struct folio ** foliop)3186 int shmem_mfill_atomic_pte(pmd_t *dst_pmd,
3187 struct vm_area_struct *dst_vma,
3188 unsigned long dst_addr,
3189 unsigned long src_addr,
3190 uffd_flags_t flags,
3191 struct folio **foliop)
3192 {
3193 struct inode *inode = file_inode(dst_vma->vm_file);
3194 struct shmem_inode_info *info = SHMEM_I(inode);
3195 struct address_space *mapping = inode->i_mapping;
3196 gfp_t gfp = mapping_gfp_mask(mapping);
3197 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
3198 void *page_kaddr;
3199 struct folio *folio;
3200 int ret;
3201 pgoff_t max_off;
3202
3203 if (shmem_inode_acct_blocks(inode, 1)) {
3204 /*
3205 * We may have got a page, returned -ENOENT triggering a retry,
3206 * and now we find ourselves with -ENOMEM. Release the page, to
3207 * avoid a BUG_ON in our caller.
3208 */
3209 if (unlikely(*foliop)) {
3210 folio_put(*foliop);
3211 *foliop = NULL;
3212 }
3213 return -ENOMEM;
3214 }
3215
3216 if (!*foliop) {
3217 ret = -ENOMEM;
3218 folio = shmem_alloc_folio(gfp, 0, info, pgoff);
3219 if (!folio)
3220 goto out_unacct_blocks;
3221
3222 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY)) {
3223 page_kaddr = kmap_local_folio(folio, 0);
3224 /*
3225 * The read mmap_lock is held here. Despite the
3226 * mmap_lock being read recursive a deadlock is still
3227 * possible if a writer has taken a lock. For example:
3228 *
3229 * process A thread 1 takes read lock on own mmap_lock
3230 * process A thread 2 calls mmap, blocks taking write lock
3231 * process B thread 1 takes page fault, read lock on own mmap lock
3232 * process B thread 2 calls mmap, blocks taking write lock
3233 * process A thread 1 blocks taking read lock on process B
3234 * process B thread 1 blocks taking read lock on process A
3235 *
3236 * Disable page faults to prevent potential deadlock
3237 * and retry the copy outside the mmap_lock.
3238 */
3239 pagefault_disable();
3240 ret = copy_from_user(page_kaddr,
3241 (const void __user *)src_addr,
3242 PAGE_SIZE);
3243 pagefault_enable();
3244 kunmap_local(page_kaddr);
3245
3246 /* fallback to copy_from_user outside mmap_lock */
3247 if (unlikely(ret)) {
3248 *foliop = folio;
3249 ret = -ENOENT;
3250 /* don't free the page */
3251 goto out_unacct_blocks;
3252 }
3253
3254 flush_dcache_folio(folio);
3255 } else { /* ZEROPAGE */
3256 clear_user_highpage(&folio->page, dst_addr);
3257 }
3258 } else {
3259 folio = *foliop;
3260 VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
3261 *foliop = NULL;
3262 }
3263
3264 VM_BUG_ON(folio_test_locked(folio));
3265 VM_BUG_ON(folio_test_swapbacked(folio));
3266 __folio_set_locked(folio);
3267 __folio_set_swapbacked(folio);
3268 __folio_mark_uptodate(folio);
3269
3270 ret = -EFAULT;
3271 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3272 if (unlikely(pgoff >= max_off))
3273 goto out_release;
3274
3275 ret = mem_cgroup_charge(folio, dst_vma->vm_mm, gfp);
3276 if (ret)
3277 goto out_release;
3278 ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL, gfp);
3279 if (ret)
3280 goto out_release;
3281
3282 ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
3283 &folio->page, true, flags);
3284 if (ret)
3285 goto out_delete_from_cache;
3286
3287 shmem_recalc_inode(inode, 1, 0);
3288 folio_unlock(folio);
3289 return 0;
3290 out_delete_from_cache:
3291 filemap_remove_folio(folio);
3292 out_release:
3293 folio_unlock(folio);
3294 folio_put(folio);
3295 out_unacct_blocks:
3296 shmem_inode_unacct_blocks(inode, 1);
3297 return ret;
3298 }
3299 #endif /* CONFIG_USERFAULTFD */
3300
3301 #ifdef CONFIG_TMPFS
3302 static const struct inode_operations shmem_symlink_inode_operations;
3303 static const struct inode_operations shmem_short_symlink_operations;
3304
3305 static int
shmem_write_begin(const struct kiocb * iocb,struct address_space * mapping,loff_t pos,unsigned len,struct folio ** foliop,void ** fsdata)3306 shmem_write_begin(const struct kiocb *iocb, struct address_space *mapping,
3307 loff_t pos, unsigned len,
3308 struct folio **foliop, void **fsdata)
3309 {
3310 struct inode *inode = mapping->host;
3311 struct shmem_inode_info *info = SHMEM_I(inode);
3312 pgoff_t index = pos >> PAGE_SHIFT;
3313 struct folio *folio;
3314 int ret = 0;
3315
3316 /* i_rwsem is held by caller */
3317 if (unlikely(info->seals & (F_SEAL_GROW |
3318 F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
3319 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
3320 return -EPERM;
3321 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
3322 return -EPERM;
3323 }
3324
3325 if (unlikely((info->flags & SHMEM_F_MAPPING_FROZEN) &&
3326 pos + len > inode->i_size))
3327 return -EPERM;
3328
3329 ret = shmem_get_folio(inode, index, pos + len, &folio, SGP_WRITE);
3330 if (ret)
3331 return ret;
3332
3333 if (folio_contain_hwpoisoned_page(folio)) {
3334 folio_unlock(folio);
3335 folio_put(folio);
3336 return -EIO;
3337 }
3338
3339 *foliop = folio;
3340 return 0;
3341 }
3342
3343 static int
shmem_write_end(const struct kiocb * iocb,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct folio * folio,void * fsdata)3344 shmem_write_end(const struct kiocb *iocb, struct address_space *mapping,
3345 loff_t pos, unsigned len, unsigned copied,
3346 struct folio *folio, void *fsdata)
3347 {
3348 struct inode *inode = mapping->host;
3349
3350 if (pos + copied > inode->i_size)
3351 i_size_write(inode, pos + copied);
3352
3353 if (!folio_test_uptodate(folio)) {
3354 if (copied < folio_size(folio)) {
3355 size_t from = offset_in_folio(folio, pos);
3356 folio_zero_segments(folio, 0, from,
3357 from + copied, folio_size(folio));
3358 }
3359 folio_mark_uptodate(folio);
3360 }
3361 folio_mark_dirty(folio);
3362 folio_unlock(folio);
3363 folio_put(folio);
3364
3365 return copied;
3366 }
3367
shmem_file_read_iter(struct kiocb * iocb,struct iov_iter * to)3368 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
3369 {
3370 struct file *file = iocb->ki_filp;
3371 struct inode *inode = file_inode(file);
3372 struct address_space *mapping = inode->i_mapping;
3373 pgoff_t index;
3374 unsigned long offset;
3375 int error = 0;
3376 ssize_t retval = 0;
3377
3378 for (;;) {
3379 struct folio *folio = NULL;
3380 struct page *page = NULL;
3381 unsigned long nr, ret;
3382 loff_t end_offset, i_size = i_size_read(inode);
3383 bool fallback_page_copy = false;
3384 size_t fsize;
3385
3386 if (unlikely(iocb->ki_pos >= i_size))
3387 break;
3388
3389 index = iocb->ki_pos >> PAGE_SHIFT;
3390 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ);
3391 if (error) {
3392 if (error == -EINVAL)
3393 error = 0;
3394 break;
3395 }
3396 if (folio) {
3397 folio_unlock(folio);
3398
3399 page = folio_file_page(folio, index);
3400 if (PageHWPoison(page)) {
3401 folio_put(folio);
3402 error = -EIO;
3403 break;
3404 }
3405
3406 if (folio_test_large(folio) &&
3407 folio_test_has_hwpoisoned(folio))
3408 fallback_page_copy = true;
3409 }
3410
3411 /*
3412 * We must evaluate after, since reads (unlike writes)
3413 * are called without i_rwsem protection against truncate
3414 */
3415 i_size = i_size_read(inode);
3416 if (unlikely(iocb->ki_pos >= i_size)) {
3417 if (folio)
3418 folio_put(folio);
3419 break;
3420 }
3421 end_offset = min_t(loff_t, i_size, iocb->ki_pos + to->count);
3422 if (folio && likely(!fallback_page_copy))
3423 fsize = folio_size(folio);
3424 else
3425 fsize = PAGE_SIZE;
3426 offset = iocb->ki_pos & (fsize - 1);
3427 nr = min_t(loff_t, end_offset - iocb->ki_pos, fsize - offset);
3428
3429 if (folio) {
3430 /*
3431 * If users can be writing to this page using arbitrary
3432 * virtual addresses, take care about potential aliasing
3433 * before reading the page on the kernel side.
3434 */
3435 if (mapping_writably_mapped(mapping)) {
3436 if (likely(!fallback_page_copy))
3437 flush_dcache_folio(folio);
3438 else
3439 flush_dcache_page(page);
3440 }
3441
3442 /*
3443 * Mark the folio accessed if we read the beginning.
3444 */
3445 if (!offset)
3446 folio_mark_accessed(folio);
3447 /*
3448 * Ok, we have the page, and it's up-to-date, so
3449 * now we can copy it to user space...
3450 */
3451 if (likely(!fallback_page_copy))
3452 ret = copy_folio_to_iter(folio, offset, nr, to);
3453 else
3454 ret = copy_page_to_iter(page, offset, nr, to);
3455 folio_put(folio);
3456 } else if (user_backed_iter(to)) {
3457 /*
3458 * Copy to user tends to be so well optimized, but
3459 * clear_user() not so much, that it is noticeably
3460 * faster to copy the zero page instead of clearing.
3461 */
3462 ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to);
3463 } else {
3464 /*
3465 * But submitting the same page twice in a row to
3466 * splice() - or others? - can result in confusion:
3467 * so don't attempt that optimization on pipes etc.
3468 */
3469 ret = iov_iter_zero(nr, to);
3470 }
3471
3472 retval += ret;
3473 iocb->ki_pos += ret;
3474
3475 if (!iov_iter_count(to))
3476 break;
3477 if (ret < nr) {
3478 error = -EFAULT;
3479 break;
3480 }
3481 cond_resched();
3482 }
3483
3484 file_accessed(file);
3485 return retval ? retval : error;
3486 }
3487
shmem_file_write_iter(struct kiocb * iocb,struct iov_iter * from)3488 static ssize_t shmem_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3489 {
3490 struct file *file = iocb->ki_filp;
3491 struct inode *inode = file->f_mapping->host;
3492 ssize_t ret;
3493
3494 inode_lock(inode);
3495 ret = generic_write_checks(iocb, from);
3496 if (ret <= 0)
3497 goto unlock;
3498 ret = file_remove_privs(file);
3499 if (ret)
3500 goto unlock;
3501 ret = file_update_time(file);
3502 if (ret)
3503 goto unlock;
3504 ret = generic_perform_write(iocb, from);
3505 unlock:
3506 inode_unlock(inode);
3507 return ret;
3508 }
3509
zero_pipe_buf_get(struct pipe_inode_info * pipe,struct pipe_buffer * buf)3510 static bool zero_pipe_buf_get(struct pipe_inode_info *pipe,
3511 struct pipe_buffer *buf)
3512 {
3513 return true;
3514 }
3515
zero_pipe_buf_release(struct pipe_inode_info * pipe,struct pipe_buffer * buf)3516 static void zero_pipe_buf_release(struct pipe_inode_info *pipe,
3517 struct pipe_buffer *buf)
3518 {
3519 }
3520
zero_pipe_buf_try_steal(struct pipe_inode_info * pipe,struct pipe_buffer * buf)3521 static bool zero_pipe_buf_try_steal(struct pipe_inode_info *pipe,
3522 struct pipe_buffer *buf)
3523 {
3524 return false;
3525 }
3526
3527 static const struct pipe_buf_operations zero_pipe_buf_ops = {
3528 .release = zero_pipe_buf_release,
3529 .try_steal = zero_pipe_buf_try_steal,
3530 .get = zero_pipe_buf_get,
3531 };
3532
splice_zeropage_into_pipe(struct pipe_inode_info * pipe,loff_t fpos,size_t size)3533 static size_t splice_zeropage_into_pipe(struct pipe_inode_info *pipe,
3534 loff_t fpos, size_t size)
3535 {
3536 size_t offset = fpos & ~PAGE_MASK;
3537
3538 size = min_t(size_t, size, PAGE_SIZE - offset);
3539
3540 if (!pipe_is_full(pipe)) {
3541 struct pipe_buffer *buf = pipe_head_buf(pipe);
3542
3543 *buf = (struct pipe_buffer) {
3544 .ops = &zero_pipe_buf_ops,
3545 .page = ZERO_PAGE(0),
3546 .offset = offset,
3547 .len = size,
3548 };
3549 pipe->head++;
3550 }
3551
3552 return size;
3553 }
3554
shmem_file_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)3555 static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
3556 struct pipe_inode_info *pipe,
3557 size_t len, unsigned int flags)
3558 {
3559 struct inode *inode = file_inode(in);
3560 struct address_space *mapping = inode->i_mapping;
3561 struct folio *folio = NULL;
3562 size_t total_spliced = 0, used, npages, n, part;
3563 loff_t isize;
3564 int error = 0;
3565
3566 /* Work out how much data we can actually add into the pipe */
3567 used = pipe_buf_usage(pipe);
3568 npages = max_t(ssize_t, pipe->max_usage - used, 0);
3569 len = min_t(size_t, len, npages * PAGE_SIZE);
3570
3571 do {
3572 bool fallback_page_splice = false;
3573 struct page *page = NULL;
3574 pgoff_t index;
3575 size_t size;
3576
3577 if (*ppos >= i_size_read(inode))
3578 break;
3579
3580 index = *ppos >> PAGE_SHIFT;
3581 error = shmem_get_folio(inode, index, 0, &folio, SGP_READ);
3582 if (error) {
3583 if (error == -EINVAL)
3584 error = 0;
3585 break;
3586 }
3587 if (folio) {
3588 folio_unlock(folio);
3589
3590 page = folio_file_page(folio, index);
3591 if (PageHWPoison(page)) {
3592 error = -EIO;
3593 break;
3594 }
3595
3596 if (folio_test_large(folio) &&
3597 folio_test_has_hwpoisoned(folio))
3598 fallback_page_splice = true;
3599 }
3600
3601 /*
3602 * i_size must be checked after we know the pages are Uptodate.
3603 *
3604 * Checking i_size after the check allows us to calculate
3605 * the correct value for "nr", which means the zero-filled
3606 * part of the page is not copied back to userspace (unless
3607 * another truncate extends the file - this is desired though).
3608 */
3609 isize = i_size_read(inode);
3610 if (unlikely(*ppos >= isize))
3611 break;
3612 /*
3613 * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned
3614 * pages.
3615 */
3616 size = len;
3617 if (unlikely(fallback_page_splice)) {
3618 size_t offset = *ppos & ~PAGE_MASK;
3619
3620 size = umin(size, PAGE_SIZE - offset);
3621 }
3622 part = min_t(loff_t, isize - *ppos, size);
3623
3624 if (folio) {
3625 /*
3626 * If users can be writing to this page using arbitrary
3627 * virtual addresses, take care about potential aliasing
3628 * before reading the page on the kernel side.
3629 */
3630 if (mapping_writably_mapped(mapping)) {
3631 if (likely(!fallback_page_splice))
3632 flush_dcache_folio(folio);
3633 else
3634 flush_dcache_page(page);
3635 }
3636 folio_mark_accessed(folio);
3637 /*
3638 * Ok, we have the page, and it's up-to-date, so we can
3639 * now splice it into the pipe.
3640 */
3641 n = splice_folio_into_pipe(pipe, folio, *ppos, part);
3642 folio_put(folio);
3643 folio = NULL;
3644 } else {
3645 n = splice_zeropage_into_pipe(pipe, *ppos, part);
3646 }
3647
3648 if (!n)
3649 break;
3650 len -= n;
3651 total_spliced += n;
3652 *ppos += n;
3653 in->f_ra.prev_pos = *ppos;
3654 if (pipe_is_full(pipe))
3655 break;
3656
3657 cond_resched();
3658 } while (len);
3659
3660 if (folio)
3661 folio_put(folio);
3662
3663 file_accessed(in);
3664 return total_spliced ? total_spliced : error;
3665 }
3666
shmem_file_llseek(struct file * file,loff_t offset,int whence)3667 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
3668 {
3669 struct address_space *mapping = file->f_mapping;
3670 struct inode *inode = mapping->host;
3671
3672 if (whence != SEEK_DATA && whence != SEEK_HOLE)
3673 return generic_file_llseek_size(file, offset, whence,
3674 MAX_LFS_FILESIZE, i_size_read(inode));
3675 if (offset < 0)
3676 return -ENXIO;
3677
3678 inode_lock(inode);
3679 /* We're holding i_rwsem so we can access i_size directly */
3680 offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
3681 if (offset >= 0)
3682 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
3683 inode_unlock(inode);
3684 return offset;
3685 }
3686
shmem_fallocate(struct file * file,int mode,loff_t offset,loff_t len)3687 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
3688 loff_t len)
3689 {
3690 struct inode *inode = file_inode(file);
3691 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3692 struct shmem_inode_info *info = SHMEM_I(inode);
3693 struct shmem_falloc shmem_falloc;
3694 pgoff_t start, index, end, undo_fallocend;
3695 int error;
3696
3697 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
3698 return -EOPNOTSUPP;
3699
3700 inode_lock(inode);
3701
3702 if (info->flags & SHMEM_F_MAPPING_FROZEN) {
3703 error = -EPERM;
3704 goto out;
3705 }
3706
3707 if (mode & FALLOC_FL_PUNCH_HOLE) {
3708 struct address_space *mapping = file->f_mapping;
3709 loff_t unmap_start = round_up(offset, PAGE_SIZE);
3710 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
3711 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
3712
3713 /* protected by i_rwsem */
3714 if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
3715 error = -EPERM;
3716 goto out;
3717 }
3718
3719 shmem_falloc.waitq = &shmem_falloc_waitq;
3720 shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
3721 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
3722 spin_lock(&inode->i_lock);
3723 inode->i_private = &shmem_falloc;
3724 spin_unlock(&inode->i_lock);
3725
3726 if ((u64)unmap_end > (u64)unmap_start)
3727 unmap_mapping_range(mapping, unmap_start,
3728 1 + unmap_end - unmap_start, 0);
3729 shmem_truncate_range(inode, offset, offset + len - 1);
3730 /* No need to unmap again: hole-punching leaves COWed pages */
3731
3732 spin_lock(&inode->i_lock);
3733 inode->i_private = NULL;
3734 wake_up_all(&shmem_falloc_waitq);
3735 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
3736 spin_unlock(&inode->i_lock);
3737 error = 0;
3738 goto out;
3739 }
3740
3741 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
3742 error = inode_newsize_ok(inode, offset + len);
3743 if (error)
3744 goto out;
3745
3746 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
3747 error = -EPERM;
3748 goto out;
3749 }
3750
3751 start = offset >> PAGE_SHIFT;
3752 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3753 /* Try to avoid a swapstorm if len is impossible to satisfy */
3754 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
3755 error = -ENOSPC;
3756 goto out;
3757 }
3758
3759 shmem_falloc.waitq = NULL;
3760 shmem_falloc.start = start;
3761 shmem_falloc.next = start;
3762 shmem_falloc.nr_falloced = 0;
3763 shmem_falloc.nr_unswapped = 0;
3764 spin_lock(&inode->i_lock);
3765 inode->i_private = &shmem_falloc;
3766 spin_unlock(&inode->i_lock);
3767
3768 /*
3769 * info->fallocend is only relevant when huge pages might be
3770 * involved: to prevent split_huge_page() freeing fallocated
3771 * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
3772 */
3773 undo_fallocend = info->fallocend;
3774 if (info->fallocend < end)
3775 info->fallocend = end;
3776
3777 for (index = start; index < end; ) {
3778 struct folio *folio;
3779
3780 /*
3781 * Check for fatal signal so that we abort early in OOM
3782 * situations. We don't want to abort in case of non-fatal
3783 * signals as large fallocate can take noticeable time and
3784 * e.g. periodic timers may result in fallocate constantly
3785 * restarting.
3786 */
3787 if (fatal_signal_pending(current))
3788 error = -EINTR;
3789 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
3790 error = -ENOMEM;
3791 else
3792 error = shmem_get_folio(inode, index, offset + len,
3793 &folio, SGP_FALLOC);
3794 if (error) {
3795 info->fallocend = undo_fallocend;
3796 /* Remove the !uptodate folios we added */
3797 if (index > start) {
3798 shmem_undo_range(inode,
3799 (loff_t)start << PAGE_SHIFT,
3800 ((loff_t)index << PAGE_SHIFT) - 1, true);
3801 }
3802 goto undone;
3803 }
3804
3805 /*
3806 * Here is a more important optimization than it appears:
3807 * a second SGP_FALLOC on the same large folio will clear it,
3808 * making it uptodate and un-undoable if we fail later.
3809 */
3810 index = folio_next_index(folio);
3811 /* Beware 32-bit wraparound */
3812 if (!index)
3813 index--;
3814
3815 /*
3816 * Inform shmem_writeout() how far we have reached.
3817 * No need for lock or barrier: we have the page lock.
3818 */
3819 if (!folio_test_uptodate(folio))
3820 shmem_falloc.nr_falloced += index - shmem_falloc.next;
3821 shmem_falloc.next = index;
3822
3823 /*
3824 * If !uptodate, leave it that way so that freeable folios
3825 * can be recognized if we need to rollback on error later.
3826 * But mark it dirty so that memory pressure will swap rather
3827 * than free the folios we are allocating (and SGP_CACHE folios
3828 * might still be clean: we now need to mark those dirty too).
3829 */
3830 folio_mark_dirty(folio);
3831 folio_unlock(folio);
3832 folio_put(folio);
3833 cond_resched();
3834 }
3835
3836 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
3837 i_size_write(inode, offset + len);
3838 undone:
3839 spin_lock(&inode->i_lock);
3840 inode->i_private = NULL;
3841 spin_unlock(&inode->i_lock);
3842 out:
3843 if (!error)
3844 file_modified(file);
3845 inode_unlock(inode);
3846 return error;
3847 }
3848
shmem_statfs(struct dentry * dentry,struct kstatfs * buf)3849 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
3850 {
3851 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
3852
3853 buf->f_type = TMPFS_MAGIC;
3854 buf->f_bsize = PAGE_SIZE;
3855 buf->f_namelen = NAME_MAX;
3856 if (sbinfo->max_blocks) {
3857 buf->f_blocks = sbinfo->max_blocks;
3858 buf->f_bavail =
3859 buf->f_bfree = sbinfo->max_blocks -
3860 percpu_counter_sum(&sbinfo->used_blocks);
3861 }
3862 if (sbinfo->max_inodes) {
3863 buf->f_files = sbinfo->max_inodes;
3864 buf->f_ffree = sbinfo->free_ispace / BOGO_INODE_SIZE;
3865 }
3866 /* else leave those fields 0 like simple_statfs */
3867
3868 buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
3869
3870 return 0;
3871 }
3872
3873 /*
3874 * File creation. Allocate an inode, and we're done..
3875 */
3876 static int
shmem_mknod(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3877 shmem_mknod(struct mnt_idmap *idmap, struct inode *dir,
3878 struct dentry *dentry, umode_t mode, dev_t dev)
3879 {
3880 struct inode *inode;
3881 int error;
3882
3883 if (!generic_ci_validate_strict_name(dir, &dentry->d_name))
3884 return -EINVAL;
3885
3886 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, dev,
3887 mk_vma_flags(VMA_NORESERVE_BIT));
3888 if (IS_ERR(inode))
3889 return PTR_ERR(inode);
3890
3891 error = simple_acl_create(dir, inode);
3892 if (error)
3893 goto out_iput;
3894 error = security_inode_init_security(inode, dir, &dentry->d_name,
3895 shmem_initxattrs, NULL);
3896 if (error && error != -EOPNOTSUPP)
3897 goto out_iput;
3898
3899 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
3900 if (error)
3901 goto out_iput;
3902
3903 dir->i_size += BOGO_DIRENT_SIZE;
3904 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
3905 inode_inc_iversion(dir);
3906
3907 d_make_persistent(dentry, inode);
3908 return error;
3909
3910 out_iput:
3911 iput(inode);
3912 return error;
3913 }
3914
3915 static int
shmem_tmpfile(struct mnt_idmap * idmap,struct inode * dir,struct file * file,umode_t mode)3916 shmem_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
3917 struct file *file, umode_t mode)
3918 {
3919 struct inode *inode;
3920 int error;
3921
3922 inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, 0,
3923 mk_vma_flags(VMA_NORESERVE_BIT));
3924 if (IS_ERR(inode)) {
3925 error = PTR_ERR(inode);
3926 goto err_out;
3927 }
3928 error = security_inode_init_security(inode, dir, NULL,
3929 shmem_initxattrs, NULL);
3930 if (error && error != -EOPNOTSUPP)
3931 goto out_iput;
3932 error = simple_acl_create(dir, inode);
3933 if (error)
3934 goto out_iput;
3935 d_tmpfile(file, inode);
3936
3937 err_out:
3938 return finish_open_simple(file, error);
3939 out_iput:
3940 iput(inode);
3941 return error;
3942 }
3943
shmem_mkdir(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode)3944 static struct dentry *shmem_mkdir(struct mnt_idmap *idmap, struct inode *dir,
3945 struct dentry *dentry, umode_t mode)
3946 {
3947 int error;
3948
3949 error = shmem_mknod(idmap, dir, dentry, mode | S_IFDIR, 0);
3950 if (error)
3951 return ERR_PTR(error);
3952 inc_nlink(dir);
3953 return NULL;
3954 }
3955
shmem_create(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,bool excl)3956 static int shmem_create(struct mnt_idmap *idmap, struct inode *dir,
3957 struct dentry *dentry, umode_t mode, bool excl)
3958 {
3959 return shmem_mknod(idmap, dir, dentry, mode | S_IFREG, 0);
3960 }
3961
3962 /*
3963 * Link a file..
3964 */
shmem_link(struct dentry * old_dentry,struct inode * dir,struct dentry * dentry)3965 static int shmem_link(struct dentry *old_dentry, struct inode *dir,
3966 struct dentry *dentry)
3967 {
3968 struct inode *inode = d_inode(old_dentry);
3969 int ret;
3970
3971 /*
3972 * No ordinary (disk based) filesystem counts links as inodes;
3973 * but each new link needs a new dentry, pinning lowmem, and
3974 * tmpfs dentries cannot be pruned until they are unlinked.
3975 * But if an O_TMPFILE file is linked into the tmpfs, the
3976 * first link must skip that, to get the accounting right.
3977 */
3978 if (inode->i_nlink) {
3979 ret = shmem_reserve_inode(inode->i_sb, NULL);
3980 if (ret)
3981 return ret;
3982 }
3983
3984 ret = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
3985 if (ret) {
3986 if (inode->i_nlink)
3987 shmem_free_inode(inode->i_sb, 0);
3988 return ret;
3989 }
3990
3991 dir->i_size += BOGO_DIRENT_SIZE;
3992 inode_inc_iversion(dir);
3993 return simple_link(old_dentry, dir, dentry);
3994 }
3995
shmem_unlink(struct inode * dir,struct dentry * dentry)3996 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
3997 {
3998 struct inode *inode = d_inode(dentry);
3999
4000 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
4001 shmem_free_inode(inode->i_sb, 0);
4002
4003 simple_offset_remove(shmem_get_offset_ctx(dir), dentry);
4004
4005 dir->i_size -= BOGO_DIRENT_SIZE;
4006 inode_inc_iversion(dir);
4007 simple_unlink(dir, dentry);
4008
4009 /*
4010 * For now, VFS can't deal with case-insensitive negative dentries, so
4011 * we invalidate them
4012 */
4013 if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
4014 d_invalidate(dentry);
4015
4016 return 0;
4017 }
4018
shmem_rmdir(struct inode * dir,struct dentry * dentry)4019 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
4020 {
4021 if (!simple_empty(dentry))
4022 return -ENOTEMPTY;
4023
4024 drop_nlink(d_inode(dentry));
4025 drop_nlink(dir);
4026 return shmem_unlink(dir, dentry);
4027 }
4028
shmem_whiteout(struct mnt_idmap * idmap,struct inode * old_dir,struct dentry * old_dentry)4029 static int shmem_whiteout(struct mnt_idmap *idmap,
4030 struct inode *old_dir, struct dentry *old_dentry)
4031 {
4032 struct dentry *whiteout;
4033 int error;
4034
4035 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
4036 if (!whiteout)
4037 return -ENOMEM;
4038 error = shmem_mknod(idmap, old_dir, whiteout,
4039 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
4040 dput(whiteout);
4041 return error;
4042 }
4043
4044 /*
4045 * The VFS layer already does all the dentry stuff for rename,
4046 * we just have to decrement the usage count for the target if
4047 * it exists so that the VFS layer correctly free's it when it
4048 * gets overwritten.
4049 */
shmem_rename2(struct mnt_idmap * idmap,struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry,unsigned int flags)4050 static int shmem_rename2(struct mnt_idmap *idmap,
4051 struct inode *old_dir, struct dentry *old_dentry,
4052 struct inode *new_dir, struct dentry *new_dentry,
4053 unsigned int flags)
4054 {
4055 struct inode *inode = d_inode(old_dentry);
4056 int they_are_dirs = S_ISDIR(inode->i_mode);
4057 bool had_offset = false;
4058 int error;
4059
4060 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
4061 return -EINVAL;
4062
4063 if (flags & RENAME_EXCHANGE)
4064 return simple_offset_rename_exchange(old_dir, old_dentry,
4065 new_dir, new_dentry);
4066
4067 if (!simple_empty(new_dentry))
4068 return -ENOTEMPTY;
4069
4070 error = simple_offset_add(shmem_get_offset_ctx(new_dir), new_dentry);
4071 if (error == -EBUSY)
4072 had_offset = true;
4073 else if (unlikely(error))
4074 return error;
4075
4076 if (flags & RENAME_WHITEOUT) {
4077 error = shmem_whiteout(idmap, old_dir, old_dentry);
4078 if (error) {
4079 if (!had_offset)
4080 simple_offset_remove(shmem_get_offset_ctx(new_dir),
4081 new_dentry);
4082 return error;
4083 }
4084 }
4085
4086 simple_offset_rename(old_dir, old_dentry, new_dir, new_dentry);
4087 if (d_really_is_positive(new_dentry)) {
4088 (void) shmem_unlink(new_dir, new_dentry);
4089 if (they_are_dirs) {
4090 drop_nlink(d_inode(new_dentry));
4091 drop_nlink(old_dir);
4092 }
4093 } else if (they_are_dirs) {
4094 drop_nlink(old_dir);
4095 inc_nlink(new_dir);
4096 }
4097
4098 old_dir->i_size -= BOGO_DIRENT_SIZE;
4099 new_dir->i_size += BOGO_DIRENT_SIZE;
4100 simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
4101 inode_inc_iversion(old_dir);
4102 inode_inc_iversion(new_dir);
4103 return 0;
4104 }
4105
shmem_symlink(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,const char * symname)4106 static int shmem_symlink(struct mnt_idmap *idmap, struct inode *dir,
4107 struct dentry *dentry, const char *symname)
4108 {
4109 int error;
4110 int len;
4111 struct inode *inode;
4112 struct folio *folio;
4113 char *link;
4114
4115 len = strlen(symname) + 1;
4116 if (len > PAGE_SIZE)
4117 return -ENAMETOOLONG;
4118
4119 inode = shmem_get_inode(idmap, dir->i_sb, dir, S_IFLNK | 0777, 0,
4120 mk_vma_flags(VMA_NORESERVE_BIT));
4121 if (IS_ERR(inode))
4122 return PTR_ERR(inode);
4123
4124 error = security_inode_init_security(inode, dir, &dentry->d_name,
4125 shmem_initxattrs, NULL);
4126 if (error && error != -EOPNOTSUPP)
4127 goto out_iput;
4128
4129 error = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
4130 if (error)
4131 goto out_iput;
4132
4133 inode->i_size = len-1;
4134 if (len <= SHORT_SYMLINK_LEN) {
4135 link = kmemdup(symname, len, GFP_KERNEL);
4136 if (!link) {
4137 error = -ENOMEM;
4138 goto out_remove_offset;
4139 }
4140 inode->i_op = &shmem_short_symlink_operations;
4141 inode_set_cached_link(inode, link, len - 1);
4142 } else {
4143 inode_nohighmem(inode);
4144 inode->i_mapping->a_ops = &shmem_aops;
4145 error = shmem_get_folio(inode, 0, 0, &folio, SGP_WRITE);
4146 if (error)
4147 goto out_remove_offset;
4148 inode->i_op = &shmem_symlink_inode_operations;
4149 memcpy(folio_address(folio), symname, len);
4150 folio_mark_uptodate(folio);
4151 folio_mark_dirty(folio);
4152 folio_unlock(folio);
4153 folio_put(folio);
4154 }
4155 dir->i_size += BOGO_DIRENT_SIZE;
4156 inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
4157 inode_inc_iversion(dir);
4158 d_make_persistent(dentry, inode);
4159 return 0;
4160
4161 out_remove_offset:
4162 simple_offset_remove(shmem_get_offset_ctx(dir), dentry);
4163 out_iput:
4164 iput(inode);
4165 return error;
4166 }
4167
shmem_put_link(void * arg)4168 static void shmem_put_link(void *arg)
4169 {
4170 folio_mark_accessed(arg);
4171 folio_put(arg);
4172 }
4173
shmem_get_link(struct dentry * dentry,struct inode * inode,struct delayed_call * done)4174 static const char *shmem_get_link(struct dentry *dentry, struct inode *inode,
4175 struct delayed_call *done)
4176 {
4177 struct folio *folio = NULL;
4178 int error;
4179
4180 if (!dentry) {
4181 folio = filemap_get_folio(inode->i_mapping, 0);
4182 if (IS_ERR(folio))
4183 return ERR_PTR(-ECHILD);
4184 if (PageHWPoison(folio_page(folio, 0)) ||
4185 !folio_test_uptodate(folio)) {
4186 folio_put(folio);
4187 return ERR_PTR(-ECHILD);
4188 }
4189 } else {
4190 error = shmem_get_folio(inode, 0, 0, &folio, SGP_READ);
4191 if (error)
4192 return ERR_PTR(error);
4193 if (!folio)
4194 return ERR_PTR(-ECHILD);
4195 if (PageHWPoison(folio_page(folio, 0))) {
4196 folio_unlock(folio);
4197 folio_put(folio);
4198 return ERR_PTR(-ECHILD);
4199 }
4200 folio_unlock(folio);
4201 }
4202 set_delayed_call(done, shmem_put_link, folio);
4203 return folio_address(folio);
4204 }
4205
4206 #ifdef CONFIG_TMPFS_XATTR
4207
shmem_fileattr_get(struct dentry * dentry,struct file_kattr * fa)4208 static int shmem_fileattr_get(struct dentry *dentry, struct file_kattr *fa)
4209 {
4210 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
4211
4212 fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE);
4213
4214 return 0;
4215 }
4216
shmem_fileattr_set(struct mnt_idmap * idmap,struct dentry * dentry,struct file_kattr * fa)4217 static int shmem_fileattr_set(struct mnt_idmap *idmap,
4218 struct dentry *dentry, struct file_kattr *fa)
4219 {
4220 struct inode *inode = d_inode(dentry);
4221 struct shmem_inode_info *info = SHMEM_I(inode);
4222 int ret, flags;
4223
4224 if (fileattr_has_fsx(fa))
4225 return -EOPNOTSUPP;
4226 if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE)
4227 return -EOPNOTSUPP;
4228
4229 flags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) |
4230 (fa->flags & SHMEM_FL_USER_MODIFIABLE);
4231
4232 ret = shmem_set_inode_flags(inode, flags, dentry);
4233
4234 if (ret)
4235 return ret;
4236
4237 info->fsflags = flags;
4238
4239 inode_set_ctime_current(inode);
4240 inode_inc_iversion(inode);
4241 return 0;
4242 }
4243
4244 /*
4245 * Superblocks without xattr inode operations may get some security.* xattr
4246 * support from the LSM "for free". As soon as we have any other xattrs
4247 * like ACLs, we also need to implement the security.* handlers at
4248 * filesystem level, though.
4249 */
4250
4251 /*
4252 * Callback for security_inode_init_security() for acquiring xattrs.
4253 */
shmem_initxattrs(struct inode * inode,const struct xattr * xattr_array,void * fs_info)4254 static int shmem_initxattrs(struct inode *inode,
4255 const struct xattr *xattr_array, void *fs_info)
4256 {
4257 struct shmem_inode_info *info = SHMEM_I(inode);
4258 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
4259 const struct xattr *xattr;
4260 size_t ispace = 0;
4261 size_t len;
4262
4263 CLASS(simple_xattrs, xattrs)();
4264 if (IS_ERR(xattrs))
4265 return PTR_ERR(xattrs);
4266
4267 if (sbinfo->max_inodes) {
4268 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
4269 ispace += simple_xattr_space(xattr->name,
4270 xattr->value_len + XATTR_SECURITY_PREFIX_LEN);
4271 }
4272 if (ispace) {
4273 raw_spin_lock(&sbinfo->stat_lock);
4274 if (sbinfo->free_ispace < ispace)
4275 ispace = 0;
4276 else
4277 sbinfo->free_ispace -= ispace;
4278 raw_spin_unlock(&sbinfo->stat_lock);
4279 if (!ispace)
4280 return -ENOSPC;
4281 }
4282 }
4283
4284 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
4285 CLASS(simple_xattr, new_xattr)(xattr->value, xattr->value_len);
4286 if (IS_ERR(new_xattr))
4287 break;
4288
4289 len = strlen(xattr->name) + 1;
4290 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
4291 GFP_KERNEL_ACCOUNT);
4292 if (!new_xattr->name)
4293 break;
4294
4295 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
4296 XATTR_SECURITY_PREFIX_LEN);
4297 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
4298 xattr->name, len);
4299
4300 if (simple_xattr_add(xattrs, new_xattr))
4301 break;
4302 retain_and_null_ptr(new_xattr);
4303 }
4304
4305 if (xattr->name != NULL) {
4306 if (ispace) {
4307 raw_spin_lock(&sbinfo->stat_lock);
4308 sbinfo->free_ispace += ispace;
4309 raw_spin_unlock(&sbinfo->stat_lock);
4310 }
4311 return -ENOMEM;
4312 }
4313
4314 smp_store_release(&info->xattrs, no_free_ptr(xattrs));
4315 return 0;
4316 }
4317
shmem_xattr_handler_get(const struct xattr_handler * handler,struct dentry * unused,struct inode * inode,const char * name,void * buffer,size_t size)4318 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
4319 struct dentry *unused, struct inode *inode,
4320 const char *name, void *buffer, size_t size)
4321 {
4322 struct shmem_inode_info *info = SHMEM_I(inode);
4323 struct simple_xattrs *xattrs;
4324
4325 xattrs = READ_ONCE(info->xattrs);
4326 if (!xattrs)
4327 return -ENODATA;
4328
4329 name = xattr_full_name(handler, name);
4330 return simple_xattr_get(xattrs, name, buffer, size);
4331 }
4332
shmem_xattr_handler_set(const struct xattr_handler * handler,struct mnt_idmap * idmap,struct dentry * unused,struct inode * inode,const char * name,const void * value,size_t size,int flags)4333 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
4334 struct mnt_idmap *idmap,
4335 struct dentry *unused, struct inode *inode,
4336 const char *name, const void *value,
4337 size_t size, int flags)
4338 {
4339 struct shmem_inode_info *info = SHMEM_I(inode);
4340 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
4341 struct simple_xattrs *xattrs;
4342 struct simple_xattr *old_xattr;
4343 size_t ispace = 0;
4344
4345 name = xattr_full_name(handler, name);
4346
4347 xattrs = simple_xattrs_lazy_alloc(&info->xattrs, value, flags);
4348 if (IS_ERR_OR_NULL(xattrs))
4349 return PTR_ERR(xattrs);
4350
4351 if (value && sbinfo->max_inodes) {
4352 ispace = simple_xattr_space(name, size);
4353 raw_spin_lock(&sbinfo->stat_lock);
4354 if (sbinfo->free_ispace < ispace)
4355 ispace = 0;
4356 else
4357 sbinfo->free_ispace -= ispace;
4358 raw_spin_unlock(&sbinfo->stat_lock);
4359 if (!ispace)
4360 return -ENOSPC;
4361 }
4362
4363 old_xattr = simple_xattr_set(xattrs, name, value, size, flags);
4364 if (!IS_ERR(old_xattr)) {
4365 ispace = 0;
4366 if (old_xattr && sbinfo->max_inodes)
4367 ispace = simple_xattr_space(old_xattr->name,
4368 old_xattr->size);
4369 simple_xattr_free_rcu(old_xattr);
4370 old_xattr = NULL;
4371 inode_set_ctime_current(inode);
4372 inode_inc_iversion(inode);
4373 }
4374 if (ispace) {
4375 raw_spin_lock(&sbinfo->stat_lock);
4376 sbinfo->free_ispace += ispace;
4377 raw_spin_unlock(&sbinfo->stat_lock);
4378 }
4379 return PTR_ERR(old_xattr);
4380 }
4381
4382 static const struct xattr_handler shmem_security_xattr_handler = {
4383 .prefix = XATTR_SECURITY_PREFIX,
4384 .get = shmem_xattr_handler_get,
4385 .set = shmem_xattr_handler_set,
4386 };
4387
4388 static const struct xattr_handler shmem_trusted_xattr_handler = {
4389 .prefix = XATTR_TRUSTED_PREFIX,
4390 .get = shmem_xattr_handler_get,
4391 .set = shmem_xattr_handler_set,
4392 };
4393
4394 static const struct xattr_handler shmem_user_xattr_handler = {
4395 .prefix = XATTR_USER_PREFIX,
4396 .get = shmem_xattr_handler_get,
4397 .set = shmem_xattr_handler_set,
4398 };
4399
4400 static const struct xattr_handler * const shmem_xattr_handlers[] = {
4401 &shmem_security_xattr_handler,
4402 &shmem_trusted_xattr_handler,
4403 &shmem_user_xattr_handler,
4404 NULL
4405 };
4406
shmem_listxattr(struct dentry * dentry,char * buffer,size_t size)4407 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
4408 {
4409 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
4410
4411 return simple_xattr_list(d_inode(dentry), READ_ONCE(info->xattrs),
4412 buffer, size);
4413 }
4414 #endif /* CONFIG_TMPFS_XATTR */
4415
4416 static const struct inode_operations shmem_short_symlink_operations = {
4417 .getattr = shmem_getattr,
4418 .setattr = shmem_setattr,
4419 .get_link = simple_get_link,
4420 #ifdef CONFIG_TMPFS_XATTR
4421 .listxattr = shmem_listxattr,
4422 #endif
4423 };
4424
4425 static const struct inode_operations shmem_symlink_inode_operations = {
4426 .getattr = shmem_getattr,
4427 .setattr = shmem_setattr,
4428 .get_link = shmem_get_link,
4429 #ifdef CONFIG_TMPFS_XATTR
4430 .listxattr = shmem_listxattr,
4431 #endif
4432 };
4433
shmem_get_parent(struct dentry * child)4434 static struct dentry *shmem_get_parent(struct dentry *child)
4435 {
4436 return ERR_PTR(-ESTALE);
4437 }
4438
shmem_match(struct inode * ino,void * vfh)4439 static int shmem_match(struct inode *ino, void *vfh)
4440 {
4441 __u32 *fh = vfh;
4442 __u64 inum = fh[2];
4443 inum = (inum << 32) | fh[1];
4444 return ino->i_ino == inum && fh[0] == ino->i_generation;
4445 }
4446
4447 /* Find any alias of inode, but prefer a hashed alias */
shmem_find_alias(struct inode * inode)4448 static struct dentry *shmem_find_alias(struct inode *inode)
4449 {
4450 struct dentry *alias = d_find_alias(inode);
4451
4452 return alias ?: d_find_any_alias(inode);
4453 }
4454
shmem_fh_to_dentry(struct super_block * sb,struct fid * fid,int fh_len,int fh_type)4455 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
4456 struct fid *fid, int fh_len, int fh_type)
4457 {
4458 struct inode *inode;
4459 struct dentry *dentry = NULL;
4460 u64 inum;
4461
4462 if (fh_len < 3)
4463 return NULL;
4464
4465 inum = fid->raw[2];
4466 inum = (inum << 32) | fid->raw[1];
4467
4468 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
4469 shmem_match, fid->raw);
4470 if (inode) {
4471 dentry = shmem_find_alias(inode);
4472 iput(inode);
4473 }
4474
4475 return dentry;
4476 }
4477
shmem_encode_fh(struct inode * inode,__u32 * fh,int * len,struct inode * parent)4478 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
4479 struct inode *parent)
4480 {
4481 if (*len < 3) {
4482 *len = 3;
4483 return FILEID_INVALID;
4484 }
4485
4486 if (inode_unhashed(inode)) {
4487 /* Unfortunately insert_inode_hash is not idempotent,
4488 * so as we hash inodes here rather than at creation
4489 * time, we need a lock to ensure we only try
4490 * to do it once
4491 */
4492 static DEFINE_SPINLOCK(lock);
4493 spin_lock(&lock);
4494 if (inode_unhashed(inode))
4495 __insert_inode_hash(inode,
4496 inode->i_ino + inode->i_generation);
4497 spin_unlock(&lock);
4498 }
4499
4500 fh[0] = inode->i_generation;
4501 fh[1] = inode->i_ino;
4502 fh[2] = ((__u64)inode->i_ino) >> 32;
4503
4504 *len = 3;
4505 return 1;
4506 }
4507
4508 static const struct export_operations shmem_export_ops = {
4509 .get_parent = shmem_get_parent,
4510 .encode_fh = shmem_encode_fh,
4511 .fh_to_dentry = shmem_fh_to_dentry,
4512 };
4513
4514 enum shmem_param {
4515 Opt_gid,
4516 Opt_huge,
4517 Opt_mode,
4518 Opt_mpol,
4519 Opt_nr_blocks,
4520 Opt_nr_inodes,
4521 Opt_size,
4522 Opt_uid,
4523 Opt_inode32,
4524 Opt_inode64,
4525 Opt_noswap,
4526 Opt_quota,
4527 Opt_usrquota,
4528 Opt_grpquota,
4529 Opt_usrquota_block_hardlimit,
4530 Opt_usrquota_inode_hardlimit,
4531 Opt_grpquota_block_hardlimit,
4532 Opt_grpquota_inode_hardlimit,
4533 Opt_casefold_version,
4534 Opt_casefold,
4535 Opt_strict_encoding,
4536 };
4537
4538 static const struct constant_table shmem_param_enums_huge[] = {
4539 {"never", SHMEM_HUGE_NEVER },
4540 {"always", SHMEM_HUGE_ALWAYS },
4541 {"within_size", SHMEM_HUGE_WITHIN_SIZE },
4542 {"advise", SHMEM_HUGE_ADVISE },
4543 {}
4544 };
4545
4546 const struct fs_parameter_spec shmem_fs_parameters[] = {
4547 fsparam_gid ("gid", Opt_gid),
4548 fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge),
4549 fsparam_u32oct("mode", Opt_mode),
4550 fsparam_string("mpol", Opt_mpol),
4551 fsparam_string("nr_blocks", Opt_nr_blocks),
4552 fsparam_string("nr_inodes", Opt_nr_inodes),
4553 fsparam_string("size", Opt_size),
4554 fsparam_uid ("uid", Opt_uid),
4555 fsparam_flag ("inode32", Opt_inode32),
4556 fsparam_flag ("inode64", Opt_inode64),
4557 fsparam_flag ("noswap", Opt_noswap),
4558 #ifdef CONFIG_TMPFS_QUOTA
4559 fsparam_flag ("quota", Opt_quota),
4560 fsparam_flag ("usrquota", Opt_usrquota),
4561 fsparam_flag ("grpquota", Opt_grpquota),
4562 fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit),
4563 fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit),
4564 fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit),
4565 fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit),
4566 #endif
4567 fsparam_string("casefold", Opt_casefold_version),
4568 fsparam_flag ("casefold", Opt_casefold),
4569 fsparam_flag ("strict_encoding", Opt_strict_encoding),
4570 {}
4571 };
4572
4573 #if IS_ENABLED(CONFIG_UNICODE)
shmem_parse_opt_casefold(struct fs_context * fc,struct fs_parameter * param,bool latest_version)4574 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param,
4575 bool latest_version)
4576 {
4577 struct shmem_options *ctx = fc->fs_private;
4578 int version = UTF8_LATEST;
4579 struct unicode_map *encoding;
4580 char *version_str = param->string + 5;
4581
4582 if (!latest_version) {
4583 if (strncmp(param->string, "utf8-", 5))
4584 return invalfc(fc, "Only UTF-8 encodings are supported "
4585 "in the format: utf8-<version number>");
4586
4587 version = utf8_parse_version(version_str);
4588 if (version < 0)
4589 return invalfc(fc, "Invalid UTF-8 version: %s", version_str);
4590 }
4591
4592 encoding = utf8_load(version);
4593
4594 if (IS_ERR(encoding)) {
4595 return invalfc(fc, "Failed loading UTF-8 version: utf8-%u.%u.%u\n",
4596 unicode_major(version), unicode_minor(version),
4597 unicode_rev(version));
4598 }
4599
4600 pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n",
4601 unicode_major(version), unicode_minor(version), unicode_rev(version));
4602
4603 ctx->encoding = encoding;
4604
4605 return 0;
4606 }
4607 #else
shmem_parse_opt_casefold(struct fs_context * fc,struct fs_parameter * param,bool latest_version)4608 static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param,
4609 bool latest_version)
4610 {
4611 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4612 }
4613 #endif
4614
shmem_parse_one(struct fs_context * fc,struct fs_parameter * param)4615 static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
4616 {
4617 struct shmem_options *ctx = fc->fs_private;
4618 struct fs_parse_result result;
4619 unsigned long long size;
4620 char *rest;
4621 int opt;
4622 kuid_t kuid;
4623 kgid_t kgid;
4624
4625 opt = fs_parse(fc, shmem_fs_parameters, param, &result);
4626 if (opt < 0)
4627 return opt;
4628
4629 switch (opt) {
4630 case Opt_size:
4631 size = memparse(param->string, &rest);
4632 if (*rest == '%') {
4633 size <<= PAGE_SHIFT;
4634 size *= totalram_pages();
4635 do_div(size, 100);
4636 rest++;
4637 }
4638 if (*rest)
4639 goto bad_value;
4640 ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
4641 ctx->seen |= SHMEM_SEEN_BLOCKS;
4642 break;
4643 case Opt_nr_blocks:
4644 ctx->blocks = memparse(param->string, &rest);
4645 if (*rest || ctx->blocks > LONG_MAX)
4646 goto bad_value;
4647 ctx->seen |= SHMEM_SEEN_BLOCKS;
4648 break;
4649 case Opt_nr_inodes:
4650 ctx->inodes = memparse(param->string, &rest);
4651 if (*rest || ctx->inodes > ULONG_MAX / BOGO_INODE_SIZE)
4652 goto bad_value;
4653 ctx->seen |= SHMEM_SEEN_INODES;
4654 break;
4655 case Opt_mode:
4656 ctx->mode = result.uint_32 & 07777;
4657 break;
4658 case Opt_uid:
4659 kuid = result.uid;
4660
4661 /*
4662 * The requested uid must be representable in the
4663 * filesystem's idmapping.
4664 */
4665 if (!kuid_has_mapping(fc->user_ns, kuid))
4666 goto bad_value;
4667
4668 ctx->uid = kuid;
4669 break;
4670 case Opt_gid:
4671 kgid = result.gid;
4672
4673 /*
4674 * The requested gid must be representable in the
4675 * filesystem's idmapping.
4676 */
4677 if (!kgid_has_mapping(fc->user_ns, kgid))
4678 goto bad_value;
4679
4680 ctx->gid = kgid;
4681 break;
4682 case Opt_huge:
4683 ctx->huge = result.uint_32;
4684 if (ctx->huge != SHMEM_HUGE_NEVER &&
4685 !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
4686 has_transparent_hugepage()))
4687 goto unsupported_parameter;
4688 ctx->seen |= SHMEM_SEEN_HUGE;
4689 break;
4690 case Opt_mpol:
4691 if (IS_ENABLED(CONFIG_NUMA)) {
4692 mpol_put(ctx->mpol);
4693 ctx->mpol = NULL;
4694 if (mpol_parse_str(param->string, &ctx->mpol))
4695 goto bad_value;
4696 break;
4697 }
4698 goto unsupported_parameter;
4699 case Opt_inode32:
4700 ctx->full_inums = false;
4701 ctx->seen |= SHMEM_SEEN_INUMS;
4702 break;
4703 case Opt_inode64:
4704 if (sizeof(ino_t) < 8) {
4705 return invalfc(fc,
4706 "Cannot use inode64 with <64bit inums in kernel\n");
4707 }
4708 ctx->full_inums = true;
4709 ctx->seen |= SHMEM_SEEN_INUMS;
4710 break;
4711 case Opt_noswap:
4712 if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) {
4713 return invalfc(fc,
4714 "Turning off swap in unprivileged tmpfs mounts unsupported");
4715 }
4716 ctx->noswap = true;
4717 break;
4718 case Opt_quota:
4719 if (fc->user_ns != &init_user_ns)
4720 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
4721 ctx->seen |= SHMEM_SEEN_QUOTA;
4722 ctx->quota_types |= (QTYPE_MASK_USR | QTYPE_MASK_GRP);
4723 break;
4724 case Opt_usrquota:
4725 if (fc->user_ns != &init_user_ns)
4726 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
4727 ctx->seen |= SHMEM_SEEN_QUOTA;
4728 ctx->quota_types |= QTYPE_MASK_USR;
4729 break;
4730 case Opt_grpquota:
4731 if (fc->user_ns != &init_user_ns)
4732 return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
4733 ctx->seen |= SHMEM_SEEN_QUOTA;
4734 ctx->quota_types |= QTYPE_MASK_GRP;
4735 break;
4736 case Opt_usrquota_block_hardlimit:
4737 size = memparse(param->string, &rest);
4738 if (*rest || !size)
4739 goto bad_value;
4740 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT)
4741 return invalfc(fc,
4742 "User quota block hardlimit too large.");
4743 ctx->qlimits.usrquota_bhardlimit = size;
4744 break;
4745 case Opt_grpquota_block_hardlimit:
4746 size = memparse(param->string, &rest);
4747 if (*rest || !size)
4748 goto bad_value;
4749 if (size > SHMEM_QUOTA_MAX_SPC_LIMIT)
4750 return invalfc(fc,
4751 "Group quota block hardlimit too large.");
4752 ctx->qlimits.grpquota_bhardlimit = size;
4753 break;
4754 case Opt_usrquota_inode_hardlimit:
4755 size = memparse(param->string, &rest);
4756 if (*rest || !size)
4757 goto bad_value;
4758 if (size > SHMEM_QUOTA_MAX_INO_LIMIT)
4759 return invalfc(fc,
4760 "User quota inode hardlimit too large.");
4761 ctx->qlimits.usrquota_ihardlimit = size;
4762 break;
4763 case Opt_grpquota_inode_hardlimit:
4764 size = memparse(param->string, &rest);
4765 if (*rest || !size)
4766 goto bad_value;
4767 if (size > SHMEM_QUOTA_MAX_INO_LIMIT)
4768 return invalfc(fc,
4769 "Group quota inode hardlimit too large.");
4770 ctx->qlimits.grpquota_ihardlimit = size;
4771 break;
4772 case Opt_casefold_version:
4773 return shmem_parse_opt_casefold(fc, param, false);
4774 case Opt_casefold:
4775 return shmem_parse_opt_casefold(fc, param, true);
4776 case Opt_strict_encoding:
4777 #if IS_ENABLED(CONFIG_UNICODE)
4778 ctx->strict_encoding = true;
4779 break;
4780 #else
4781 return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
4782 #endif
4783 }
4784 return 0;
4785
4786 unsupported_parameter:
4787 return invalfc(fc, "Unsupported parameter '%s'", param->key);
4788 bad_value:
4789 return invalfc(fc, "Bad value for '%s'", param->key);
4790 }
4791
shmem_next_opt(char ** s)4792 static char *shmem_next_opt(char **s)
4793 {
4794 char *sbegin = *s;
4795 char *p;
4796
4797 if (sbegin == NULL)
4798 return NULL;
4799
4800 /*
4801 * NUL-terminate this option: unfortunately,
4802 * mount options form a comma-separated list,
4803 * but mpol's nodelist may also contain commas.
4804 */
4805 for (;;) {
4806 p = strchr(*s, ',');
4807 if (p == NULL)
4808 break;
4809 *s = p + 1;
4810 if (!isdigit(*(p+1))) {
4811 *p = '\0';
4812 return sbegin;
4813 }
4814 }
4815
4816 *s = NULL;
4817 return sbegin;
4818 }
4819
shmem_parse_monolithic(struct fs_context * fc,void * data)4820 static int shmem_parse_monolithic(struct fs_context *fc, void *data)
4821 {
4822 return vfs_parse_monolithic_sep(fc, data, shmem_next_opt);
4823 }
4824
4825 /*
4826 * Reconfigure a shmem filesystem.
4827 */
shmem_reconfigure(struct fs_context * fc)4828 static int shmem_reconfigure(struct fs_context *fc)
4829 {
4830 struct shmem_options *ctx = fc->fs_private;
4831 struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
4832 unsigned long used_isp;
4833 struct mempolicy *mpol = NULL;
4834 const char *err;
4835
4836 raw_spin_lock(&sbinfo->stat_lock);
4837 used_isp = sbinfo->max_inodes * BOGO_INODE_SIZE - sbinfo->free_ispace;
4838
4839 if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
4840 if (!sbinfo->max_blocks) {
4841 err = "Cannot retroactively limit size";
4842 goto out;
4843 }
4844 if (percpu_counter_compare(&sbinfo->used_blocks,
4845 ctx->blocks) > 0) {
4846 err = "Too small a size for current use";
4847 goto out;
4848 }
4849 }
4850 if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
4851 if (!sbinfo->max_inodes) {
4852 err = "Cannot retroactively limit inodes";
4853 goto out;
4854 }
4855 if (ctx->inodes * BOGO_INODE_SIZE < used_isp) {
4856 err = "Too few inodes for current use";
4857 goto out;
4858 }
4859 }
4860
4861 if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
4862 sbinfo->next_ino > UINT_MAX) {
4863 err = "Current inum too high to switch to 32-bit inums";
4864 goto out;
4865 }
4866
4867 /*
4868 * "noswap" doesn't use fsparam_flag_no, i.e. there's no "swap"
4869 * counterpart for (re-)enabling swap.
4870 */
4871 if (ctx->noswap && !sbinfo->noswap) {
4872 err = "Cannot disable swap on remount";
4873 goto out;
4874 }
4875
4876 if (ctx->seen & SHMEM_SEEN_QUOTA &&
4877 !sb_any_quota_loaded(fc->root->d_sb)) {
4878 err = "Cannot enable quota on remount";
4879 goto out;
4880 }
4881
4882 #ifdef CONFIG_TMPFS_QUOTA
4883 #define CHANGED_LIMIT(name) \
4884 (ctx->qlimits.name## hardlimit && \
4885 (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit))
4886
4887 if (CHANGED_LIMIT(usrquota_b) || CHANGED_LIMIT(usrquota_i) ||
4888 CHANGED_LIMIT(grpquota_b) || CHANGED_LIMIT(grpquota_i)) {
4889 err = "Cannot change global quota limit on remount";
4890 goto out;
4891 }
4892 #endif /* CONFIG_TMPFS_QUOTA */
4893
4894 if (ctx->seen & SHMEM_SEEN_HUGE)
4895 sbinfo->huge = ctx->huge;
4896 if (ctx->seen & SHMEM_SEEN_INUMS)
4897 sbinfo->full_inums = ctx->full_inums;
4898 if (ctx->seen & SHMEM_SEEN_BLOCKS)
4899 sbinfo->max_blocks = ctx->blocks;
4900 if (ctx->seen & SHMEM_SEEN_INODES) {
4901 sbinfo->max_inodes = ctx->inodes;
4902 sbinfo->free_ispace = ctx->inodes * BOGO_INODE_SIZE - used_isp;
4903 }
4904
4905 /*
4906 * Preserve previous mempolicy unless mpol remount option was specified.
4907 */
4908 if (ctx->mpol) {
4909 mpol = sbinfo->mpol;
4910 sbinfo->mpol = ctx->mpol; /* transfers initial ref */
4911 ctx->mpol = NULL;
4912 }
4913
4914 if (ctx->noswap)
4915 sbinfo->noswap = true;
4916
4917 raw_spin_unlock(&sbinfo->stat_lock);
4918 mpol_put(mpol);
4919 return 0;
4920 out:
4921 raw_spin_unlock(&sbinfo->stat_lock);
4922 return invalfc(fc, "%s", err);
4923 }
4924
shmem_show_options(struct seq_file * seq,struct dentry * root)4925 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
4926 {
4927 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
4928 struct mempolicy *mpol;
4929
4930 if (sbinfo->max_blocks != shmem_default_max_blocks())
4931 seq_printf(seq, ",size=%luk", K(sbinfo->max_blocks));
4932 if (sbinfo->max_inodes != shmem_default_max_inodes())
4933 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
4934 if (sbinfo->mode != (0777 | S_ISVTX))
4935 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
4936 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
4937 seq_printf(seq, ",uid=%u",
4938 from_kuid_munged(&init_user_ns, sbinfo->uid));
4939 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
4940 seq_printf(seq, ",gid=%u",
4941 from_kgid_munged(&init_user_ns, sbinfo->gid));
4942
4943 /*
4944 * Showing inode{64,32} might be useful even if it's the system default,
4945 * since then people don't have to resort to checking both here and
4946 * /proc/config.gz to confirm 64-bit inums were successfully applied
4947 * (which may not even exist if IKCONFIG_PROC isn't enabled).
4948 *
4949 * We hide it when inode64 isn't the default and we are using 32-bit
4950 * inodes, since that probably just means the feature isn't even under
4951 * consideration.
4952 *
4953 * As such:
4954 *
4955 * +-----------------+-----------------+
4956 * | TMPFS_INODE64=y | TMPFS_INODE64=n |
4957 * +------------------+-----------------+-----------------+
4958 * | full_inums=true | show | show |
4959 * | full_inums=false | show | hide |
4960 * +------------------+-----------------+-----------------+
4961 *
4962 */
4963 if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
4964 seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
4965 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4966 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
4967 if (sbinfo->huge)
4968 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
4969 #endif
4970 mpol = shmem_get_sbmpol(sbinfo);
4971 shmem_show_mpol(seq, mpol);
4972 mpol_put(mpol);
4973 if (sbinfo->noswap)
4974 seq_printf(seq, ",noswap");
4975 #ifdef CONFIG_TMPFS_QUOTA
4976 if (sb_has_quota_active(root->d_sb, USRQUOTA))
4977 seq_printf(seq, ",usrquota");
4978 if (sb_has_quota_active(root->d_sb, GRPQUOTA))
4979 seq_printf(seq, ",grpquota");
4980 if (sbinfo->qlimits.usrquota_bhardlimit)
4981 seq_printf(seq, ",usrquota_block_hardlimit=%lld",
4982 sbinfo->qlimits.usrquota_bhardlimit);
4983 if (sbinfo->qlimits.grpquota_bhardlimit)
4984 seq_printf(seq, ",grpquota_block_hardlimit=%lld",
4985 sbinfo->qlimits.grpquota_bhardlimit);
4986 if (sbinfo->qlimits.usrquota_ihardlimit)
4987 seq_printf(seq, ",usrquota_inode_hardlimit=%lld",
4988 sbinfo->qlimits.usrquota_ihardlimit);
4989 if (sbinfo->qlimits.grpquota_ihardlimit)
4990 seq_printf(seq, ",grpquota_inode_hardlimit=%lld",
4991 sbinfo->qlimits.grpquota_ihardlimit);
4992 #endif
4993 return 0;
4994 }
4995
4996 #endif /* CONFIG_TMPFS */
4997
shmem_put_super(struct super_block * sb)4998 static void shmem_put_super(struct super_block *sb)
4999 {
5000 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
5001
5002 #if IS_ENABLED(CONFIG_UNICODE)
5003 if (sb->s_encoding)
5004 utf8_unload(sb->s_encoding);
5005 #endif
5006
5007 #ifdef CONFIG_TMPFS_QUOTA
5008 shmem_disable_quotas(sb);
5009 #endif
5010 free_percpu(sbinfo->ino_batch);
5011 percpu_counter_destroy(&sbinfo->used_blocks);
5012 mpol_put(sbinfo->mpol);
5013 kfree(sbinfo);
5014 sb->s_fs_info = NULL;
5015 }
5016
5017 #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS)
5018 static const struct dentry_operations shmem_ci_dentry_ops = {
5019 .d_hash = generic_ci_d_hash,
5020 .d_compare = generic_ci_d_compare,
5021 };
5022 #endif
5023
shmem_fill_super(struct super_block * sb,struct fs_context * fc)5024 static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
5025 {
5026 struct shmem_options *ctx = fc->fs_private;
5027 struct inode *inode;
5028 struct shmem_sb_info *sbinfo;
5029 int error = -ENOMEM;
5030
5031 /* Round up to L1_CACHE_BYTES to resist false sharing */
5032 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
5033 L1_CACHE_BYTES), GFP_KERNEL);
5034 if (!sbinfo)
5035 return error;
5036
5037 sb->s_fs_info = sbinfo;
5038
5039 #ifdef CONFIG_TMPFS
5040 /*
5041 * Per default we only allow half of the physical ram per
5042 * tmpfs instance, limiting inodes to one per page of lowmem;
5043 * but the internal instance is left unlimited.
5044 */
5045 if (!(sb->s_flags & SB_KERNMOUNT)) {
5046 if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
5047 ctx->blocks = shmem_default_max_blocks();
5048 if (!(ctx->seen & SHMEM_SEEN_INODES))
5049 ctx->inodes = shmem_default_max_inodes();
5050 if (!(ctx->seen & SHMEM_SEEN_INUMS))
5051 ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
5052 sbinfo->noswap = ctx->noswap;
5053 } else {
5054 sb->s_flags |= SB_NOUSER;
5055 }
5056 sb->s_export_op = &shmem_export_ops;
5057 sb->s_flags |= SB_NOSEC;
5058
5059 #if IS_ENABLED(CONFIG_UNICODE)
5060 if (!ctx->encoding && ctx->strict_encoding) {
5061 pr_err("tmpfs: strict_encoding option without encoding is forbidden\n");
5062 error = -EINVAL;
5063 goto failed;
5064 }
5065
5066 if (ctx->encoding) {
5067 sb->s_encoding = ctx->encoding;
5068 set_default_d_op(sb, &shmem_ci_dentry_ops);
5069 if (ctx->strict_encoding)
5070 sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL;
5071 }
5072 #endif
5073
5074 #else
5075 sb->s_flags |= SB_NOUSER;
5076 #endif /* CONFIG_TMPFS */
5077 sb->s_d_flags |= DCACHE_DONTCACHE;
5078 sbinfo->max_blocks = ctx->blocks;
5079 sbinfo->max_inodes = ctx->inodes;
5080 sbinfo->free_ispace = sbinfo->max_inodes * BOGO_INODE_SIZE;
5081 if (sb->s_flags & SB_KERNMOUNT) {
5082 sbinfo->ino_batch = alloc_percpu(ino_t);
5083 if (!sbinfo->ino_batch)
5084 goto failed;
5085 }
5086 sbinfo->uid = ctx->uid;
5087 sbinfo->gid = ctx->gid;
5088 sbinfo->full_inums = ctx->full_inums;
5089 sbinfo->mode = ctx->mode;
5090 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5091 if (ctx->seen & SHMEM_SEEN_HUGE)
5092 sbinfo->huge = ctx->huge;
5093 else
5094 sbinfo->huge = tmpfs_huge;
5095 #endif
5096 sbinfo->mpol = ctx->mpol;
5097 ctx->mpol = NULL;
5098
5099 raw_spin_lock_init(&sbinfo->stat_lock);
5100 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
5101 goto failed;
5102 spin_lock_init(&sbinfo->shrinklist_lock);
5103 INIT_LIST_HEAD(&sbinfo->shrinklist);
5104
5105 sb->s_maxbytes = MAX_LFS_FILESIZE;
5106 sb->s_blocksize = PAGE_SIZE;
5107 sb->s_blocksize_bits = PAGE_SHIFT;
5108 sb->s_magic = TMPFS_MAGIC;
5109 sb->s_op = &shmem_ops;
5110 sb->s_time_gran = 1;
5111 #ifdef CONFIG_TMPFS_XATTR
5112 sb->s_xattr = shmem_xattr_handlers;
5113 #endif
5114 #ifdef CONFIG_TMPFS_POSIX_ACL
5115 sb->s_flags |= SB_POSIXACL;
5116 #endif
5117 uuid_t uuid;
5118 uuid_gen(&uuid);
5119 super_set_uuid(sb, uuid.b, sizeof(uuid));
5120
5121 #ifdef CONFIG_TMPFS_QUOTA
5122 if (ctx->seen & SHMEM_SEEN_QUOTA) {
5123 sb->dq_op = &shmem_quota_operations;
5124 sb->s_qcop = &dquot_quotactl_sysfile_ops;
5125 sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
5126
5127 /* Copy the default limits from ctx into sbinfo */
5128 memcpy(&sbinfo->qlimits, &ctx->qlimits,
5129 sizeof(struct shmem_quota_limits));
5130
5131 if (shmem_enable_quotas(sb, ctx->quota_types))
5132 goto failed;
5133 }
5134 #endif /* CONFIG_TMPFS_QUOTA */
5135
5136 inode = shmem_get_inode(&nop_mnt_idmap, sb, NULL,
5137 S_IFDIR | sbinfo->mode, 0,
5138 mk_vma_flags(VMA_NORESERVE_BIT));
5139 if (IS_ERR(inode)) {
5140 error = PTR_ERR(inode);
5141 goto failed;
5142 }
5143 inode->i_uid = sbinfo->uid;
5144 inode->i_gid = sbinfo->gid;
5145 sb->s_root = d_make_root(inode);
5146 if (!sb->s_root)
5147 goto failed;
5148 return 0;
5149
5150 failed:
5151 shmem_put_super(sb);
5152 return error;
5153 }
5154
shmem_get_tree(struct fs_context * fc)5155 static int shmem_get_tree(struct fs_context *fc)
5156 {
5157 return get_tree_nodev(fc, shmem_fill_super);
5158 }
5159
shmem_free_fc(struct fs_context * fc)5160 static void shmem_free_fc(struct fs_context *fc)
5161 {
5162 struct shmem_options *ctx = fc->fs_private;
5163
5164 if (ctx) {
5165 mpol_put(ctx->mpol);
5166 kfree(ctx);
5167 }
5168 }
5169
5170 static const struct fs_context_operations shmem_fs_context_ops = {
5171 .free = shmem_free_fc,
5172 .get_tree = shmem_get_tree,
5173 #ifdef CONFIG_TMPFS
5174 .parse_monolithic = shmem_parse_monolithic,
5175 .parse_param = shmem_parse_one,
5176 .reconfigure = shmem_reconfigure,
5177 #endif
5178 };
5179
5180 static struct kmem_cache *shmem_inode_cachep __ro_after_init;
5181
shmem_alloc_inode(struct super_block * sb)5182 static struct inode *shmem_alloc_inode(struct super_block *sb)
5183 {
5184 struct shmem_inode_info *info;
5185 info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL);
5186 if (!info)
5187 return NULL;
5188 return &info->vfs_inode;
5189 }
5190
shmem_free_in_core_inode(struct inode * inode)5191 static void shmem_free_in_core_inode(struct inode *inode)
5192 {
5193 if (S_ISLNK(inode->i_mode))
5194 kfree(inode->i_link);
5195 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
5196 }
5197
shmem_destroy_inode(struct inode * inode)5198 static void shmem_destroy_inode(struct inode *inode)
5199 {
5200 if (S_ISREG(inode->i_mode))
5201 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
5202 if (S_ISDIR(inode->i_mode))
5203 simple_offset_destroy(shmem_get_offset_ctx(inode));
5204 }
5205
shmem_init_inode(void * foo)5206 static void shmem_init_inode(void *foo)
5207 {
5208 struct shmem_inode_info *info = foo;
5209 inode_init_once(&info->vfs_inode);
5210 }
5211
shmem_init_inodecache(void)5212 static void __init shmem_init_inodecache(void)
5213 {
5214 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
5215 sizeof(struct shmem_inode_info),
5216 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
5217 }
5218
shmem_destroy_inodecache(void)5219 static void __init shmem_destroy_inodecache(void)
5220 {
5221 kmem_cache_destroy(shmem_inode_cachep);
5222 }
5223
5224 /* Keep the page in page cache instead of truncating it */
shmem_error_remove_folio(struct address_space * mapping,struct folio * folio)5225 static int shmem_error_remove_folio(struct address_space *mapping,
5226 struct folio *folio)
5227 {
5228 return 0;
5229 }
5230
5231 static const struct address_space_operations shmem_aops = {
5232 .dirty_folio = noop_dirty_folio,
5233 #ifdef CONFIG_TMPFS
5234 .write_begin = shmem_write_begin,
5235 .write_end = shmem_write_end,
5236 #endif
5237 #ifdef CONFIG_MIGRATION
5238 .migrate_folio = migrate_folio,
5239 #endif
5240 .error_remove_folio = shmem_error_remove_folio,
5241 };
5242
5243 static const struct file_operations shmem_file_operations = {
5244 .mmap_prepare = shmem_mmap_prepare,
5245 .open = shmem_file_open,
5246 .get_unmapped_area = shmem_get_unmapped_area,
5247 #ifdef CONFIG_TMPFS
5248 .llseek = shmem_file_llseek,
5249 .read_iter = shmem_file_read_iter,
5250 .write_iter = shmem_file_write_iter,
5251 .fsync = noop_fsync,
5252 .splice_read = shmem_file_splice_read,
5253 .splice_write = iter_file_splice_write,
5254 .fallocate = shmem_fallocate,
5255 .setlease = generic_setlease,
5256 #endif
5257 };
5258
5259 static const struct inode_operations shmem_inode_operations = {
5260 .getattr = shmem_getattr,
5261 .setattr = shmem_setattr,
5262 #ifdef CONFIG_TMPFS_XATTR
5263 .listxattr = shmem_listxattr,
5264 .set_acl = simple_set_acl,
5265 .fileattr_get = shmem_fileattr_get,
5266 .fileattr_set = shmem_fileattr_set,
5267 #endif
5268 };
5269
5270 static const struct inode_operations shmem_dir_inode_operations = {
5271 #ifdef CONFIG_TMPFS
5272 .getattr = shmem_getattr,
5273 .create = shmem_create,
5274 .lookup = simple_lookup,
5275 .link = shmem_link,
5276 .unlink = shmem_unlink,
5277 .symlink = shmem_symlink,
5278 .mkdir = shmem_mkdir,
5279 .rmdir = shmem_rmdir,
5280 .mknod = shmem_mknod,
5281 .rename = shmem_rename2,
5282 .tmpfile = shmem_tmpfile,
5283 .get_offset_ctx = shmem_get_offset_ctx,
5284 #endif
5285 #ifdef CONFIG_TMPFS_XATTR
5286 .listxattr = shmem_listxattr,
5287 .fileattr_get = shmem_fileattr_get,
5288 .fileattr_set = shmem_fileattr_set,
5289 #endif
5290 #ifdef CONFIG_TMPFS_POSIX_ACL
5291 .setattr = shmem_setattr,
5292 .set_acl = simple_set_acl,
5293 #endif
5294 };
5295
5296 static const struct inode_operations shmem_special_inode_operations = {
5297 .getattr = shmem_getattr,
5298 #ifdef CONFIG_TMPFS_XATTR
5299 .listxattr = shmem_listxattr,
5300 #endif
5301 #ifdef CONFIG_TMPFS_POSIX_ACL
5302 .setattr = shmem_setattr,
5303 .set_acl = simple_set_acl,
5304 #endif
5305 };
5306
5307 static const struct super_operations shmem_ops = {
5308 .alloc_inode = shmem_alloc_inode,
5309 .free_inode = shmem_free_in_core_inode,
5310 .destroy_inode = shmem_destroy_inode,
5311 #ifdef CONFIG_TMPFS
5312 .statfs = shmem_statfs,
5313 .show_options = shmem_show_options,
5314 #endif
5315 #ifdef CONFIG_TMPFS_QUOTA
5316 .get_dquots = shmem_get_dquots,
5317 #endif
5318 .evict_inode = shmem_evict_inode,
5319 .drop_inode = inode_just_drop,
5320 .put_super = shmem_put_super,
5321 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5322 .nr_cached_objects = shmem_unused_huge_count,
5323 .free_cached_objects = shmem_unused_huge_scan,
5324 #endif
5325 };
5326
5327 static const struct vm_operations_struct shmem_vm_ops = {
5328 .fault = shmem_fault,
5329 .map_pages = filemap_map_pages,
5330 #ifdef CONFIG_NUMA
5331 .set_policy = shmem_set_policy,
5332 .get_policy = shmem_get_policy,
5333 #endif
5334 };
5335
5336 static const struct vm_operations_struct shmem_anon_vm_ops = {
5337 .fault = shmem_fault,
5338 .map_pages = filemap_map_pages,
5339 #ifdef CONFIG_NUMA
5340 .set_policy = shmem_set_policy,
5341 .get_policy = shmem_get_policy,
5342 #endif
5343 };
5344
shmem_init_fs_context(struct fs_context * fc)5345 int shmem_init_fs_context(struct fs_context *fc)
5346 {
5347 struct shmem_options *ctx;
5348
5349 ctx = kzalloc_obj(struct shmem_options);
5350 if (!ctx)
5351 return -ENOMEM;
5352
5353 ctx->mode = 0777 | S_ISVTX;
5354 ctx->uid = current_fsuid();
5355 ctx->gid = current_fsgid();
5356
5357 #if IS_ENABLED(CONFIG_UNICODE)
5358 ctx->encoding = NULL;
5359 #endif
5360
5361 fc->fs_private = ctx;
5362 fc->ops = &shmem_fs_context_ops;
5363 #ifdef CONFIG_TMPFS
5364 fc->sb_flags |= SB_I_VERSION;
5365 #endif
5366 return 0;
5367 }
5368
5369 static struct file_system_type shmem_fs_type = {
5370 .owner = THIS_MODULE,
5371 .name = "tmpfs",
5372 .init_fs_context = shmem_init_fs_context,
5373 #ifdef CONFIG_TMPFS
5374 .parameters = shmem_fs_parameters,
5375 #endif
5376 .kill_sb = kill_anon_super,
5377 .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME,
5378 };
5379
5380 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5381
5382 #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \
5383 { \
5384 .attr = { .name = __stringify(_name), .mode = _mode }, \
5385 .show = _show, \
5386 .store = _store, \
5387 }
5388
5389 #define TMPFS_ATTR_W(_name, _store) \
5390 static struct kobj_attribute tmpfs_attr_##_name = \
5391 __INIT_KOBJ_ATTR(_name, 0200, NULL, _store)
5392
5393 #define TMPFS_ATTR_RW(_name, _show, _store) \
5394 static struct kobj_attribute tmpfs_attr_##_name = \
5395 __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
5396
5397 #define TMPFS_ATTR_RO(_name, _show) \
5398 static struct kobj_attribute tmpfs_attr_##_name = \
5399 __INIT_KOBJ_ATTR(_name, 0444, _show, NULL)
5400
5401 #if IS_ENABLED(CONFIG_UNICODE)
casefold_show(struct kobject * kobj,struct kobj_attribute * a,char * buf)5402 static ssize_t casefold_show(struct kobject *kobj, struct kobj_attribute *a,
5403 char *buf)
5404 {
5405 return sysfs_emit(buf, "supported\n");
5406 }
5407 TMPFS_ATTR_RO(casefold, casefold_show);
5408 #endif
5409
5410 static struct attribute *tmpfs_attributes[] = {
5411 #if IS_ENABLED(CONFIG_UNICODE)
5412 &tmpfs_attr_casefold.attr,
5413 #endif
5414 NULL
5415 };
5416
5417 static const struct attribute_group tmpfs_attribute_group = {
5418 .attrs = tmpfs_attributes,
5419 .name = "features"
5420 };
5421
5422 static struct kobject *tmpfs_kobj;
5423
tmpfs_sysfs_init(void)5424 static int __init tmpfs_sysfs_init(void)
5425 {
5426 int ret;
5427
5428 tmpfs_kobj = kobject_create_and_add("tmpfs", fs_kobj);
5429 if (!tmpfs_kobj)
5430 return -ENOMEM;
5431
5432 ret = sysfs_create_group(tmpfs_kobj, &tmpfs_attribute_group);
5433 if (ret)
5434 kobject_put(tmpfs_kobj);
5435
5436 return ret;
5437 }
5438 #endif /* CONFIG_SYSFS && CONFIG_TMPFS */
5439
shmem_init(void)5440 void __init shmem_init(void)
5441 {
5442 int error;
5443
5444 shmem_init_inodecache();
5445
5446 #ifdef CONFIG_TMPFS_QUOTA
5447 register_quota_format(&shmem_quota_format);
5448 #endif
5449
5450 error = register_filesystem(&shmem_fs_type);
5451 if (error) {
5452 pr_err("Could not register tmpfs\n");
5453 goto out2;
5454 }
5455
5456 shm_mnt = kern_mount(&shmem_fs_type);
5457 if (IS_ERR(shm_mnt)) {
5458 error = PTR_ERR(shm_mnt);
5459 pr_err("Could not kern_mount tmpfs\n");
5460 goto out1;
5461 }
5462
5463 #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
5464 error = tmpfs_sysfs_init();
5465 if (error) {
5466 pr_err("Could not init tmpfs sysfs\n");
5467 goto out1;
5468 }
5469 #endif
5470
5471 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5472 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
5473 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
5474 else
5475 shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
5476
5477 /*
5478 * Default to setting PMD-sized THP to inherit the global setting and
5479 * disable all other multi-size THPs.
5480 */
5481 if (!shmem_orders_configured)
5482 huge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER);
5483 #endif
5484 return;
5485
5486 out1:
5487 unregister_filesystem(&shmem_fs_type);
5488 out2:
5489 #ifdef CONFIG_TMPFS_QUOTA
5490 unregister_quota_format(&shmem_quota_format);
5491 #endif
5492 shmem_destroy_inodecache();
5493 shm_mnt = ERR_PTR(error);
5494 }
5495
5496 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
shmem_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5497 static ssize_t shmem_enabled_show(struct kobject *kobj,
5498 struct kobj_attribute *attr, char *buf)
5499 {
5500 static const int values[] = {
5501 SHMEM_HUGE_ALWAYS,
5502 SHMEM_HUGE_WITHIN_SIZE,
5503 SHMEM_HUGE_ADVISE,
5504 SHMEM_HUGE_NEVER,
5505 SHMEM_HUGE_DENY,
5506 SHMEM_HUGE_FORCE,
5507 };
5508 int len = 0;
5509 int i;
5510
5511 for (i = 0; i < ARRAY_SIZE(values); i++) {
5512 len += sysfs_emit_at(buf, len,
5513 shmem_huge == values[i] ? "%s[%s]" : "%s%s",
5514 i ? " " : "", shmem_format_huge(values[i]));
5515 }
5516 len += sysfs_emit_at(buf, len, "\n");
5517
5518 return len;
5519 }
5520
shmem_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)5521 static ssize_t shmem_enabled_store(struct kobject *kobj,
5522 struct kobj_attribute *attr, const char *buf, size_t count)
5523 {
5524 char tmp[16];
5525 int huge, err;
5526
5527 if (count + 1 > sizeof(tmp))
5528 return -EINVAL;
5529 memcpy(tmp, buf, count);
5530 tmp[count] = '\0';
5531 if (count && tmp[count - 1] == '\n')
5532 tmp[count - 1] = '\0';
5533
5534 huge = shmem_parse_huge(tmp);
5535 if (huge == -EINVAL)
5536 return huge;
5537
5538 shmem_huge = huge;
5539 if (shmem_huge > SHMEM_HUGE_DENY)
5540 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
5541
5542 err = start_stop_khugepaged();
5543 return err ? err : count;
5544 }
5545
5546 struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);
5547 static DEFINE_SPINLOCK(huge_shmem_orders_lock);
5548
thpsize_shmem_enabled_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)5549 static ssize_t thpsize_shmem_enabled_show(struct kobject *kobj,
5550 struct kobj_attribute *attr, char *buf)
5551 {
5552 int order = to_thpsize(kobj)->order;
5553 const char *output;
5554
5555 if (test_bit(order, &huge_shmem_orders_always))
5556 output = "[always] inherit within_size advise never";
5557 else if (test_bit(order, &huge_shmem_orders_inherit))
5558 output = "always [inherit] within_size advise never";
5559 else if (test_bit(order, &huge_shmem_orders_within_size))
5560 output = "always inherit [within_size] advise never";
5561 else if (test_bit(order, &huge_shmem_orders_madvise))
5562 output = "always inherit within_size [advise] never";
5563 else
5564 output = "always inherit within_size advise [never]";
5565
5566 return sysfs_emit(buf, "%s\n", output);
5567 }
5568
thpsize_shmem_enabled_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)5569 static ssize_t thpsize_shmem_enabled_store(struct kobject *kobj,
5570 struct kobj_attribute *attr,
5571 const char *buf, size_t count)
5572 {
5573 int order = to_thpsize(kobj)->order;
5574 ssize_t ret = count;
5575
5576 if (sysfs_streq(buf, "always")) {
5577 spin_lock(&huge_shmem_orders_lock);
5578 clear_bit(order, &huge_shmem_orders_inherit);
5579 clear_bit(order, &huge_shmem_orders_madvise);
5580 clear_bit(order, &huge_shmem_orders_within_size);
5581 set_bit(order, &huge_shmem_orders_always);
5582 spin_unlock(&huge_shmem_orders_lock);
5583 } else if (sysfs_streq(buf, "inherit")) {
5584 /* Do not override huge allocation policy with non-PMD sized mTHP */
5585 if (shmem_huge == SHMEM_HUGE_FORCE &&
5586 order != HPAGE_PMD_ORDER)
5587 return -EINVAL;
5588
5589 spin_lock(&huge_shmem_orders_lock);
5590 clear_bit(order, &huge_shmem_orders_always);
5591 clear_bit(order, &huge_shmem_orders_madvise);
5592 clear_bit(order, &huge_shmem_orders_within_size);
5593 set_bit(order, &huge_shmem_orders_inherit);
5594 spin_unlock(&huge_shmem_orders_lock);
5595 } else if (sysfs_streq(buf, "within_size")) {
5596 spin_lock(&huge_shmem_orders_lock);
5597 clear_bit(order, &huge_shmem_orders_always);
5598 clear_bit(order, &huge_shmem_orders_inherit);
5599 clear_bit(order, &huge_shmem_orders_madvise);
5600 set_bit(order, &huge_shmem_orders_within_size);
5601 spin_unlock(&huge_shmem_orders_lock);
5602 } else if (sysfs_streq(buf, "advise")) {
5603 spin_lock(&huge_shmem_orders_lock);
5604 clear_bit(order, &huge_shmem_orders_always);
5605 clear_bit(order, &huge_shmem_orders_inherit);
5606 clear_bit(order, &huge_shmem_orders_within_size);
5607 set_bit(order, &huge_shmem_orders_madvise);
5608 spin_unlock(&huge_shmem_orders_lock);
5609 } else if (sysfs_streq(buf, "never")) {
5610 spin_lock(&huge_shmem_orders_lock);
5611 clear_bit(order, &huge_shmem_orders_always);
5612 clear_bit(order, &huge_shmem_orders_inherit);
5613 clear_bit(order, &huge_shmem_orders_within_size);
5614 clear_bit(order, &huge_shmem_orders_madvise);
5615 spin_unlock(&huge_shmem_orders_lock);
5616 } else {
5617 ret = -EINVAL;
5618 }
5619
5620 if (ret > 0) {
5621 int err = start_stop_khugepaged();
5622
5623 if (err)
5624 ret = err;
5625 }
5626 return ret;
5627 }
5628
5629 struct kobj_attribute thpsize_shmem_enabled_attr =
5630 __ATTR(shmem_enabled, 0644, thpsize_shmem_enabled_show, thpsize_shmem_enabled_store);
5631 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
5632
5633 #if defined(CONFIG_TRANSPARENT_HUGEPAGE)
5634
setup_transparent_hugepage_shmem(char * str)5635 static int __init setup_transparent_hugepage_shmem(char *str)
5636 {
5637 int huge;
5638
5639 huge = shmem_parse_huge(str);
5640 if (huge == -EINVAL) {
5641 pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
5642 return huge;
5643 }
5644
5645 shmem_huge = huge;
5646 return 1;
5647 }
5648 __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem);
5649
setup_transparent_hugepage_tmpfs(char * str)5650 static int __init setup_transparent_hugepage_tmpfs(char *str)
5651 {
5652 int huge;
5653
5654 huge = shmem_parse_huge(str);
5655 if (huge < 0) {
5656 pr_warn("transparent_hugepage_tmpfs= cannot parse, ignored\n");
5657 return huge;
5658 }
5659
5660 tmpfs_huge = huge;
5661 return 1;
5662 }
5663 __setup("transparent_hugepage_tmpfs=", setup_transparent_hugepage_tmpfs);
5664
5665 static char str_dup[PAGE_SIZE] __initdata;
setup_thp_shmem(char * str)5666 static int __init setup_thp_shmem(char *str)
5667 {
5668 char *token, *range, *policy, *subtoken;
5669 unsigned long always, inherit, madvise, within_size;
5670 char *start_size, *end_size;
5671 int start, end, nr;
5672 char *p;
5673
5674 if (!str || strlen(str) + 1 > PAGE_SIZE)
5675 goto err;
5676 strscpy(str_dup, str);
5677
5678 always = huge_shmem_orders_always;
5679 inherit = huge_shmem_orders_inherit;
5680 madvise = huge_shmem_orders_madvise;
5681 within_size = huge_shmem_orders_within_size;
5682 p = str_dup;
5683 while ((token = strsep(&p, ";")) != NULL) {
5684 range = strsep(&token, ":");
5685 policy = token;
5686
5687 if (!policy)
5688 goto err;
5689
5690 while ((subtoken = strsep(&range, ",")) != NULL) {
5691 if (strchr(subtoken, '-')) {
5692 start_size = strsep(&subtoken, "-");
5693 end_size = subtoken;
5694
5695 start = get_order_from_str(start_size,
5696 THP_ORDERS_ALL_FILE_DEFAULT);
5697 end = get_order_from_str(end_size,
5698 THP_ORDERS_ALL_FILE_DEFAULT);
5699 } else {
5700 start_size = end_size = subtoken;
5701 start = end = get_order_from_str(subtoken,
5702 THP_ORDERS_ALL_FILE_DEFAULT);
5703 }
5704
5705 if (start < 0) {
5706 pr_err("invalid size %s in thp_shmem boot parameter\n",
5707 start_size);
5708 goto err;
5709 }
5710
5711 if (end < 0) {
5712 pr_err("invalid size %s in thp_shmem boot parameter\n",
5713 end_size);
5714 goto err;
5715 }
5716
5717 if (start > end)
5718 goto err;
5719
5720 nr = end - start + 1;
5721 if (!strcmp(policy, "always")) {
5722 bitmap_set(&always, start, nr);
5723 bitmap_clear(&inherit, start, nr);
5724 bitmap_clear(&madvise, start, nr);
5725 bitmap_clear(&within_size, start, nr);
5726 } else if (!strcmp(policy, "advise")) {
5727 bitmap_set(&madvise, start, nr);
5728 bitmap_clear(&inherit, start, nr);
5729 bitmap_clear(&always, start, nr);
5730 bitmap_clear(&within_size, start, nr);
5731 } else if (!strcmp(policy, "inherit")) {
5732 bitmap_set(&inherit, start, nr);
5733 bitmap_clear(&madvise, start, nr);
5734 bitmap_clear(&always, start, nr);
5735 bitmap_clear(&within_size, start, nr);
5736 } else if (!strcmp(policy, "within_size")) {
5737 bitmap_set(&within_size, start, nr);
5738 bitmap_clear(&inherit, start, nr);
5739 bitmap_clear(&madvise, start, nr);
5740 bitmap_clear(&always, start, nr);
5741 } else if (!strcmp(policy, "never")) {
5742 bitmap_clear(&inherit, start, nr);
5743 bitmap_clear(&madvise, start, nr);
5744 bitmap_clear(&always, start, nr);
5745 bitmap_clear(&within_size, start, nr);
5746 } else {
5747 pr_err("invalid policy %s in thp_shmem boot parameter\n", policy);
5748 goto err;
5749 }
5750 }
5751 }
5752
5753 huge_shmem_orders_always = always;
5754 huge_shmem_orders_madvise = madvise;
5755 huge_shmem_orders_inherit = inherit;
5756 huge_shmem_orders_within_size = within_size;
5757 shmem_orders_configured = true;
5758 return 1;
5759
5760 err:
5761 pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str);
5762 return 0;
5763 }
5764 __setup("thp_shmem=", setup_thp_shmem);
5765
5766 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5767
5768 #else /* !CONFIG_SHMEM */
5769
5770 /*
5771 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
5772 *
5773 * This is intended for small system where the benefits of the full
5774 * shmem code (swap-backed and resource-limited) are outweighed by
5775 * their complexity. On systems without swap this code should be
5776 * effectively equivalent, but much lighter weight.
5777 */
5778
5779 static struct file_system_type shmem_fs_type = {
5780 .name = "tmpfs",
5781 .init_fs_context = ramfs_init_fs_context,
5782 .parameters = ramfs_fs_parameters,
5783 .kill_sb = ramfs_kill_sb,
5784 .fs_flags = FS_USERNS_MOUNT,
5785 };
5786
shmem_init(void)5787 void __init shmem_init(void)
5788 {
5789 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
5790
5791 shm_mnt = kern_mount(&shmem_fs_type);
5792 BUG_ON(IS_ERR(shm_mnt));
5793 }
5794
shmem_unuse(unsigned int type)5795 int shmem_unuse(unsigned int type)
5796 {
5797 return 0;
5798 }
5799
shmem_lock(struct file * file,int lock,struct ucounts * ucounts)5800 int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
5801 {
5802 return 0;
5803 }
5804
shmem_unlock_mapping(struct address_space * mapping)5805 void shmem_unlock_mapping(struct address_space *mapping)
5806 {
5807 }
5808
5809 #ifdef CONFIG_MMU
shmem_get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)5810 unsigned long shmem_get_unmapped_area(struct file *file,
5811 unsigned long addr, unsigned long len,
5812 unsigned long pgoff, unsigned long flags)
5813 {
5814 return mm_get_unmapped_area(file, addr, len, pgoff, flags);
5815 }
5816 #endif
5817
shmem_truncate_range(struct inode * inode,loff_t lstart,uoff_t lend)5818 void shmem_truncate_range(struct inode *inode, loff_t lstart, uoff_t lend)
5819 {
5820 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
5821 }
5822 EXPORT_SYMBOL_GPL(shmem_truncate_range);
5823
5824 #define shmem_vm_ops generic_file_vm_ops
5825 #define shmem_anon_vm_ops generic_file_vm_ops
5826 #define shmem_file_operations ramfs_file_operations
5827
shmem_acct_size(unsigned long flags,loff_t size)5828 static inline int shmem_acct_size(unsigned long flags, loff_t size)
5829 {
5830 return 0;
5831 }
5832
shmem_unacct_size(unsigned long flags,loff_t size)5833 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
5834 {
5835 }
5836
shmem_get_inode(struct mnt_idmap * idmap,struct super_block * sb,struct inode * dir,umode_t mode,dev_t dev,vma_flags_t flags)5837 static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap,
5838 struct super_block *sb, struct inode *dir,
5839 umode_t mode, dev_t dev, vma_flags_t flags)
5840 {
5841 struct inode *inode = ramfs_get_inode(sb, dir, mode, dev);
5842 return inode ? inode : ERR_PTR(-ENOSPC);
5843 }
5844
5845 #endif /* CONFIG_SHMEM */
5846
5847 /* common code */
5848
__shmem_file_setup(struct vfsmount * mnt,const char * name,loff_t size,vma_flags_t flags,unsigned int i_flags)5849 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name,
5850 loff_t size, vma_flags_t flags,
5851 unsigned int i_flags)
5852 {
5853 const unsigned long shmem_flags =
5854 vma_flags_test(&flags, VMA_NORESERVE_BIT) ? SHMEM_F_NORESERVE : 0;
5855 struct inode *inode;
5856 struct file *res;
5857
5858 if (IS_ERR(mnt))
5859 return ERR_CAST(mnt);
5860
5861 if (size < 0 || size > MAX_LFS_FILESIZE)
5862 return ERR_PTR(-EINVAL);
5863
5864 if (is_idmapped_mnt(mnt))
5865 return ERR_PTR(-EINVAL);
5866
5867 if (shmem_acct_size(shmem_flags, size))
5868 return ERR_PTR(-ENOMEM);
5869
5870 inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL,
5871 S_IFREG | S_IRWXUGO, 0, flags);
5872 if (IS_ERR(inode)) {
5873 shmem_unacct_size(shmem_flags, size);
5874 return ERR_CAST(inode);
5875 }
5876 inode->i_flags |= i_flags;
5877 inode->i_size = size;
5878 clear_nlink(inode); /* It is unlinked */
5879 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
5880 if (!IS_ERR(res))
5881 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
5882 &shmem_file_operations);
5883 if (IS_ERR(res))
5884 iput(inode);
5885 return res;
5886 }
5887
5888 /**
5889 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
5890 * kernel internal. There will be NO LSM permission checks against the
5891 * underlying inode. So users of this interface must do LSM checks at a
5892 * higher layer. The users are the big_key and shm implementations. LSM
5893 * checks are provided at the key or shm level rather than the inode.
5894 * @name: name for dentry (to be seen in /proc/<pid>/maps)
5895 * @size: size to be set for the file
5896 * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
5897 */
shmem_kernel_file_setup(const char * name,loff_t size,vma_flags_t flags)5898 struct file *shmem_kernel_file_setup(const char *name, loff_t size,
5899 vma_flags_t flags)
5900 {
5901 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
5902 }
5903 EXPORT_SYMBOL_GPL(shmem_kernel_file_setup);
5904
5905 /**
5906 * shmem_file_setup - get an unlinked file living in tmpfs
5907 * @name: name for dentry (to be seen in /proc/<pid>/maps)
5908 * @size: size to be set for the file
5909 * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
5910 */
shmem_file_setup(const char * name,loff_t size,vma_flags_t flags)5911 struct file *shmem_file_setup(const char *name, loff_t size, vma_flags_t flags)
5912 {
5913 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
5914 }
5915 EXPORT_SYMBOL_GPL(shmem_file_setup);
5916
5917 /**
5918 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
5919 * @mnt: the tmpfs mount where the file will be created
5920 * @name: name for dentry (to be seen in /proc/<pid>/maps)
5921 * @size: size to be set for the file
5922 * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
5923 */
shmem_file_setup_with_mnt(struct vfsmount * mnt,const char * name,loff_t size,vma_flags_t flags)5924 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
5925 loff_t size, vma_flags_t flags)
5926 {
5927 return __shmem_file_setup(mnt, name, size, flags, 0);
5928 }
5929 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
5930
__shmem_zero_setup(unsigned long start,unsigned long end,vma_flags_t flags)5931 static struct file *__shmem_zero_setup(unsigned long start, unsigned long end,
5932 vma_flags_t flags)
5933 {
5934 loff_t size = end - start;
5935
5936 /*
5937 * Cloning a new file under mmap_lock leads to a lock ordering conflict
5938 * between XFS directory reading and selinux: since this file is only
5939 * accessible to the user through its mapping, use S_PRIVATE flag to
5940 * bypass file security, in the same way as shmem_kernel_file_setup().
5941 */
5942 return shmem_kernel_file_setup("dev/zero", size, flags);
5943 }
5944
5945 /**
5946 * shmem_zero_setup - setup a shared anonymous mapping
5947 * @vma: the vma to be mmapped is prepared by do_mmap
5948 * Returns: 0 on success, or error
5949 */
shmem_zero_setup(struct vm_area_struct * vma)5950 int shmem_zero_setup(struct vm_area_struct *vma)
5951 {
5952 struct file *file = __shmem_zero_setup(vma->vm_start, vma->vm_end, vma->flags);
5953
5954 if (IS_ERR(file))
5955 return PTR_ERR(file);
5956
5957 if (vma->vm_file)
5958 fput(vma->vm_file);
5959 vma->vm_file = file;
5960 vma->vm_ops = &shmem_anon_vm_ops;
5961
5962 return 0;
5963 }
5964
5965 /**
5966 * shmem_zero_setup_desc - same as shmem_zero_setup, but determined by VMA
5967 * descriptor for convenience.
5968 * @desc: Describes VMA
5969 * Returns: 0 on success, or error
5970 */
shmem_zero_setup_desc(struct vm_area_desc * desc)5971 int shmem_zero_setup_desc(struct vm_area_desc *desc)
5972 {
5973 struct file *file = __shmem_zero_setup(desc->start, desc->end, desc->vma_flags);
5974
5975 if (IS_ERR(file))
5976 return PTR_ERR(file);
5977
5978 desc->vm_file = file;
5979 desc->vm_ops = &shmem_anon_vm_ops;
5980
5981 return 0;
5982 }
5983
5984 /**
5985 * shmem_read_folio_gfp - read into page cache, using specified page allocation flags.
5986 * @mapping: the folio's address_space
5987 * @index: the folio index
5988 * @gfp: the page allocator flags to use if allocating
5989 *
5990 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
5991 * with any new page allocations done using the specified allocation flags.
5992 * But read_cache_page_gfp() uses the ->read_folio() method: which does not
5993 * suit tmpfs, since it may have pages in swapcache, and needs to find those
5994 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
5995 *
5996 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
5997 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
5998 */
shmem_read_folio_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)5999 struct folio *shmem_read_folio_gfp(struct address_space *mapping,
6000 pgoff_t index, gfp_t gfp)
6001 {
6002 #ifdef CONFIG_SHMEM
6003 struct inode *inode = mapping->host;
6004 struct folio *folio;
6005 int error;
6006
6007 error = shmem_get_folio_gfp(inode, index, i_size_read(inode),
6008 &folio, SGP_CACHE, gfp, NULL, NULL);
6009 if (error)
6010 return ERR_PTR(error);
6011
6012 folio_unlock(folio);
6013 return folio;
6014 #else
6015 /*
6016 * The tiny !SHMEM case uses ramfs without swap
6017 */
6018 return mapping_read_folio_gfp(mapping, index, gfp);
6019 #endif
6020 }
6021 EXPORT_SYMBOL_GPL(shmem_read_folio_gfp);
6022
shmem_read_mapping_page_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)6023 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
6024 pgoff_t index, gfp_t gfp)
6025 {
6026 struct folio *folio = shmem_read_folio_gfp(mapping, index, gfp);
6027 struct page *page;
6028
6029 if (IS_ERR(folio))
6030 return &folio->page;
6031
6032 page = folio_file_page(folio, index);
6033 if (PageHWPoison(page)) {
6034 folio_put(folio);
6035 return ERR_PTR(-EIO);
6036 }
6037
6038 return page;
6039 }
6040 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
6041