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