ACPI / tables: add DSDT AmlCode new declaration name support
[linux/fpc-iii.git] / mm / shmem.c
blobd44991ea5ed4b7612482525ebaa502457cbf1ead
1 /*
2 * Resizable virtual memory filesystem for Linux.
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
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>
18 * tiny-shmem:
19 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
21 * This file is released under the GPL.
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/mm.h>
32 #include <linux/random.h>
33 #include <linux/sched/signal.h>
34 #include <linux/export.h>
35 #include <linux/swap.h>
36 #include <linux/uio.h>
37 #include <linux/khugepaged.h>
38 #include <linux/hugetlb.h>
40 #include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
42 static struct vfsmount *shm_mnt;
44 #ifdef CONFIG_SHMEM
46 * This virtual memory filesystem is heavily based on the ramfs. It
47 * extends ramfs by the ability to use swap and honor resource limits
48 * which makes it a completely usable filesystem.
51 #include <linux/xattr.h>
52 #include <linux/exportfs.h>
53 #include <linux/posix_acl.h>
54 #include <linux/posix_acl_xattr.h>
55 #include <linux/mman.h>
56 #include <linux/string.h>
57 #include <linux/slab.h>
58 #include <linux/backing-dev.h>
59 #include <linux/shmem_fs.h>
60 #include <linux/writeback.h>
61 #include <linux/blkdev.h>
62 #include <linux/pagevec.h>
63 #include <linux/percpu_counter.h>
64 #include <linux/falloc.h>
65 #include <linux/splice.h>
66 #include <linux/security.h>
67 #include <linux/swapops.h>
68 #include <linux/mempolicy.h>
69 #include <linux/namei.h>
70 #include <linux/ctype.h>
71 #include <linux/migrate.h>
72 #include <linux/highmem.h>
73 #include <linux/seq_file.h>
74 #include <linux/magic.h>
75 #include <linux/syscalls.h>
76 #include <linux/fcntl.h>
77 #include <uapi/linux/memfd.h>
78 #include <linux/userfaultfd_k.h>
79 #include <linux/rmap.h>
80 #include <linux/uuid.h>
82 #include <linux/uaccess.h>
83 #include <asm/pgtable.h>
85 #include "internal.h"
87 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
88 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
90 /* Pretend that each entry is of this size in directory's i_size */
91 #define BOGO_DIRENT_SIZE 20
93 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
94 #define SHORT_SYMLINK_LEN 128
97 * shmem_fallocate communicates with shmem_fault or shmem_writepage via
98 * inode->i_private (with i_mutex making sure that it has only one user at
99 * a time): we would prefer not to enlarge the shmem inode just for that.
101 struct shmem_falloc {
102 wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
103 pgoff_t start; /* start of range currently being fallocated */
104 pgoff_t next; /* the next page offset to be fallocated */
105 pgoff_t nr_falloced; /* how many new pages have been fallocated */
106 pgoff_t nr_unswapped; /* how often writepage refused to swap out */
109 #ifdef CONFIG_TMPFS
110 static unsigned long shmem_default_max_blocks(void)
112 return totalram_pages / 2;
115 static unsigned long shmem_default_max_inodes(void)
117 return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
119 #endif
121 static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
122 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
123 struct shmem_inode_info *info, pgoff_t index);
124 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
125 struct page **pagep, enum sgp_type sgp,
126 gfp_t gfp, struct vm_area_struct *vma,
127 struct vm_fault *vmf, vm_fault_t *fault_type);
129 int shmem_getpage(struct inode *inode, pgoff_t index,
130 struct page **pagep, enum sgp_type sgp)
132 return shmem_getpage_gfp(inode, index, pagep, sgp,
133 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
136 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
138 return sb->s_fs_info;
142 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
143 * for shared memory and for shared anonymous (/dev/zero) mappings
144 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
145 * consistent with the pre-accounting of private mappings ...
147 static inline int shmem_acct_size(unsigned long flags, loff_t size)
149 return (flags & VM_NORESERVE) ?
150 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
153 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
155 if (!(flags & VM_NORESERVE))
156 vm_unacct_memory(VM_ACCT(size));
159 static inline int shmem_reacct_size(unsigned long flags,
160 loff_t oldsize, loff_t newsize)
162 if (!(flags & VM_NORESERVE)) {
163 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
164 return security_vm_enough_memory_mm(current->mm,
165 VM_ACCT(newsize) - VM_ACCT(oldsize));
166 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
167 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
169 return 0;
173 * ... whereas tmpfs objects are accounted incrementally as
174 * pages are allocated, in order to allow large sparse files.
175 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
176 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
178 static inline int shmem_acct_block(unsigned long flags, long pages)
180 if (!(flags & VM_NORESERVE))
181 return 0;
183 return security_vm_enough_memory_mm(current->mm,
184 pages * VM_ACCT(PAGE_SIZE));
187 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
189 if (flags & VM_NORESERVE)
190 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
193 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
195 struct shmem_inode_info *info = SHMEM_I(inode);
196 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
198 if (shmem_acct_block(info->flags, pages))
199 return false;
201 if (sbinfo->max_blocks) {
202 if (percpu_counter_compare(&sbinfo->used_blocks,
203 sbinfo->max_blocks - pages) > 0)
204 goto unacct;
205 percpu_counter_add(&sbinfo->used_blocks, pages);
208 return true;
210 unacct:
211 shmem_unacct_blocks(info->flags, pages);
212 return false;
215 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
217 struct shmem_inode_info *info = SHMEM_I(inode);
218 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
220 if (sbinfo->max_blocks)
221 percpu_counter_sub(&sbinfo->used_blocks, pages);
222 shmem_unacct_blocks(info->flags, pages);
225 static const struct super_operations shmem_ops;
226 static const struct address_space_operations shmem_aops;
227 static const struct file_operations shmem_file_operations;
228 static const struct inode_operations shmem_inode_operations;
229 static const struct inode_operations shmem_dir_inode_operations;
230 static const struct inode_operations shmem_special_inode_operations;
231 static const struct vm_operations_struct shmem_vm_ops;
232 static struct file_system_type shmem_fs_type;
234 bool vma_is_shmem(struct vm_area_struct *vma)
236 return vma->vm_ops == &shmem_vm_ops;
239 static LIST_HEAD(shmem_swaplist);
240 static DEFINE_MUTEX(shmem_swaplist_mutex);
242 static int shmem_reserve_inode(struct super_block *sb)
244 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
245 if (sbinfo->max_inodes) {
246 spin_lock(&sbinfo->stat_lock);
247 if (!sbinfo->free_inodes) {
248 spin_unlock(&sbinfo->stat_lock);
249 return -ENOSPC;
251 sbinfo->free_inodes--;
252 spin_unlock(&sbinfo->stat_lock);
254 return 0;
257 static void shmem_free_inode(struct super_block *sb)
259 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
260 if (sbinfo->max_inodes) {
261 spin_lock(&sbinfo->stat_lock);
262 sbinfo->free_inodes++;
263 spin_unlock(&sbinfo->stat_lock);
268 * shmem_recalc_inode - recalculate the block usage of an inode
269 * @inode: inode to recalc
271 * We have to calculate the free blocks since the mm can drop
272 * undirtied hole pages behind our back.
274 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
275 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
277 * It has to be called with the spinlock held.
279 static void shmem_recalc_inode(struct inode *inode)
281 struct shmem_inode_info *info = SHMEM_I(inode);
282 long freed;
284 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
285 if (freed > 0) {
286 info->alloced -= freed;
287 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
288 shmem_inode_unacct_blocks(inode, freed);
292 bool shmem_charge(struct inode *inode, long pages)
294 struct shmem_inode_info *info = SHMEM_I(inode);
295 unsigned long flags;
297 if (!shmem_inode_acct_block(inode, pages))
298 return false;
300 spin_lock_irqsave(&info->lock, flags);
301 info->alloced += pages;
302 inode->i_blocks += pages * BLOCKS_PER_PAGE;
303 shmem_recalc_inode(inode);
304 spin_unlock_irqrestore(&info->lock, flags);
305 inode->i_mapping->nrpages += pages;
307 return true;
310 void shmem_uncharge(struct inode *inode, long pages)
312 struct shmem_inode_info *info = SHMEM_I(inode);
313 unsigned long flags;
315 spin_lock_irqsave(&info->lock, flags);
316 info->alloced -= pages;
317 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
318 shmem_recalc_inode(inode);
319 spin_unlock_irqrestore(&info->lock, flags);
321 shmem_inode_unacct_blocks(inode, pages);
325 * Replace item expected in xarray by a new item, while holding xa_lock.
327 static int shmem_replace_entry(struct address_space *mapping,
328 pgoff_t index, void *expected, void *replacement)
330 XA_STATE(xas, &mapping->i_pages, index);
331 void *item;
333 VM_BUG_ON(!expected);
334 VM_BUG_ON(!replacement);
335 item = xas_load(&xas);
336 if (item != expected)
337 return -ENOENT;
338 xas_store(&xas, replacement);
339 return 0;
343 * Sometimes, before we decide whether to proceed or to fail, we must check
344 * that an entry was not already brought back from swap by a racing thread.
346 * Checking page is not enough: by the time a SwapCache page is locked, it
347 * might be reused, and again be SwapCache, using the same swap as before.
349 static bool shmem_confirm_swap(struct address_space *mapping,
350 pgoff_t index, swp_entry_t swap)
352 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
356 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
358 * SHMEM_HUGE_NEVER:
359 * disables huge pages for the mount;
360 * SHMEM_HUGE_ALWAYS:
361 * enables huge pages for the mount;
362 * SHMEM_HUGE_WITHIN_SIZE:
363 * only allocate huge pages if the page will be fully within i_size,
364 * also respect fadvise()/madvise() hints;
365 * SHMEM_HUGE_ADVISE:
366 * only allocate huge pages if requested with fadvise()/madvise();
369 #define SHMEM_HUGE_NEVER 0
370 #define SHMEM_HUGE_ALWAYS 1
371 #define SHMEM_HUGE_WITHIN_SIZE 2
372 #define SHMEM_HUGE_ADVISE 3
375 * Special values.
376 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
378 * SHMEM_HUGE_DENY:
379 * disables huge on shm_mnt and all mounts, for emergency use;
380 * SHMEM_HUGE_FORCE:
381 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
384 #define SHMEM_HUGE_DENY (-1)
385 #define SHMEM_HUGE_FORCE (-2)
387 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
388 /* ifdef here to avoid bloating shmem.o when not necessary */
390 static int shmem_huge __read_mostly;
392 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
393 static int shmem_parse_huge(const char *str)
395 if (!strcmp(str, "never"))
396 return SHMEM_HUGE_NEVER;
397 if (!strcmp(str, "always"))
398 return SHMEM_HUGE_ALWAYS;
399 if (!strcmp(str, "within_size"))
400 return SHMEM_HUGE_WITHIN_SIZE;
401 if (!strcmp(str, "advise"))
402 return SHMEM_HUGE_ADVISE;
403 if (!strcmp(str, "deny"))
404 return SHMEM_HUGE_DENY;
405 if (!strcmp(str, "force"))
406 return SHMEM_HUGE_FORCE;
407 return -EINVAL;
410 static const char *shmem_format_huge(int huge)
412 switch (huge) {
413 case SHMEM_HUGE_NEVER:
414 return "never";
415 case SHMEM_HUGE_ALWAYS:
416 return "always";
417 case SHMEM_HUGE_WITHIN_SIZE:
418 return "within_size";
419 case SHMEM_HUGE_ADVISE:
420 return "advise";
421 case SHMEM_HUGE_DENY:
422 return "deny";
423 case SHMEM_HUGE_FORCE:
424 return "force";
425 default:
426 VM_BUG_ON(1);
427 return "bad_val";
430 #endif
432 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
433 struct shrink_control *sc, unsigned long nr_to_split)
435 LIST_HEAD(list), *pos, *next;
436 LIST_HEAD(to_remove);
437 struct inode *inode;
438 struct shmem_inode_info *info;
439 struct page *page;
440 unsigned long batch = sc ? sc->nr_to_scan : 128;
441 int removed = 0, split = 0;
443 if (list_empty(&sbinfo->shrinklist))
444 return SHRINK_STOP;
446 spin_lock(&sbinfo->shrinklist_lock);
447 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
448 info = list_entry(pos, struct shmem_inode_info, shrinklist);
450 /* pin the inode */
451 inode = igrab(&info->vfs_inode);
453 /* inode is about to be evicted */
454 if (!inode) {
455 list_del_init(&info->shrinklist);
456 removed++;
457 goto next;
460 /* Check if there's anything to gain */
461 if (round_up(inode->i_size, PAGE_SIZE) ==
462 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
463 list_move(&info->shrinklist, &to_remove);
464 removed++;
465 goto next;
468 list_move(&info->shrinklist, &list);
469 next:
470 if (!--batch)
471 break;
473 spin_unlock(&sbinfo->shrinklist_lock);
475 list_for_each_safe(pos, next, &to_remove) {
476 info = list_entry(pos, struct shmem_inode_info, shrinklist);
477 inode = &info->vfs_inode;
478 list_del_init(&info->shrinklist);
479 iput(inode);
482 list_for_each_safe(pos, next, &list) {
483 int ret;
485 info = list_entry(pos, struct shmem_inode_info, shrinklist);
486 inode = &info->vfs_inode;
488 if (nr_to_split && split >= nr_to_split)
489 goto leave;
491 page = find_get_page(inode->i_mapping,
492 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
493 if (!page)
494 goto drop;
496 /* No huge page at the end of the file: nothing to split */
497 if (!PageTransHuge(page)) {
498 put_page(page);
499 goto drop;
503 * Leave the inode on the list if we failed to lock
504 * the page at this time.
506 * Waiting for the lock may lead to deadlock in the
507 * reclaim path.
509 if (!trylock_page(page)) {
510 put_page(page);
511 goto leave;
514 ret = split_huge_page(page);
515 unlock_page(page);
516 put_page(page);
518 /* If split failed leave the inode on the list */
519 if (ret)
520 goto leave;
522 split++;
523 drop:
524 list_del_init(&info->shrinklist);
525 removed++;
526 leave:
527 iput(inode);
530 spin_lock(&sbinfo->shrinklist_lock);
531 list_splice_tail(&list, &sbinfo->shrinklist);
532 sbinfo->shrinklist_len -= removed;
533 spin_unlock(&sbinfo->shrinklist_lock);
535 return split;
538 static long shmem_unused_huge_scan(struct super_block *sb,
539 struct shrink_control *sc)
541 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
543 if (!READ_ONCE(sbinfo->shrinklist_len))
544 return SHRINK_STOP;
546 return shmem_unused_huge_shrink(sbinfo, sc, 0);
549 static long shmem_unused_huge_count(struct super_block *sb,
550 struct shrink_control *sc)
552 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
553 return READ_ONCE(sbinfo->shrinklist_len);
555 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
557 #define shmem_huge SHMEM_HUGE_DENY
559 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
560 struct shrink_control *sc, unsigned long nr_to_split)
562 return 0;
564 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
566 static inline bool is_huge_enabled(struct shmem_sb_info *sbinfo)
568 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
569 (shmem_huge == SHMEM_HUGE_FORCE || sbinfo->huge) &&
570 shmem_huge != SHMEM_HUGE_DENY)
571 return true;
572 return false;
576 * Like add_to_page_cache_locked, but error if expected item has gone.
578 static int shmem_add_to_page_cache(struct page *page,
579 struct address_space *mapping,
580 pgoff_t index, void *expected, gfp_t gfp)
582 XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
583 unsigned long i = 0;
584 unsigned long nr = 1UL << compound_order(page);
586 VM_BUG_ON_PAGE(PageTail(page), page);
587 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
588 VM_BUG_ON_PAGE(!PageLocked(page), page);
589 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
590 VM_BUG_ON(expected && PageTransHuge(page));
592 page_ref_add(page, nr);
593 page->mapping = mapping;
594 page->index = index;
596 do {
597 void *entry;
598 xas_lock_irq(&xas);
599 entry = xas_find_conflict(&xas);
600 if (entry != expected)
601 xas_set_err(&xas, -EEXIST);
602 xas_create_range(&xas);
603 if (xas_error(&xas))
604 goto unlock;
605 next:
606 xas_store(&xas, page + i);
607 if (++i < nr) {
608 xas_next(&xas);
609 goto next;
611 if (PageTransHuge(page)) {
612 count_vm_event(THP_FILE_ALLOC);
613 __inc_node_page_state(page, NR_SHMEM_THPS);
615 mapping->nrpages += nr;
616 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
617 __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
618 unlock:
619 xas_unlock_irq(&xas);
620 } while (xas_nomem(&xas, gfp));
622 if (xas_error(&xas)) {
623 page->mapping = NULL;
624 page_ref_sub(page, nr);
625 return xas_error(&xas);
628 return 0;
632 * Like delete_from_page_cache, but substitutes swap for page.
634 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
636 struct address_space *mapping = page->mapping;
637 int error;
639 VM_BUG_ON_PAGE(PageCompound(page), page);
641 xa_lock_irq(&mapping->i_pages);
642 error = shmem_replace_entry(mapping, page->index, page, radswap);
643 page->mapping = NULL;
644 mapping->nrpages--;
645 __dec_node_page_state(page, NR_FILE_PAGES);
646 __dec_node_page_state(page, NR_SHMEM);
647 xa_unlock_irq(&mapping->i_pages);
648 put_page(page);
649 BUG_ON(error);
653 * Remove swap entry from page cache, free the swap and its page cache.
655 static int shmem_free_swap(struct address_space *mapping,
656 pgoff_t index, void *radswap)
658 void *old;
660 xa_lock_irq(&mapping->i_pages);
661 old = __xa_cmpxchg(&mapping->i_pages, index, radswap, NULL, 0);
662 xa_unlock_irq(&mapping->i_pages);
663 if (old != radswap)
664 return -ENOENT;
665 free_swap_and_cache(radix_to_swp_entry(radswap));
666 return 0;
670 * Determine (in bytes) how many of the shmem object's pages mapped by the
671 * given offsets are swapped out.
673 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
674 * as long as the inode doesn't go away and racy results are not a problem.
676 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
677 pgoff_t start, pgoff_t end)
679 XA_STATE(xas, &mapping->i_pages, start);
680 struct page *page;
681 unsigned long swapped = 0;
683 rcu_read_lock();
684 xas_for_each(&xas, page, end - 1) {
685 if (xas_retry(&xas, page))
686 continue;
687 if (xa_is_value(page))
688 swapped++;
690 if (need_resched()) {
691 xas_pause(&xas);
692 cond_resched_rcu();
696 rcu_read_unlock();
698 return swapped << PAGE_SHIFT;
702 * Determine (in bytes) how many of the shmem object's pages mapped by the
703 * given vma is swapped out.
705 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
706 * as long as the inode doesn't go away and racy results are not a problem.
708 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
710 struct inode *inode = file_inode(vma->vm_file);
711 struct shmem_inode_info *info = SHMEM_I(inode);
712 struct address_space *mapping = inode->i_mapping;
713 unsigned long swapped;
715 /* Be careful as we don't hold info->lock */
716 swapped = READ_ONCE(info->swapped);
719 * The easier cases are when the shmem object has nothing in swap, or
720 * the vma maps it whole. Then we can simply use the stats that we
721 * already track.
723 if (!swapped)
724 return 0;
726 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
727 return swapped << PAGE_SHIFT;
729 /* Here comes the more involved part */
730 return shmem_partial_swap_usage(mapping,
731 linear_page_index(vma, vma->vm_start),
732 linear_page_index(vma, vma->vm_end));
736 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
738 void shmem_unlock_mapping(struct address_space *mapping)
740 struct pagevec pvec;
741 pgoff_t indices[PAGEVEC_SIZE];
742 pgoff_t index = 0;
744 pagevec_init(&pvec);
746 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
748 while (!mapping_unevictable(mapping)) {
750 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
751 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
753 pvec.nr = find_get_entries(mapping, index,
754 PAGEVEC_SIZE, pvec.pages, indices);
755 if (!pvec.nr)
756 break;
757 index = indices[pvec.nr - 1] + 1;
758 pagevec_remove_exceptionals(&pvec);
759 check_move_unevictable_pages(pvec.pages, pvec.nr);
760 pagevec_release(&pvec);
761 cond_resched();
766 * Remove range of pages and swap entries from page cache, and free them.
767 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
769 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
770 bool unfalloc)
772 struct address_space *mapping = inode->i_mapping;
773 struct shmem_inode_info *info = SHMEM_I(inode);
774 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
775 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
776 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
777 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
778 struct pagevec pvec;
779 pgoff_t indices[PAGEVEC_SIZE];
780 long nr_swaps_freed = 0;
781 pgoff_t index;
782 int i;
784 if (lend == -1)
785 end = -1; /* unsigned, so actually very big */
787 pagevec_init(&pvec);
788 index = start;
789 while (index < end) {
790 pvec.nr = find_get_entries(mapping, index,
791 min(end - index, (pgoff_t)PAGEVEC_SIZE),
792 pvec.pages, indices);
793 if (!pvec.nr)
794 break;
795 for (i = 0; i < pagevec_count(&pvec); i++) {
796 struct page *page = pvec.pages[i];
798 index = indices[i];
799 if (index >= end)
800 break;
802 if (xa_is_value(page)) {
803 if (unfalloc)
804 continue;
805 nr_swaps_freed += !shmem_free_swap(mapping,
806 index, page);
807 continue;
810 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
812 if (!trylock_page(page))
813 continue;
815 if (PageTransTail(page)) {
816 /* Middle of THP: zero out the page */
817 clear_highpage(page);
818 unlock_page(page);
819 continue;
820 } else if (PageTransHuge(page)) {
821 if (index == round_down(end, HPAGE_PMD_NR)) {
823 * Range ends in the middle of THP:
824 * zero out the page
826 clear_highpage(page);
827 unlock_page(page);
828 continue;
830 index += HPAGE_PMD_NR - 1;
831 i += HPAGE_PMD_NR - 1;
834 if (!unfalloc || !PageUptodate(page)) {
835 VM_BUG_ON_PAGE(PageTail(page), page);
836 if (page_mapping(page) == mapping) {
837 VM_BUG_ON_PAGE(PageWriteback(page), page);
838 truncate_inode_page(mapping, page);
841 unlock_page(page);
843 pagevec_remove_exceptionals(&pvec);
844 pagevec_release(&pvec);
845 cond_resched();
846 index++;
849 if (partial_start) {
850 struct page *page = NULL;
851 shmem_getpage(inode, start - 1, &page, SGP_READ);
852 if (page) {
853 unsigned int top = PAGE_SIZE;
854 if (start > end) {
855 top = partial_end;
856 partial_end = 0;
858 zero_user_segment(page, partial_start, top);
859 set_page_dirty(page);
860 unlock_page(page);
861 put_page(page);
864 if (partial_end) {
865 struct page *page = NULL;
866 shmem_getpage(inode, end, &page, SGP_READ);
867 if (page) {
868 zero_user_segment(page, 0, partial_end);
869 set_page_dirty(page);
870 unlock_page(page);
871 put_page(page);
874 if (start >= end)
875 return;
877 index = start;
878 while (index < end) {
879 cond_resched();
881 pvec.nr = find_get_entries(mapping, index,
882 min(end - index, (pgoff_t)PAGEVEC_SIZE),
883 pvec.pages, indices);
884 if (!pvec.nr) {
885 /* If all gone or hole-punch or unfalloc, we're done */
886 if (index == start || end != -1)
887 break;
888 /* But if truncating, restart to make sure all gone */
889 index = start;
890 continue;
892 for (i = 0; i < pagevec_count(&pvec); i++) {
893 struct page *page = pvec.pages[i];
895 index = indices[i];
896 if (index >= end)
897 break;
899 if (xa_is_value(page)) {
900 if (unfalloc)
901 continue;
902 if (shmem_free_swap(mapping, index, page)) {
903 /* Swap was replaced by page: retry */
904 index--;
905 break;
907 nr_swaps_freed++;
908 continue;
911 lock_page(page);
913 if (PageTransTail(page)) {
914 /* Middle of THP: zero out the page */
915 clear_highpage(page);
916 unlock_page(page);
918 * Partial thp truncate due 'start' in middle
919 * of THP: don't need to look on these pages
920 * again on !pvec.nr restart.
922 if (index != round_down(end, HPAGE_PMD_NR))
923 start++;
924 continue;
925 } else if (PageTransHuge(page)) {
926 if (index == round_down(end, HPAGE_PMD_NR)) {
928 * Range ends in the middle of THP:
929 * zero out the page
931 clear_highpage(page);
932 unlock_page(page);
933 continue;
935 index += HPAGE_PMD_NR - 1;
936 i += HPAGE_PMD_NR - 1;
939 if (!unfalloc || !PageUptodate(page)) {
940 VM_BUG_ON_PAGE(PageTail(page), page);
941 if (page_mapping(page) == mapping) {
942 VM_BUG_ON_PAGE(PageWriteback(page), page);
943 truncate_inode_page(mapping, page);
944 } else {
945 /* Page was replaced by swap: retry */
946 unlock_page(page);
947 index--;
948 break;
951 unlock_page(page);
953 pagevec_remove_exceptionals(&pvec);
954 pagevec_release(&pvec);
955 index++;
958 spin_lock_irq(&info->lock);
959 info->swapped -= nr_swaps_freed;
960 shmem_recalc_inode(inode);
961 spin_unlock_irq(&info->lock);
964 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
966 shmem_undo_range(inode, lstart, lend, false);
967 inode->i_ctime = inode->i_mtime = current_time(inode);
969 EXPORT_SYMBOL_GPL(shmem_truncate_range);
971 static int shmem_getattr(const struct path *path, struct kstat *stat,
972 u32 request_mask, unsigned int query_flags)
974 struct inode *inode = path->dentry->d_inode;
975 struct shmem_inode_info *info = SHMEM_I(inode);
976 struct shmem_sb_info *sb_info = SHMEM_SB(inode->i_sb);
978 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
979 spin_lock_irq(&info->lock);
980 shmem_recalc_inode(inode);
981 spin_unlock_irq(&info->lock);
983 generic_fillattr(inode, stat);
985 if (is_huge_enabled(sb_info))
986 stat->blksize = HPAGE_PMD_SIZE;
988 return 0;
991 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
993 struct inode *inode = d_inode(dentry);
994 struct shmem_inode_info *info = SHMEM_I(inode);
995 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
996 int error;
998 error = setattr_prepare(dentry, attr);
999 if (error)
1000 return error;
1002 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1003 loff_t oldsize = inode->i_size;
1004 loff_t newsize = attr->ia_size;
1006 /* protected by i_mutex */
1007 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1008 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1009 return -EPERM;
1011 if (newsize != oldsize) {
1012 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1013 oldsize, newsize);
1014 if (error)
1015 return error;
1016 i_size_write(inode, newsize);
1017 inode->i_ctime = inode->i_mtime = current_time(inode);
1019 if (newsize <= oldsize) {
1020 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1021 if (oldsize > holebegin)
1022 unmap_mapping_range(inode->i_mapping,
1023 holebegin, 0, 1);
1024 if (info->alloced)
1025 shmem_truncate_range(inode,
1026 newsize, (loff_t)-1);
1027 /* unmap again to remove racily COWed private pages */
1028 if (oldsize > holebegin)
1029 unmap_mapping_range(inode->i_mapping,
1030 holebegin, 0, 1);
1033 * Part of the huge page can be beyond i_size: subject
1034 * to shrink under memory pressure.
1036 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
1037 spin_lock(&sbinfo->shrinklist_lock);
1039 * _careful to defend against unlocked access to
1040 * ->shrink_list in shmem_unused_huge_shrink()
1042 if (list_empty_careful(&info->shrinklist)) {
1043 list_add_tail(&info->shrinklist,
1044 &sbinfo->shrinklist);
1045 sbinfo->shrinklist_len++;
1047 spin_unlock(&sbinfo->shrinklist_lock);
1052 setattr_copy(inode, attr);
1053 if (attr->ia_valid & ATTR_MODE)
1054 error = posix_acl_chmod(inode, inode->i_mode);
1055 return error;
1058 static void shmem_evict_inode(struct inode *inode)
1060 struct shmem_inode_info *info = SHMEM_I(inode);
1061 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1063 if (inode->i_mapping->a_ops == &shmem_aops) {
1064 shmem_unacct_size(info->flags, inode->i_size);
1065 inode->i_size = 0;
1066 shmem_truncate_range(inode, 0, (loff_t)-1);
1067 if (!list_empty(&info->shrinklist)) {
1068 spin_lock(&sbinfo->shrinklist_lock);
1069 if (!list_empty(&info->shrinklist)) {
1070 list_del_init(&info->shrinklist);
1071 sbinfo->shrinklist_len--;
1073 spin_unlock(&sbinfo->shrinklist_lock);
1075 if (!list_empty(&info->swaplist)) {
1076 mutex_lock(&shmem_swaplist_mutex);
1077 list_del_init(&info->swaplist);
1078 mutex_unlock(&shmem_swaplist_mutex);
1082 simple_xattrs_free(&info->xattrs);
1083 WARN_ON(inode->i_blocks);
1084 shmem_free_inode(inode->i_sb);
1085 clear_inode(inode);
1088 static unsigned long find_swap_entry(struct xarray *xa, void *item)
1090 XA_STATE(xas, xa, 0);
1091 unsigned int checked = 0;
1092 void *entry;
1094 rcu_read_lock();
1095 xas_for_each(&xas, entry, ULONG_MAX) {
1096 if (xas_retry(&xas, entry))
1097 continue;
1098 if (entry == item)
1099 break;
1100 checked++;
1101 if ((checked % XA_CHECK_SCHED) != 0)
1102 continue;
1103 xas_pause(&xas);
1104 cond_resched_rcu();
1106 rcu_read_unlock();
1108 return entry ? xas.xa_index : -1;
1112 * If swap found in inode, free it and move page from swapcache to filecache.
1114 static int shmem_unuse_inode(struct shmem_inode_info *info,
1115 swp_entry_t swap, struct page **pagep)
1117 struct address_space *mapping = info->vfs_inode.i_mapping;
1118 void *radswap;
1119 pgoff_t index;
1120 gfp_t gfp;
1121 int error = 0;
1123 radswap = swp_to_radix_entry(swap);
1124 index = find_swap_entry(&mapping->i_pages, radswap);
1125 if (index == -1)
1126 return -EAGAIN; /* tell shmem_unuse we found nothing */
1129 * Move _head_ to start search for next from here.
1130 * But be careful: shmem_evict_inode checks list_empty without taking
1131 * mutex, and there's an instant in list_move_tail when info->swaplist
1132 * would appear empty, if it were the only one on shmem_swaplist.
1134 if (shmem_swaplist.next != &info->swaplist)
1135 list_move_tail(&shmem_swaplist, &info->swaplist);
1137 gfp = mapping_gfp_mask(mapping);
1138 if (shmem_should_replace_page(*pagep, gfp)) {
1139 mutex_unlock(&shmem_swaplist_mutex);
1140 error = shmem_replace_page(pagep, gfp, info, index);
1141 mutex_lock(&shmem_swaplist_mutex);
1143 * We needed to drop mutex to make that restrictive page
1144 * allocation, but the inode might have been freed while we
1145 * dropped it: although a racing shmem_evict_inode() cannot
1146 * complete without emptying the page cache, our page lock
1147 * on this swapcache page is not enough to prevent that -
1148 * free_swap_and_cache() of our swap entry will only
1149 * trylock_page(), removing swap from page cache whatever.
1151 * We must not proceed to shmem_add_to_page_cache() if the
1152 * inode has been freed, but of course we cannot rely on
1153 * inode or mapping or info to check that. However, we can
1154 * safely check if our swap entry is still in use (and here
1155 * it can't have got reused for another page): if it's still
1156 * in use, then the inode cannot have been freed yet, and we
1157 * can safely proceed (if it's no longer in use, that tells
1158 * nothing about the inode, but we don't need to unuse swap).
1160 if (!page_swapcount(*pagep))
1161 error = -ENOENT;
1165 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
1166 * but also to hold up shmem_evict_inode(): so inode cannot be freed
1167 * beneath us (pagelock doesn't help until the page is in pagecache).
1169 if (!error)
1170 error = shmem_add_to_page_cache(*pagep, mapping, index,
1171 radswap, gfp);
1172 if (error != -ENOMEM) {
1174 * Truncation and eviction use free_swap_and_cache(), which
1175 * only does trylock page: if we raced, best clean up here.
1177 delete_from_swap_cache(*pagep);
1178 set_page_dirty(*pagep);
1179 if (!error) {
1180 spin_lock_irq(&info->lock);
1181 info->swapped--;
1182 spin_unlock_irq(&info->lock);
1183 swap_free(swap);
1186 return error;
1190 * Search through swapped inodes to find and replace swap by page.
1192 int shmem_unuse(swp_entry_t swap, struct page *page)
1194 struct list_head *this, *next;
1195 struct shmem_inode_info *info;
1196 struct mem_cgroup *memcg;
1197 int error = 0;
1200 * There's a faint possibility that swap page was replaced before
1201 * caller locked it: caller will come back later with the right page.
1203 if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
1204 goto out;
1207 * Charge page using GFP_KERNEL while we can wait, before taking
1208 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1209 * Charged back to the user (not to caller) when swap account is used.
1211 error = mem_cgroup_try_charge_delay(page, current->mm, GFP_KERNEL,
1212 &memcg, false);
1213 if (error)
1214 goto out;
1215 /* No memory allocation: swap entry occupies the slot for the page */
1216 error = -EAGAIN;
1218 mutex_lock(&shmem_swaplist_mutex);
1219 list_for_each_safe(this, next, &shmem_swaplist) {
1220 info = list_entry(this, struct shmem_inode_info, swaplist);
1221 if (info->swapped)
1222 error = shmem_unuse_inode(info, swap, &page);
1223 else
1224 list_del_init(&info->swaplist);
1225 cond_resched();
1226 if (error != -EAGAIN)
1227 break;
1228 /* found nothing in this: move on to search the next */
1230 mutex_unlock(&shmem_swaplist_mutex);
1232 if (error) {
1233 if (error != -ENOMEM)
1234 error = 0;
1235 mem_cgroup_cancel_charge(page, memcg, false);
1236 } else
1237 mem_cgroup_commit_charge(page, memcg, true, false);
1238 out:
1239 unlock_page(page);
1240 put_page(page);
1241 return error;
1245 * Move the page from the page cache to the swap cache.
1247 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1249 struct shmem_inode_info *info;
1250 struct address_space *mapping;
1251 struct inode *inode;
1252 swp_entry_t swap;
1253 pgoff_t index;
1255 VM_BUG_ON_PAGE(PageCompound(page), page);
1256 BUG_ON(!PageLocked(page));
1257 mapping = page->mapping;
1258 index = page->index;
1259 inode = mapping->host;
1260 info = SHMEM_I(inode);
1261 if (info->flags & VM_LOCKED)
1262 goto redirty;
1263 if (!total_swap_pages)
1264 goto redirty;
1267 * Our capabilities prevent regular writeback or sync from ever calling
1268 * shmem_writepage; but a stacking filesystem might use ->writepage of
1269 * its underlying filesystem, in which case tmpfs should write out to
1270 * swap only in response to memory pressure, and not for the writeback
1271 * threads or sync.
1273 if (!wbc->for_reclaim) {
1274 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1275 goto redirty;
1279 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1280 * value into swapfile.c, the only way we can correctly account for a
1281 * fallocated page arriving here is now to initialize it and write it.
1283 * That's okay for a page already fallocated earlier, but if we have
1284 * not yet completed the fallocation, then (a) we want to keep track
1285 * of this page in case we have to undo it, and (b) it may not be a
1286 * good idea to continue anyway, once we're pushing into swap. So
1287 * reactivate the page, and let shmem_fallocate() quit when too many.
1289 if (!PageUptodate(page)) {
1290 if (inode->i_private) {
1291 struct shmem_falloc *shmem_falloc;
1292 spin_lock(&inode->i_lock);
1293 shmem_falloc = inode->i_private;
1294 if (shmem_falloc &&
1295 !shmem_falloc->waitq &&
1296 index >= shmem_falloc->start &&
1297 index < shmem_falloc->next)
1298 shmem_falloc->nr_unswapped++;
1299 else
1300 shmem_falloc = NULL;
1301 spin_unlock(&inode->i_lock);
1302 if (shmem_falloc)
1303 goto redirty;
1305 clear_highpage(page);
1306 flush_dcache_page(page);
1307 SetPageUptodate(page);
1310 swap = get_swap_page(page);
1311 if (!swap.val)
1312 goto redirty;
1315 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1316 * if it's not already there. Do it now before the page is
1317 * moved to swap cache, when its pagelock no longer protects
1318 * the inode from eviction. But don't unlock the mutex until
1319 * we've incremented swapped, because shmem_unuse_inode() will
1320 * prune a !swapped inode from the swaplist under this mutex.
1322 mutex_lock(&shmem_swaplist_mutex);
1323 if (list_empty(&info->swaplist))
1324 list_add_tail(&info->swaplist, &shmem_swaplist);
1326 if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1327 spin_lock_irq(&info->lock);
1328 shmem_recalc_inode(inode);
1329 info->swapped++;
1330 spin_unlock_irq(&info->lock);
1332 swap_shmem_alloc(swap);
1333 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1335 mutex_unlock(&shmem_swaplist_mutex);
1336 BUG_ON(page_mapped(page));
1337 swap_writepage(page, wbc);
1338 return 0;
1341 mutex_unlock(&shmem_swaplist_mutex);
1342 put_swap_page(page, swap);
1343 redirty:
1344 set_page_dirty(page);
1345 if (wbc->for_reclaim)
1346 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1347 unlock_page(page);
1348 return 0;
1351 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1352 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1354 char buffer[64];
1356 if (!mpol || mpol->mode == MPOL_DEFAULT)
1357 return; /* show nothing */
1359 mpol_to_str(buffer, sizeof(buffer), mpol);
1361 seq_printf(seq, ",mpol=%s", buffer);
1364 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1366 struct mempolicy *mpol = NULL;
1367 if (sbinfo->mpol) {
1368 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1369 mpol = sbinfo->mpol;
1370 mpol_get(mpol);
1371 spin_unlock(&sbinfo->stat_lock);
1373 return mpol;
1375 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1376 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1379 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1381 return NULL;
1383 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1384 #ifndef CONFIG_NUMA
1385 #define vm_policy vm_private_data
1386 #endif
1388 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1389 struct shmem_inode_info *info, pgoff_t index)
1391 /* Create a pseudo vma that just contains the policy */
1392 vma_init(vma, NULL);
1393 /* Bias interleave by inode number to distribute better across nodes */
1394 vma->vm_pgoff = index + info->vfs_inode.i_ino;
1395 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1398 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1400 /* Drop reference taken by mpol_shared_policy_lookup() */
1401 mpol_cond_put(vma->vm_policy);
1404 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1405 struct shmem_inode_info *info, pgoff_t index)
1407 struct vm_area_struct pvma;
1408 struct page *page;
1409 struct vm_fault vmf;
1411 shmem_pseudo_vma_init(&pvma, info, index);
1412 vmf.vma = &pvma;
1413 vmf.address = 0;
1414 page = swap_cluster_readahead(swap, gfp, &vmf);
1415 shmem_pseudo_vma_destroy(&pvma);
1417 return page;
1420 static struct page *shmem_alloc_hugepage(gfp_t gfp,
1421 struct shmem_inode_info *info, pgoff_t index)
1423 struct vm_area_struct pvma;
1424 struct address_space *mapping = info->vfs_inode.i_mapping;
1425 pgoff_t hindex;
1426 struct page *page;
1428 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1429 return NULL;
1431 hindex = round_down(index, HPAGE_PMD_NR);
1432 if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
1433 XA_PRESENT))
1434 return NULL;
1436 shmem_pseudo_vma_init(&pvma, info, hindex);
1437 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1438 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id());
1439 shmem_pseudo_vma_destroy(&pvma);
1440 if (page)
1441 prep_transhuge_page(page);
1442 return page;
1445 static struct page *shmem_alloc_page(gfp_t gfp,
1446 struct shmem_inode_info *info, pgoff_t index)
1448 struct vm_area_struct pvma;
1449 struct page *page;
1451 shmem_pseudo_vma_init(&pvma, info, index);
1452 page = alloc_page_vma(gfp, &pvma, 0);
1453 shmem_pseudo_vma_destroy(&pvma);
1455 return page;
1458 static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1459 struct inode *inode,
1460 pgoff_t index, bool huge)
1462 struct shmem_inode_info *info = SHMEM_I(inode);
1463 struct page *page;
1464 int nr;
1465 int err = -ENOSPC;
1467 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1468 huge = false;
1469 nr = huge ? HPAGE_PMD_NR : 1;
1471 if (!shmem_inode_acct_block(inode, nr))
1472 goto failed;
1474 if (huge)
1475 page = shmem_alloc_hugepage(gfp, info, index);
1476 else
1477 page = shmem_alloc_page(gfp, info, index);
1478 if (page) {
1479 __SetPageLocked(page);
1480 __SetPageSwapBacked(page);
1481 return page;
1484 err = -ENOMEM;
1485 shmem_inode_unacct_blocks(inode, nr);
1486 failed:
1487 return ERR_PTR(err);
1491 * When a page is moved from swapcache to shmem filecache (either by the
1492 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1493 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1494 * ignorance of the mapping it belongs to. If that mapping has special
1495 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1496 * we may need to copy to a suitable page before moving to filecache.
1498 * In a future release, this may well be extended to respect cpuset and
1499 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1500 * but for now it is a simple matter of zone.
1502 static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1504 return page_zonenum(page) > gfp_zone(gfp);
1507 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1508 struct shmem_inode_info *info, pgoff_t index)
1510 struct page *oldpage, *newpage;
1511 struct address_space *swap_mapping;
1512 pgoff_t swap_index;
1513 int error;
1515 oldpage = *pagep;
1516 swap_index = page_private(oldpage);
1517 swap_mapping = page_mapping(oldpage);
1520 * We have arrived here because our zones are constrained, so don't
1521 * limit chance of success by further cpuset and node constraints.
1523 gfp &= ~GFP_CONSTRAINT_MASK;
1524 newpage = shmem_alloc_page(gfp, info, index);
1525 if (!newpage)
1526 return -ENOMEM;
1528 get_page(newpage);
1529 copy_highpage(newpage, oldpage);
1530 flush_dcache_page(newpage);
1532 __SetPageLocked(newpage);
1533 __SetPageSwapBacked(newpage);
1534 SetPageUptodate(newpage);
1535 set_page_private(newpage, swap_index);
1536 SetPageSwapCache(newpage);
1539 * Our caller will very soon move newpage out of swapcache, but it's
1540 * a nice clean interface for us to replace oldpage by newpage there.
1542 xa_lock_irq(&swap_mapping->i_pages);
1543 error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
1544 if (!error) {
1545 __inc_node_page_state(newpage, NR_FILE_PAGES);
1546 __dec_node_page_state(oldpage, NR_FILE_PAGES);
1548 xa_unlock_irq(&swap_mapping->i_pages);
1550 if (unlikely(error)) {
1552 * Is this possible? I think not, now that our callers check
1553 * both PageSwapCache and page_private after getting page lock;
1554 * but be defensive. Reverse old to newpage for clear and free.
1556 oldpage = newpage;
1557 } else {
1558 mem_cgroup_migrate(oldpage, newpage);
1559 lru_cache_add_anon(newpage);
1560 *pagep = newpage;
1563 ClearPageSwapCache(oldpage);
1564 set_page_private(oldpage, 0);
1566 unlock_page(oldpage);
1567 put_page(oldpage);
1568 put_page(oldpage);
1569 return error;
1573 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1575 * If we allocate a new one we do not mark it dirty. That's up to the
1576 * vm. If we swap it in we mark it dirty since we also free the swap
1577 * entry since a page cannot live in both the swap and page cache.
1579 * fault_mm and fault_type are only supplied by shmem_fault:
1580 * otherwise they are NULL.
1582 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1583 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1584 struct vm_area_struct *vma, struct vm_fault *vmf,
1585 vm_fault_t *fault_type)
1587 struct address_space *mapping = inode->i_mapping;
1588 struct shmem_inode_info *info = SHMEM_I(inode);
1589 struct shmem_sb_info *sbinfo;
1590 struct mm_struct *charge_mm;
1591 struct mem_cgroup *memcg;
1592 struct page *page;
1593 swp_entry_t swap;
1594 enum sgp_type sgp_huge = sgp;
1595 pgoff_t hindex = index;
1596 int error;
1597 int once = 0;
1598 int alloced = 0;
1600 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1601 return -EFBIG;
1602 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1603 sgp = SGP_CACHE;
1604 repeat:
1605 swap.val = 0;
1606 page = find_lock_entry(mapping, index);
1607 if (xa_is_value(page)) {
1608 swap = radix_to_swp_entry(page);
1609 page = NULL;
1612 if (sgp <= SGP_CACHE &&
1613 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1614 error = -EINVAL;
1615 goto unlock;
1618 if (page && sgp == SGP_WRITE)
1619 mark_page_accessed(page);
1621 /* fallocated page? */
1622 if (page && !PageUptodate(page)) {
1623 if (sgp != SGP_READ)
1624 goto clear;
1625 unlock_page(page);
1626 put_page(page);
1627 page = NULL;
1629 if (page || (sgp == SGP_READ && !swap.val)) {
1630 *pagep = page;
1631 return 0;
1635 * Fast cache lookup did not find it:
1636 * bring it back from swap or allocate.
1638 sbinfo = SHMEM_SB(inode->i_sb);
1639 charge_mm = vma ? vma->vm_mm : current->mm;
1641 if (swap.val) {
1642 /* Look it up and read it in.. */
1643 page = lookup_swap_cache(swap, NULL, 0);
1644 if (!page) {
1645 /* Or update major stats only when swapin succeeds?? */
1646 if (fault_type) {
1647 *fault_type |= VM_FAULT_MAJOR;
1648 count_vm_event(PGMAJFAULT);
1649 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1651 /* Here we actually start the io */
1652 page = shmem_swapin(swap, gfp, info, index);
1653 if (!page) {
1654 error = -ENOMEM;
1655 goto failed;
1659 /* We have to do this with page locked to prevent races */
1660 lock_page(page);
1661 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1662 !shmem_confirm_swap(mapping, index, swap)) {
1663 error = -EEXIST; /* try again */
1664 goto unlock;
1666 if (!PageUptodate(page)) {
1667 error = -EIO;
1668 goto failed;
1670 wait_on_page_writeback(page);
1672 if (shmem_should_replace_page(page, gfp)) {
1673 error = shmem_replace_page(&page, gfp, info, index);
1674 if (error)
1675 goto failed;
1678 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1679 false);
1680 if (!error) {
1681 error = shmem_add_to_page_cache(page, mapping, index,
1682 swp_to_radix_entry(swap), gfp);
1684 * We already confirmed swap under page lock, and make
1685 * no memory allocation here, so usually no possibility
1686 * of error; but free_swap_and_cache() only trylocks a
1687 * page, so it is just possible that the entry has been
1688 * truncated or holepunched since swap was confirmed.
1689 * shmem_undo_range() will have done some of the
1690 * unaccounting, now delete_from_swap_cache() will do
1691 * the rest.
1692 * Reset swap.val? No, leave it so "failed" goes back to
1693 * "repeat": reading a hole and writing should succeed.
1695 if (error) {
1696 mem_cgroup_cancel_charge(page, memcg, false);
1697 delete_from_swap_cache(page);
1700 if (error)
1701 goto failed;
1703 mem_cgroup_commit_charge(page, memcg, true, false);
1705 spin_lock_irq(&info->lock);
1706 info->swapped--;
1707 shmem_recalc_inode(inode);
1708 spin_unlock_irq(&info->lock);
1710 if (sgp == SGP_WRITE)
1711 mark_page_accessed(page);
1713 delete_from_swap_cache(page);
1714 set_page_dirty(page);
1715 swap_free(swap);
1717 } else {
1718 if (vma && userfaultfd_missing(vma)) {
1719 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1720 return 0;
1723 /* shmem_symlink() */
1724 if (mapping->a_ops != &shmem_aops)
1725 goto alloc_nohuge;
1726 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1727 goto alloc_nohuge;
1728 if (shmem_huge == SHMEM_HUGE_FORCE)
1729 goto alloc_huge;
1730 switch (sbinfo->huge) {
1731 loff_t i_size;
1732 pgoff_t off;
1733 case SHMEM_HUGE_NEVER:
1734 goto alloc_nohuge;
1735 case SHMEM_HUGE_WITHIN_SIZE:
1736 off = round_up(index, HPAGE_PMD_NR);
1737 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1738 if (i_size >= HPAGE_PMD_SIZE &&
1739 i_size >> PAGE_SHIFT >= off)
1740 goto alloc_huge;
1741 /* fallthrough */
1742 case SHMEM_HUGE_ADVISE:
1743 if (sgp_huge == SGP_HUGE)
1744 goto alloc_huge;
1745 /* TODO: implement fadvise() hints */
1746 goto alloc_nohuge;
1749 alloc_huge:
1750 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1751 if (IS_ERR(page)) {
1752 alloc_nohuge: page = shmem_alloc_and_acct_page(gfp, inode,
1753 index, false);
1755 if (IS_ERR(page)) {
1756 int retry = 5;
1757 error = PTR_ERR(page);
1758 page = NULL;
1759 if (error != -ENOSPC)
1760 goto failed;
1762 * Try to reclaim some spece by splitting a huge page
1763 * beyond i_size on the filesystem.
1765 while (retry--) {
1766 int ret;
1767 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1768 if (ret == SHRINK_STOP)
1769 break;
1770 if (ret)
1771 goto alloc_nohuge;
1773 goto failed;
1776 if (PageTransHuge(page))
1777 hindex = round_down(index, HPAGE_PMD_NR);
1778 else
1779 hindex = index;
1781 if (sgp == SGP_WRITE)
1782 __SetPageReferenced(page);
1784 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1785 PageTransHuge(page));
1786 if (error)
1787 goto unacct;
1788 error = shmem_add_to_page_cache(page, mapping, hindex,
1789 NULL, gfp & GFP_RECLAIM_MASK);
1790 if (error) {
1791 mem_cgroup_cancel_charge(page, memcg,
1792 PageTransHuge(page));
1793 goto unacct;
1795 mem_cgroup_commit_charge(page, memcg, false,
1796 PageTransHuge(page));
1797 lru_cache_add_anon(page);
1799 spin_lock_irq(&info->lock);
1800 info->alloced += 1 << compound_order(page);
1801 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1802 shmem_recalc_inode(inode);
1803 spin_unlock_irq(&info->lock);
1804 alloced = true;
1806 if (PageTransHuge(page) &&
1807 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1808 hindex + HPAGE_PMD_NR - 1) {
1810 * Part of the huge page is beyond i_size: subject
1811 * to shrink under memory pressure.
1813 spin_lock(&sbinfo->shrinklist_lock);
1815 * _careful to defend against unlocked access to
1816 * ->shrink_list in shmem_unused_huge_shrink()
1818 if (list_empty_careful(&info->shrinklist)) {
1819 list_add_tail(&info->shrinklist,
1820 &sbinfo->shrinklist);
1821 sbinfo->shrinklist_len++;
1823 spin_unlock(&sbinfo->shrinklist_lock);
1827 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1829 if (sgp == SGP_FALLOC)
1830 sgp = SGP_WRITE;
1831 clear:
1833 * Let SGP_WRITE caller clear ends if write does not fill page;
1834 * but SGP_FALLOC on a page fallocated earlier must initialize
1835 * it now, lest undo on failure cancel our earlier guarantee.
1837 if (sgp != SGP_WRITE && !PageUptodate(page)) {
1838 struct page *head = compound_head(page);
1839 int i;
1841 for (i = 0; i < (1 << compound_order(head)); i++) {
1842 clear_highpage(head + i);
1843 flush_dcache_page(head + i);
1845 SetPageUptodate(head);
1849 /* Perhaps the file has been truncated since we checked */
1850 if (sgp <= SGP_CACHE &&
1851 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1852 if (alloced) {
1853 ClearPageDirty(page);
1854 delete_from_page_cache(page);
1855 spin_lock_irq(&info->lock);
1856 shmem_recalc_inode(inode);
1857 spin_unlock_irq(&info->lock);
1859 error = -EINVAL;
1860 goto unlock;
1862 *pagep = page + index - hindex;
1863 return 0;
1866 * Error recovery.
1868 unacct:
1869 shmem_inode_unacct_blocks(inode, 1 << compound_order(page));
1871 if (PageTransHuge(page)) {
1872 unlock_page(page);
1873 put_page(page);
1874 goto alloc_nohuge;
1876 failed:
1877 if (swap.val && !shmem_confirm_swap(mapping, index, swap))
1878 error = -EEXIST;
1879 unlock:
1880 if (page) {
1881 unlock_page(page);
1882 put_page(page);
1884 if (error == -ENOSPC && !once++) {
1885 spin_lock_irq(&info->lock);
1886 shmem_recalc_inode(inode);
1887 spin_unlock_irq(&info->lock);
1888 goto repeat;
1890 if (error == -EEXIST)
1891 goto repeat;
1892 return error;
1896 * This is like autoremove_wake_function, but it removes the wait queue
1897 * entry unconditionally - even if something else had already woken the
1898 * target.
1900 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
1902 int ret = default_wake_function(wait, mode, sync, key);
1903 list_del_init(&wait->entry);
1904 return ret;
1907 static vm_fault_t shmem_fault(struct vm_fault *vmf)
1909 struct vm_area_struct *vma = vmf->vma;
1910 struct inode *inode = file_inode(vma->vm_file);
1911 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1912 enum sgp_type sgp;
1913 int err;
1914 vm_fault_t ret = VM_FAULT_LOCKED;
1917 * Trinity finds that probing a hole which tmpfs is punching can
1918 * prevent the hole-punch from ever completing: which in turn
1919 * locks writers out with its hold on i_mutex. So refrain from
1920 * faulting pages into the hole while it's being punched. Although
1921 * shmem_undo_range() does remove the additions, it may be unable to
1922 * keep up, as each new page needs its own unmap_mapping_range() call,
1923 * and the i_mmap tree grows ever slower to scan if new vmas are added.
1925 * It does not matter if we sometimes reach this check just before the
1926 * hole-punch begins, so that one fault then races with the punch:
1927 * we just need to make racing faults a rare case.
1929 * The implementation below would be much simpler if we just used a
1930 * standard mutex or completion: but we cannot take i_mutex in fault,
1931 * and bloating every shmem inode for this unlikely case would be sad.
1933 if (unlikely(inode->i_private)) {
1934 struct shmem_falloc *shmem_falloc;
1936 spin_lock(&inode->i_lock);
1937 shmem_falloc = inode->i_private;
1938 if (shmem_falloc &&
1939 shmem_falloc->waitq &&
1940 vmf->pgoff >= shmem_falloc->start &&
1941 vmf->pgoff < shmem_falloc->next) {
1942 wait_queue_head_t *shmem_falloc_waitq;
1943 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
1945 ret = VM_FAULT_NOPAGE;
1946 if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
1947 !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
1948 /* It's polite to up mmap_sem if we can */
1949 up_read(&vma->vm_mm->mmap_sem);
1950 ret = VM_FAULT_RETRY;
1953 shmem_falloc_waitq = shmem_falloc->waitq;
1954 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
1955 TASK_UNINTERRUPTIBLE);
1956 spin_unlock(&inode->i_lock);
1957 schedule();
1960 * shmem_falloc_waitq points into the shmem_fallocate()
1961 * stack of the hole-punching task: shmem_falloc_waitq
1962 * is usually invalid by the time we reach here, but
1963 * finish_wait() does not dereference it in that case;
1964 * though i_lock needed lest racing with wake_up_all().
1966 spin_lock(&inode->i_lock);
1967 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
1968 spin_unlock(&inode->i_lock);
1969 return ret;
1971 spin_unlock(&inode->i_lock);
1974 sgp = SGP_CACHE;
1976 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
1977 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
1978 sgp = SGP_NOHUGE;
1979 else if (vma->vm_flags & VM_HUGEPAGE)
1980 sgp = SGP_HUGE;
1982 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
1983 gfp, vma, vmf, &ret);
1984 if (err)
1985 return vmf_error(err);
1986 return ret;
1989 unsigned long shmem_get_unmapped_area(struct file *file,
1990 unsigned long uaddr, unsigned long len,
1991 unsigned long pgoff, unsigned long flags)
1993 unsigned long (*get_area)(struct file *,
1994 unsigned long, unsigned long, unsigned long, unsigned long);
1995 unsigned long addr;
1996 unsigned long offset;
1997 unsigned long inflated_len;
1998 unsigned long inflated_addr;
1999 unsigned long inflated_offset;
2001 if (len > TASK_SIZE)
2002 return -ENOMEM;
2004 get_area = current->mm->get_unmapped_area;
2005 addr = get_area(file, uaddr, len, pgoff, flags);
2007 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
2008 return addr;
2009 if (IS_ERR_VALUE(addr))
2010 return addr;
2011 if (addr & ~PAGE_MASK)
2012 return addr;
2013 if (addr > TASK_SIZE - len)
2014 return addr;
2016 if (shmem_huge == SHMEM_HUGE_DENY)
2017 return addr;
2018 if (len < HPAGE_PMD_SIZE)
2019 return addr;
2020 if (flags & MAP_FIXED)
2021 return addr;
2023 * Our priority is to support MAP_SHARED mapped hugely;
2024 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2025 * But if caller specified an address hint, respect that as before.
2027 if (uaddr)
2028 return addr;
2030 if (shmem_huge != SHMEM_HUGE_FORCE) {
2031 struct super_block *sb;
2033 if (file) {
2034 VM_BUG_ON(file->f_op != &shmem_file_operations);
2035 sb = file_inode(file)->i_sb;
2036 } else {
2038 * Called directly from mm/mmap.c, or drivers/char/mem.c
2039 * for "/dev/zero", to create a shared anonymous object.
2041 if (IS_ERR(shm_mnt))
2042 return addr;
2043 sb = shm_mnt->mnt_sb;
2045 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2046 return addr;
2049 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2050 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2051 return addr;
2052 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2053 return addr;
2055 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2056 if (inflated_len > TASK_SIZE)
2057 return addr;
2058 if (inflated_len < len)
2059 return addr;
2061 inflated_addr = get_area(NULL, 0, inflated_len, 0, flags);
2062 if (IS_ERR_VALUE(inflated_addr))
2063 return addr;
2064 if (inflated_addr & ~PAGE_MASK)
2065 return addr;
2067 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2068 inflated_addr += offset - inflated_offset;
2069 if (inflated_offset > offset)
2070 inflated_addr += HPAGE_PMD_SIZE;
2072 if (inflated_addr > TASK_SIZE - len)
2073 return addr;
2074 return inflated_addr;
2077 #ifdef CONFIG_NUMA
2078 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2080 struct inode *inode = file_inode(vma->vm_file);
2081 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2084 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2085 unsigned long addr)
2087 struct inode *inode = file_inode(vma->vm_file);
2088 pgoff_t index;
2090 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2091 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2093 #endif
2095 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2097 struct inode *inode = file_inode(file);
2098 struct shmem_inode_info *info = SHMEM_I(inode);
2099 int retval = -ENOMEM;
2101 spin_lock_irq(&info->lock);
2102 if (lock && !(info->flags & VM_LOCKED)) {
2103 if (!user_shm_lock(inode->i_size, user))
2104 goto out_nomem;
2105 info->flags |= VM_LOCKED;
2106 mapping_set_unevictable(file->f_mapping);
2108 if (!lock && (info->flags & VM_LOCKED) && user) {
2109 user_shm_unlock(inode->i_size, user);
2110 info->flags &= ~VM_LOCKED;
2111 mapping_clear_unevictable(file->f_mapping);
2113 retval = 0;
2115 out_nomem:
2116 spin_unlock_irq(&info->lock);
2117 return retval;
2120 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2122 file_accessed(file);
2123 vma->vm_ops = &shmem_vm_ops;
2124 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
2125 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2126 (vma->vm_end & HPAGE_PMD_MASK)) {
2127 khugepaged_enter(vma, vma->vm_flags);
2129 return 0;
2132 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
2133 umode_t mode, dev_t dev, unsigned long flags)
2135 struct inode *inode;
2136 struct shmem_inode_info *info;
2137 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2139 if (shmem_reserve_inode(sb))
2140 return NULL;
2142 inode = new_inode(sb);
2143 if (inode) {
2144 inode->i_ino = get_next_ino();
2145 inode_init_owner(inode, dir, mode);
2146 inode->i_blocks = 0;
2147 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2148 inode->i_generation = prandom_u32();
2149 info = SHMEM_I(inode);
2150 memset(info, 0, (char *)inode - (char *)info);
2151 spin_lock_init(&info->lock);
2152 info->seals = F_SEAL_SEAL;
2153 info->flags = flags & VM_NORESERVE;
2154 INIT_LIST_HEAD(&info->shrinklist);
2155 INIT_LIST_HEAD(&info->swaplist);
2156 simple_xattrs_init(&info->xattrs);
2157 cache_no_acl(inode);
2159 switch (mode & S_IFMT) {
2160 default:
2161 inode->i_op = &shmem_special_inode_operations;
2162 init_special_inode(inode, mode, dev);
2163 break;
2164 case S_IFREG:
2165 inode->i_mapping->a_ops = &shmem_aops;
2166 inode->i_op = &shmem_inode_operations;
2167 inode->i_fop = &shmem_file_operations;
2168 mpol_shared_policy_init(&info->policy,
2169 shmem_get_sbmpol(sbinfo));
2170 break;
2171 case S_IFDIR:
2172 inc_nlink(inode);
2173 /* Some things misbehave if size == 0 on a directory */
2174 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2175 inode->i_op = &shmem_dir_inode_operations;
2176 inode->i_fop = &simple_dir_operations;
2177 break;
2178 case S_IFLNK:
2180 * Must not load anything in the rbtree,
2181 * mpol_free_shared_policy will not be called.
2183 mpol_shared_policy_init(&info->policy, NULL);
2184 break;
2187 lockdep_annotate_inode_mutex_key(inode);
2188 } else
2189 shmem_free_inode(sb);
2190 return inode;
2193 bool shmem_mapping(struct address_space *mapping)
2195 return mapping->a_ops == &shmem_aops;
2198 static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2199 pmd_t *dst_pmd,
2200 struct vm_area_struct *dst_vma,
2201 unsigned long dst_addr,
2202 unsigned long src_addr,
2203 bool zeropage,
2204 struct page **pagep)
2206 struct inode *inode = file_inode(dst_vma->vm_file);
2207 struct shmem_inode_info *info = SHMEM_I(inode);
2208 struct address_space *mapping = inode->i_mapping;
2209 gfp_t gfp = mapping_gfp_mask(mapping);
2210 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2211 struct mem_cgroup *memcg;
2212 spinlock_t *ptl;
2213 void *page_kaddr;
2214 struct page *page;
2215 pte_t _dst_pte, *dst_pte;
2216 int ret;
2218 ret = -ENOMEM;
2219 if (!shmem_inode_acct_block(inode, 1))
2220 goto out;
2222 if (!*pagep) {
2223 page = shmem_alloc_page(gfp, info, pgoff);
2224 if (!page)
2225 goto out_unacct_blocks;
2227 if (!zeropage) { /* mcopy_atomic */
2228 page_kaddr = kmap_atomic(page);
2229 ret = copy_from_user(page_kaddr,
2230 (const void __user *)src_addr,
2231 PAGE_SIZE);
2232 kunmap_atomic(page_kaddr);
2234 /* fallback to copy_from_user outside mmap_sem */
2235 if (unlikely(ret)) {
2236 *pagep = page;
2237 shmem_inode_unacct_blocks(inode, 1);
2238 /* don't free the page */
2239 return -EFAULT;
2241 } else { /* mfill_zeropage_atomic */
2242 clear_highpage(page);
2244 } else {
2245 page = *pagep;
2246 *pagep = NULL;
2249 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2250 __SetPageLocked(page);
2251 __SetPageSwapBacked(page);
2252 __SetPageUptodate(page);
2254 ret = mem_cgroup_try_charge_delay(page, dst_mm, gfp, &memcg, false);
2255 if (ret)
2256 goto out_release;
2258 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
2259 gfp & GFP_RECLAIM_MASK);
2260 if (ret)
2261 goto out_release_uncharge;
2263 mem_cgroup_commit_charge(page, memcg, false, false);
2265 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2266 if (dst_vma->vm_flags & VM_WRITE)
2267 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
2269 ret = -EEXIST;
2270 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
2271 if (!pte_none(*dst_pte))
2272 goto out_release_uncharge_unlock;
2274 lru_cache_add_anon(page);
2276 spin_lock(&info->lock);
2277 info->alloced++;
2278 inode->i_blocks += BLOCKS_PER_PAGE;
2279 shmem_recalc_inode(inode);
2280 spin_unlock(&info->lock);
2282 inc_mm_counter(dst_mm, mm_counter_file(page));
2283 page_add_file_rmap(page, false);
2284 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2286 /* No need to invalidate - it was non-present before */
2287 update_mmu_cache(dst_vma, dst_addr, dst_pte);
2288 unlock_page(page);
2289 pte_unmap_unlock(dst_pte, ptl);
2290 ret = 0;
2291 out:
2292 return ret;
2293 out_release_uncharge_unlock:
2294 pte_unmap_unlock(dst_pte, ptl);
2295 out_release_uncharge:
2296 mem_cgroup_cancel_charge(page, memcg, false);
2297 out_release:
2298 unlock_page(page);
2299 put_page(page);
2300 out_unacct_blocks:
2301 shmem_inode_unacct_blocks(inode, 1);
2302 goto out;
2305 int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2306 pmd_t *dst_pmd,
2307 struct vm_area_struct *dst_vma,
2308 unsigned long dst_addr,
2309 unsigned long src_addr,
2310 struct page **pagep)
2312 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2313 dst_addr, src_addr, false, pagep);
2316 int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2317 pmd_t *dst_pmd,
2318 struct vm_area_struct *dst_vma,
2319 unsigned long dst_addr)
2321 struct page *page = NULL;
2323 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2324 dst_addr, 0, true, &page);
2327 #ifdef CONFIG_TMPFS
2328 static const struct inode_operations shmem_symlink_inode_operations;
2329 static const struct inode_operations shmem_short_symlink_operations;
2331 #ifdef CONFIG_TMPFS_XATTR
2332 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2333 #else
2334 #define shmem_initxattrs NULL
2335 #endif
2337 static int
2338 shmem_write_begin(struct file *file, struct address_space *mapping,
2339 loff_t pos, unsigned len, unsigned flags,
2340 struct page **pagep, void **fsdata)
2342 struct inode *inode = mapping->host;
2343 struct shmem_inode_info *info = SHMEM_I(inode);
2344 pgoff_t index = pos >> PAGE_SHIFT;
2346 /* i_mutex is held by caller */
2347 if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
2348 if (info->seals & F_SEAL_WRITE)
2349 return -EPERM;
2350 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2351 return -EPERM;
2354 return shmem_getpage(inode, index, pagep, SGP_WRITE);
2357 static int
2358 shmem_write_end(struct file *file, struct address_space *mapping,
2359 loff_t pos, unsigned len, unsigned copied,
2360 struct page *page, void *fsdata)
2362 struct inode *inode = mapping->host;
2364 if (pos + copied > inode->i_size)
2365 i_size_write(inode, pos + copied);
2367 if (!PageUptodate(page)) {
2368 struct page *head = compound_head(page);
2369 if (PageTransCompound(page)) {
2370 int i;
2372 for (i = 0; i < HPAGE_PMD_NR; i++) {
2373 if (head + i == page)
2374 continue;
2375 clear_highpage(head + i);
2376 flush_dcache_page(head + i);
2379 if (copied < PAGE_SIZE) {
2380 unsigned from = pos & (PAGE_SIZE - 1);
2381 zero_user_segments(page, 0, from,
2382 from + copied, PAGE_SIZE);
2384 SetPageUptodate(head);
2386 set_page_dirty(page);
2387 unlock_page(page);
2388 put_page(page);
2390 return copied;
2393 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2395 struct file *file = iocb->ki_filp;
2396 struct inode *inode = file_inode(file);
2397 struct address_space *mapping = inode->i_mapping;
2398 pgoff_t index;
2399 unsigned long offset;
2400 enum sgp_type sgp = SGP_READ;
2401 int error = 0;
2402 ssize_t retval = 0;
2403 loff_t *ppos = &iocb->ki_pos;
2406 * Might this read be for a stacking filesystem? Then when reading
2407 * holes of a sparse file, we actually need to allocate those pages,
2408 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2410 if (!iter_is_iovec(to))
2411 sgp = SGP_CACHE;
2413 index = *ppos >> PAGE_SHIFT;
2414 offset = *ppos & ~PAGE_MASK;
2416 for (;;) {
2417 struct page *page = NULL;
2418 pgoff_t end_index;
2419 unsigned long nr, ret;
2420 loff_t i_size = i_size_read(inode);
2422 end_index = i_size >> PAGE_SHIFT;
2423 if (index > end_index)
2424 break;
2425 if (index == end_index) {
2426 nr = i_size & ~PAGE_MASK;
2427 if (nr <= offset)
2428 break;
2431 error = shmem_getpage(inode, index, &page, sgp);
2432 if (error) {
2433 if (error == -EINVAL)
2434 error = 0;
2435 break;
2437 if (page) {
2438 if (sgp == SGP_CACHE)
2439 set_page_dirty(page);
2440 unlock_page(page);
2444 * We must evaluate after, since reads (unlike writes)
2445 * are called without i_mutex protection against truncate
2447 nr = PAGE_SIZE;
2448 i_size = i_size_read(inode);
2449 end_index = i_size >> PAGE_SHIFT;
2450 if (index == end_index) {
2451 nr = i_size & ~PAGE_MASK;
2452 if (nr <= offset) {
2453 if (page)
2454 put_page(page);
2455 break;
2458 nr -= offset;
2460 if (page) {
2462 * If users can be writing to this page using arbitrary
2463 * virtual addresses, take care about potential aliasing
2464 * before reading the page on the kernel side.
2466 if (mapping_writably_mapped(mapping))
2467 flush_dcache_page(page);
2469 * Mark the page accessed if we read the beginning.
2471 if (!offset)
2472 mark_page_accessed(page);
2473 } else {
2474 page = ZERO_PAGE(0);
2475 get_page(page);
2479 * Ok, we have the page, and it's up-to-date, so
2480 * now we can copy it to user space...
2482 ret = copy_page_to_iter(page, offset, nr, to);
2483 retval += ret;
2484 offset += ret;
2485 index += offset >> PAGE_SHIFT;
2486 offset &= ~PAGE_MASK;
2488 put_page(page);
2489 if (!iov_iter_count(to))
2490 break;
2491 if (ret < nr) {
2492 error = -EFAULT;
2493 break;
2495 cond_resched();
2498 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2499 file_accessed(file);
2500 return retval ? retval : error;
2504 * llseek SEEK_DATA or SEEK_HOLE through the page cache.
2506 static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2507 pgoff_t index, pgoff_t end, int whence)
2509 struct page *page;
2510 struct pagevec pvec;
2511 pgoff_t indices[PAGEVEC_SIZE];
2512 bool done = false;
2513 int i;
2515 pagevec_init(&pvec);
2516 pvec.nr = 1; /* start small: we may be there already */
2517 while (!done) {
2518 pvec.nr = find_get_entries(mapping, index,
2519 pvec.nr, pvec.pages, indices);
2520 if (!pvec.nr) {
2521 if (whence == SEEK_DATA)
2522 index = end;
2523 break;
2525 for (i = 0; i < pvec.nr; i++, index++) {
2526 if (index < indices[i]) {
2527 if (whence == SEEK_HOLE) {
2528 done = true;
2529 break;
2531 index = indices[i];
2533 page = pvec.pages[i];
2534 if (page && !xa_is_value(page)) {
2535 if (!PageUptodate(page))
2536 page = NULL;
2538 if (index >= end ||
2539 (page && whence == SEEK_DATA) ||
2540 (!page && whence == SEEK_HOLE)) {
2541 done = true;
2542 break;
2545 pagevec_remove_exceptionals(&pvec);
2546 pagevec_release(&pvec);
2547 pvec.nr = PAGEVEC_SIZE;
2548 cond_resched();
2550 return index;
2553 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2555 struct address_space *mapping = file->f_mapping;
2556 struct inode *inode = mapping->host;
2557 pgoff_t start, end;
2558 loff_t new_offset;
2560 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2561 return generic_file_llseek_size(file, offset, whence,
2562 MAX_LFS_FILESIZE, i_size_read(inode));
2563 inode_lock(inode);
2564 /* We're holding i_mutex so we can access i_size directly */
2566 if (offset < 0 || offset >= inode->i_size)
2567 offset = -ENXIO;
2568 else {
2569 start = offset >> PAGE_SHIFT;
2570 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2571 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
2572 new_offset <<= PAGE_SHIFT;
2573 if (new_offset > offset) {
2574 if (new_offset < inode->i_size)
2575 offset = new_offset;
2576 else if (whence == SEEK_DATA)
2577 offset = -ENXIO;
2578 else
2579 offset = inode->i_size;
2583 if (offset >= 0)
2584 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2585 inode_unlock(inode);
2586 return offset;
2589 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2590 loff_t len)
2592 struct inode *inode = file_inode(file);
2593 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2594 struct shmem_inode_info *info = SHMEM_I(inode);
2595 struct shmem_falloc shmem_falloc;
2596 pgoff_t start, index, end;
2597 int error;
2599 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2600 return -EOPNOTSUPP;
2602 inode_lock(inode);
2604 if (mode & FALLOC_FL_PUNCH_HOLE) {
2605 struct address_space *mapping = file->f_mapping;
2606 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2607 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2608 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2610 /* protected by i_mutex */
2611 if (info->seals & F_SEAL_WRITE) {
2612 error = -EPERM;
2613 goto out;
2616 shmem_falloc.waitq = &shmem_falloc_waitq;
2617 shmem_falloc.start = unmap_start >> PAGE_SHIFT;
2618 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2619 spin_lock(&inode->i_lock);
2620 inode->i_private = &shmem_falloc;
2621 spin_unlock(&inode->i_lock);
2623 if ((u64)unmap_end > (u64)unmap_start)
2624 unmap_mapping_range(mapping, unmap_start,
2625 1 + unmap_end - unmap_start, 0);
2626 shmem_truncate_range(inode, offset, offset + len - 1);
2627 /* No need to unmap again: hole-punching leaves COWed pages */
2629 spin_lock(&inode->i_lock);
2630 inode->i_private = NULL;
2631 wake_up_all(&shmem_falloc_waitq);
2632 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2633 spin_unlock(&inode->i_lock);
2634 error = 0;
2635 goto out;
2638 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2639 error = inode_newsize_ok(inode, offset + len);
2640 if (error)
2641 goto out;
2643 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2644 error = -EPERM;
2645 goto out;
2648 start = offset >> PAGE_SHIFT;
2649 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2650 /* Try to avoid a swapstorm if len is impossible to satisfy */
2651 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2652 error = -ENOSPC;
2653 goto out;
2656 shmem_falloc.waitq = NULL;
2657 shmem_falloc.start = start;
2658 shmem_falloc.next = start;
2659 shmem_falloc.nr_falloced = 0;
2660 shmem_falloc.nr_unswapped = 0;
2661 spin_lock(&inode->i_lock);
2662 inode->i_private = &shmem_falloc;
2663 spin_unlock(&inode->i_lock);
2665 for (index = start; index < end; index++) {
2666 struct page *page;
2669 * Good, the fallocate(2) manpage permits EINTR: we may have
2670 * been interrupted because we are using up too much memory.
2672 if (signal_pending(current))
2673 error = -EINTR;
2674 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2675 error = -ENOMEM;
2676 else
2677 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2678 if (error) {
2679 /* Remove the !PageUptodate pages we added */
2680 if (index > start) {
2681 shmem_undo_range(inode,
2682 (loff_t)start << PAGE_SHIFT,
2683 ((loff_t)index << PAGE_SHIFT) - 1, true);
2685 goto undone;
2689 * Inform shmem_writepage() how far we have reached.
2690 * No need for lock or barrier: we have the page lock.
2692 shmem_falloc.next++;
2693 if (!PageUptodate(page))
2694 shmem_falloc.nr_falloced++;
2697 * If !PageUptodate, leave it that way so that freeable pages
2698 * can be recognized if we need to rollback on error later.
2699 * But set_page_dirty so that memory pressure will swap rather
2700 * than free the pages we are allocating (and SGP_CACHE pages
2701 * might still be clean: we now need to mark those dirty too).
2703 set_page_dirty(page);
2704 unlock_page(page);
2705 put_page(page);
2706 cond_resched();
2709 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2710 i_size_write(inode, offset + len);
2711 inode->i_ctime = current_time(inode);
2712 undone:
2713 spin_lock(&inode->i_lock);
2714 inode->i_private = NULL;
2715 spin_unlock(&inode->i_lock);
2716 out:
2717 inode_unlock(inode);
2718 return error;
2721 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2723 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2725 buf->f_type = TMPFS_MAGIC;
2726 buf->f_bsize = PAGE_SIZE;
2727 buf->f_namelen = NAME_MAX;
2728 if (sbinfo->max_blocks) {
2729 buf->f_blocks = sbinfo->max_blocks;
2730 buf->f_bavail =
2731 buf->f_bfree = sbinfo->max_blocks -
2732 percpu_counter_sum(&sbinfo->used_blocks);
2734 if (sbinfo->max_inodes) {
2735 buf->f_files = sbinfo->max_inodes;
2736 buf->f_ffree = sbinfo->free_inodes;
2738 /* else leave those fields 0 like simple_statfs */
2739 return 0;
2743 * File creation. Allocate an inode, and we're done..
2745 static int
2746 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2748 struct inode *inode;
2749 int error = -ENOSPC;
2751 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2752 if (inode) {
2753 error = simple_acl_create(dir, inode);
2754 if (error)
2755 goto out_iput;
2756 error = security_inode_init_security(inode, dir,
2757 &dentry->d_name,
2758 shmem_initxattrs, NULL);
2759 if (error && error != -EOPNOTSUPP)
2760 goto out_iput;
2762 error = 0;
2763 dir->i_size += BOGO_DIRENT_SIZE;
2764 dir->i_ctime = dir->i_mtime = current_time(dir);
2765 d_instantiate(dentry, inode);
2766 dget(dentry); /* Extra count - pin the dentry in core */
2768 return error;
2769 out_iput:
2770 iput(inode);
2771 return error;
2774 static int
2775 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2777 struct inode *inode;
2778 int error = -ENOSPC;
2780 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2781 if (inode) {
2782 error = security_inode_init_security(inode, dir,
2783 NULL,
2784 shmem_initxattrs, NULL);
2785 if (error && error != -EOPNOTSUPP)
2786 goto out_iput;
2787 error = simple_acl_create(dir, inode);
2788 if (error)
2789 goto out_iput;
2790 d_tmpfile(dentry, inode);
2792 return error;
2793 out_iput:
2794 iput(inode);
2795 return error;
2798 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2800 int error;
2802 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
2803 return error;
2804 inc_nlink(dir);
2805 return 0;
2808 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2809 bool excl)
2811 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
2815 * Link a file..
2817 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2819 struct inode *inode = d_inode(old_dentry);
2820 int ret;
2823 * No ordinary (disk based) filesystem counts links as inodes;
2824 * but each new link needs a new dentry, pinning lowmem, and
2825 * tmpfs dentries cannot be pruned until they are unlinked.
2827 ret = shmem_reserve_inode(inode->i_sb);
2828 if (ret)
2829 goto out;
2831 dir->i_size += BOGO_DIRENT_SIZE;
2832 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2833 inc_nlink(inode);
2834 ihold(inode); /* New dentry reference */
2835 dget(dentry); /* Extra pinning count for the created dentry */
2836 d_instantiate(dentry, inode);
2837 out:
2838 return ret;
2841 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
2843 struct inode *inode = d_inode(dentry);
2845 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
2846 shmem_free_inode(inode->i_sb);
2848 dir->i_size -= BOGO_DIRENT_SIZE;
2849 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2850 drop_nlink(inode);
2851 dput(dentry); /* Undo the count from "create" - this does all the work */
2852 return 0;
2855 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
2857 if (!simple_empty(dentry))
2858 return -ENOTEMPTY;
2860 drop_nlink(d_inode(dentry));
2861 drop_nlink(dir);
2862 return shmem_unlink(dir, dentry);
2865 static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
2867 bool old_is_dir = d_is_dir(old_dentry);
2868 bool new_is_dir = d_is_dir(new_dentry);
2870 if (old_dir != new_dir && old_is_dir != new_is_dir) {
2871 if (old_is_dir) {
2872 drop_nlink(old_dir);
2873 inc_nlink(new_dir);
2874 } else {
2875 drop_nlink(new_dir);
2876 inc_nlink(old_dir);
2879 old_dir->i_ctime = old_dir->i_mtime =
2880 new_dir->i_ctime = new_dir->i_mtime =
2881 d_inode(old_dentry)->i_ctime =
2882 d_inode(new_dentry)->i_ctime = current_time(old_dir);
2884 return 0;
2887 static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
2889 struct dentry *whiteout;
2890 int error;
2892 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
2893 if (!whiteout)
2894 return -ENOMEM;
2896 error = shmem_mknod(old_dir, whiteout,
2897 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
2898 dput(whiteout);
2899 if (error)
2900 return error;
2903 * Cheat and hash the whiteout while the old dentry is still in
2904 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
2906 * d_lookup() will consistently find one of them at this point,
2907 * not sure which one, but that isn't even important.
2909 d_rehash(whiteout);
2910 return 0;
2914 * The VFS layer already does all the dentry stuff for rename,
2915 * we just have to decrement the usage count for the target if
2916 * it exists so that the VFS layer correctly free's it when it
2917 * gets overwritten.
2919 static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
2921 struct inode *inode = d_inode(old_dentry);
2922 int they_are_dirs = S_ISDIR(inode->i_mode);
2924 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
2925 return -EINVAL;
2927 if (flags & RENAME_EXCHANGE)
2928 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
2930 if (!simple_empty(new_dentry))
2931 return -ENOTEMPTY;
2933 if (flags & RENAME_WHITEOUT) {
2934 int error;
2936 error = shmem_whiteout(old_dir, old_dentry);
2937 if (error)
2938 return error;
2941 if (d_really_is_positive(new_dentry)) {
2942 (void) shmem_unlink(new_dir, new_dentry);
2943 if (they_are_dirs) {
2944 drop_nlink(d_inode(new_dentry));
2945 drop_nlink(old_dir);
2947 } else if (they_are_dirs) {
2948 drop_nlink(old_dir);
2949 inc_nlink(new_dir);
2952 old_dir->i_size -= BOGO_DIRENT_SIZE;
2953 new_dir->i_size += BOGO_DIRENT_SIZE;
2954 old_dir->i_ctime = old_dir->i_mtime =
2955 new_dir->i_ctime = new_dir->i_mtime =
2956 inode->i_ctime = current_time(old_dir);
2957 return 0;
2960 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
2962 int error;
2963 int len;
2964 struct inode *inode;
2965 struct page *page;
2967 len = strlen(symname) + 1;
2968 if (len > PAGE_SIZE)
2969 return -ENAMETOOLONG;
2971 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
2972 VM_NORESERVE);
2973 if (!inode)
2974 return -ENOSPC;
2976 error = security_inode_init_security(inode, dir, &dentry->d_name,
2977 shmem_initxattrs, NULL);
2978 if (error) {
2979 if (error != -EOPNOTSUPP) {
2980 iput(inode);
2981 return error;
2983 error = 0;
2986 inode->i_size = len-1;
2987 if (len <= SHORT_SYMLINK_LEN) {
2988 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
2989 if (!inode->i_link) {
2990 iput(inode);
2991 return -ENOMEM;
2993 inode->i_op = &shmem_short_symlink_operations;
2994 } else {
2995 inode_nohighmem(inode);
2996 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
2997 if (error) {
2998 iput(inode);
2999 return error;
3001 inode->i_mapping->a_ops = &shmem_aops;
3002 inode->i_op = &shmem_symlink_inode_operations;
3003 memcpy(page_address(page), symname, len);
3004 SetPageUptodate(page);
3005 set_page_dirty(page);
3006 unlock_page(page);
3007 put_page(page);
3009 dir->i_size += BOGO_DIRENT_SIZE;
3010 dir->i_ctime = dir->i_mtime = current_time(dir);
3011 d_instantiate(dentry, inode);
3012 dget(dentry);
3013 return 0;
3016 static void shmem_put_link(void *arg)
3018 mark_page_accessed(arg);
3019 put_page(arg);
3022 static const char *shmem_get_link(struct dentry *dentry,
3023 struct inode *inode,
3024 struct delayed_call *done)
3026 struct page *page = NULL;
3027 int error;
3028 if (!dentry) {
3029 page = find_get_page(inode->i_mapping, 0);
3030 if (!page)
3031 return ERR_PTR(-ECHILD);
3032 if (!PageUptodate(page)) {
3033 put_page(page);
3034 return ERR_PTR(-ECHILD);
3036 } else {
3037 error = shmem_getpage(inode, 0, &page, SGP_READ);
3038 if (error)
3039 return ERR_PTR(error);
3040 unlock_page(page);
3042 set_delayed_call(done, shmem_put_link, page);
3043 return page_address(page);
3046 #ifdef CONFIG_TMPFS_XATTR
3048 * Superblocks without xattr inode operations may get some security.* xattr
3049 * support from the LSM "for free". As soon as we have any other xattrs
3050 * like ACLs, we also need to implement the security.* handlers at
3051 * filesystem level, though.
3055 * Callback for security_inode_init_security() for acquiring xattrs.
3057 static int shmem_initxattrs(struct inode *inode,
3058 const struct xattr *xattr_array,
3059 void *fs_info)
3061 struct shmem_inode_info *info = SHMEM_I(inode);
3062 const struct xattr *xattr;
3063 struct simple_xattr *new_xattr;
3064 size_t len;
3066 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3067 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3068 if (!new_xattr)
3069 return -ENOMEM;
3071 len = strlen(xattr->name) + 1;
3072 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3073 GFP_KERNEL);
3074 if (!new_xattr->name) {
3075 kfree(new_xattr);
3076 return -ENOMEM;
3079 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3080 XATTR_SECURITY_PREFIX_LEN);
3081 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3082 xattr->name, len);
3084 simple_xattr_list_add(&info->xattrs, new_xattr);
3087 return 0;
3090 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3091 struct dentry *unused, struct inode *inode,
3092 const char *name, void *buffer, size_t size)
3094 struct shmem_inode_info *info = SHMEM_I(inode);
3096 name = xattr_full_name(handler, name);
3097 return simple_xattr_get(&info->xattrs, name, buffer, size);
3100 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3101 struct dentry *unused, struct inode *inode,
3102 const char *name, const void *value,
3103 size_t size, int flags)
3105 struct shmem_inode_info *info = SHMEM_I(inode);
3107 name = xattr_full_name(handler, name);
3108 return simple_xattr_set(&info->xattrs, name, value, size, flags);
3111 static const struct xattr_handler shmem_security_xattr_handler = {
3112 .prefix = XATTR_SECURITY_PREFIX,
3113 .get = shmem_xattr_handler_get,
3114 .set = shmem_xattr_handler_set,
3117 static const struct xattr_handler shmem_trusted_xattr_handler = {
3118 .prefix = XATTR_TRUSTED_PREFIX,
3119 .get = shmem_xattr_handler_get,
3120 .set = shmem_xattr_handler_set,
3123 static const struct xattr_handler *shmem_xattr_handlers[] = {
3124 #ifdef CONFIG_TMPFS_POSIX_ACL
3125 &posix_acl_access_xattr_handler,
3126 &posix_acl_default_xattr_handler,
3127 #endif
3128 &shmem_security_xattr_handler,
3129 &shmem_trusted_xattr_handler,
3130 NULL
3133 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3135 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3136 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3138 #endif /* CONFIG_TMPFS_XATTR */
3140 static const struct inode_operations shmem_short_symlink_operations = {
3141 .get_link = simple_get_link,
3142 #ifdef CONFIG_TMPFS_XATTR
3143 .listxattr = shmem_listxattr,
3144 #endif
3147 static const struct inode_operations shmem_symlink_inode_operations = {
3148 .get_link = shmem_get_link,
3149 #ifdef CONFIG_TMPFS_XATTR
3150 .listxattr = shmem_listxattr,
3151 #endif
3154 static struct dentry *shmem_get_parent(struct dentry *child)
3156 return ERR_PTR(-ESTALE);
3159 static int shmem_match(struct inode *ino, void *vfh)
3161 __u32 *fh = vfh;
3162 __u64 inum = fh[2];
3163 inum = (inum << 32) | fh[1];
3164 return ino->i_ino == inum && fh[0] == ino->i_generation;
3167 /* Find any alias of inode, but prefer a hashed alias */
3168 static struct dentry *shmem_find_alias(struct inode *inode)
3170 struct dentry *alias = d_find_alias(inode);
3172 return alias ?: d_find_any_alias(inode);
3176 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3177 struct fid *fid, int fh_len, int fh_type)
3179 struct inode *inode;
3180 struct dentry *dentry = NULL;
3181 u64 inum;
3183 if (fh_len < 3)
3184 return NULL;
3186 inum = fid->raw[2];
3187 inum = (inum << 32) | fid->raw[1];
3189 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
3190 shmem_match, fid->raw);
3191 if (inode) {
3192 dentry = shmem_find_alias(inode);
3193 iput(inode);
3196 return dentry;
3199 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3200 struct inode *parent)
3202 if (*len < 3) {
3203 *len = 3;
3204 return FILEID_INVALID;
3207 if (inode_unhashed(inode)) {
3208 /* Unfortunately insert_inode_hash is not idempotent,
3209 * so as we hash inodes here rather than at creation
3210 * time, we need a lock to ensure we only try
3211 * to do it once
3213 static DEFINE_SPINLOCK(lock);
3214 spin_lock(&lock);
3215 if (inode_unhashed(inode))
3216 __insert_inode_hash(inode,
3217 inode->i_ino + inode->i_generation);
3218 spin_unlock(&lock);
3221 fh[0] = inode->i_generation;
3222 fh[1] = inode->i_ino;
3223 fh[2] = ((__u64)inode->i_ino) >> 32;
3225 *len = 3;
3226 return 1;
3229 static const struct export_operations shmem_export_ops = {
3230 .get_parent = shmem_get_parent,
3231 .encode_fh = shmem_encode_fh,
3232 .fh_to_dentry = shmem_fh_to_dentry,
3235 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
3236 bool remount)
3238 char *this_char, *value, *rest;
3239 struct mempolicy *mpol = NULL;
3240 uid_t uid;
3241 gid_t gid;
3243 while (options != NULL) {
3244 this_char = options;
3245 for (;;) {
3247 * NUL-terminate this option: unfortunately,
3248 * mount options form a comma-separated list,
3249 * but mpol's nodelist may also contain commas.
3251 options = strchr(options, ',');
3252 if (options == NULL)
3253 break;
3254 options++;
3255 if (!isdigit(*options)) {
3256 options[-1] = '\0';
3257 break;
3260 if (!*this_char)
3261 continue;
3262 if ((value = strchr(this_char,'=')) != NULL) {
3263 *value++ = 0;
3264 } else {
3265 pr_err("tmpfs: No value for mount option '%s'\n",
3266 this_char);
3267 goto error;
3270 if (!strcmp(this_char,"size")) {
3271 unsigned long long size;
3272 size = memparse(value,&rest);
3273 if (*rest == '%') {
3274 size <<= PAGE_SHIFT;
3275 size *= totalram_pages;
3276 do_div(size, 100);
3277 rest++;
3279 if (*rest)
3280 goto bad_val;
3281 sbinfo->max_blocks =
3282 DIV_ROUND_UP(size, PAGE_SIZE);
3283 } else if (!strcmp(this_char,"nr_blocks")) {
3284 sbinfo->max_blocks = memparse(value, &rest);
3285 if (*rest)
3286 goto bad_val;
3287 } else if (!strcmp(this_char,"nr_inodes")) {
3288 sbinfo->max_inodes = memparse(value, &rest);
3289 if (*rest)
3290 goto bad_val;
3291 } else if (!strcmp(this_char,"mode")) {
3292 if (remount)
3293 continue;
3294 sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
3295 if (*rest)
3296 goto bad_val;
3297 } else if (!strcmp(this_char,"uid")) {
3298 if (remount)
3299 continue;
3300 uid = simple_strtoul(value, &rest, 0);
3301 if (*rest)
3302 goto bad_val;
3303 sbinfo->uid = make_kuid(current_user_ns(), uid);
3304 if (!uid_valid(sbinfo->uid))
3305 goto bad_val;
3306 } else if (!strcmp(this_char,"gid")) {
3307 if (remount)
3308 continue;
3309 gid = simple_strtoul(value, &rest, 0);
3310 if (*rest)
3311 goto bad_val;
3312 sbinfo->gid = make_kgid(current_user_ns(), gid);
3313 if (!gid_valid(sbinfo->gid))
3314 goto bad_val;
3315 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3316 } else if (!strcmp(this_char, "huge")) {
3317 int huge;
3318 huge = shmem_parse_huge(value);
3319 if (huge < 0)
3320 goto bad_val;
3321 if (!has_transparent_hugepage() &&
3322 huge != SHMEM_HUGE_NEVER)
3323 goto bad_val;
3324 sbinfo->huge = huge;
3325 #endif
3326 #ifdef CONFIG_NUMA
3327 } else if (!strcmp(this_char,"mpol")) {
3328 mpol_put(mpol);
3329 mpol = NULL;
3330 if (mpol_parse_str(value, &mpol))
3331 goto bad_val;
3332 #endif
3333 } else {
3334 pr_err("tmpfs: Bad mount option %s\n", this_char);
3335 goto error;
3338 sbinfo->mpol = mpol;
3339 return 0;
3341 bad_val:
3342 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3343 value, this_char);
3344 error:
3345 mpol_put(mpol);
3346 return 1;
3350 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
3352 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3353 struct shmem_sb_info config = *sbinfo;
3354 unsigned long inodes;
3355 int error = -EINVAL;
3357 config.mpol = NULL;
3358 if (shmem_parse_options(data, &config, true))
3359 return error;
3361 spin_lock(&sbinfo->stat_lock);
3362 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3363 if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
3364 goto out;
3365 if (config.max_inodes < inodes)
3366 goto out;
3368 * Those tests disallow limited->unlimited while any are in use;
3369 * but we must separately disallow unlimited->limited, because
3370 * in that case we have no record of how much is already in use.
3372 if (config.max_blocks && !sbinfo->max_blocks)
3373 goto out;
3374 if (config.max_inodes && !sbinfo->max_inodes)
3375 goto out;
3377 error = 0;
3378 sbinfo->huge = config.huge;
3379 sbinfo->max_blocks = config.max_blocks;
3380 sbinfo->max_inodes = config.max_inodes;
3381 sbinfo->free_inodes = config.max_inodes - inodes;
3384 * Preserve previous mempolicy unless mpol remount option was specified.
3386 if (config.mpol) {
3387 mpol_put(sbinfo->mpol);
3388 sbinfo->mpol = config.mpol; /* transfers initial ref */
3390 out:
3391 spin_unlock(&sbinfo->stat_lock);
3392 return error;
3395 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3397 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3399 if (sbinfo->max_blocks != shmem_default_max_blocks())
3400 seq_printf(seq, ",size=%luk",
3401 sbinfo->max_blocks << (PAGE_SHIFT - 10));
3402 if (sbinfo->max_inodes != shmem_default_max_inodes())
3403 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
3404 if (sbinfo->mode != (0777 | S_ISVTX))
3405 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3406 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3407 seq_printf(seq, ",uid=%u",
3408 from_kuid_munged(&init_user_ns, sbinfo->uid));
3409 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3410 seq_printf(seq, ",gid=%u",
3411 from_kgid_munged(&init_user_ns, sbinfo->gid));
3412 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3413 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3414 if (sbinfo->huge)
3415 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3416 #endif
3417 shmem_show_mpol(seq, sbinfo->mpol);
3418 return 0;
3421 #endif /* CONFIG_TMPFS */
3423 static void shmem_put_super(struct super_block *sb)
3425 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3427 percpu_counter_destroy(&sbinfo->used_blocks);
3428 mpol_put(sbinfo->mpol);
3429 kfree(sbinfo);
3430 sb->s_fs_info = NULL;
3433 int shmem_fill_super(struct super_block *sb, void *data, int silent)
3435 struct inode *inode;
3436 struct shmem_sb_info *sbinfo;
3437 int err = -ENOMEM;
3439 /* Round up to L1_CACHE_BYTES to resist false sharing */
3440 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3441 L1_CACHE_BYTES), GFP_KERNEL);
3442 if (!sbinfo)
3443 return -ENOMEM;
3445 sbinfo->mode = 0777 | S_ISVTX;
3446 sbinfo->uid = current_fsuid();
3447 sbinfo->gid = current_fsgid();
3448 sb->s_fs_info = sbinfo;
3450 #ifdef CONFIG_TMPFS
3452 * Per default we only allow half of the physical ram per
3453 * tmpfs instance, limiting inodes to one per page of lowmem;
3454 * but the internal instance is left unlimited.
3456 if (!(sb->s_flags & SB_KERNMOUNT)) {
3457 sbinfo->max_blocks = shmem_default_max_blocks();
3458 sbinfo->max_inodes = shmem_default_max_inodes();
3459 if (shmem_parse_options(data, sbinfo, false)) {
3460 err = -EINVAL;
3461 goto failed;
3463 } else {
3464 sb->s_flags |= SB_NOUSER;
3466 sb->s_export_op = &shmem_export_ops;
3467 sb->s_flags |= SB_NOSEC;
3468 #else
3469 sb->s_flags |= SB_NOUSER;
3470 #endif
3472 spin_lock_init(&sbinfo->stat_lock);
3473 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3474 goto failed;
3475 sbinfo->free_inodes = sbinfo->max_inodes;
3476 spin_lock_init(&sbinfo->shrinklist_lock);
3477 INIT_LIST_HEAD(&sbinfo->shrinklist);
3479 sb->s_maxbytes = MAX_LFS_FILESIZE;
3480 sb->s_blocksize = PAGE_SIZE;
3481 sb->s_blocksize_bits = PAGE_SHIFT;
3482 sb->s_magic = TMPFS_MAGIC;
3483 sb->s_op = &shmem_ops;
3484 sb->s_time_gran = 1;
3485 #ifdef CONFIG_TMPFS_XATTR
3486 sb->s_xattr = shmem_xattr_handlers;
3487 #endif
3488 #ifdef CONFIG_TMPFS_POSIX_ACL
3489 sb->s_flags |= SB_POSIXACL;
3490 #endif
3491 uuid_gen(&sb->s_uuid);
3493 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3494 if (!inode)
3495 goto failed;
3496 inode->i_uid = sbinfo->uid;
3497 inode->i_gid = sbinfo->gid;
3498 sb->s_root = d_make_root(inode);
3499 if (!sb->s_root)
3500 goto failed;
3501 return 0;
3503 failed:
3504 shmem_put_super(sb);
3505 return err;
3508 static struct kmem_cache *shmem_inode_cachep;
3510 static struct inode *shmem_alloc_inode(struct super_block *sb)
3512 struct shmem_inode_info *info;
3513 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3514 if (!info)
3515 return NULL;
3516 return &info->vfs_inode;
3519 static void shmem_destroy_callback(struct rcu_head *head)
3521 struct inode *inode = container_of(head, struct inode, i_rcu);
3522 if (S_ISLNK(inode->i_mode))
3523 kfree(inode->i_link);
3524 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3527 static void shmem_destroy_inode(struct inode *inode)
3529 if (S_ISREG(inode->i_mode))
3530 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3531 call_rcu(&inode->i_rcu, shmem_destroy_callback);
3534 static void shmem_init_inode(void *foo)
3536 struct shmem_inode_info *info = foo;
3537 inode_init_once(&info->vfs_inode);
3540 static void shmem_init_inodecache(void)
3542 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3543 sizeof(struct shmem_inode_info),
3544 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3547 static void shmem_destroy_inodecache(void)
3549 kmem_cache_destroy(shmem_inode_cachep);
3552 static const struct address_space_operations shmem_aops = {
3553 .writepage = shmem_writepage,
3554 .set_page_dirty = __set_page_dirty_no_writeback,
3555 #ifdef CONFIG_TMPFS
3556 .write_begin = shmem_write_begin,
3557 .write_end = shmem_write_end,
3558 #endif
3559 #ifdef CONFIG_MIGRATION
3560 .migratepage = migrate_page,
3561 #endif
3562 .error_remove_page = generic_error_remove_page,
3565 static const struct file_operations shmem_file_operations = {
3566 .mmap = shmem_mmap,
3567 .get_unmapped_area = shmem_get_unmapped_area,
3568 #ifdef CONFIG_TMPFS
3569 .llseek = shmem_file_llseek,
3570 .read_iter = shmem_file_read_iter,
3571 .write_iter = generic_file_write_iter,
3572 .fsync = noop_fsync,
3573 .splice_read = generic_file_splice_read,
3574 .splice_write = iter_file_splice_write,
3575 .fallocate = shmem_fallocate,
3576 #endif
3579 static const struct inode_operations shmem_inode_operations = {
3580 .getattr = shmem_getattr,
3581 .setattr = shmem_setattr,
3582 #ifdef CONFIG_TMPFS_XATTR
3583 .listxattr = shmem_listxattr,
3584 .set_acl = simple_set_acl,
3585 #endif
3588 static const struct inode_operations shmem_dir_inode_operations = {
3589 #ifdef CONFIG_TMPFS
3590 .create = shmem_create,
3591 .lookup = simple_lookup,
3592 .link = shmem_link,
3593 .unlink = shmem_unlink,
3594 .symlink = shmem_symlink,
3595 .mkdir = shmem_mkdir,
3596 .rmdir = shmem_rmdir,
3597 .mknod = shmem_mknod,
3598 .rename = shmem_rename2,
3599 .tmpfile = shmem_tmpfile,
3600 #endif
3601 #ifdef CONFIG_TMPFS_XATTR
3602 .listxattr = shmem_listxattr,
3603 #endif
3604 #ifdef CONFIG_TMPFS_POSIX_ACL
3605 .setattr = shmem_setattr,
3606 .set_acl = simple_set_acl,
3607 #endif
3610 static const struct inode_operations shmem_special_inode_operations = {
3611 #ifdef CONFIG_TMPFS_XATTR
3612 .listxattr = shmem_listxattr,
3613 #endif
3614 #ifdef CONFIG_TMPFS_POSIX_ACL
3615 .setattr = shmem_setattr,
3616 .set_acl = simple_set_acl,
3617 #endif
3620 static const struct super_operations shmem_ops = {
3621 .alloc_inode = shmem_alloc_inode,
3622 .destroy_inode = shmem_destroy_inode,
3623 #ifdef CONFIG_TMPFS
3624 .statfs = shmem_statfs,
3625 .remount_fs = shmem_remount_fs,
3626 .show_options = shmem_show_options,
3627 #endif
3628 .evict_inode = shmem_evict_inode,
3629 .drop_inode = generic_delete_inode,
3630 .put_super = shmem_put_super,
3631 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3632 .nr_cached_objects = shmem_unused_huge_count,
3633 .free_cached_objects = shmem_unused_huge_scan,
3634 #endif
3637 static const struct vm_operations_struct shmem_vm_ops = {
3638 .fault = shmem_fault,
3639 .map_pages = filemap_map_pages,
3640 #ifdef CONFIG_NUMA
3641 .set_policy = shmem_set_policy,
3642 .get_policy = shmem_get_policy,
3643 #endif
3646 static struct dentry *shmem_mount(struct file_system_type *fs_type,
3647 int flags, const char *dev_name, void *data)
3649 return mount_nodev(fs_type, flags, data, shmem_fill_super);
3652 static struct file_system_type shmem_fs_type = {
3653 .owner = THIS_MODULE,
3654 .name = "tmpfs",
3655 .mount = shmem_mount,
3656 .kill_sb = kill_litter_super,
3657 .fs_flags = FS_USERNS_MOUNT,
3660 int __init shmem_init(void)
3662 int error;
3664 /* If rootfs called this, don't re-init */
3665 if (shmem_inode_cachep)
3666 return 0;
3668 shmem_init_inodecache();
3670 error = register_filesystem(&shmem_fs_type);
3671 if (error) {
3672 pr_err("Could not register tmpfs\n");
3673 goto out2;
3676 shm_mnt = kern_mount(&shmem_fs_type);
3677 if (IS_ERR(shm_mnt)) {
3678 error = PTR_ERR(shm_mnt);
3679 pr_err("Could not kern_mount tmpfs\n");
3680 goto out1;
3683 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3684 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
3685 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3686 else
3687 shmem_huge = 0; /* just in case it was patched */
3688 #endif
3689 return 0;
3691 out1:
3692 unregister_filesystem(&shmem_fs_type);
3693 out2:
3694 shmem_destroy_inodecache();
3695 shm_mnt = ERR_PTR(error);
3696 return error;
3699 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
3700 static ssize_t shmem_enabled_show(struct kobject *kobj,
3701 struct kobj_attribute *attr, char *buf)
3703 int values[] = {
3704 SHMEM_HUGE_ALWAYS,
3705 SHMEM_HUGE_WITHIN_SIZE,
3706 SHMEM_HUGE_ADVISE,
3707 SHMEM_HUGE_NEVER,
3708 SHMEM_HUGE_DENY,
3709 SHMEM_HUGE_FORCE,
3711 int i, count;
3713 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
3714 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
3716 count += sprintf(buf + count, fmt,
3717 shmem_format_huge(values[i]));
3719 buf[count - 1] = '\n';
3720 return count;
3723 static ssize_t shmem_enabled_store(struct kobject *kobj,
3724 struct kobj_attribute *attr, const char *buf, size_t count)
3726 char tmp[16];
3727 int huge;
3729 if (count + 1 > sizeof(tmp))
3730 return -EINVAL;
3731 memcpy(tmp, buf, count);
3732 tmp[count] = '\0';
3733 if (count && tmp[count - 1] == '\n')
3734 tmp[count - 1] = '\0';
3736 huge = shmem_parse_huge(tmp);
3737 if (huge == -EINVAL)
3738 return -EINVAL;
3739 if (!has_transparent_hugepage() &&
3740 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
3741 return -EINVAL;
3743 shmem_huge = huge;
3744 if (shmem_huge > SHMEM_HUGE_DENY)
3745 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3746 return count;
3749 struct kobj_attribute shmem_enabled_attr =
3750 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
3751 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
3753 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3754 bool shmem_huge_enabled(struct vm_area_struct *vma)
3756 struct inode *inode = file_inode(vma->vm_file);
3757 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3758 loff_t i_size;
3759 pgoff_t off;
3761 if (shmem_huge == SHMEM_HUGE_FORCE)
3762 return true;
3763 if (shmem_huge == SHMEM_HUGE_DENY)
3764 return false;
3765 switch (sbinfo->huge) {
3766 case SHMEM_HUGE_NEVER:
3767 return false;
3768 case SHMEM_HUGE_ALWAYS:
3769 return true;
3770 case SHMEM_HUGE_WITHIN_SIZE:
3771 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
3772 i_size = round_up(i_size_read(inode), PAGE_SIZE);
3773 if (i_size >= HPAGE_PMD_SIZE &&
3774 i_size >> PAGE_SHIFT >= off)
3775 return true;
3776 /* fall through */
3777 case SHMEM_HUGE_ADVISE:
3778 /* TODO: implement fadvise() hints */
3779 return (vma->vm_flags & VM_HUGEPAGE);
3780 default:
3781 VM_BUG_ON(1);
3782 return false;
3785 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
3787 #else /* !CONFIG_SHMEM */
3790 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3792 * This is intended for small system where the benefits of the full
3793 * shmem code (swap-backed and resource-limited) are outweighed by
3794 * their complexity. On systems without swap this code should be
3795 * effectively equivalent, but much lighter weight.
3798 static struct file_system_type shmem_fs_type = {
3799 .name = "tmpfs",
3800 .mount = ramfs_mount,
3801 .kill_sb = kill_litter_super,
3802 .fs_flags = FS_USERNS_MOUNT,
3805 int __init shmem_init(void)
3807 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3809 shm_mnt = kern_mount(&shmem_fs_type);
3810 BUG_ON(IS_ERR(shm_mnt));
3812 return 0;
3815 int shmem_unuse(swp_entry_t swap, struct page *page)
3817 return 0;
3820 int shmem_lock(struct file *file, int lock, struct user_struct *user)
3822 return 0;
3825 void shmem_unlock_mapping(struct address_space *mapping)
3829 #ifdef CONFIG_MMU
3830 unsigned long shmem_get_unmapped_area(struct file *file,
3831 unsigned long addr, unsigned long len,
3832 unsigned long pgoff, unsigned long flags)
3834 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
3836 #endif
3838 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
3840 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
3842 EXPORT_SYMBOL_GPL(shmem_truncate_range);
3844 #define shmem_vm_ops generic_file_vm_ops
3845 #define shmem_file_operations ramfs_file_operations
3846 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
3847 #define shmem_acct_size(flags, size) 0
3848 #define shmem_unacct_size(flags, size) do {} while (0)
3850 #endif /* CONFIG_SHMEM */
3852 /* common code */
3854 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
3855 unsigned long flags, unsigned int i_flags)
3857 struct inode *inode;
3858 struct file *res;
3860 if (IS_ERR(mnt))
3861 return ERR_CAST(mnt);
3863 if (size < 0 || size > MAX_LFS_FILESIZE)
3864 return ERR_PTR(-EINVAL);
3866 if (shmem_acct_size(flags, size))
3867 return ERR_PTR(-ENOMEM);
3869 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
3870 flags);
3871 if (unlikely(!inode)) {
3872 shmem_unacct_size(flags, size);
3873 return ERR_PTR(-ENOSPC);
3875 inode->i_flags |= i_flags;
3876 inode->i_size = size;
3877 clear_nlink(inode); /* It is unlinked */
3878 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
3879 if (!IS_ERR(res))
3880 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
3881 &shmem_file_operations);
3882 if (IS_ERR(res))
3883 iput(inode);
3884 return res;
3888 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
3889 * kernel internal. There will be NO LSM permission checks against the
3890 * underlying inode. So users of this interface must do LSM checks at a
3891 * higher layer. The users are the big_key and shm implementations. LSM
3892 * checks are provided at the key or shm level rather than the inode.
3893 * @name: name for dentry (to be seen in /proc/<pid>/maps
3894 * @size: size to be set for the file
3895 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3897 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
3899 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
3903 * shmem_file_setup - get an unlinked file living in tmpfs
3904 * @name: name for dentry (to be seen in /proc/<pid>/maps
3905 * @size: size to be set for the file
3906 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3908 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
3910 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
3912 EXPORT_SYMBOL_GPL(shmem_file_setup);
3915 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
3916 * @mnt: the tmpfs mount where the file will be created
3917 * @name: name for dentry (to be seen in /proc/<pid>/maps
3918 * @size: size to be set for the file
3919 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3921 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
3922 loff_t size, unsigned long flags)
3924 return __shmem_file_setup(mnt, name, size, flags, 0);
3926 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
3929 * shmem_zero_setup - setup a shared anonymous mapping
3930 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
3932 int shmem_zero_setup(struct vm_area_struct *vma)
3934 struct file *file;
3935 loff_t size = vma->vm_end - vma->vm_start;
3938 * Cloning a new file under mmap_sem leads to a lock ordering conflict
3939 * between XFS directory reading and selinux: since this file is only
3940 * accessible to the user through its mapping, use S_PRIVATE flag to
3941 * bypass file security, in the same way as shmem_kernel_file_setup().
3943 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
3944 if (IS_ERR(file))
3945 return PTR_ERR(file);
3947 if (vma->vm_file)
3948 fput(vma->vm_file);
3949 vma->vm_file = file;
3950 vma->vm_ops = &shmem_vm_ops;
3952 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
3953 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
3954 (vma->vm_end & HPAGE_PMD_MASK)) {
3955 khugepaged_enter(vma, vma->vm_flags);
3958 return 0;
3962 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
3963 * @mapping: the page's address_space
3964 * @index: the page index
3965 * @gfp: the page allocator flags to use if allocating
3967 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
3968 * with any new page allocations done using the specified allocation flags.
3969 * But read_cache_page_gfp() uses the ->readpage() method: which does not
3970 * suit tmpfs, since it may have pages in swapcache, and needs to find those
3971 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
3973 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
3974 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
3976 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
3977 pgoff_t index, gfp_t gfp)
3979 #ifdef CONFIG_SHMEM
3980 struct inode *inode = mapping->host;
3981 struct page *page;
3982 int error;
3984 BUG_ON(mapping->a_ops != &shmem_aops);
3985 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
3986 gfp, NULL, NULL, NULL);
3987 if (error)
3988 page = ERR_PTR(error);
3989 else
3990 unlock_page(page);
3991 return page;
3992 #else
3994 * The tiny !SHMEM case uses ramfs without swap
3996 return read_cache_page_gfp(mapping, index, gfp);
3997 #endif
3999 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);