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