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