]> git.proxmox.com Git - mirror_ubuntu-disco-kernel.git/blob - mm/shmem.c
mm, swap: bounds check swap_info array accesses to avoid NULL derefs
[mirror_ubuntu-disco-kernel.git] / mm / shmem.c
1 /*
2 * Resizable virtual memory filesystem for Linux.
3 *
4 * Copyright (C) 2000 Linus Torvalds.
5 * 2000 Transmeta Corp.
6 * 2000-2001 Christoph Rohland
7 * 2000-2001 SAP AG
8 * 2002 Red Hat Inc.
9 * Copyright (C) 2002-2011 Hugh Dickins.
10 * Copyright (C) 2011 Google Inc.
11 * Copyright (C) 2002-2005 VERITAS Software Corporation.
12 * Copyright (C) 2004 Andi Kleen, SuSE Labs
13 *
14 * Extended attribute support for tmpfs:
15 * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
16 * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
17 *
18 * tiny-shmem:
19 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
20 *
21 * This file is released under the GPL.
22 */
23
24 #include <linux/fs.h>
25 #include <linux/init.h>
26 #include <linux/vfs.h>
27 #include <linux/mount.h>
28 #include <linux/ramfs.h>
29 #include <linux/pagemap.h>
30 #include <linux/file.h>
31 #include <linux/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>
39
40 #include <asm/tlbflush.h> /* for arch/microblaze update_mmu_cache() */
41
42 static struct vfsmount *shm_mnt;
43
44 #ifdef CONFIG_SHMEM
45 /*
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.
49 */
50
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>
81
82 #include <linux/uaccess.h>
83 #include <asm/pgtable.h>
84
85 #include "internal.h"
86
87 #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
88 #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
89
90 /* Pretend that each entry is of this size in directory's i_size */
91 #define BOGO_DIRENT_SIZE 20
92
93 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
94 #define SHORT_SYMLINK_LEN 128
95
96 /*
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.
100 */
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 */
107 };
108
109 #ifdef CONFIG_TMPFS
110 static unsigned long shmem_default_max_blocks(void)
111 {
112 return totalram_pages() / 2;
113 }
114
115 static int shmem_default_max_inodes(void)
116 {
117 unsigned long nr_pages = totalram_pages();
118 unsigned long ul;
119
120 ul = INT_MAX;
121 ul = min3(ul, nr_pages - totalhigh_pages(), nr_pages / 2);
122 return ul;
123 }
124 #endif
125
126 static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
127 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
128 struct shmem_inode_info *info, pgoff_t index);
129 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
130 struct page **pagep, enum sgp_type sgp,
131 gfp_t gfp, struct vm_area_struct *vma,
132 struct vm_fault *vmf, vm_fault_t *fault_type);
133
134 int shmem_getpage(struct inode *inode, pgoff_t index,
135 struct page **pagep, enum sgp_type sgp)
136 {
137 return shmem_getpage_gfp(inode, index, pagep, sgp,
138 mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
139 }
140
141 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
142 {
143 return sb->s_fs_info;
144 }
145
146 /*
147 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
148 * for shared memory and for shared anonymous (/dev/zero) mappings
149 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
150 * consistent with the pre-accounting of private mappings ...
151 */
152 static inline int shmem_acct_size(unsigned long flags, loff_t size)
153 {
154 return (flags & VM_NORESERVE) ?
155 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
156 }
157
158 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
159 {
160 if (!(flags & VM_NORESERVE))
161 vm_unacct_memory(VM_ACCT(size));
162 }
163
164 static inline int shmem_reacct_size(unsigned long flags,
165 loff_t oldsize, loff_t newsize)
166 {
167 if (!(flags & VM_NORESERVE)) {
168 if (VM_ACCT(newsize) > VM_ACCT(oldsize))
169 return security_vm_enough_memory_mm(current->mm,
170 VM_ACCT(newsize) - VM_ACCT(oldsize));
171 else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
172 vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
173 }
174 return 0;
175 }
176
177 /*
178 * ... whereas tmpfs objects are accounted incrementally as
179 * pages are allocated, in order to allow large sparse files.
180 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
181 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
182 */
183 static inline int shmem_acct_block(unsigned long flags, long pages)
184 {
185 if (!(flags & VM_NORESERVE))
186 return 0;
187
188 return security_vm_enough_memory_mm(current->mm,
189 pages * VM_ACCT(PAGE_SIZE));
190 }
191
192 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
193 {
194 if (flags & VM_NORESERVE)
195 vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
196 }
197
198 static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
199 {
200 struct shmem_inode_info *info = SHMEM_I(inode);
201 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
202
203 if (shmem_acct_block(info->flags, pages))
204 return false;
205
206 if (sbinfo->max_blocks) {
207 if (percpu_counter_compare(&sbinfo->used_blocks,
208 sbinfo->max_blocks - pages) > 0)
209 goto unacct;
210 percpu_counter_add(&sbinfo->used_blocks, pages);
211 }
212
213 return true;
214
215 unacct:
216 shmem_unacct_blocks(info->flags, pages);
217 return false;
218 }
219
220 static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
221 {
222 struct shmem_inode_info *info = SHMEM_I(inode);
223 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
224
225 if (sbinfo->max_blocks)
226 percpu_counter_sub(&sbinfo->used_blocks, pages);
227 shmem_unacct_blocks(info->flags, pages);
228 }
229
230 static const struct super_operations shmem_ops;
231 static const struct address_space_operations shmem_aops;
232 static const struct file_operations shmem_file_operations;
233 static const struct inode_operations shmem_inode_operations;
234 static const struct inode_operations shmem_dir_inode_operations;
235 static const struct inode_operations shmem_special_inode_operations;
236 static const struct vm_operations_struct shmem_vm_ops;
237 static struct file_system_type shmem_fs_type;
238
239 bool vma_is_shmem(struct vm_area_struct *vma)
240 {
241 return vma->vm_ops == &shmem_vm_ops;
242 }
243
244 static LIST_HEAD(shmem_swaplist);
245 static DEFINE_MUTEX(shmem_swaplist_mutex);
246
247 static int shmem_reserve_inode(struct super_block *sb)
248 {
249 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
250 if (sbinfo->max_inodes) {
251 spin_lock(&sbinfo->stat_lock);
252 if (!sbinfo->free_inodes) {
253 spin_unlock(&sbinfo->stat_lock);
254 return -ENOSPC;
255 }
256 sbinfo->free_inodes--;
257 spin_unlock(&sbinfo->stat_lock);
258 }
259 return 0;
260 }
261
262 static void shmem_free_inode(struct super_block *sb)
263 {
264 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
265 if (sbinfo->max_inodes) {
266 spin_lock(&sbinfo->stat_lock);
267 sbinfo->free_inodes++;
268 spin_unlock(&sbinfo->stat_lock);
269 }
270 }
271
272 /**
273 * shmem_recalc_inode - recalculate the block usage of an inode
274 * @inode: inode to recalc
275 *
276 * We have to calculate the free blocks since the mm can drop
277 * undirtied hole pages behind our back.
278 *
279 * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
280 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
281 *
282 * It has to be called with the spinlock held.
283 */
284 static void shmem_recalc_inode(struct inode *inode)
285 {
286 struct shmem_inode_info *info = SHMEM_I(inode);
287 long freed;
288
289 freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
290 if (freed > 0) {
291 info->alloced -= freed;
292 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
293 shmem_inode_unacct_blocks(inode, freed);
294 }
295 }
296
297 bool shmem_charge(struct inode *inode, long pages)
298 {
299 struct shmem_inode_info *info = SHMEM_I(inode);
300 unsigned long flags;
301
302 if (!shmem_inode_acct_block(inode, pages))
303 return false;
304
305 /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
306 inode->i_mapping->nrpages += pages;
307
308 spin_lock_irqsave(&info->lock, flags);
309 info->alloced += pages;
310 inode->i_blocks += pages * BLOCKS_PER_PAGE;
311 shmem_recalc_inode(inode);
312 spin_unlock_irqrestore(&info->lock, flags);
313
314 return true;
315 }
316
317 void shmem_uncharge(struct inode *inode, long pages)
318 {
319 struct shmem_inode_info *info = SHMEM_I(inode);
320 unsigned long flags;
321
322 /* nrpages adjustment done by __delete_from_page_cache() or caller */
323
324 spin_lock_irqsave(&info->lock, flags);
325 info->alloced -= pages;
326 inode->i_blocks -= pages * BLOCKS_PER_PAGE;
327 shmem_recalc_inode(inode);
328 spin_unlock_irqrestore(&info->lock, flags);
329
330 shmem_inode_unacct_blocks(inode, pages);
331 }
332
333 /*
334 * Replace item expected in xarray by a new item, while holding xa_lock.
335 */
336 static int shmem_replace_entry(struct address_space *mapping,
337 pgoff_t index, void *expected, void *replacement)
338 {
339 XA_STATE(xas, &mapping->i_pages, index);
340 void *item;
341
342 VM_BUG_ON(!expected);
343 VM_BUG_ON(!replacement);
344 item = xas_load(&xas);
345 if (item != expected)
346 return -ENOENT;
347 xas_store(&xas, replacement);
348 return 0;
349 }
350
351 /*
352 * Sometimes, before we decide whether to proceed or to fail, we must check
353 * that an entry was not already brought back from swap by a racing thread.
354 *
355 * Checking page is not enough: by the time a SwapCache page is locked, it
356 * might be reused, and again be SwapCache, using the same swap as before.
357 */
358 static bool shmem_confirm_swap(struct address_space *mapping,
359 pgoff_t index, swp_entry_t swap)
360 {
361 return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
362 }
363
364 /*
365 * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
366 *
367 * SHMEM_HUGE_NEVER:
368 * disables huge pages for the mount;
369 * SHMEM_HUGE_ALWAYS:
370 * enables huge pages for the mount;
371 * SHMEM_HUGE_WITHIN_SIZE:
372 * only allocate huge pages if the page will be fully within i_size,
373 * also respect fadvise()/madvise() hints;
374 * SHMEM_HUGE_ADVISE:
375 * only allocate huge pages if requested with fadvise()/madvise();
376 */
377
378 #define SHMEM_HUGE_NEVER 0
379 #define SHMEM_HUGE_ALWAYS 1
380 #define SHMEM_HUGE_WITHIN_SIZE 2
381 #define SHMEM_HUGE_ADVISE 3
382
383 /*
384 * Special values.
385 * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
386 *
387 * SHMEM_HUGE_DENY:
388 * disables huge on shm_mnt and all mounts, for emergency use;
389 * SHMEM_HUGE_FORCE:
390 * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
391 *
392 */
393 #define SHMEM_HUGE_DENY (-1)
394 #define SHMEM_HUGE_FORCE (-2)
395
396 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
397 /* ifdef here to avoid bloating shmem.o when not necessary */
398
399 static int shmem_huge __read_mostly;
400
401 #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
402 static int shmem_parse_huge(const char *str)
403 {
404 if (!strcmp(str, "never"))
405 return SHMEM_HUGE_NEVER;
406 if (!strcmp(str, "always"))
407 return SHMEM_HUGE_ALWAYS;
408 if (!strcmp(str, "within_size"))
409 return SHMEM_HUGE_WITHIN_SIZE;
410 if (!strcmp(str, "advise"))
411 return SHMEM_HUGE_ADVISE;
412 if (!strcmp(str, "deny"))
413 return SHMEM_HUGE_DENY;
414 if (!strcmp(str, "force"))
415 return SHMEM_HUGE_FORCE;
416 return -EINVAL;
417 }
418
419 static const char *shmem_format_huge(int huge)
420 {
421 switch (huge) {
422 case SHMEM_HUGE_NEVER:
423 return "never";
424 case SHMEM_HUGE_ALWAYS:
425 return "always";
426 case SHMEM_HUGE_WITHIN_SIZE:
427 return "within_size";
428 case SHMEM_HUGE_ADVISE:
429 return "advise";
430 case SHMEM_HUGE_DENY:
431 return "deny";
432 case SHMEM_HUGE_FORCE:
433 return "force";
434 default:
435 VM_BUG_ON(1);
436 return "bad_val";
437 }
438 }
439 #endif
440
441 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
442 struct shrink_control *sc, unsigned long nr_to_split)
443 {
444 LIST_HEAD(list), *pos, *next;
445 LIST_HEAD(to_remove);
446 struct inode *inode;
447 struct shmem_inode_info *info;
448 struct page *page;
449 unsigned long batch = sc ? sc->nr_to_scan : 128;
450 int removed = 0, split = 0;
451
452 if (list_empty(&sbinfo->shrinklist))
453 return SHRINK_STOP;
454
455 spin_lock(&sbinfo->shrinklist_lock);
456 list_for_each_safe(pos, next, &sbinfo->shrinklist) {
457 info = list_entry(pos, struct shmem_inode_info, shrinklist);
458
459 /* pin the inode */
460 inode = igrab(&info->vfs_inode);
461
462 /* inode is about to be evicted */
463 if (!inode) {
464 list_del_init(&info->shrinklist);
465 removed++;
466 goto next;
467 }
468
469 /* Check if there's anything to gain */
470 if (round_up(inode->i_size, PAGE_SIZE) ==
471 round_up(inode->i_size, HPAGE_PMD_SIZE)) {
472 list_move(&info->shrinklist, &to_remove);
473 removed++;
474 goto next;
475 }
476
477 list_move(&info->shrinklist, &list);
478 next:
479 if (!--batch)
480 break;
481 }
482 spin_unlock(&sbinfo->shrinklist_lock);
483
484 list_for_each_safe(pos, next, &to_remove) {
485 info = list_entry(pos, struct shmem_inode_info, shrinklist);
486 inode = &info->vfs_inode;
487 list_del_init(&info->shrinklist);
488 iput(inode);
489 }
490
491 list_for_each_safe(pos, next, &list) {
492 int ret;
493
494 info = list_entry(pos, struct shmem_inode_info, shrinklist);
495 inode = &info->vfs_inode;
496
497 if (nr_to_split && split >= nr_to_split)
498 goto leave;
499
500 page = find_get_page(inode->i_mapping,
501 (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
502 if (!page)
503 goto drop;
504
505 /* No huge page at the end of the file: nothing to split */
506 if (!PageTransHuge(page)) {
507 put_page(page);
508 goto drop;
509 }
510
511 /*
512 * Leave the inode on the list if we failed to lock
513 * the page at this time.
514 *
515 * Waiting for the lock may lead to deadlock in the
516 * reclaim path.
517 */
518 if (!trylock_page(page)) {
519 put_page(page);
520 goto leave;
521 }
522
523 ret = split_huge_page(page);
524 unlock_page(page);
525 put_page(page);
526
527 /* If split failed leave the inode on the list */
528 if (ret)
529 goto leave;
530
531 split++;
532 drop:
533 list_del_init(&info->shrinklist);
534 removed++;
535 leave:
536 iput(inode);
537 }
538
539 spin_lock(&sbinfo->shrinklist_lock);
540 list_splice_tail(&list, &sbinfo->shrinklist);
541 sbinfo->shrinklist_len -= removed;
542 spin_unlock(&sbinfo->shrinklist_lock);
543
544 return split;
545 }
546
547 static long shmem_unused_huge_scan(struct super_block *sb,
548 struct shrink_control *sc)
549 {
550 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
551
552 if (!READ_ONCE(sbinfo->shrinklist_len))
553 return SHRINK_STOP;
554
555 return shmem_unused_huge_shrink(sbinfo, sc, 0);
556 }
557
558 static long shmem_unused_huge_count(struct super_block *sb,
559 struct shrink_control *sc)
560 {
561 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
562 return READ_ONCE(sbinfo->shrinklist_len);
563 }
564 #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
565
566 #define shmem_huge SHMEM_HUGE_DENY
567
568 static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
569 struct shrink_control *sc, unsigned long nr_to_split)
570 {
571 return 0;
572 }
573 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
574
575 static inline bool is_huge_enabled(struct shmem_sb_info *sbinfo)
576 {
577 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
578 (shmem_huge == SHMEM_HUGE_FORCE || sbinfo->huge) &&
579 shmem_huge != SHMEM_HUGE_DENY)
580 return true;
581 return false;
582 }
583
584 /*
585 * Like add_to_page_cache_locked, but error if expected item has gone.
586 */
587 static int shmem_add_to_page_cache(struct page *page,
588 struct address_space *mapping,
589 pgoff_t index, void *expected, gfp_t gfp)
590 {
591 XA_STATE_ORDER(xas, &mapping->i_pages, index, compound_order(page));
592 unsigned long i = 0;
593 unsigned long nr = 1UL << compound_order(page);
594
595 VM_BUG_ON_PAGE(PageTail(page), page);
596 VM_BUG_ON_PAGE(index != round_down(index, nr), page);
597 VM_BUG_ON_PAGE(!PageLocked(page), page);
598 VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
599 VM_BUG_ON(expected && PageTransHuge(page));
600
601 page_ref_add(page, nr);
602 page->mapping = mapping;
603 page->index = index;
604
605 do {
606 void *entry;
607 xas_lock_irq(&xas);
608 entry = xas_find_conflict(&xas);
609 if (entry != expected)
610 xas_set_err(&xas, -EEXIST);
611 xas_create_range(&xas);
612 if (xas_error(&xas))
613 goto unlock;
614 next:
615 xas_store(&xas, page + i);
616 if (++i < nr) {
617 xas_next(&xas);
618 goto next;
619 }
620 if (PageTransHuge(page)) {
621 count_vm_event(THP_FILE_ALLOC);
622 __inc_node_page_state(page, NR_SHMEM_THPS);
623 }
624 mapping->nrpages += nr;
625 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
626 __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
627 unlock:
628 xas_unlock_irq(&xas);
629 } while (xas_nomem(&xas, gfp));
630
631 if (xas_error(&xas)) {
632 page->mapping = NULL;
633 page_ref_sub(page, nr);
634 return xas_error(&xas);
635 }
636
637 return 0;
638 }
639
640 /*
641 * Like delete_from_page_cache, but substitutes swap for page.
642 */
643 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
644 {
645 struct address_space *mapping = page->mapping;
646 int error;
647
648 VM_BUG_ON_PAGE(PageCompound(page), page);
649
650 xa_lock_irq(&mapping->i_pages);
651 error = shmem_replace_entry(mapping, page->index, page, radswap);
652 page->mapping = NULL;
653 mapping->nrpages--;
654 __dec_node_page_state(page, NR_FILE_PAGES);
655 __dec_node_page_state(page, NR_SHMEM);
656 xa_unlock_irq(&mapping->i_pages);
657 put_page(page);
658 BUG_ON(error);
659 }
660
661 /*
662 * Remove swap entry from page cache, free the swap and its page cache.
663 */
664 static int shmem_free_swap(struct address_space *mapping,
665 pgoff_t index, void *radswap)
666 {
667 void *old;
668
669 old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
670 if (old != radswap)
671 return -ENOENT;
672 free_swap_and_cache(radix_to_swp_entry(radswap));
673 return 0;
674 }
675
676 /*
677 * Determine (in bytes) how many of the shmem object's pages mapped by the
678 * given offsets are swapped out.
679 *
680 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
681 * as long as the inode doesn't go away and racy results are not a problem.
682 */
683 unsigned long shmem_partial_swap_usage(struct address_space *mapping,
684 pgoff_t start, pgoff_t end)
685 {
686 XA_STATE(xas, &mapping->i_pages, start);
687 struct page *page;
688 unsigned long swapped = 0;
689
690 rcu_read_lock();
691 xas_for_each(&xas, page, end - 1) {
692 if (xas_retry(&xas, page))
693 continue;
694 if (xa_is_value(page))
695 swapped++;
696
697 if (need_resched()) {
698 xas_pause(&xas);
699 cond_resched_rcu();
700 }
701 }
702
703 rcu_read_unlock();
704
705 return swapped << PAGE_SHIFT;
706 }
707
708 /*
709 * Determine (in bytes) how many of the shmem object's pages mapped by the
710 * given vma is swapped out.
711 *
712 * This is safe to call without i_mutex or the i_pages lock thanks to RCU,
713 * as long as the inode doesn't go away and racy results are not a problem.
714 */
715 unsigned long shmem_swap_usage(struct vm_area_struct *vma)
716 {
717 struct inode *inode = file_inode(vma->vm_file);
718 struct shmem_inode_info *info = SHMEM_I(inode);
719 struct address_space *mapping = inode->i_mapping;
720 unsigned long swapped;
721
722 /* Be careful as we don't hold info->lock */
723 swapped = READ_ONCE(info->swapped);
724
725 /*
726 * The easier cases are when the shmem object has nothing in swap, or
727 * the vma maps it whole. Then we can simply use the stats that we
728 * already track.
729 */
730 if (!swapped)
731 return 0;
732
733 if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
734 return swapped << PAGE_SHIFT;
735
736 /* Here comes the more involved part */
737 return shmem_partial_swap_usage(mapping,
738 linear_page_index(vma, vma->vm_start),
739 linear_page_index(vma, vma->vm_end));
740 }
741
742 /*
743 * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
744 */
745 void shmem_unlock_mapping(struct address_space *mapping)
746 {
747 struct pagevec pvec;
748 pgoff_t indices[PAGEVEC_SIZE];
749 pgoff_t index = 0;
750
751 pagevec_init(&pvec);
752 /*
753 * Minor point, but we might as well stop if someone else SHM_LOCKs it.
754 */
755 while (!mapping_unevictable(mapping)) {
756 /*
757 * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
758 * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
759 */
760 pvec.nr = find_get_entries(mapping, index,
761 PAGEVEC_SIZE, pvec.pages, indices);
762 if (!pvec.nr)
763 break;
764 index = indices[pvec.nr - 1] + 1;
765 pagevec_remove_exceptionals(&pvec);
766 check_move_unevictable_pages(&pvec);
767 pagevec_release(&pvec);
768 cond_resched();
769 }
770 }
771
772 /*
773 * Remove range of pages and swap entries from page cache, and free them.
774 * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
775 */
776 static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
777 bool unfalloc)
778 {
779 struct address_space *mapping = inode->i_mapping;
780 struct shmem_inode_info *info = SHMEM_I(inode);
781 pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
782 pgoff_t end = (lend + 1) >> PAGE_SHIFT;
783 unsigned int partial_start = lstart & (PAGE_SIZE - 1);
784 unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
785 struct pagevec pvec;
786 pgoff_t indices[PAGEVEC_SIZE];
787 long nr_swaps_freed = 0;
788 pgoff_t index;
789 int i;
790
791 if (lend == -1)
792 end = -1; /* unsigned, so actually very big */
793
794 pagevec_init(&pvec);
795 index = start;
796 while (index < end) {
797 pvec.nr = find_get_entries(mapping, index,
798 min(end - index, (pgoff_t)PAGEVEC_SIZE),
799 pvec.pages, indices);
800 if (!pvec.nr)
801 break;
802 for (i = 0; i < pagevec_count(&pvec); i++) {
803 struct page *page = pvec.pages[i];
804
805 index = indices[i];
806 if (index >= end)
807 break;
808
809 if (xa_is_value(page)) {
810 if (unfalloc)
811 continue;
812 nr_swaps_freed += !shmem_free_swap(mapping,
813 index, page);
814 continue;
815 }
816
817 VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
818
819 if (!trylock_page(page))
820 continue;
821
822 if (PageTransTail(page)) {
823 /* Middle of THP: zero out the page */
824 clear_highpage(page);
825 unlock_page(page);
826 continue;
827 } else if (PageTransHuge(page)) {
828 if (index == round_down(end, HPAGE_PMD_NR)) {
829 /*
830 * Range ends in the middle of THP:
831 * zero out the page
832 */
833 clear_highpage(page);
834 unlock_page(page);
835 continue;
836 }
837 index += HPAGE_PMD_NR - 1;
838 i += HPAGE_PMD_NR - 1;
839 }
840
841 if (!unfalloc || !PageUptodate(page)) {
842 VM_BUG_ON_PAGE(PageTail(page), page);
843 if (page_mapping(page) == mapping) {
844 VM_BUG_ON_PAGE(PageWriteback(page), page);
845 truncate_inode_page(mapping, page);
846 }
847 }
848 unlock_page(page);
849 }
850 pagevec_remove_exceptionals(&pvec);
851 pagevec_release(&pvec);
852 cond_resched();
853 index++;
854 }
855
856 if (partial_start) {
857 struct page *page = NULL;
858 shmem_getpage(inode, start - 1, &page, SGP_READ);
859 if (page) {
860 unsigned int top = PAGE_SIZE;
861 if (start > end) {
862 top = partial_end;
863 partial_end = 0;
864 }
865 zero_user_segment(page, partial_start, top);
866 set_page_dirty(page);
867 unlock_page(page);
868 put_page(page);
869 }
870 }
871 if (partial_end) {
872 struct page *page = NULL;
873 shmem_getpage(inode, end, &page, SGP_READ);
874 if (page) {
875 zero_user_segment(page, 0, partial_end);
876 set_page_dirty(page);
877 unlock_page(page);
878 put_page(page);
879 }
880 }
881 if (start >= end)
882 return;
883
884 index = start;
885 while (index < end) {
886 cond_resched();
887
888 pvec.nr = find_get_entries(mapping, index,
889 min(end - index, (pgoff_t)PAGEVEC_SIZE),
890 pvec.pages, indices);
891 if (!pvec.nr) {
892 /* If all gone or hole-punch or unfalloc, we're done */
893 if (index == start || end != -1)
894 break;
895 /* But if truncating, restart to make sure all gone */
896 index = start;
897 continue;
898 }
899 for (i = 0; i < pagevec_count(&pvec); i++) {
900 struct page *page = pvec.pages[i];
901
902 index = indices[i];
903 if (index >= end)
904 break;
905
906 if (xa_is_value(page)) {
907 if (unfalloc)
908 continue;
909 if (shmem_free_swap(mapping, index, page)) {
910 /* Swap was replaced by page: retry */
911 index--;
912 break;
913 }
914 nr_swaps_freed++;
915 continue;
916 }
917
918 lock_page(page);
919
920 if (PageTransTail(page)) {
921 /* Middle of THP: zero out the page */
922 clear_highpage(page);
923 unlock_page(page);
924 /*
925 * Partial thp truncate due 'start' in middle
926 * of THP: don't need to look on these pages
927 * again on !pvec.nr restart.
928 */
929 if (index != round_down(end, HPAGE_PMD_NR))
930 start++;
931 continue;
932 } else if (PageTransHuge(page)) {
933 if (index == round_down(end, HPAGE_PMD_NR)) {
934 /*
935 * Range ends in the middle of THP:
936 * zero out the page
937 */
938 clear_highpage(page);
939 unlock_page(page);
940 continue;
941 }
942 index += HPAGE_PMD_NR - 1;
943 i += HPAGE_PMD_NR - 1;
944 }
945
946 if (!unfalloc || !PageUptodate(page)) {
947 VM_BUG_ON_PAGE(PageTail(page), page);
948 if (page_mapping(page) == mapping) {
949 VM_BUG_ON_PAGE(PageWriteback(page), page);
950 truncate_inode_page(mapping, page);
951 } else {
952 /* Page was replaced by swap: retry */
953 unlock_page(page);
954 index--;
955 break;
956 }
957 }
958 unlock_page(page);
959 }
960 pagevec_remove_exceptionals(&pvec);
961 pagevec_release(&pvec);
962 index++;
963 }
964
965 spin_lock_irq(&info->lock);
966 info->swapped -= nr_swaps_freed;
967 shmem_recalc_inode(inode);
968 spin_unlock_irq(&info->lock);
969 }
970
971 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
972 {
973 shmem_undo_range(inode, lstart, lend, false);
974 inode->i_ctime = inode->i_mtime = current_time(inode);
975 }
976 EXPORT_SYMBOL_GPL(shmem_truncate_range);
977
978 static int shmem_getattr(const struct path *path, struct kstat *stat,
979 u32 request_mask, unsigned int query_flags)
980 {
981 struct inode *inode = path->dentry->d_inode;
982 struct shmem_inode_info *info = SHMEM_I(inode);
983 struct shmem_sb_info *sb_info = SHMEM_SB(inode->i_sb);
984
985 if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
986 spin_lock_irq(&info->lock);
987 shmem_recalc_inode(inode);
988 spin_unlock_irq(&info->lock);
989 }
990 generic_fillattr(inode, stat);
991
992 if (is_huge_enabled(sb_info))
993 stat->blksize = HPAGE_PMD_SIZE;
994
995 return 0;
996 }
997
998 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
999 {
1000 struct inode *inode = d_inode(dentry);
1001 struct shmem_inode_info *info = SHMEM_I(inode);
1002 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1003 int error;
1004
1005 error = setattr_prepare(dentry, attr);
1006 if (error)
1007 return error;
1008
1009 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
1010 loff_t oldsize = inode->i_size;
1011 loff_t newsize = attr->ia_size;
1012
1013 /* protected by i_mutex */
1014 if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
1015 (newsize > oldsize && (info->seals & F_SEAL_GROW)))
1016 return -EPERM;
1017
1018 if (newsize != oldsize) {
1019 error = shmem_reacct_size(SHMEM_I(inode)->flags,
1020 oldsize, newsize);
1021 if (error)
1022 return error;
1023 i_size_write(inode, newsize);
1024 inode->i_ctime = inode->i_mtime = current_time(inode);
1025 }
1026 if (newsize <= oldsize) {
1027 loff_t holebegin = round_up(newsize, PAGE_SIZE);
1028 if (oldsize > holebegin)
1029 unmap_mapping_range(inode->i_mapping,
1030 holebegin, 0, 1);
1031 if (info->alloced)
1032 shmem_truncate_range(inode,
1033 newsize, (loff_t)-1);
1034 /* unmap again to remove racily COWed private pages */
1035 if (oldsize > holebegin)
1036 unmap_mapping_range(inode->i_mapping,
1037 holebegin, 0, 1);
1038
1039 /*
1040 * Part of the huge page can be beyond i_size: subject
1041 * to shrink under memory pressure.
1042 */
1043 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
1044 spin_lock(&sbinfo->shrinklist_lock);
1045 /*
1046 * _careful to defend against unlocked access to
1047 * ->shrink_list in shmem_unused_huge_shrink()
1048 */
1049 if (list_empty_careful(&info->shrinklist)) {
1050 list_add_tail(&info->shrinklist,
1051 &sbinfo->shrinklist);
1052 sbinfo->shrinklist_len++;
1053 }
1054 spin_unlock(&sbinfo->shrinklist_lock);
1055 }
1056 }
1057 }
1058
1059 setattr_copy(inode, attr);
1060 if (attr->ia_valid & ATTR_MODE)
1061 error = posix_acl_chmod(inode, inode->i_mode);
1062 return error;
1063 }
1064
1065 static void shmem_evict_inode(struct inode *inode)
1066 {
1067 struct shmem_inode_info *info = SHMEM_I(inode);
1068 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
1069
1070 if (inode->i_mapping->a_ops == &shmem_aops) {
1071 shmem_unacct_size(info->flags, inode->i_size);
1072 inode->i_size = 0;
1073 shmem_truncate_range(inode, 0, (loff_t)-1);
1074 if (!list_empty(&info->shrinklist)) {
1075 spin_lock(&sbinfo->shrinklist_lock);
1076 if (!list_empty(&info->shrinklist)) {
1077 list_del_init(&info->shrinklist);
1078 sbinfo->shrinklist_len--;
1079 }
1080 spin_unlock(&sbinfo->shrinklist_lock);
1081 }
1082 if (!list_empty(&info->swaplist)) {
1083 mutex_lock(&shmem_swaplist_mutex);
1084 list_del_init(&info->swaplist);
1085 mutex_unlock(&shmem_swaplist_mutex);
1086 }
1087 }
1088
1089 simple_xattrs_free(&info->xattrs);
1090 WARN_ON(inode->i_blocks);
1091 if (!sbinfo->idr_nouse && inode->i_ino) {
1092 mutex_lock(&sbinfo->idr_lock);
1093 idr_remove(&sbinfo->idr, inode->i_ino);
1094 mutex_unlock(&sbinfo->idr_lock);
1095 }
1096 shmem_free_inode(inode->i_sb);
1097 clear_inode(inode);
1098 }
1099
1100 static unsigned long find_swap_entry(struct xarray *xa, void *item)
1101 {
1102 XA_STATE(xas, xa, 0);
1103 unsigned int checked = 0;
1104 void *entry;
1105
1106 rcu_read_lock();
1107 xas_for_each(&xas, entry, ULONG_MAX) {
1108 if (xas_retry(&xas, entry))
1109 continue;
1110 if (entry == item)
1111 break;
1112 checked++;
1113 if ((checked % XA_CHECK_SCHED) != 0)
1114 continue;
1115 xas_pause(&xas);
1116 cond_resched_rcu();
1117 }
1118 rcu_read_unlock();
1119
1120 return entry ? xas.xa_index : -1;
1121 }
1122
1123 /*
1124 * If swap found in inode, free it and move page from swapcache to filecache.
1125 */
1126 static int shmem_unuse_inode(struct shmem_inode_info *info,
1127 swp_entry_t swap, struct page **pagep)
1128 {
1129 struct address_space *mapping = info->vfs_inode.i_mapping;
1130 void *radswap;
1131 pgoff_t index;
1132 gfp_t gfp;
1133 int error = 0;
1134
1135 radswap = swp_to_radix_entry(swap);
1136 index = find_swap_entry(&mapping->i_pages, radswap);
1137 if (index == -1)
1138 return -EAGAIN; /* tell shmem_unuse we found nothing */
1139
1140 /*
1141 * Move _head_ to start search for next from here.
1142 * But be careful: shmem_evict_inode checks list_empty without taking
1143 * mutex, and there's an instant in list_move_tail when info->swaplist
1144 * would appear empty, if it were the only one on shmem_swaplist.
1145 */
1146 if (shmem_swaplist.next != &info->swaplist)
1147 list_move_tail(&shmem_swaplist, &info->swaplist);
1148
1149 gfp = mapping_gfp_mask(mapping);
1150 if (shmem_should_replace_page(*pagep, gfp)) {
1151 mutex_unlock(&shmem_swaplist_mutex);
1152 error = shmem_replace_page(pagep, gfp, info, index);
1153 mutex_lock(&shmem_swaplist_mutex);
1154 /*
1155 * We needed to drop mutex to make that restrictive page
1156 * allocation, but the inode might have been freed while we
1157 * dropped it: although a racing shmem_evict_inode() cannot
1158 * complete without emptying the page cache, our page lock
1159 * on this swapcache page is not enough to prevent that -
1160 * free_swap_and_cache() of our swap entry will only
1161 * trylock_page(), removing swap from page cache whatever.
1162 *
1163 * We must not proceed to shmem_add_to_page_cache() if the
1164 * inode has been freed, but of course we cannot rely on
1165 * inode or mapping or info to check that. However, we can
1166 * safely check if our swap entry is still in use (and here
1167 * it can't have got reused for another page): if it's still
1168 * in use, then the inode cannot have been freed yet, and we
1169 * can safely proceed (if it's no longer in use, that tells
1170 * nothing about the inode, but we don't need to unuse swap).
1171 */
1172 if (!page_swapcount(*pagep))
1173 error = -ENOENT;
1174 }
1175
1176 /*
1177 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
1178 * but also to hold up shmem_evict_inode(): so inode cannot be freed
1179 * beneath us (pagelock doesn't help until the page is in pagecache).
1180 */
1181 if (!error)
1182 error = shmem_add_to_page_cache(*pagep, mapping, index,
1183 radswap, gfp);
1184 if (error != -ENOMEM) {
1185 /*
1186 * Truncation and eviction use free_swap_and_cache(), which
1187 * only does trylock page: if we raced, best clean up here.
1188 */
1189 delete_from_swap_cache(*pagep);
1190 set_page_dirty(*pagep);
1191 if (!error) {
1192 spin_lock_irq(&info->lock);
1193 info->swapped--;
1194 spin_unlock_irq(&info->lock);
1195 swap_free(swap);
1196 }
1197 }
1198 return error;
1199 }
1200
1201 /*
1202 * Search through swapped inodes to find and replace swap by page.
1203 */
1204 int shmem_unuse(swp_entry_t swap, struct page *page)
1205 {
1206 struct list_head *this, *next;
1207 struct shmem_inode_info *info;
1208 struct mem_cgroup *memcg;
1209 int error = 0;
1210
1211 /*
1212 * There's a faint possibility that swap page was replaced before
1213 * caller locked it: caller will come back later with the right page.
1214 */
1215 if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
1216 goto out;
1217
1218 /*
1219 * Charge page using GFP_KERNEL while we can wait, before taking
1220 * the shmem_swaplist_mutex which might hold up shmem_writepage().
1221 * Charged back to the user (not to caller) when swap account is used.
1222 */
1223 error = mem_cgroup_try_charge_delay(page, current->mm, GFP_KERNEL,
1224 &memcg, false);
1225 if (error)
1226 goto out;
1227 /* No memory allocation: swap entry occupies the slot for the page */
1228 error = -EAGAIN;
1229
1230 mutex_lock(&shmem_swaplist_mutex);
1231 list_for_each_safe(this, next, &shmem_swaplist) {
1232 info = list_entry(this, struct shmem_inode_info, swaplist);
1233 if (info->swapped)
1234 error = shmem_unuse_inode(info, swap, &page);
1235 else
1236 list_del_init(&info->swaplist);
1237 cond_resched();
1238 if (error != -EAGAIN)
1239 break;
1240 /* found nothing in this: move on to search the next */
1241 }
1242 mutex_unlock(&shmem_swaplist_mutex);
1243
1244 if (error) {
1245 if (error != -ENOMEM)
1246 error = 0;
1247 mem_cgroup_cancel_charge(page, memcg, false);
1248 } else
1249 mem_cgroup_commit_charge(page, memcg, true, false);
1250 out:
1251 unlock_page(page);
1252 put_page(page);
1253 return error;
1254 }
1255
1256 /*
1257 * Move the page from the page cache to the swap cache.
1258 */
1259 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
1260 {
1261 struct shmem_inode_info *info;
1262 struct address_space *mapping;
1263 struct inode *inode;
1264 swp_entry_t swap;
1265 pgoff_t index;
1266
1267 VM_BUG_ON_PAGE(PageCompound(page), page);
1268 BUG_ON(!PageLocked(page));
1269 mapping = page->mapping;
1270 index = page->index;
1271 inode = mapping->host;
1272 info = SHMEM_I(inode);
1273 if (info->flags & VM_LOCKED)
1274 goto redirty;
1275 if (!total_swap_pages)
1276 goto redirty;
1277
1278 /*
1279 * Our capabilities prevent regular writeback or sync from ever calling
1280 * shmem_writepage; but a stacking filesystem might use ->writepage of
1281 * its underlying filesystem, in which case tmpfs should write out to
1282 * swap only in response to memory pressure, and not for the writeback
1283 * threads or sync.
1284 */
1285 if (!wbc->for_reclaim) {
1286 WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
1287 goto redirty;
1288 }
1289
1290 /*
1291 * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
1292 * value into swapfile.c, the only way we can correctly account for a
1293 * fallocated page arriving here is now to initialize it and write it.
1294 *
1295 * That's okay for a page already fallocated earlier, but if we have
1296 * not yet completed the fallocation, then (a) we want to keep track
1297 * of this page in case we have to undo it, and (b) it may not be a
1298 * good idea to continue anyway, once we're pushing into swap. So
1299 * reactivate the page, and let shmem_fallocate() quit when too many.
1300 */
1301 if (!PageUptodate(page)) {
1302 if (inode->i_private) {
1303 struct shmem_falloc *shmem_falloc;
1304 spin_lock(&inode->i_lock);
1305 shmem_falloc = inode->i_private;
1306 if (shmem_falloc &&
1307 !shmem_falloc->waitq &&
1308 index >= shmem_falloc->start &&
1309 index < shmem_falloc->next)
1310 shmem_falloc->nr_unswapped++;
1311 else
1312 shmem_falloc = NULL;
1313 spin_unlock(&inode->i_lock);
1314 if (shmem_falloc)
1315 goto redirty;
1316 }
1317 clear_highpage(page);
1318 flush_dcache_page(page);
1319 SetPageUptodate(page);
1320 }
1321
1322 swap = get_swap_page(page);
1323 if (!swap.val)
1324 goto redirty;
1325
1326 /*
1327 * Add inode to shmem_unuse()'s list of swapped-out inodes,
1328 * if it's not already there. Do it now before the page is
1329 * moved to swap cache, when its pagelock no longer protects
1330 * the inode from eviction. But don't unlock the mutex until
1331 * we've incremented swapped, because shmem_unuse_inode() will
1332 * prune a !swapped inode from the swaplist under this mutex.
1333 */
1334 mutex_lock(&shmem_swaplist_mutex);
1335 if (list_empty(&info->swaplist))
1336 list_add_tail(&info->swaplist, &shmem_swaplist);
1337
1338 if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
1339 spin_lock_irq(&info->lock);
1340 shmem_recalc_inode(inode);
1341 info->swapped++;
1342 spin_unlock_irq(&info->lock);
1343
1344 swap_shmem_alloc(swap);
1345 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
1346
1347 mutex_unlock(&shmem_swaplist_mutex);
1348 BUG_ON(page_mapped(page));
1349 swap_writepage(page, wbc);
1350 return 0;
1351 }
1352
1353 mutex_unlock(&shmem_swaplist_mutex);
1354 put_swap_page(page, swap);
1355 redirty:
1356 set_page_dirty(page);
1357 if (wbc->for_reclaim)
1358 return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
1359 unlock_page(page);
1360 return 0;
1361 }
1362
1363 #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
1364 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1365 {
1366 char buffer[64];
1367
1368 if (!mpol || mpol->mode == MPOL_DEFAULT)
1369 return; /* show nothing */
1370
1371 mpol_to_str(buffer, sizeof(buffer), mpol);
1372
1373 seq_printf(seq, ",mpol=%s", buffer);
1374 }
1375
1376 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1377 {
1378 struct mempolicy *mpol = NULL;
1379 if (sbinfo->mpol) {
1380 spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
1381 mpol = sbinfo->mpol;
1382 mpol_get(mpol);
1383 spin_unlock(&sbinfo->stat_lock);
1384 }
1385 return mpol;
1386 }
1387 #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
1388 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
1389 {
1390 }
1391 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
1392 {
1393 return NULL;
1394 }
1395 #endif /* CONFIG_NUMA && CONFIG_TMPFS */
1396 #ifndef CONFIG_NUMA
1397 #define vm_policy vm_private_data
1398 #endif
1399
1400 static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
1401 struct shmem_inode_info *info, pgoff_t index)
1402 {
1403 /* Create a pseudo vma that just contains the policy */
1404 vma_init(vma, NULL);
1405 /* Bias interleave by inode number to distribute better across nodes */
1406 vma->vm_pgoff = index + info->vfs_inode.i_ino;
1407 vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
1408 }
1409
1410 static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
1411 {
1412 /* Drop reference taken by mpol_shared_policy_lookup() */
1413 mpol_cond_put(vma->vm_policy);
1414 }
1415
1416 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
1417 struct shmem_inode_info *info, pgoff_t index)
1418 {
1419 struct vm_area_struct pvma;
1420 struct page *page;
1421 struct vm_fault vmf;
1422
1423 shmem_pseudo_vma_init(&pvma, info, index);
1424 vmf.vma = &pvma;
1425 vmf.address = 0;
1426 page = swap_cluster_readahead(swap, gfp, &vmf);
1427 shmem_pseudo_vma_destroy(&pvma);
1428
1429 return page;
1430 }
1431
1432 static struct page *shmem_alloc_hugepage(gfp_t gfp,
1433 struct shmem_inode_info *info, pgoff_t index)
1434 {
1435 struct vm_area_struct pvma;
1436 struct address_space *mapping = info->vfs_inode.i_mapping;
1437 pgoff_t hindex;
1438 struct page *page;
1439
1440 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1441 return NULL;
1442
1443 hindex = round_down(index, HPAGE_PMD_NR);
1444 if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
1445 XA_PRESENT))
1446 return NULL;
1447
1448 shmem_pseudo_vma_init(&pvma, info, hindex);
1449 page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
1450 HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
1451 shmem_pseudo_vma_destroy(&pvma);
1452 if (page)
1453 prep_transhuge_page(page);
1454 return page;
1455 }
1456
1457 static struct page *shmem_alloc_page(gfp_t gfp,
1458 struct shmem_inode_info *info, pgoff_t index)
1459 {
1460 struct vm_area_struct pvma;
1461 struct page *page;
1462
1463 shmem_pseudo_vma_init(&pvma, info, index);
1464 page = alloc_page_vma(gfp, &pvma, 0);
1465 shmem_pseudo_vma_destroy(&pvma);
1466
1467 return page;
1468 }
1469
1470 static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
1471 struct inode *inode,
1472 pgoff_t index, bool huge)
1473 {
1474 struct shmem_inode_info *info = SHMEM_I(inode);
1475 struct page *page;
1476 int nr;
1477 int err = -ENOSPC;
1478
1479 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
1480 huge = false;
1481 nr = huge ? HPAGE_PMD_NR : 1;
1482
1483 if (!shmem_inode_acct_block(inode, nr))
1484 goto failed;
1485
1486 if (huge)
1487 page = shmem_alloc_hugepage(gfp, info, index);
1488 else
1489 page = shmem_alloc_page(gfp, info, index);
1490 if (page) {
1491 __SetPageLocked(page);
1492 __SetPageSwapBacked(page);
1493 return page;
1494 }
1495
1496 err = -ENOMEM;
1497 shmem_inode_unacct_blocks(inode, nr);
1498 failed:
1499 return ERR_PTR(err);
1500 }
1501
1502 /*
1503 * When a page is moved from swapcache to shmem filecache (either by the
1504 * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
1505 * shmem_unuse_inode()), it may have been read in earlier from swap, in
1506 * ignorance of the mapping it belongs to. If that mapping has special
1507 * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
1508 * we may need to copy to a suitable page before moving to filecache.
1509 *
1510 * In a future release, this may well be extended to respect cpuset and
1511 * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
1512 * but for now it is a simple matter of zone.
1513 */
1514 static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
1515 {
1516 return page_zonenum(page) > gfp_zone(gfp);
1517 }
1518
1519 static int shmem_replace_page(struct page **pagep, gfp_t gfp,
1520 struct shmem_inode_info *info, pgoff_t index)
1521 {
1522 struct page *oldpage, *newpage;
1523 struct address_space *swap_mapping;
1524 swp_entry_t entry;
1525 pgoff_t swap_index;
1526 int error;
1527
1528 oldpage = *pagep;
1529 entry.val = page_private(oldpage);
1530 swap_index = swp_offset(entry);
1531 swap_mapping = page_mapping(oldpage);
1532
1533 /*
1534 * We have arrived here because our zones are constrained, so don't
1535 * limit chance of success by further cpuset and node constraints.
1536 */
1537 gfp &= ~GFP_CONSTRAINT_MASK;
1538 newpage = shmem_alloc_page(gfp, info, index);
1539 if (!newpage)
1540 return -ENOMEM;
1541
1542 get_page(newpage);
1543 copy_highpage(newpage, oldpage);
1544 flush_dcache_page(newpage);
1545
1546 __SetPageLocked(newpage);
1547 __SetPageSwapBacked(newpage);
1548 SetPageUptodate(newpage);
1549 set_page_private(newpage, entry.val);
1550 SetPageSwapCache(newpage);
1551
1552 /*
1553 * Our caller will very soon move newpage out of swapcache, but it's
1554 * a nice clean interface for us to replace oldpage by newpage there.
1555 */
1556 xa_lock_irq(&swap_mapping->i_pages);
1557 error = shmem_replace_entry(swap_mapping, swap_index, oldpage, newpage);
1558 if (!error) {
1559 __inc_node_page_state(newpage, NR_FILE_PAGES);
1560 __dec_node_page_state(oldpage, NR_FILE_PAGES);
1561 }
1562 xa_unlock_irq(&swap_mapping->i_pages);
1563
1564 if (unlikely(error)) {
1565 /*
1566 * Is this possible? I think not, now that our callers check
1567 * both PageSwapCache and page_private after getting page lock;
1568 * but be defensive. Reverse old to newpage for clear and free.
1569 */
1570 oldpage = newpage;
1571 } else {
1572 mem_cgroup_migrate(oldpage, newpage);
1573 lru_cache_add_anon(newpage);
1574 *pagep = newpage;
1575 }
1576
1577 ClearPageSwapCache(oldpage);
1578 set_page_private(oldpage, 0);
1579
1580 unlock_page(oldpage);
1581 put_page(oldpage);
1582 put_page(oldpage);
1583 return error;
1584 }
1585
1586 /*
1587 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
1588 *
1589 * If we allocate a new one we do not mark it dirty. That's up to the
1590 * vm. If we swap it in we mark it dirty since we also free the swap
1591 * entry since a page cannot live in both the swap and page cache.
1592 *
1593 * fault_mm and fault_type are only supplied by shmem_fault:
1594 * otherwise they are NULL.
1595 */
1596 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
1597 struct page **pagep, enum sgp_type sgp, gfp_t gfp,
1598 struct vm_area_struct *vma, struct vm_fault *vmf,
1599 vm_fault_t *fault_type)
1600 {
1601 struct address_space *mapping = inode->i_mapping;
1602 struct shmem_inode_info *info = SHMEM_I(inode);
1603 struct shmem_sb_info *sbinfo;
1604 struct mm_struct *charge_mm;
1605 struct mem_cgroup *memcg;
1606 struct page *page;
1607 swp_entry_t swap;
1608 enum sgp_type sgp_huge = sgp;
1609 pgoff_t hindex = index;
1610 int error;
1611 int once = 0;
1612 int alloced = 0;
1613
1614 if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
1615 return -EFBIG;
1616 if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
1617 sgp = SGP_CACHE;
1618 repeat:
1619 swap.val = 0;
1620 page = find_lock_entry(mapping, index);
1621 if (xa_is_value(page)) {
1622 swap = radix_to_swp_entry(page);
1623 page = NULL;
1624 }
1625
1626 if (sgp <= SGP_CACHE &&
1627 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1628 error = -EINVAL;
1629 goto unlock;
1630 }
1631
1632 if (page && sgp == SGP_WRITE)
1633 mark_page_accessed(page);
1634
1635 /* fallocated page? */
1636 if (page && !PageUptodate(page)) {
1637 if (sgp != SGP_READ)
1638 goto clear;
1639 unlock_page(page);
1640 put_page(page);
1641 page = NULL;
1642 }
1643 if (page || (sgp == SGP_READ && !swap.val)) {
1644 *pagep = page;
1645 return 0;
1646 }
1647
1648 /*
1649 * Fast cache lookup did not find it:
1650 * bring it back from swap or allocate.
1651 */
1652 sbinfo = SHMEM_SB(inode->i_sb);
1653 charge_mm = vma ? vma->vm_mm : current->mm;
1654
1655 if (swap.val) {
1656 /* Look it up and read it in.. */
1657 page = lookup_swap_cache(swap, NULL, 0);
1658 if (!page) {
1659 /* Or update major stats only when swapin succeeds?? */
1660 if (fault_type) {
1661 *fault_type |= VM_FAULT_MAJOR;
1662 count_vm_event(PGMAJFAULT);
1663 count_memcg_event_mm(charge_mm, PGMAJFAULT);
1664 }
1665 /* Here we actually start the io */
1666 page = shmem_swapin(swap, gfp, info, index);
1667 if (!page) {
1668 error = -ENOMEM;
1669 goto failed;
1670 }
1671 }
1672
1673 /* We have to do this with page locked to prevent races */
1674 lock_page(page);
1675 if (!PageSwapCache(page) || page_private(page) != swap.val ||
1676 !shmem_confirm_swap(mapping, index, swap)) {
1677 error = -EEXIST; /* try again */
1678 goto unlock;
1679 }
1680 if (!PageUptodate(page)) {
1681 error = -EIO;
1682 goto failed;
1683 }
1684 wait_on_page_writeback(page);
1685
1686 if (shmem_should_replace_page(page, gfp)) {
1687 error = shmem_replace_page(&page, gfp, info, index);
1688 if (error)
1689 goto failed;
1690 }
1691
1692 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1693 false);
1694 if (!error) {
1695 error = shmem_add_to_page_cache(page, mapping, index,
1696 swp_to_radix_entry(swap), gfp);
1697 /*
1698 * We already confirmed swap under page lock, and make
1699 * no memory allocation here, so usually no possibility
1700 * of error; but free_swap_and_cache() only trylocks a
1701 * page, so it is just possible that the entry has been
1702 * truncated or holepunched since swap was confirmed.
1703 * shmem_undo_range() will have done some of the
1704 * unaccounting, now delete_from_swap_cache() will do
1705 * the rest.
1706 * Reset swap.val? No, leave it so "failed" goes back to
1707 * "repeat": reading a hole and writing should succeed.
1708 */
1709 if (error) {
1710 mem_cgroup_cancel_charge(page, memcg, false);
1711 delete_from_swap_cache(page);
1712 }
1713 }
1714 if (error)
1715 goto failed;
1716
1717 mem_cgroup_commit_charge(page, memcg, true, false);
1718
1719 spin_lock_irq(&info->lock);
1720 info->swapped--;
1721 shmem_recalc_inode(inode);
1722 spin_unlock_irq(&info->lock);
1723
1724 if (sgp == SGP_WRITE)
1725 mark_page_accessed(page);
1726
1727 delete_from_swap_cache(page);
1728 set_page_dirty(page);
1729 swap_free(swap);
1730
1731 } else {
1732 if (vma && userfaultfd_missing(vma)) {
1733 *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
1734 return 0;
1735 }
1736
1737 /* shmem_symlink() */
1738 if (mapping->a_ops != &shmem_aops)
1739 goto alloc_nohuge;
1740 if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
1741 goto alloc_nohuge;
1742 if (shmem_huge == SHMEM_HUGE_FORCE)
1743 goto alloc_huge;
1744 switch (sbinfo->huge) {
1745 loff_t i_size;
1746 pgoff_t off;
1747 case SHMEM_HUGE_NEVER:
1748 goto alloc_nohuge;
1749 case SHMEM_HUGE_WITHIN_SIZE:
1750 off = round_up(index, HPAGE_PMD_NR);
1751 i_size = round_up(i_size_read(inode), PAGE_SIZE);
1752 if (i_size >= HPAGE_PMD_SIZE &&
1753 i_size >> PAGE_SHIFT >= off)
1754 goto alloc_huge;
1755 /* fallthrough */
1756 case SHMEM_HUGE_ADVISE:
1757 if (sgp_huge == SGP_HUGE)
1758 goto alloc_huge;
1759 /* TODO: implement fadvise() hints */
1760 goto alloc_nohuge;
1761 }
1762
1763 alloc_huge:
1764 page = shmem_alloc_and_acct_page(gfp, inode, index, true);
1765 if (IS_ERR(page)) {
1766 alloc_nohuge: page = shmem_alloc_and_acct_page(gfp, inode,
1767 index, false);
1768 }
1769 if (IS_ERR(page)) {
1770 int retry = 5;
1771 error = PTR_ERR(page);
1772 page = NULL;
1773 if (error != -ENOSPC)
1774 goto failed;
1775 /*
1776 * Try to reclaim some spece by splitting a huge page
1777 * beyond i_size on the filesystem.
1778 */
1779 while (retry--) {
1780 int ret;
1781 ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
1782 if (ret == SHRINK_STOP)
1783 break;
1784 if (ret)
1785 goto alloc_nohuge;
1786 }
1787 goto failed;
1788 }
1789
1790 if (PageTransHuge(page))
1791 hindex = round_down(index, HPAGE_PMD_NR);
1792 else
1793 hindex = index;
1794
1795 if (sgp == SGP_WRITE)
1796 __SetPageReferenced(page);
1797
1798 error = mem_cgroup_try_charge_delay(page, charge_mm, gfp, &memcg,
1799 PageTransHuge(page));
1800 if (error)
1801 goto unacct;
1802 error = shmem_add_to_page_cache(page, mapping, hindex,
1803 NULL, gfp & GFP_RECLAIM_MASK);
1804 if (error) {
1805 mem_cgroup_cancel_charge(page, memcg,
1806 PageTransHuge(page));
1807 goto unacct;
1808 }
1809 mem_cgroup_commit_charge(page, memcg, false,
1810 PageTransHuge(page));
1811 lru_cache_add_anon(page);
1812
1813 spin_lock_irq(&info->lock);
1814 info->alloced += 1 << compound_order(page);
1815 inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
1816 shmem_recalc_inode(inode);
1817 spin_unlock_irq(&info->lock);
1818 alloced = true;
1819
1820 if (PageTransHuge(page) &&
1821 DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
1822 hindex + HPAGE_PMD_NR - 1) {
1823 /*
1824 * Part of the huge page is beyond i_size: subject
1825 * to shrink under memory pressure.
1826 */
1827 spin_lock(&sbinfo->shrinklist_lock);
1828 /*
1829 * _careful to defend against unlocked access to
1830 * ->shrink_list in shmem_unused_huge_shrink()
1831 */
1832 if (list_empty_careful(&info->shrinklist)) {
1833 list_add_tail(&info->shrinklist,
1834 &sbinfo->shrinklist);
1835 sbinfo->shrinklist_len++;
1836 }
1837 spin_unlock(&sbinfo->shrinklist_lock);
1838 }
1839
1840 /*
1841 * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
1842 */
1843 if (sgp == SGP_FALLOC)
1844 sgp = SGP_WRITE;
1845 clear:
1846 /*
1847 * Let SGP_WRITE caller clear ends if write does not fill page;
1848 * but SGP_FALLOC on a page fallocated earlier must initialize
1849 * it now, lest undo on failure cancel our earlier guarantee.
1850 */
1851 if (sgp != SGP_WRITE && !PageUptodate(page)) {
1852 struct page *head = compound_head(page);
1853 int i;
1854
1855 for (i = 0; i < (1 << compound_order(head)); i++) {
1856 clear_highpage(head + i);
1857 flush_dcache_page(head + i);
1858 }
1859 SetPageUptodate(head);
1860 }
1861 }
1862
1863 /* Perhaps the file has been truncated since we checked */
1864 if (sgp <= SGP_CACHE &&
1865 ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
1866 if (alloced) {
1867 ClearPageDirty(page);
1868 delete_from_page_cache(page);
1869 spin_lock_irq(&info->lock);
1870 shmem_recalc_inode(inode);
1871 spin_unlock_irq(&info->lock);
1872 }
1873 error = -EINVAL;
1874 goto unlock;
1875 }
1876 *pagep = page + index - hindex;
1877 return 0;
1878
1879 /*
1880 * Error recovery.
1881 */
1882 unacct:
1883 shmem_inode_unacct_blocks(inode, 1 << compound_order(page));
1884
1885 if (PageTransHuge(page)) {
1886 unlock_page(page);
1887 put_page(page);
1888 goto alloc_nohuge;
1889 }
1890 failed:
1891 if (swap.val && !shmem_confirm_swap(mapping, index, swap))
1892 error = -EEXIST;
1893 unlock:
1894 if (page) {
1895 unlock_page(page);
1896 put_page(page);
1897 }
1898 if (error == -ENOSPC && !once++) {
1899 spin_lock_irq(&info->lock);
1900 shmem_recalc_inode(inode);
1901 spin_unlock_irq(&info->lock);
1902 goto repeat;
1903 }
1904 if (error == -EEXIST)
1905 goto repeat;
1906 return error;
1907 }
1908
1909 /*
1910 * This is like autoremove_wake_function, but it removes the wait queue
1911 * entry unconditionally - even if something else had already woken the
1912 * target.
1913 */
1914 static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
1915 {
1916 int ret = default_wake_function(wait, mode, sync, key);
1917 list_del_init(&wait->entry);
1918 return ret;
1919 }
1920
1921 static vm_fault_t shmem_fault(struct vm_fault *vmf)
1922 {
1923 struct vm_area_struct *vma = vmf->vma;
1924 struct inode *inode = file_inode(vma->vm_file);
1925 gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
1926 enum sgp_type sgp;
1927 int err;
1928 vm_fault_t ret = VM_FAULT_LOCKED;
1929
1930 /*
1931 * Trinity finds that probing a hole which tmpfs is punching can
1932 * prevent the hole-punch from ever completing: which in turn
1933 * locks writers out with its hold on i_mutex. So refrain from
1934 * faulting pages into the hole while it's being punched. Although
1935 * shmem_undo_range() does remove the additions, it may be unable to
1936 * keep up, as each new page needs its own unmap_mapping_range() call,
1937 * and the i_mmap tree grows ever slower to scan if new vmas are added.
1938 *
1939 * It does not matter if we sometimes reach this check just before the
1940 * hole-punch begins, so that one fault then races with the punch:
1941 * we just need to make racing faults a rare case.
1942 *
1943 * The implementation below would be much simpler if we just used a
1944 * standard mutex or completion: but we cannot take i_mutex in fault,
1945 * and bloating every shmem inode for this unlikely case would be sad.
1946 */
1947 if (unlikely(inode->i_private)) {
1948 struct shmem_falloc *shmem_falloc;
1949
1950 spin_lock(&inode->i_lock);
1951 shmem_falloc = inode->i_private;
1952 if (shmem_falloc &&
1953 shmem_falloc->waitq &&
1954 vmf->pgoff >= shmem_falloc->start &&
1955 vmf->pgoff < shmem_falloc->next) {
1956 wait_queue_head_t *shmem_falloc_waitq;
1957 DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
1958
1959 ret = VM_FAULT_NOPAGE;
1960 if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
1961 !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
1962 /* It's polite to up mmap_sem if we can */
1963 up_read(&vma->vm_mm->mmap_sem);
1964 ret = VM_FAULT_RETRY;
1965 }
1966
1967 shmem_falloc_waitq = shmem_falloc->waitq;
1968 prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
1969 TASK_UNINTERRUPTIBLE);
1970 spin_unlock(&inode->i_lock);
1971 schedule();
1972
1973 /*
1974 * shmem_falloc_waitq points into the shmem_fallocate()
1975 * stack of the hole-punching task: shmem_falloc_waitq
1976 * is usually invalid by the time we reach here, but
1977 * finish_wait() does not dereference it in that case;
1978 * though i_lock needed lest racing with wake_up_all().
1979 */
1980 spin_lock(&inode->i_lock);
1981 finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
1982 spin_unlock(&inode->i_lock);
1983 return ret;
1984 }
1985 spin_unlock(&inode->i_lock);
1986 }
1987
1988 sgp = SGP_CACHE;
1989
1990 if ((vma->vm_flags & VM_NOHUGEPAGE) ||
1991 test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags))
1992 sgp = SGP_NOHUGE;
1993 else if (vma->vm_flags & VM_HUGEPAGE)
1994 sgp = SGP_HUGE;
1995
1996 err = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, sgp,
1997 gfp, vma, vmf, &ret);
1998 if (err)
1999 return vmf_error(err);
2000 return ret;
2001 }
2002
2003 unsigned long shmem_get_unmapped_area(struct file *file,
2004 unsigned long uaddr, unsigned long len,
2005 unsigned long pgoff, unsigned long flags)
2006 {
2007 unsigned long (*get_area)(struct file *,
2008 unsigned long, unsigned long, unsigned long, unsigned long);
2009 unsigned long addr;
2010 unsigned long offset;
2011 unsigned long inflated_len;
2012 unsigned long inflated_addr;
2013 unsigned long inflated_offset;
2014
2015 if (len > TASK_SIZE)
2016 return -ENOMEM;
2017
2018 get_area = current->mm->get_unmapped_area;
2019 addr = get_area(file, uaddr, len, pgoff, flags);
2020
2021 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
2022 return addr;
2023 if (IS_ERR_VALUE(addr))
2024 return addr;
2025 if (addr & ~PAGE_MASK)
2026 return addr;
2027 if (addr > TASK_SIZE - len)
2028 return addr;
2029
2030 if (shmem_huge == SHMEM_HUGE_DENY)
2031 return addr;
2032 if (len < HPAGE_PMD_SIZE)
2033 return addr;
2034 if (flags & MAP_FIXED)
2035 return addr;
2036 /*
2037 * Our priority is to support MAP_SHARED mapped hugely;
2038 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
2039 * But if caller specified an address hint, respect that as before.
2040 */
2041 if (uaddr)
2042 return addr;
2043
2044 if (shmem_huge != SHMEM_HUGE_FORCE) {
2045 struct super_block *sb;
2046
2047 if (file) {
2048 VM_BUG_ON(file->f_op != &shmem_file_operations);
2049 sb = file_inode(file)->i_sb;
2050 } else {
2051 /*
2052 * Called directly from mm/mmap.c, or drivers/char/mem.c
2053 * for "/dev/zero", to create a shared anonymous object.
2054 */
2055 if (IS_ERR(shm_mnt))
2056 return addr;
2057 sb = shm_mnt->mnt_sb;
2058 }
2059 if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
2060 return addr;
2061 }
2062
2063 offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
2064 if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
2065 return addr;
2066 if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
2067 return addr;
2068
2069 inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
2070 if (inflated_len > TASK_SIZE)
2071 return addr;
2072 if (inflated_len < len)
2073 return addr;
2074
2075 inflated_addr = get_area(NULL, 0, inflated_len, 0, flags);
2076 if (IS_ERR_VALUE(inflated_addr))
2077 return addr;
2078 if (inflated_addr & ~PAGE_MASK)
2079 return addr;
2080
2081 inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
2082 inflated_addr += offset - inflated_offset;
2083 if (inflated_offset > offset)
2084 inflated_addr += HPAGE_PMD_SIZE;
2085
2086 if (inflated_addr > TASK_SIZE - len)
2087 return addr;
2088 return inflated_addr;
2089 }
2090
2091 #ifdef CONFIG_NUMA
2092 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
2093 {
2094 struct inode *inode = file_inode(vma->vm_file);
2095 return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
2096 }
2097
2098 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
2099 unsigned long addr)
2100 {
2101 struct inode *inode = file_inode(vma->vm_file);
2102 pgoff_t index;
2103
2104 index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2105 return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
2106 }
2107 #endif
2108
2109 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2110 {
2111 struct inode *inode = file_inode(file);
2112 struct shmem_inode_info *info = SHMEM_I(inode);
2113 int retval = -ENOMEM;
2114
2115 spin_lock_irq(&info->lock);
2116 if (lock && !(info->flags & VM_LOCKED)) {
2117 if (!user_shm_lock(inode->i_size, user))
2118 goto out_nomem;
2119 info->flags |= VM_LOCKED;
2120 mapping_set_unevictable(file->f_mapping);
2121 }
2122 if (!lock && (info->flags & VM_LOCKED) && user) {
2123 user_shm_unlock(inode->i_size, user);
2124 info->flags &= ~VM_LOCKED;
2125 mapping_clear_unevictable(file->f_mapping);
2126 }
2127 retval = 0;
2128
2129 out_nomem:
2130 spin_unlock_irq(&info->lock);
2131 return retval;
2132 }
2133
2134 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
2135 {
2136 file_accessed(file);
2137 vma->vm_ops = &shmem_vm_ops;
2138 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
2139 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
2140 (vma->vm_end & HPAGE_PMD_MASK)) {
2141 khugepaged_enter(vma, vma->vm_flags);
2142 }
2143 return 0;
2144 }
2145
2146 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
2147 umode_t mode, dev_t dev, unsigned long flags)
2148 {
2149 struct inode *inode;
2150 struct shmem_inode_info *info;
2151 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2152 int ino;
2153
2154 if (shmem_reserve_inode(sb))
2155 return NULL;
2156
2157 inode = new_inode(sb);
2158 if (inode) {
2159 inode_init_owner(inode, dir, mode);
2160 inode->i_blocks = 0;
2161 inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
2162 inode->i_generation = prandom_u32();
2163 info = SHMEM_I(inode);
2164 memset(info, 0, (char *)inode - (char *)info);
2165 spin_lock_init(&info->lock);
2166 info->seals = F_SEAL_SEAL;
2167 info->flags = flags & VM_NORESERVE;
2168 INIT_LIST_HEAD(&info->shrinklist);
2169 INIT_LIST_HEAD(&info->swaplist);
2170 simple_xattrs_init(&info->xattrs);
2171 cache_no_acl(inode);
2172
2173 switch (mode & S_IFMT) {
2174 default:
2175 inode->i_op = &shmem_special_inode_operations;
2176 init_special_inode(inode, mode, dev);
2177 break;
2178 case S_IFREG:
2179 inode->i_mapping->a_ops = &shmem_aops;
2180 inode->i_op = &shmem_inode_operations;
2181 inode->i_fop = &shmem_file_operations;
2182 mpol_shared_policy_init(&info->policy,
2183 shmem_get_sbmpol(sbinfo));
2184 break;
2185 case S_IFDIR:
2186 inc_nlink(inode);
2187 /* Some things misbehave if size == 0 on a directory */
2188 inode->i_size = 2 * BOGO_DIRENT_SIZE;
2189 inode->i_op = &shmem_dir_inode_operations;
2190 inode->i_fop = &simple_dir_operations;
2191 break;
2192 case S_IFLNK:
2193 /*
2194 * Must not load anything in the rbtree,
2195 * mpol_free_shared_policy will not be called.
2196 */
2197 mpol_shared_policy_init(&info->policy, NULL);
2198 break;
2199 }
2200
2201 if (!sbinfo->idr_nouse) {
2202 /* inum 0 and 1 are unused */
2203 mutex_lock(&sbinfo->idr_lock);
2204 ino = idr_alloc(&sbinfo->idr, inode, 2, INT_MAX,
2205 GFP_NOFS);
2206 if (ino > 0) {
2207 inode->i_ino = ino;
2208 mutex_unlock(&sbinfo->idr_lock);
2209 __insert_inode_hash(inode, inode->i_ino);
2210 } else {
2211 inode->i_ino = 0;
2212 mutex_unlock(&sbinfo->idr_lock);
2213 iput(inode);
2214 /* shmem_free_inode() will be called */
2215 inode = NULL;
2216 }
2217 } else
2218 inode->i_ino = get_next_ino();
2219
2220 lockdep_annotate_inode_mutex_key(inode);
2221 } else
2222 shmem_free_inode(sb);
2223 return inode;
2224 }
2225
2226 bool shmem_mapping(struct address_space *mapping)
2227 {
2228 return mapping->a_ops == &shmem_aops;
2229 }
2230
2231 static int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
2232 pmd_t *dst_pmd,
2233 struct vm_area_struct *dst_vma,
2234 unsigned long dst_addr,
2235 unsigned long src_addr,
2236 bool zeropage,
2237 struct page **pagep)
2238 {
2239 struct inode *inode = file_inode(dst_vma->vm_file);
2240 struct shmem_inode_info *info = SHMEM_I(inode);
2241 struct address_space *mapping = inode->i_mapping;
2242 gfp_t gfp = mapping_gfp_mask(mapping);
2243 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
2244 struct mem_cgroup *memcg;
2245 spinlock_t *ptl;
2246 void *page_kaddr;
2247 struct page *page;
2248 pte_t _dst_pte, *dst_pte;
2249 int ret;
2250 pgoff_t offset, max_off;
2251
2252 ret = -ENOMEM;
2253 if (!shmem_inode_acct_block(inode, 1))
2254 goto out;
2255
2256 if (!*pagep) {
2257 page = shmem_alloc_page(gfp, info, pgoff);
2258 if (!page)
2259 goto out_unacct_blocks;
2260
2261 if (!zeropage) { /* mcopy_atomic */
2262 page_kaddr = kmap_atomic(page);
2263 ret = copy_from_user(page_kaddr,
2264 (const void __user *)src_addr,
2265 PAGE_SIZE);
2266 kunmap_atomic(page_kaddr);
2267
2268 /* fallback to copy_from_user outside mmap_sem */
2269 if (unlikely(ret)) {
2270 *pagep = page;
2271 shmem_inode_unacct_blocks(inode, 1);
2272 /* don't free the page */
2273 return -ENOENT;
2274 }
2275 } else { /* mfill_zeropage_atomic */
2276 clear_highpage(page);
2277 }
2278 } else {
2279 page = *pagep;
2280 *pagep = NULL;
2281 }
2282
2283 VM_BUG_ON(PageLocked(page) || PageSwapBacked(page));
2284 __SetPageLocked(page);
2285 __SetPageSwapBacked(page);
2286 __SetPageUptodate(page);
2287
2288 ret = -EFAULT;
2289 offset = linear_page_index(dst_vma, dst_addr);
2290 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2291 if (unlikely(offset >= max_off))
2292 goto out_release;
2293
2294 ret = mem_cgroup_try_charge_delay(page, dst_mm, gfp, &memcg, false);
2295 if (ret)
2296 goto out_release;
2297
2298 ret = shmem_add_to_page_cache(page, mapping, pgoff, NULL,
2299 gfp & GFP_RECLAIM_MASK);
2300 if (ret)
2301 goto out_release_uncharge;
2302
2303 mem_cgroup_commit_charge(page, memcg, false, false);
2304
2305 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
2306 if (dst_vma->vm_flags & VM_WRITE)
2307 _dst_pte = pte_mkwrite(pte_mkdirty(_dst_pte));
2308 else {
2309 /*
2310 * We don't set the pte dirty if the vma has no
2311 * VM_WRITE permission, so mark the page dirty or it
2312 * could be freed from under us. We could do it
2313 * unconditionally before unlock_page(), but doing it
2314 * only if VM_WRITE is not set is faster.
2315 */
2316 set_page_dirty(page);
2317 }
2318
2319 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
2320
2321 ret = -EFAULT;
2322 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2323 if (unlikely(offset >= max_off))
2324 goto out_release_uncharge_unlock;
2325
2326 ret = -EEXIST;
2327 if (!pte_none(*dst_pte))
2328 goto out_release_uncharge_unlock;
2329
2330 lru_cache_add_anon(page);
2331
2332 spin_lock(&info->lock);
2333 info->alloced++;
2334 inode->i_blocks += BLOCKS_PER_PAGE;
2335 shmem_recalc_inode(inode);
2336 spin_unlock(&info->lock);
2337
2338 inc_mm_counter(dst_mm, mm_counter_file(page));
2339 page_add_file_rmap(page, false);
2340 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
2341
2342 /* No need to invalidate - it was non-present before */
2343 update_mmu_cache(dst_vma, dst_addr, dst_pte);
2344 pte_unmap_unlock(dst_pte, ptl);
2345 unlock_page(page);
2346 ret = 0;
2347 out:
2348 return ret;
2349 out_release_uncharge_unlock:
2350 pte_unmap_unlock(dst_pte, ptl);
2351 ClearPageDirty(page);
2352 delete_from_page_cache(page);
2353 out_release_uncharge:
2354 mem_cgroup_cancel_charge(page, memcg, false);
2355 out_release:
2356 unlock_page(page);
2357 put_page(page);
2358 out_unacct_blocks:
2359 shmem_inode_unacct_blocks(inode, 1);
2360 goto out;
2361 }
2362
2363 int shmem_mcopy_atomic_pte(struct mm_struct *dst_mm,
2364 pmd_t *dst_pmd,
2365 struct vm_area_struct *dst_vma,
2366 unsigned long dst_addr,
2367 unsigned long src_addr,
2368 struct page **pagep)
2369 {
2370 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2371 dst_addr, src_addr, false, pagep);
2372 }
2373
2374 int shmem_mfill_zeropage_pte(struct mm_struct *dst_mm,
2375 pmd_t *dst_pmd,
2376 struct vm_area_struct *dst_vma,
2377 unsigned long dst_addr)
2378 {
2379 struct page *page = NULL;
2380
2381 return shmem_mfill_atomic_pte(dst_mm, dst_pmd, dst_vma,
2382 dst_addr, 0, true, &page);
2383 }
2384
2385 #ifdef CONFIG_TMPFS
2386 static const struct inode_operations shmem_symlink_inode_operations;
2387 static const struct inode_operations shmem_short_symlink_operations;
2388
2389 #ifdef CONFIG_TMPFS_XATTR
2390 static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
2391 #else
2392 #define shmem_initxattrs NULL
2393 #endif
2394
2395 static int
2396 shmem_write_begin(struct file *file, struct address_space *mapping,
2397 loff_t pos, unsigned len, unsigned flags,
2398 struct page **pagep, void **fsdata)
2399 {
2400 struct inode *inode = mapping->host;
2401 struct shmem_inode_info *info = SHMEM_I(inode);
2402 pgoff_t index = pos >> PAGE_SHIFT;
2403
2404 /* i_mutex is held by caller */
2405 if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
2406 if (info->seals & F_SEAL_WRITE)
2407 return -EPERM;
2408 if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
2409 return -EPERM;
2410 }
2411
2412 return shmem_getpage(inode, index, pagep, SGP_WRITE);
2413 }
2414
2415 static int
2416 shmem_write_end(struct file *file, struct address_space *mapping,
2417 loff_t pos, unsigned len, unsigned copied,
2418 struct page *page, void *fsdata)
2419 {
2420 struct inode *inode = mapping->host;
2421
2422 if (pos + copied > inode->i_size)
2423 i_size_write(inode, pos + copied);
2424
2425 if (!PageUptodate(page)) {
2426 struct page *head = compound_head(page);
2427 if (PageTransCompound(page)) {
2428 int i;
2429
2430 for (i = 0; i < HPAGE_PMD_NR; i++) {
2431 if (head + i == page)
2432 continue;
2433 clear_highpage(head + i);
2434 flush_dcache_page(head + i);
2435 }
2436 }
2437 if (copied < PAGE_SIZE) {
2438 unsigned from = pos & (PAGE_SIZE - 1);
2439 zero_user_segments(page, 0, from,
2440 from + copied, PAGE_SIZE);
2441 }
2442 SetPageUptodate(head);
2443 }
2444 set_page_dirty(page);
2445 unlock_page(page);
2446 put_page(page);
2447
2448 return copied;
2449 }
2450
2451 static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2452 {
2453 struct file *file = iocb->ki_filp;
2454 struct inode *inode = file_inode(file);
2455 struct address_space *mapping = inode->i_mapping;
2456 pgoff_t index;
2457 unsigned long offset;
2458 enum sgp_type sgp = SGP_READ;
2459 int error = 0;
2460 ssize_t retval = 0;
2461 loff_t *ppos = &iocb->ki_pos;
2462
2463 /*
2464 * Might this read be for a stacking filesystem? Then when reading
2465 * holes of a sparse file, we actually need to allocate those pages,
2466 * and even mark them dirty, so it cannot exceed the max_blocks limit.
2467 */
2468 if (!iter_is_iovec(to))
2469 sgp = SGP_CACHE;
2470
2471 index = *ppos >> PAGE_SHIFT;
2472 offset = *ppos & ~PAGE_MASK;
2473
2474 for (;;) {
2475 struct page *page = NULL;
2476 pgoff_t end_index;
2477 unsigned long nr, ret;
2478 loff_t i_size = i_size_read(inode);
2479
2480 end_index = i_size >> PAGE_SHIFT;
2481 if (index > end_index)
2482 break;
2483 if (index == end_index) {
2484 nr = i_size & ~PAGE_MASK;
2485 if (nr <= offset)
2486 break;
2487 }
2488
2489 error = shmem_getpage(inode, index, &page, sgp);
2490 if (error) {
2491 if (error == -EINVAL)
2492 error = 0;
2493 break;
2494 }
2495 if (page) {
2496 if (sgp == SGP_CACHE)
2497 set_page_dirty(page);
2498 unlock_page(page);
2499 }
2500
2501 /*
2502 * We must evaluate after, since reads (unlike writes)
2503 * are called without i_mutex protection against truncate
2504 */
2505 nr = PAGE_SIZE;
2506 i_size = i_size_read(inode);
2507 end_index = i_size >> PAGE_SHIFT;
2508 if (index == end_index) {
2509 nr = i_size & ~PAGE_MASK;
2510 if (nr <= offset) {
2511 if (page)
2512 put_page(page);
2513 break;
2514 }
2515 }
2516 nr -= offset;
2517
2518 if (page) {
2519 /*
2520 * If users can be writing to this page using arbitrary
2521 * virtual addresses, take care about potential aliasing
2522 * before reading the page on the kernel side.
2523 */
2524 if (mapping_writably_mapped(mapping))
2525 flush_dcache_page(page);
2526 /*
2527 * Mark the page accessed if we read the beginning.
2528 */
2529 if (!offset)
2530 mark_page_accessed(page);
2531 } else {
2532 page = ZERO_PAGE(0);
2533 get_page(page);
2534 }
2535
2536 /*
2537 * Ok, we have the page, and it's up-to-date, so
2538 * now we can copy it to user space...
2539 */
2540 ret = copy_page_to_iter(page, offset, nr, to);
2541 retval += ret;
2542 offset += ret;
2543 index += offset >> PAGE_SHIFT;
2544 offset &= ~PAGE_MASK;
2545
2546 put_page(page);
2547 if (!iov_iter_count(to))
2548 break;
2549 if (ret < nr) {
2550 error = -EFAULT;
2551 break;
2552 }
2553 cond_resched();
2554 }
2555
2556 *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
2557 file_accessed(file);
2558 return retval ? retval : error;
2559 }
2560
2561 /*
2562 * llseek SEEK_DATA or SEEK_HOLE through the page cache.
2563 */
2564 static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
2565 pgoff_t index, pgoff_t end, int whence)
2566 {
2567 struct page *page;
2568 struct pagevec pvec;
2569 pgoff_t indices[PAGEVEC_SIZE];
2570 bool done = false;
2571 int i;
2572
2573 pagevec_init(&pvec);
2574 pvec.nr = 1; /* start small: we may be there already */
2575 while (!done) {
2576 pvec.nr = find_get_entries(mapping, index,
2577 pvec.nr, pvec.pages, indices);
2578 if (!pvec.nr) {
2579 if (whence == SEEK_DATA)
2580 index = end;
2581 break;
2582 }
2583 for (i = 0; i < pvec.nr; i++, index++) {
2584 if (index < indices[i]) {
2585 if (whence == SEEK_HOLE) {
2586 done = true;
2587 break;
2588 }
2589 index = indices[i];
2590 }
2591 page = pvec.pages[i];
2592 if (page && !xa_is_value(page)) {
2593 if (!PageUptodate(page))
2594 page = NULL;
2595 }
2596 if (index >= end ||
2597 (page && whence == SEEK_DATA) ||
2598 (!page && whence == SEEK_HOLE)) {
2599 done = true;
2600 break;
2601 }
2602 }
2603 pagevec_remove_exceptionals(&pvec);
2604 pagevec_release(&pvec);
2605 pvec.nr = PAGEVEC_SIZE;
2606 cond_resched();
2607 }
2608 return index;
2609 }
2610
2611 static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
2612 {
2613 struct address_space *mapping = file->f_mapping;
2614 struct inode *inode = mapping->host;
2615 pgoff_t start, end;
2616 loff_t new_offset;
2617
2618 if (whence != SEEK_DATA && whence != SEEK_HOLE)
2619 return generic_file_llseek_size(file, offset, whence,
2620 MAX_LFS_FILESIZE, i_size_read(inode));
2621 inode_lock(inode);
2622 /* We're holding i_mutex so we can access i_size directly */
2623
2624 if (offset < 0 || offset >= inode->i_size)
2625 offset = -ENXIO;
2626 else {
2627 start = offset >> PAGE_SHIFT;
2628 end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2629 new_offset = shmem_seek_hole_data(mapping, start, end, whence);
2630 new_offset <<= PAGE_SHIFT;
2631 if (new_offset > offset) {
2632 if (new_offset < inode->i_size)
2633 offset = new_offset;
2634 else if (whence == SEEK_DATA)
2635 offset = -ENXIO;
2636 else
2637 offset = inode->i_size;
2638 }
2639 }
2640
2641 if (offset >= 0)
2642 offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
2643 inode_unlock(inode);
2644 return offset;
2645 }
2646
2647 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2648 loff_t len)
2649 {
2650 struct inode *inode = file_inode(file);
2651 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2652 struct shmem_inode_info *info = SHMEM_I(inode);
2653 struct shmem_falloc shmem_falloc;
2654 pgoff_t start, index, end;
2655 int error;
2656
2657 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2658 return -EOPNOTSUPP;
2659
2660 inode_lock(inode);
2661
2662 if (mode & FALLOC_FL_PUNCH_HOLE) {
2663 struct address_space *mapping = file->f_mapping;
2664 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2665 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2666 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2667
2668 /* protected by i_mutex */
2669 if (info->seals & F_SEAL_WRITE) {
2670 error = -EPERM;
2671 goto out;
2672 }
2673
2674 shmem_falloc.waitq = &shmem_falloc_waitq;
2675 shmem_falloc.start = unmap_start >> PAGE_SHIFT;
2676 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2677 spin_lock(&inode->i_lock);
2678 inode->i_private = &shmem_falloc;
2679 spin_unlock(&inode->i_lock);
2680
2681 if ((u64)unmap_end > (u64)unmap_start)
2682 unmap_mapping_range(mapping, unmap_start,
2683 1 + unmap_end - unmap_start, 0);
2684 shmem_truncate_range(inode, offset, offset + len - 1);
2685 /* No need to unmap again: hole-punching leaves COWed pages */
2686
2687 spin_lock(&inode->i_lock);
2688 inode->i_private = NULL;
2689 wake_up_all(&shmem_falloc_waitq);
2690 WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
2691 spin_unlock(&inode->i_lock);
2692 error = 0;
2693 goto out;
2694 }
2695
2696 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2697 error = inode_newsize_ok(inode, offset + len);
2698 if (error)
2699 goto out;
2700
2701 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2702 error = -EPERM;
2703 goto out;
2704 }
2705
2706 start = offset >> PAGE_SHIFT;
2707 end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2708 /* Try to avoid a swapstorm if len is impossible to satisfy */
2709 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2710 error = -ENOSPC;
2711 goto out;
2712 }
2713
2714 shmem_falloc.waitq = NULL;
2715 shmem_falloc.start = start;
2716 shmem_falloc.next = start;
2717 shmem_falloc.nr_falloced = 0;
2718 shmem_falloc.nr_unswapped = 0;
2719 spin_lock(&inode->i_lock);
2720 inode->i_private = &shmem_falloc;
2721 spin_unlock(&inode->i_lock);
2722
2723 for (index = start; index < end; index++) {
2724 struct page *page;
2725
2726 /*
2727 * Good, the fallocate(2) manpage permits EINTR: we may have
2728 * been interrupted because we are using up too much memory.
2729 */
2730 if (signal_pending(current))
2731 error = -EINTR;
2732 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2733 error = -ENOMEM;
2734 else
2735 error = shmem_getpage(inode, index, &page, SGP_FALLOC);
2736 if (error) {
2737 /* Remove the !PageUptodate pages we added */
2738 if (index > start) {
2739 shmem_undo_range(inode,
2740 (loff_t)start << PAGE_SHIFT,
2741 ((loff_t)index << PAGE_SHIFT) - 1, true);
2742 }
2743 goto undone;
2744 }
2745
2746 /*
2747 * Inform shmem_writepage() how far we have reached.
2748 * No need for lock or barrier: we have the page lock.
2749 */
2750 shmem_falloc.next++;
2751 if (!PageUptodate(page))
2752 shmem_falloc.nr_falloced++;
2753
2754 /*
2755 * If !PageUptodate, leave it that way so that freeable pages
2756 * can be recognized if we need to rollback on error later.
2757 * But set_page_dirty so that memory pressure will swap rather
2758 * than free the pages we are allocating (and SGP_CACHE pages
2759 * might still be clean: we now need to mark those dirty too).
2760 */
2761 set_page_dirty(page);
2762 unlock_page(page);
2763 put_page(page);
2764 cond_resched();
2765 }
2766
2767 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2768 i_size_write(inode, offset + len);
2769 inode->i_ctime = current_time(inode);
2770 undone:
2771 spin_lock(&inode->i_lock);
2772 inode->i_private = NULL;
2773 spin_unlock(&inode->i_lock);
2774 out:
2775 inode_unlock(inode);
2776 return error;
2777 }
2778
2779 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2780 {
2781 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2782
2783 buf->f_type = TMPFS_MAGIC;
2784 buf->f_bsize = PAGE_SIZE;
2785 buf->f_namelen = NAME_MAX;
2786 if (sbinfo->max_blocks) {
2787 buf->f_blocks = sbinfo->max_blocks;
2788 buf->f_bavail =
2789 buf->f_bfree = sbinfo->max_blocks -
2790 percpu_counter_sum(&sbinfo->used_blocks);
2791 }
2792 if (sbinfo->max_inodes) {
2793 buf->f_files = sbinfo->max_inodes;
2794 buf->f_ffree = sbinfo->free_inodes;
2795 }
2796 /* else leave those fields 0 like simple_statfs */
2797 return 0;
2798 }
2799
2800 /*
2801 * File creation. Allocate an inode, and we're done..
2802 */
2803 static int
2804 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2805 {
2806 struct inode *inode;
2807 int error = -ENOSPC;
2808
2809 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2810 if (inode) {
2811 error = simple_acl_create(dir, inode);
2812 if (error)
2813 goto out_iput;
2814 error = security_inode_init_security(inode, dir,
2815 &dentry->d_name,
2816 shmem_initxattrs, NULL);
2817 if (error && error != -EOPNOTSUPP)
2818 goto out_iput;
2819
2820 error = 0;
2821 dir->i_size += BOGO_DIRENT_SIZE;
2822 dir->i_ctime = dir->i_mtime = current_time(dir);
2823 d_instantiate(dentry, inode);
2824 dget(dentry); /* Extra count - pin the dentry in core */
2825 }
2826 return error;
2827 out_iput:
2828 iput(inode);
2829 return error;
2830 }
2831
2832 static int
2833 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2834 {
2835 struct inode *inode;
2836 int error = -ENOSPC;
2837
2838 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2839 if (inode) {
2840 error = security_inode_init_security(inode, dir,
2841 NULL,
2842 shmem_initxattrs, NULL);
2843 if (error && error != -EOPNOTSUPP)
2844 goto out_iput;
2845 error = simple_acl_create(dir, inode);
2846 if (error)
2847 goto out_iput;
2848 d_tmpfile(dentry, inode);
2849 }
2850 return error;
2851 out_iput:
2852 iput(inode);
2853 return error;
2854 }
2855
2856 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2857 {
2858 int error;
2859
2860 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
2861 return error;
2862 inc_nlink(dir);
2863 return 0;
2864 }
2865
2866 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2867 bool excl)
2868 {
2869 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
2870 }
2871
2872 /*
2873 * Link a file..
2874 */
2875 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2876 {
2877 struct inode *inode = d_inode(old_dentry);
2878 int ret = 0;
2879
2880 /*
2881 * No ordinary (disk based) filesystem counts links as inodes;
2882 * but each new link needs a new dentry, pinning lowmem, and
2883 * tmpfs dentries cannot be pruned until they are unlinked.
2884 * But if an O_TMPFILE file is linked into the tmpfs, the
2885 * first link must skip that, to get the accounting right.
2886 */
2887 if (inode->i_nlink) {
2888 ret = shmem_reserve_inode(inode->i_sb);
2889 if (ret)
2890 goto out;
2891 }
2892
2893 dir->i_size += BOGO_DIRENT_SIZE;
2894 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2895 inc_nlink(inode);
2896 ihold(inode); /* New dentry reference */
2897 dget(dentry); /* Extra pinning count for the created dentry */
2898 d_instantiate(dentry, inode);
2899 out:
2900 return ret;
2901 }
2902
2903 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
2904 {
2905 struct inode *inode = d_inode(dentry);
2906
2907 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
2908 shmem_free_inode(inode->i_sb);
2909
2910 dir->i_size -= BOGO_DIRENT_SIZE;
2911 inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
2912 drop_nlink(inode);
2913 dput(dentry); /* Undo the count from "create" - this does all the work */
2914 return 0;
2915 }
2916
2917 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
2918 {
2919 if (!simple_empty(dentry))
2920 return -ENOTEMPTY;
2921
2922 drop_nlink(d_inode(dentry));
2923 drop_nlink(dir);
2924 return shmem_unlink(dir, dentry);
2925 }
2926
2927 static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
2928 {
2929 bool old_is_dir = d_is_dir(old_dentry);
2930 bool new_is_dir = d_is_dir(new_dentry);
2931
2932 if (old_dir != new_dir && old_is_dir != new_is_dir) {
2933 if (old_is_dir) {
2934 drop_nlink(old_dir);
2935 inc_nlink(new_dir);
2936 } else {
2937 drop_nlink(new_dir);
2938 inc_nlink(old_dir);
2939 }
2940 }
2941 old_dir->i_ctime = old_dir->i_mtime =
2942 new_dir->i_ctime = new_dir->i_mtime =
2943 d_inode(old_dentry)->i_ctime =
2944 d_inode(new_dentry)->i_ctime = current_time(old_dir);
2945
2946 return 0;
2947 }
2948
2949 static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
2950 {
2951 struct dentry *whiteout;
2952 int error;
2953
2954 whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
2955 if (!whiteout)
2956 return -ENOMEM;
2957
2958 error = shmem_mknod(old_dir, whiteout,
2959 S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
2960 dput(whiteout);
2961 if (error)
2962 return error;
2963
2964 /*
2965 * Cheat and hash the whiteout while the old dentry is still in
2966 * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
2967 *
2968 * d_lookup() will consistently find one of them at this point,
2969 * not sure which one, but that isn't even important.
2970 */
2971 d_rehash(whiteout);
2972 return 0;
2973 }
2974
2975 /*
2976 * The VFS layer already does all the dentry stuff for rename,
2977 * we just have to decrement the usage count for the target if
2978 * it exists so that the VFS layer correctly free's it when it
2979 * gets overwritten.
2980 */
2981 static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
2982 {
2983 struct inode *inode = d_inode(old_dentry);
2984 int they_are_dirs = S_ISDIR(inode->i_mode);
2985
2986 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
2987 return -EINVAL;
2988
2989 if (flags & RENAME_EXCHANGE)
2990 return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
2991
2992 if (!simple_empty(new_dentry))
2993 return -ENOTEMPTY;
2994
2995 if (flags & RENAME_WHITEOUT) {
2996 int error;
2997
2998 error = shmem_whiteout(old_dir, old_dentry);
2999 if (error)
3000 return error;
3001 }
3002
3003 if (d_really_is_positive(new_dentry)) {
3004 (void) shmem_unlink(new_dir, new_dentry);
3005 if (they_are_dirs) {
3006 drop_nlink(d_inode(new_dentry));
3007 drop_nlink(old_dir);
3008 }
3009 } else if (they_are_dirs) {
3010 drop_nlink(old_dir);
3011 inc_nlink(new_dir);
3012 }
3013
3014 old_dir->i_size -= BOGO_DIRENT_SIZE;
3015 new_dir->i_size += BOGO_DIRENT_SIZE;
3016 old_dir->i_ctime = old_dir->i_mtime =
3017 new_dir->i_ctime = new_dir->i_mtime =
3018 inode->i_ctime = current_time(old_dir);
3019 return 0;
3020 }
3021
3022 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
3023 {
3024 int error;
3025 int len;
3026 struct inode *inode;
3027 struct page *page;
3028
3029 len = strlen(symname) + 1;
3030 if (len > PAGE_SIZE)
3031 return -ENAMETOOLONG;
3032
3033 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
3034 VM_NORESERVE);
3035 if (!inode)
3036 return -ENOSPC;
3037
3038 error = security_inode_init_security(inode, dir, &dentry->d_name,
3039 shmem_initxattrs, NULL);
3040 if (error) {
3041 if (error != -EOPNOTSUPP) {
3042 iput(inode);
3043 return error;
3044 }
3045 error = 0;
3046 }
3047
3048 inode->i_size = len-1;
3049 if (len <= SHORT_SYMLINK_LEN) {
3050 inode->i_link = kmemdup(symname, len, GFP_KERNEL);
3051 if (!inode->i_link) {
3052 iput(inode);
3053 return -ENOMEM;
3054 }
3055 inode->i_op = &shmem_short_symlink_operations;
3056 } else {
3057 inode_nohighmem(inode);
3058 error = shmem_getpage(inode, 0, &page, SGP_WRITE);
3059 if (error) {
3060 iput(inode);
3061 return error;
3062 }
3063 inode->i_mapping->a_ops = &shmem_aops;
3064 inode->i_op = &shmem_symlink_inode_operations;
3065 memcpy(page_address(page), symname, len);
3066 SetPageUptodate(page);
3067 set_page_dirty(page);
3068 unlock_page(page);
3069 put_page(page);
3070 }
3071 dir->i_size += BOGO_DIRENT_SIZE;
3072 dir->i_ctime = dir->i_mtime = current_time(dir);
3073 d_instantiate(dentry, inode);
3074 dget(dentry);
3075 return 0;
3076 }
3077
3078 static void shmem_put_link(void *arg)
3079 {
3080 mark_page_accessed(arg);
3081 put_page(arg);
3082 }
3083
3084 static const char *shmem_get_link(struct dentry *dentry,
3085 struct inode *inode,
3086 struct delayed_call *done)
3087 {
3088 struct page *page = NULL;
3089 int error;
3090 if (!dentry) {
3091 page = find_get_page(inode->i_mapping, 0);
3092 if (!page)
3093 return ERR_PTR(-ECHILD);
3094 if (!PageUptodate(page)) {
3095 put_page(page);
3096 return ERR_PTR(-ECHILD);
3097 }
3098 } else {
3099 error = shmem_getpage(inode, 0, &page, SGP_READ);
3100 if (error)
3101 return ERR_PTR(error);
3102 unlock_page(page);
3103 }
3104 set_delayed_call(done, shmem_put_link, page);
3105 return page_address(page);
3106 }
3107
3108 #ifdef CONFIG_TMPFS_XATTR
3109 /*
3110 * Superblocks without xattr inode operations may get some security.* xattr
3111 * support from the LSM "for free". As soon as we have any other xattrs
3112 * like ACLs, we also need to implement the security.* handlers at
3113 * filesystem level, though.
3114 */
3115
3116 /*
3117 * Callback for security_inode_init_security() for acquiring xattrs.
3118 */
3119 static int shmem_initxattrs(struct inode *inode,
3120 const struct xattr *xattr_array,
3121 void *fs_info)
3122 {
3123 struct shmem_inode_info *info = SHMEM_I(inode);
3124 const struct xattr *xattr;
3125 struct simple_xattr *new_xattr;
3126 size_t len;
3127
3128 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
3129 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
3130 if (!new_xattr)
3131 return -ENOMEM;
3132
3133 len = strlen(xattr->name) + 1;
3134 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
3135 GFP_KERNEL);
3136 if (!new_xattr->name) {
3137 kfree(new_xattr);
3138 return -ENOMEM;
3139 }
3140
3141 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
3142 XATTR_SECURITY_PREFIX_LEN);
3143 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
3144 xattr->name, len);
3145
3146 simple_xattr_list_add(&info->xattrs, new_xattr);
3147 }
3148
3149 return 0;
3150 }
3151
3152 static int shmem_xattr_handler_get(const struct xattr_handler *handler,
3153 struct dentry *unused, struct inode *inode,
3154 const char *name, void *buffer, size_t size)
3155 {
3156 struct shmem_inode_info *info = SHMEM_I(inode);
3157
3158 name = xattr_full_name(handler, name);
3159 return simple_xattr_get(&info->xattrs, name, buffer, size);
3160 }
3161
3162 static int shmem_xattr_handler_set(const struct xattr_handler *handler,
3163 struct dentry *unused, struct inode *inode,
3164 const char *name, const void *value,
3165 size_t size, int flags)
3166 {
3167 struct shmem_inode_info *info = SHMEM_I(inode);
3168
3169 name = xattr_full_name(handler, name);
3170 return simple_xattr_set(&info->xattrs, name, value, size, flags);
3171 }
3172
3173 static const struct xattr_handler shmem_security_xattr_handler = {
3174 .prefix = XATTR_SECURITY_PREFIX,
3175 .get = shmem_xattr_handler_get,
3176 .set = shmem_xattr_handler_set,
3177 };
3178
3179 static const struct xattr_handler shmem_trusted_xattr_handler = {
3180 .prefix = XATTR_TRUSTED_PREFIX,
3181 .get = shmem_xattr_handler_get,
3182 .set = shmem_xattr_handler_set,
3183 };
3184
3185 static const struct xattr_handler *shmem_xattr_handlers[] = {
3186 #ifdef CONFIG_TMPFS_POSIX_ACL
3187 &posix_acl_access_xattr_handler,
3188 &posix_acl_default_xattr_handler,
3189 #endif
3190 &shmem_security_xattr_handler,
3191 &shmem_trusted_xattr_handler,
3192 NULL
3193 };
3194
3195 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
3196 {
3197 struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
3198 return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
3199 }
3200 #endif /* CONFIG_TMPFS_XATTR */
3201
3202 static const struct inode_operations shmem_short_symlink_operations = {
3203 .get_link = simple_get_link,
3204 #ifdef CONFIG_TMPFS_XATTR
3205 .listxattr = shmem_listxattr,
3206 #endif
3207 };
3208
3209 static const struct inode_operations shmem_symlink_inode_operations = {
3210 .get_link = shmem_get_link,
3211 #ifdef CONFIG_TMPFS_XATTR
3212 .listxattr = shmem_listxattr,
3213 #endif
3214 };
3215
3216 static struct dentry *shmem_get_parent(struct dentry *child)
3217 {
3218 return ERR_PTR(-ESTALE);
3219 }
3220
3221 static int shmem_match(struct inode *ino, void *vfh)
3222 {
3223 __u32 *fh = vfh;
3224 __u64 inum = fh[1];
3225 return ino->i_ino == inum && fh[0] == ino->i_generation;
3226 }
3227
3228 /* Find any alias of inode, but prefer a hashed alias */
3229 static struct dentry *shmem_find_alias(struct inode *inode)
3230 {
3231 struct dentry *alias = d_find_alias(inode);
3232
3233 return alias ?: d_find_any_alias(inode);
3234 }
3235
3236
3237 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
3238 struct fid *fid, int fh_len, int fh_type)
3239 {
3240 struct inode *inode;
3241 struct dentry *dentry = NULL;
3242 u64 inum;
3243
3244 if (fh_len < 2)
3245 return NULL;
3246
3247 inum = fid->raw[1];
3248 inode = ilookup5(sb, inum, shmem_match, fid->raw);
3249 if (inode) {
3250 dentry = shmem_find_alias(inode);
3251 iput(inode);
3252 }
3253
3254 return dentry;
3255 }
3256
3257 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
3258 struct inode *parent)
3259 {
3260 if (*len < 2) {
3261 *len = 2;
3262 return FILEID_INVALID;
3263 }
3264
3265 fh[0] = inode->i_generation;
3266 fh[1] = inode->i_ino;
3267
3268 *len = 2;
3269 return 1;
3270 }
3271
3272 static const struct export_operations shmem_export_ops = {
3273 .get_parent = shmem_get_parent,
3274 .encode_fh = shmem_encode_fh,
3275 .fh_to_dentry = shmem_fh_to_dentry,
3276 };
3277
3278 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
3279 bool remount)
3280 {
3281 char *this_char, *value, *rest;
3282 struct mempolicy *mpol = NULL;
3283 uid_t uid;
3284 gid_t gid;
3285
3286 while (options != NULL) {
3287 this_char = options;
3288 for (;;) {
3289 /*
3290 * NUL-terminate this option: unfortunately,
3291 * mount options form a comma-separated list,
3292 * but mpol's nodelist may also contain commas.
3293 */
3294 options = strchr(options, ',');
3295 if (options == NULL)
3296 break;
3297 options++;
3298 if (!isdigit(*options)) {
3299 options[-1] = '\0';
3300 break;
3301 }
3302 }
3303 if (!*this_char)
3304 continue;
3305 if ((value = strchr(this_char,'=')) != NULL) {
3306 *value++ = 0;
3307 } else {
3308 pr_err("tmpfs: No value for mount option '%s'\n",
3309 this_char);
3310 goto error;
3311 }
3312
3313 if (!strcmp(this_char,"size")) {
3314 unsigned long long size;
3315 size = memparse(value,&rest);
3316 if (*rest == '%') {
3317 size <<= PAGE_SHIFT;
3318 size *= totalram_pages();
3319 do_div(size, 100);
3320 rest++;
3321 }
3322 if (*rest)
3323 goto bad_val;
3324 sbinfo->max_blocks =
3325 DIV_ROUND_UP(size, PAGE_SIZE);
3326 } else if (!strcmp(this_char,"nr_blocks")) {
3327 sbinfo->max_blocks = memparse(value, &rest);
3328 if (*rest)
3329 goto bad_val;
3330 } else if (!strcmp(this_char,"nr_inodes")) {
3331 sbinfo->max_inodes = memparse(value, &rest);
3332 if (*rest || sbinfo->max_inodes < 2)
3333 goto bad_val;
3334 } else if (!strcmp(this_char,"mode")) {
3335 if (remount)
3336 continue;
3337 sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
3338 if (*rest)
3339 goto bad_val;
3340 } else if (!strcmp(this_char,"uid")) {
3341 if (remount)
3342 continue;
3343 uid = simple_strtoul(value, &rest, 0);
3344 if (*rest)
3345 goto bad_val;
3346 sbinfo->uid = make_kuid(current_user_ns(), uid);
3347 if (!uid_valid(sbinfo->uid))
3348 goto bad_val;
3349 } else if (!strcmp(this_char,"gid")) {
3350 if (remount)
3351 continue;
3352 gid = simple_strtoul(value, &rest, 0);
3353 if (*rest)
3354 goto bad_val;
3355 sbinfo->gid = make_kgid(current_user_ns(), gid);
3356 if (!gid_valid(sbinfo->gid))
3357 goto bad_val;
3358 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3359 } else if (!strcmp(this_char, "huge")) {
3360 int huge;
3361 huge = shmem_parse_huge(value);
3362 if (huge < 0)
3363 goto bad_val;
3364 if (!has_transparent_hugepage() &&
3365 huge != SHMEM_HUGE_NEVER)
3366 goto bad_val;
3367 sbinfo->huge = huge;
3368 #endif
3369 #ifdef CONFIG_NUMA
3370 } else if (!strcmp(this_char,"mpol")) {
3371 mpol_put(mpol);
3372 mpol = NULL;
3373 if (mpol_parse_str(value, &mpol))
3374 goto bad_val;
3375 #endif
3376 } else {
3377 pr_err("tmpfs: Bad mount option %s\n", this_char);
3378 goto error;
3379 }
3380 }
3381 sbinfo->mpol = mpol;
3382 return 0;
3383
3384 bad_val:
3385 pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
3386 value, this_char);
3387 error:
3388 mpol_put(mpol);
3389 return 1;
3390
3391 }
3392
3393 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
3394 {
3395 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3396 struct shmem_sb_info config = *sbinfo;
3397 int inodes;
3398 int error = -EINVAL;
3399
3400 config.mpol = NULL;
3401 if (shmem_parse_options(data, &config, true))
3402 return error;
3403
3404 spin_lock(&sbinfo->stat_lock);
3405 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
3406 if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
3407 goto out;
3408 if (config.max_inodes < inodes)
3409 goto out;
3410 /*
3411 * Those tests disallow limited->unlimited while any are in use;
3412 * but we must separately disallow unlimited->limited, because
3413 * in that case we have no record of how much is already in use.
3414 */
3415 if (config.max_blocks && !sbinfo->max_blocks)
3416 goto out;
3417 if (config.max_inodes && !sbinfo->max_inodes)
3418 goto out;
3419
3420 error = 0;
3421 sbinfo->huge = config.huge;
3422 sbinfo->max_blocks = config.max_blocks;
3423 sbinfo->max_inodes = config.max_inodes;
3424 sbinfo->free_inodes = config.max_inodes - inodes;
3425
3426 /*
3427 * Preserve previous mempolicy unless mpol remount option was specified.
3428 */
3429 if (config.mpol) {
3430 mpol_put(sbinfo->mpol);
3431 sbinfo->mpol = config.mpol; /* transfers initial ref */
3432 }
3433 out:
3434 spin_unlock(&sbinfo->stat_lock);
3435 return error;
3436 }
3437
3438 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
3439 {
3440 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
3441
3442 if (sbinfo->max_blocks != shmem_default_max_blocks())
3443 seq_printf(seq, ",size=%luk",
3444 sbinfo->max_blocks << (PAGE_SHIFT - 10));
3445 if (sbinfo->max_inodes != shmem_default_max_inodes())
3446 seq_printf(seq, ",nr_inodes=%d", sbinfo->max_inodes);
3447 if (sbinfo->mode != (0777 | S_ISVTX))
3448 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
3449 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
3450 seq_printf(seq, ",uid=%u",
3451 from_kuid_munged(&init_user_ns, sbinfo->uid));
3452 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
3453 seq_printf(seq, ",gid=%u",
3454 from_kgid_munged(&init_user_ns, sbinfo->gid));
3455 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3456 /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
3457 if (sbinfo->huge)
3458 seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
3459 #endif
3460 shmem_show_mpol(seq, sbinfo->mpol);
3461 return 0;
3462 }
3463
3464 #endif /* CONFIG_TMPFS */
3465
3466 static void shmem_put_super(struct super_block *sb)
3467 {
3468 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3469
3470 if (!sbinfo->idr_nouse)
3471 idr_destroy(&sbinfo->idr);
3472 percpu_counter_destroy(&sbinfo->used_blocks);
3473 mpol_put(sbinfo->mpol);
3474 kfree(sbinfo);
3475 sb->s_fs_info = NULL;
3476 }
3477
3478 int shmem_fill_super(struct super_block *sb, void *data, int silent)
3479 {
3480 struct inode *inode;
3481 struct shmem_sb_info *sbinfo;
3482 int err = -ENOMEM;
3483
3484 /* Round up to L1_CACHE_BYTES to resist false sharing */
3485 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3486 L1_CACHE_BYTES), GFP_KERNEL);
3487 if (!sbinfo)
3488 return -ENOMEM;
3489
3490 mutex_init(&sbinfo->idr_lock);
3491 idr_init(&sbinfo->idr);
3492 sbinfo->mode = 0777 | S_ISVTX;
3493 sbinfo->uid = current_fsuid();
3494 sbinfo->gid = current_fsgid();
3495 sb->s_fs_info = sbinfo;
3496
3497 #ifdef CONFIG_TMPFS
3498 /*
3499 * Per default we only allow half of the physical ram per
3500 * tmpfs instance, limiting inodes to one per page of lowmem;
3501 * but the internal instance is left unlimited.
3502 */
3503 if (!(sb->s_flags & SB_KERNMOUNT)) {
3504 sbinfo->max_blocks = shmem_default_max_blocks();
3505 sbinfo->max_inodes = shmem_default_max_inodes();
3506 if (shmem_parse_options(data, sbinfo, false)) {
3507 err = -EINVAL;
3508 goto failed;
3509 }
3510 } else {
3511 sb->s_flags |= SB_NOUSER;
3512 }
3513 sb->s_export_op = &shmem_export_ops;
3514 sb->s_flags |= SB_NOSEC;
3515 #else
3516 sb->s_flags |= SB_NOUSER;
3517 #endif
3518
3519 spin_lock_init(&sbinfo->stat_lock);
3520 if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
3521 goto failed;
3522 sbinfo->free_inodes = sbinfo->max_inodes;
3523 spin_lock_init(&sbinfo->shrinklist_lock);
3524 INIT_LIST_HEAD(&sbinfo->shrinklist);
3525
3526 sb->s_maxbytes = MAX_LFS_FILESIZE;
3527 sb->s_blocksize = PAGE_SIZE;
3528 sb->s_blocksize_bits = PAGE_SHIFT;
3529 sb->s_magic = TMPFS_MAGIC;
3530 sb->s_op = &shmem_ops;
3531 sb->s_time_gran = 1;
3532 #ifdef CONFIG_TMPFS_XATTR
3533 sb->s_xattr = shmem_xattr_handlers;
3534 #endif
3535 #ifdef CONFIG_TMPFS_POSIX_ACL
3536 sb->s_flags |= SB_POSIXACL;
3537 #endif
3538 uuid_gen(&sb->s_uuid);
3539
3540 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3541 if (!inode)
3542 goto failed;
3543 inode->i_uid = sbinfo->uid;
3544 inode->i_gid = sbinfo->gid;
3545 sb->s_root = d_make_root(inode);
3546 if (!sb->s_root)
3547 goto failed;
3548 return 0;
3549
3550 failed:
3551 shmem_put_super(sb);
3552 return err;
3553 }
3554
3555 static struct kmem_cache *shmem_inode_cachep;
3556
3557 static struct inode *shmem_alloc_inode(struct super_block *sb)
3558 {
3559 struct shmem_inode_info *info;
3560 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3561 if (!info)
3562 return NULL;
3563 return &info->vfs_inode;
3564 }
3565
3566 static void shmem_destroy_callback(struct rcu_head *head)
3567 {
3568 struct inode *inode = container_of(head, struct inode, i_rcu);
3569 if (S_ISLNK(inode->i_mode))
3570 kfree(inode->i_link);
3571 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3572 }
3573
3574 static void shmem_destroy_inode(struct inode *inode)
3575 {
3576 if (S_ISREG(inode->i_mode))
3577 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3578 call_rcu(&inode->i_rcu, shmem_destroy_callback);
3579 }
3580
3581 static void shmem_init_inode(void *foo)
3582 {
3583 struct shmem_inode_info *info = foo;
3584 inode_init_once(&info->vfs_inode);
3585 }
3586
3587 static void shmem_init_inodecache(void)
3588 {
3589 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3590 sizeof(struct shmem_inode_info),
3591 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
3592 }
3593
3594 static void shmem_destroy_inodecache(void)
3595 {
3596 kmem_cache_destroy(shmem_inode_cachep);
3597 }
3598
3599 static __init void shmem_no_idr(struct super_block *sb)
3600 {
3601 struct shmem_sb_info *sbinfo;
3602
3603 sbinfo = SHMEM_SB(sb);
3604 sbinfo->idr_nouse = true;
3605 idr_destroy(&sbinfo->idr);
3606 }
3607
3608 static const struct address_space_operations shmem_aops = {
3609 .writepage = shmem_writepage,
3610 .set_page_dirty = __set_page_dirty_no_writeback,
3611 #ifdef CONFIG_TMPFS
3612 .write_begin = shmem_write_begin,
3613 .write_end = shmem_write_end,
3614 #endif
3615 #ifdef CONFIG_MIGRATION
3616 .migratepage = migrate_page,
3617 #endif
3618 .error_remove_page = generic_error_remove_page,
3619 };
3620
3621 static const struct file_operations shmem_file_operations = {
3622 .mmap = shmem_mmap,
3623 .get_unmapped_area = shmem_get_unmapped_area,
3624 #ifdef CONFIG_TMPFS
3625 .llseek = shmem_file_llseek,
3626 .read_iter = shmem_file_read_iter,
3627 .write_iter = generic_file_write_iter,
3628 .fsync = noop_fsync,
3629 .splice_read = generic_file_splice_read,
3630 .splice_write = iter_file_splice_write,
3631 .fallocate = shmem_fallocate,
3632 #endif
3633 };
3634
3635 static const struct inode_operations shmem_inode_operations = {
3636 .getattr = shmem_getattr,
3637 .setattr = shmem_setattr,
3638 #ifdef CONFIG_TMPFS_XATTR
3639 .listxattr = shmem_listxattr,
3640 .set_acl = simple_set_acl,
3641 #endif
3642 };
3643
3644 static const struct inode_operations shmem_dir_inode_operations = {
3645 #ifdef CONFIG_TMPFS
3646 .create = shmem_create,
3647 .lookup = simple_lookup,
3648 .link = shmem_link,
3649 .unlink = shmem_unlink,
3650 .symlink = shmem_symlink,
3651 .mkdir = shmem_mkdir,
3652 .rmdir = shmem_rmdir,
3653 .mknod = shmem_mknod,
3654 .rename = shmem_rename2,
3655 .tmpfile = shmem_tmpfile,
3656 #endif
3657 #ifdef CONFIG_TMPFS_XATTR
3658 .listxattr = shmem_listxattr,
3659 #endif
3660 #ifdef CONFIG_TMPFS_POSIX_ACL
3661 .setattr = shmem_setattr,
3662 .set_acl = simple_set_acl,
3663 #endif
3664 };
3665
3666 static const struct inode_operations shmem_special_inode_operations = {
3667 #ifdef CONFIG_TMPFS_XATTR
3668 .listxattr = shmem_listxattr,
3669 #endif
3670 #ifdef CONFIG_TMPFS_POSIX_ACL
3671 .setattr = shmem_setattr,
3672 .set_acl = simple_set_acl,
3673 #endif
3674 };
3675
3676 static const struct super_operations shmem_ops = {
3677 .alloc_inode = shmem_alloc_inode,
3678 .destroy_inode = shmem_destroy_inode,
3679 #ifdef CONFIG_TMPFS
3680 .statfs = shmem_statfs,
3681 .remount_fs = shmem_remount_fs,
3682 .show_options = shmem_show_options,
3683 #endif
3684 .evict_inode = shmem_evict_inode,
3685 .drop_inode = generic_delete_inode,
3686 .put_super = shmem_put_super,
3687 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3688 .nr_cached_objects = shmem_unused_huge_count,
3689 .free_cached_objects = shmem_unused_huge_scan,
3690 #endif
3691 };
3692
3693 static const struct vm_operations_struct shmem_vm_ops = {
3694 .fault = shmem_fault,
3695 .map_pages = filemap_map_pages,
3696 #ifdef CONFIG_NUMA
3697 .set_policy = shmem_set_policy,
3698 .get_policy = shmem_get_policy,
3699 #endif
3700 };
3701
3702 static struct dentry *shmem_mount(struct file_system_type *fs_type,
3703 int flags, const char *dev_name, void *data)
3704 {
3705 return mount_nodev(fs_type, flags, data, shmem_fill_super);
3706 }
3707
3708 static struct file_system_type shmem_fs_type = {
3709 .owner = THIS_MODULE,
3710 .name = "tmpfs",
3711 .mount = shmem_mount,
3712 .kill_sb = kill_litter_super,
3713 .fs_flags = FS_USERNS_MOUNT,
3714 };
3715
3716 int __init shmem_init(void)
3717 {
3718 int error;
3719
3720 /* If rootfs called this, don't re-init */
3721 if (shmem_inode_cachep)
3722 return 0;
3723
3724 shmem_init_inodecache();
3725
3726 error = register_filesystem(&shmem_fs_type);
3727 if (error) {
3728 pr_err("Could not register tmpfs\n");
3729 goto out2;
3730 }
3731
3732 shm_mnt = kern_mount(&shmem_fs_type);
3733 if (IS_ERR(shm_mnt)) {
3734 error = PTR_ERR(shm_mnt);
3735 pr_err("Could not kern_mount tmpfs\n");
3736 goto out1;
3737 }
3738 shmem_no_idr(shm_mnt->mnt_sb);
3739
3740 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3741 if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
3742 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3743 else
3744 shmem_huge = 0; /* just in case it was patched */
3745 #endif
3746 return 0;
3747
3748 out1:
3749 unregister_filesystem(&shmem_fs_type);
3750 out2:
3751 shmem_destroy_inodecache();
3752 shm_mnt = ERR_PTR(error);
3753 return error;
3754 }
3755
3756 #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
3757 static ssize_t shmem_enabled_show(struct kobject *kobj,
3758 struct kobj_attribute *attr, char *buf)
3759 {
3760 int values[] = {
3761 SHMEM_HUGE_ALWAYS,
3762 SHMEM_HUGE_WITHIN_SIZE,
3763 SHMEM_HUGE_ADVISE,
3764 SHMEM_HUGE_NEVER,
3765 SHMEM_HUGE_DENY,
3766 SHMEM_HUGE_FORCE,
3767 };
3768 int i, count;
3769
3770 for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
3771 const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
3772
3773 count += sprintf(buf + count, fmt,
3774 shmem_format_huge(values[i]));
3775 }
3776 buf[count - 1] = '\n';
3777 return count;
3778 }
3779
3780 static ssize_t shmem_enabled_store(struct kobject *kobj,
3781 struct kobj_attribute *attr, const char *buf, size_t count)
3782 {
3783 char tmp[16];
3784 int huge;
3785
3786 if (count + 1 > sizeof(tmp))
3787 return -EINVAL;
3788 memcpy(tmp, buf, count);
3789 tmp[count] = '\0';
3790 if (count && tmp[count - 1] == '\n')
3791 tmp[count - 1] = '\0';
3792
3793 huge = shmem_parse_huge(tmp);
3794 if (huge == -EINVAL)
3795 return -EINVAL;
3796 if (!has_transparent_hugepage() &&
3797 huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
3798 return -EINVAL;
3799
3800 shmem_huge = huge;
3801 if (shmem_huge > SHMEM_HUGE_DENY)
3802 SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
3803 return count;
3804 }
3805
3806 struct kobj_attribute shmem_enabled_attr =
3807 __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
3808 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
3809
3810 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3811 bool shmem_huge_enabled(struct vm_area_struct *vma)
3812 {
3813 struct inode *inode = file_inode(vma->vm_file);
3814 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3815 loff_t i_size;
3816 pgoff_t off;
3817
3818 if (shmem_huge == SHMEM_HUGE_FORCE)
3819 return true;
3820 if (shmem_huge == SHMEM_HUGE_DENY)
3821 return false;
3822 switch (sbinfo->huge) {
3823 case SHMEM_HUGE_NEVER:
3824 return false;
3825 case SHMEM_HUGE_ALWAYS:
3826 return true;
3827 case SHMEM_HUGE_WITHIN_SIZE:
3828 off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
3829 i_size = round_up(i_size_read(inode), PAGE_SIZE);
3830 if (i_size >= HPAGE_PMD_SIZE &&
3831 i_size >> PAGE_SHIFT >= off)
3832 return true;
3833 /* fall through */
3834 case SHMEM_HUGE_ADVISE:
3835 /* TODO: implement fadvise() hints */
3836 return (vma->vm_flags & VM_HUGEPAGE);
3837 default:
3838 VM_BUG_ON(1);
3839 return false;
3840 }
3841 }
3842 #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
3843
3844 #else /* !CONFIG_SHMEM */
3845
3846 /*
3847 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3848 *
3849 * This is intended for small system where the benefits of the full
3850 * shmem code (swap-backed and resource-limited) are outweighed by
3851 * their complexity. On systems without swap this code should be
3852 * effectively equivalent, but much lighter weight.
3853 */
3854
3855 static struct file_system_type shmem_fs_type = {
3856 .name = "tmpfs",
3857 .mount = ramfs_mount,
3858 .kill_sb = kill_litter_super,
3859 .fs_flags = FS_USERNS_MOUNT,
3860 };
3861
3862 int __init shmem_init(void)
3863 {
3864 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3865
3866 shm_mnt = kern_mount(&shmem_fs_type);
3867 BUG_ON(IS_ERR(shm_mnt));
3868
3869 return 0;
3870 }
3871
3872 int shmem_unuse(swp_entry_t swap, struct page *page)
3873 {
3874 return 0;
3875 }
3876
3877 int shmem_lock(struct file *file, int lock, struct user_struct *user)
3878 {
3879 return 0;
3880 }
3881
3882 void shmem_unlock_mapping(struct address_space *mapping)
3883 {
3884 }
3885
3886 #ifdef CONFIG_MMU
3887 unsigned long shmem_get_unmapped_area(struct file *file,
3888 unsigned long addr, unsigned long len,
3889 unsigned long pgoff, unsigned long flags)
3890 {
3891 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
3892 }
3893 #endif
3894
3895 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
3896 {
3897 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
3898 }
3899 EXPORT_SYMBOL_GPL(shmem_truncate_range);
3900
3901 #define shmem_vm_ops generic_file_vm_ops
3902 #define shmem_file_operations ramfs_file_operations
3903 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
3904 #define shmem_acct_size(flags, size) 0
3905 #define shmem_unacct_size(flags, size) do {} while (0)
3906
3907 #endif /* CONFIG_SHMEM */
3908
3909 /* common code */
3910
3911 static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
3912 unsigned long flags, unsigned int i_flags)
3913 {
3914 struct inode *inode;
3915 struct file *res;
3916
3917 if (IS_ERR(mnt))
3918 return ERR_CAST(mnt);
3919
3920 if (size < 0 || size > MAX_LFS_FILESIZE)
3921 return ERR_PTR(-EINVAL);
3922
3923 if (shmem_acct_size(flags, size))
3924 return ERR_PTR(-ENOMEM);
3925
3926 inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
3927 flags);
3928 if (unlikely(!inode)) {
3929 shmem_unacct_size(flags, size);
3930 return ERR_PTR(-ENOSPC);
3931 }
3932 inode->i_flags |= i_flags;
3933 inode->i_size = size;
3934 clear_nlink(inode); /* It is unlinked */
3935 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
3936 if (!IS_ERR(res))
3937 res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
3938 &shmem_file_operations);
3939 if (IS_ERR(res))
3940 iput(inode);
3941 return res;
3942 }
3943
3944 /**
3945 * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
3946 * kernel internal. There will be NO LSM permission checks against the
3947 * underlying inode. So users of this interface must do LSM checks at a
3948 * higher layer. The users are the big_key and shm implementations. LSM
3949 * checks are provided at the key or shm level rather than the inode.
3950 * @name: name for dentry (to be seen in /proc/<pid>/maps
3951 * @size: size to be set for the file
3952 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3953 */
3954 struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
3955 {
3956 return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
3957 }
3958
3959 /**
3960 * shmem_file_setup - get an unlinked file living in tmpfs
3961 * @name: name for dentry (to be seen in /proc/<pid>/maps
3962 * @size: size to be set for the file
3963 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3964 */
3965 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
3966 {
3967 return __shmem_file_setup(shm_mnt, name, size, flags, 0);
3968 }
3969 EXPORT_SYMBOL_GPL(shmem_file_setup);
3970
3971 /**
3972 * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
3973 * @mnt: the tmpfs mount where the file will be created
3974 * @name: name for dentry (to be seen in /proc/<pid>/maps
3975 * @size: size to be set for the file
3976 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3977 */
3978 struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
3979 loff_t size, unsigned long flags)
3980 {
3981 return __shmem_file_setup(mnt, name, size, flags, 0);
3982 }
3983 EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
3984
3985 /**
3986 * shmem_zero_setup - setup a shared anonymous mapping
3987 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
3988 */
3989 int shmem_zero_setup(struct vm_area_struct *vma)
3990 {
3991 struct file *file;
3992 loff_t size = vma->vm_end - vma->vm_start;
3993
3994 /*
3995 * Cloning a new file under mmap_sem leads to a lock ordering conflict
3996 * between XFS directory reading and selinux: since this file is only
3997 * accessible to the user through its mapping, use S_PRIVATE flag to
3998 * bypass file security, in the same way as shmem_kernel_file_setup().
3999 */
4000 file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
4001 if (IS_ERR(file))
4002 return PTR_ERR(file);
4003
4004 if (vma->vm_file)
4005 fput(vma->vm_file);
4006 vma->vm_file = file;
4007 vma->vm_ops = &shmem_vm_ops;
4008
4009 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
4010 ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
4011 (vma->vm_end & HPAGE_PMD_MASK)) {
4012 khugepaged_enter(vma, vma->vm_flags);
4013 }
4014
4015 return 0;
4016 }
4017 EXPORT_SYMBOL_GPL(shmem_zero_setup);
4018
4019 /**
4020 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
4021 * @mapping: the page's address_space
4022 * @index: the page index
4023 * @gfp: the page allocator flags to use if allocating
4024 *
4025 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
4026 * with any new page allocations done using the specified allocation flags.
4027 * But read_cache_page_gfp() uses the ->readpage() method: which does not
4028 * suit tmpfs, since it may have pages in swapcache, and needs to find those
4029 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
4030 *
4031 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
4032 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
4033 */
4034 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
4035 pgoff_t index, gfp_t gfp)
4036 {
4037 #ifdef CONFIG_SHMEM
4038 struct inode *inode = mapping->host;
4039 struct page *page;
4040 int error;
4041
4042 BUG_ON(mapping->a_ops != &shmem_aops);
4043 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
4044 gfp, NULL, NULL, NULL);
4045 if (error)
4046 page = ERR_PTR(error);
4047 else
4048 unlock_page(page);
4049 return page;
4050 #else
4051 /*
4052 * The tiny !SHMEM case uses ramfs without swap
4053 */
4054 return read_cache_page_gfp(mapping, index, gfp);
4055 #endif
4056 }
4057 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);