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