28da0348982650d51632d19f2ce45e6160ad5c07
[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 rcu_read_unlock();
1941 rcu_read_lock();
1942 start = iter.index + 1;
1943 goto restart;
1944 }
1945 }
1946 rcu_read_unlock();
1947 }
1948
1949 /*
1950 * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
1951 * via get_user_pages(), drivers might have some pending I/O without any active
1952 * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
1953 * and see whether it has an elevated ref-count. If so, we tag them and wait for
1954 * them to be dropped.
1955 * The caller must guarantee that no new user will acquire writable references
1956 * to those pages to avoid races.
1957 */
1958 static int shmem_wait_for_pins(struct address_space *mapping)
1959 {
1960 struct radix_tree_iter iter;
1961 void **slot;
1962 pgoff_t start;
1963 struct page *page;
1964 int error, scan;
1965
1966 shmem_tag_pins(mapping);
1967
1968 error = 0;
1969 for (scan = 0; scan <= LAST_SCAN; scan++) {
1970 if (!radix_tree_tagged(&mapping->page_tree, SHMEM_TAG_PINNED))
1971 break;
1972
1973 if (!scan)
1974 lru_add_drain_all();
1975 else if (schedule_timeout_killable((HZ << scan) / 200))
1976 scan = LAST_SCAN;
1977
1978 start = 0;
1979 rcu_read_lock();
1980 restart:
1981 radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter,
1982 start, SHMEM_TAG_PINNED) {
1983
1984 page = radix_tree_deref_slot(slot);
1985 if (radix_tree_exception(page)) {
1986 if (radix_tree_deref_retry(page))
1987 goto restart;
1988
1989 page = NULL;
1990 }
1991
1992 if (page &&
1993 page_count(page) - page_mapcount(page) != 1) {
1994 if (scan < LAST_SCAN)
1995 goto continue_resched;
1996
1997 /*
1998 * On the last scan, we clean up all those tags
1999 * we inserted; but make a note that we still
2000 * found pages pinned.
2001 */
2002 error = -EBUSY;
2003 }
2004
2005 spin_lock_irq(&mapping->tree_lock);
2006 radix_tree_tag_clear(&mapping->page_tree,
2007 iter.index, SHMEM_TAG_PINNED);
2008 spin_unlock_irq(&mapping->tree_lock);
2009 continue_resched:
2010 if (need_resched()) {
2011 rcu_read_unlock();
2012 rcu_read_lock();
2013 start = iter.index + 1;
2014 goto restart;
2015 }
2016 }
2017 rcu_read_unlock();
2018 }
2019
2020 return error;
2021 }
2022
2023 #define F_ALL_SEALS (F_SEAL_SEAL | \
2024 F_SEAL_SHRINK | \
2025 F_SEAL_GROW | \
2026 F_SEAL_WRITE)
2027
2028 int shmem_add_seals(struct file *file, unsigned int seals)
2029 {
2030 struct inode *inode = file_inode(file);
2031 struct shmem_inode_info *info = SHMEM_I(inode);
2032 int error;
2033
2034 /*
2035 * SEALING
2036 * Sealing allows multiple parties to share a shmem-file but restrict
2037 * access to a specific subset of file operations. Seals can only be
2038 * added, but never removed. This way, mutually untrusted parties can
2039 * share common memory regions with a well-defined policy. A malicious
2040 * peer can thus never perform unwanted operations on a shared object.
2041 *
2042 * Seals are only supported on special shmem-files and always affect
2043 * the whole underlying inode. Once a seal is set, it may prevent some
2044 * kinds of access to the file. Currently, the following seals are
2045 * defined:
2046 * SEAL_SEAL: Prevent further seals from being set on this file
2047 * SEAL_SHRINK: Prevent the file from shrinking
2048 * SEAL_GROW: Prevent the file from growing
2049 * SEAL_WRITE: Prevent write access to the file
2050 *
2051 * As we don't require any trust relationship between two parties, we
2052 * must prevent seals from being removed. Therefore, sealing a file
2053 * only adds a given set of seals to the file, it never touches
2054 * existing seals. Furthermore, the "setting seals"-operation can be
2055 * sealed itself, which basically prevents any further seal from being
2056 * added.
2057 *
2058 * Semantics of sealing are only defined on volatile files. Only
2059 * anonymous shmem files support sealing. More importantly, seals are
2060 * never written to disk. Therefore, there's no plan to support it on
2061 * other file types.
2062 */
2063
2064 if (file->f_op != &shmem_file_operations)
2065 return -EINVAL;
2066 if (!(file->f_mode & FMODE_WRITE))
2067 return -EPERM;
2068 if (seals & ~(unsigned int)F_ALL_SEALS)
2069 return -EINVAL;
2070
2071 mutex_lock(&inode->i_mutex);
2072
2073 if (info->seals & F_SEAL_SEAL) {
2074 error = -EPERM;
2075 goto unlock;
2076 }
2077
2078 if ((seals & F_SEAL_WRITE) && !(info->seals & F_SEAL_WRITE)) {
2079 error = mapping_deny_writable(file->f_mapping);
2080 if (error)
2081 goto unlock;
2082
2083 error = shmem_wait_for_pins(file->f_mapping);
2084 if (error) {
2085 mapping_allow_writable(file->f_mapping);
2086 goto unlock;
2087 }
2088 }
2089
2090 info->seals |= seals;
2091 error = 0;
2092
2093 unlock:
2094 mutex_unlock(&inode->i_mutex);
2095 return error;
2096 }
2097 EXPORT_SYMBOL_GPL(shmem_add_seals);
2098
2099 int shmem_get_seals(struct file *file)
2100 {
2101 if (file->f_op != &shmem_file_operations)
2102 return -EINVAL;
2103
2104 return SHMEM_I(file_inode(file))->seals;
2105 }
2106 EXPORT_SYMBOL_GPL(shmem_get_seals);
2107
2108 long shmem_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
2109 {
2110 long error;
2111
2112 switch (cmd) {
2113 case F_ADD_SEALS:
2114 /* disallow upper 32bit */
2115 if (arg > UINT_MAX)
2116 return -EINVAL;
2117
2118 error = shmem_add_seals(file, arg);
2119 break;
2120 case F_GET_SEALS:
2121 error = shmem_get_seals(file);
2122 break;
2123 default:
2124 error = -EINVAL;
2125 break;
2126 }
2127
2128 return error;
2129 }
2130
2131 static long shmem_fallocate(struct file *file, int mode, loff_t offset,
2132 loff_t len)
2133 {
2134 struct inode *inode = file_inode(file);
2135 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
2136 struct shmem_inode_info *info = SHMEM_I(inode);
2137 struct shmem_falloc shmem_falloc;
2138 pgoff_t start, index, end;
2139 int error;
2140
2141 mutex_lock(&inode->i_mutex);
2142
2143 if (mode & FALLOC_FL_PUNCH_HOLE) {
2144 struct address_space *mapping = file->f_mapping;
2145 loff_t unmap_start = round_up(offset, PAGE_SIZE);
2146 loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
2147 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
2148
2149 /* protected by i_mutex */
2150 if (info->seals & F_SEAL_WRITE) {
2151 error = -EPERM;
2152 goto out;
2153 }
2154
2155 shmem_falloc.waitq = &shmem_falloc_waitq;
2156 shmem_falloc.start = unmap_start >> PAGE_SHIFT;
2157 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
2158 spin_lock(&inode->i_lock);
2159 inode->i_private = &shmem_falloc;
2160 spin_unlock(&inode->i_lock);
2161
2162 if ((u64)unmap_end > (u64)unmap_start)
2163 unmap_mapping_range(mapping, unmap_start,
2164 1 + unmap_end - unmap_start, 0);
2165 shmem_truncate_range(inode, offset, offset + len - 1);
2166 /* No need to unmap again: hole-punching leaves COWed pages */
2167
2168 spin_lock(&inode->i_lock);
2169 inode->i_private = NULL;
2170 wake_up_all(&shmem_falloc_waitq);
2171 spin_unlock(&inode->i_lock);
2172 error = 0;
2173 goto out;
2174 }
2175
2176 /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
2177 error = inode_newsize_ok(inode, offset + len);
2178 if (error)
2179 goto out;
2180
2181 if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
2182 error = -EPERM;
2183 goto out;
2184 }
2185
2186 start = offset >> PAGE_CACHE_SHIFT;
2187 end = (offset + len + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
2188 /* Try to avoid a swapstorm if len is impossible to satisfy */
2189 if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
2190 error = -ENOSPC;
2191 goto out;
2192 }
2193
2194 shmem_falloc.waitq = NULL;
2195 shmem_falloc.start = start;
2196 shmem_falloc.next = start;
2197 shmem_falloc.nr_falloced = 0;
2198 shmem_falloc.nr_unswapped = 0;
2199 spin_lock(&inode->i_lock);
2200 inode->i_private = &shmem_falloc;
2201 spin_unlock(&inode->i_lock);
2202
2203 for (index = start; index < end; index++) {
2204 struct page *page;
2205
2206 /*
2207 * Good, the fallocate(2) manpage permits EINTR: we may have
2208 * been interrupted because we are using up too much memory.
2209 */
2210 if (signal_pending(current))
2211 error = -EINTR;
2212 else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
2213 error = -ENOMEM;
2214 else
2215 error = shmem_getpage(inode, index, &page, SGP_FALLOC,
2216 NULL);
2217 if (error) {
2218 /* Remove the !PageUptodate pages we added */
2219 if (index > start) {
2220 shmem_undo_range(inode,
2221 (loff_t)start << PAGE_CACHE_SHIFT,
2222 ((loff_t)index << PAGE_CACHE_SHIFT) - 1, true);
2223 }
2224 goto undone;
2225 }
2226
2227 /*
2228 * Inform shmem_writepage() how far we have reached.
2229 * No need for lock or barrier: we have the page lock.
2230 */
2231 shmem_falloc.next++;
2232 if (!PageUptodate(page))
2233 shmem_falloc.nr_falloced++;
2234
2235 /*
2236 * If !PageUptodate, leave it that way so that freeable pages
2237 * can be recognized if we need to rollback on error later.
2238 * But set_page_dirty so that memory pressure will swap rather
2239 * than free the pages we are allocating (and SGP_CACHE pages
2240 * might still be clean: we now need to mark those dirty too).
2241 */
2242 set_page_dirty(page);
2243 unlock_page(page);
2244 page_cache_release(page);
2245 cond_resched();
2246 }
2247
2248 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
2249 i_size_write(inode, offset + len);
2250 inode->i_ctime = CURRENT_TIME;
2251 undone:
2252 spin_lock(&inode->i_lock);
2253 inode->i_private = NULL;
2254 spin_unlock(&inode->i_lock);
2255 out:
2256 mutex_unlock(&inode->i_mutex);
2257 return error;
2258 }
2259
2260 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
2261 {
2262 struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
2263
2264 buf->f_type = TMPFS_MAGIC;
2265 buf->f_bsize = PAGE_CACHE_SIZE;
2266 buf->f_namelen = NAME_MAX;
2267 if (sbinfo->max_blocks) {
2268 buf->f_blocks = sbinfo->max_blocks;
2269 buf->f_bavail =
2270 buf->f_bfree = sbinfo->max_blocks -
2271 percpu_counter_sum(&sbinfo->used_blocks);
2272 }
2273 if (sbinfo->max_inodes) {
2274 buf->f_files = sbinfo->max_inodes;
2275 buf->f_ffree = sbinfo->free_inodes;
2276 }
2277 /* else leave those fields 0 like simple_statfs */
2278 return 0;
2279 }
2280
2281 /*
2282 * File creation. Allocate an inode, and we're done..
2283 */
2284 static int
2285 shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2286 {
2287 struct inode *inode;
2288 int error = -ENOSPC;
2289
2290 inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
2291 if (inode) {
2292 error = security_inode_init_security(inode, dir,
2293 &dentry->d_name,
2294 shmem_initxattrs, NULL);
2295 if (error) {
2296 if (error != -EOPNOTSUPP) {
2297 iput(inode);
2298 return error;
2299 }
2300 }
2301 #ifdef CONFIG_TMPFS_POSIX_ACL
2302 error = generic_acl_init(inode, dir);
2303 if (error) {
2304 iput(inode);
2305 return error;
2306 }
2307 #else
2308 error = 0;
2309 #endif
2310 dir->i_size += BOGO_DIRENT_SIZE;
2311 dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2312 d_instantiate(dentry, inode);
2313 dget(dentry); /* Extra count - pin the dentry in core */
2314 }
2315 return error;
2316 }
2317
2318 static int
2319 shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
2320 {
2321 struct inode *inode;
2322 int error = -ENOSPC;
2323
2324 inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
2325 if (inode) {
2326 error = security_inode_init_security(inode, dir,
2327 NULL,
2328 shmem_initxattrs, NULL);
2329 if (error) {
2330 if (error != -EOPNOTSUPP) {
2331 iput(inode);
2332 return error;
2333 }
2334 }
2335 #ifdef CONFIG_TMPFS_POSIX_ACL
2336 error = generic_acl_init(inode, dir);
2337 if (error) {
2338 iput(inode);
2339 return error;
2340 }
2341 #else
2342 error = 0;
2343 #endif
2344 d_tmpfile(dentry, inode);
2345 }
2346 return error;
2347 }
2348
2349 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
2350 {
2351 int error;
2352
2353 if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
2354 return error;
2355 inc_nlink(dir);
2356 return 0;
2357 }
2358
2359 static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
2360 bool excl)
2361 {
2362 return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
2363 }
2364
2365 /*
2366 * Link a file..
2367 */
2368 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
2369 {
2370 struct inode *inode = old_dentry->d_inode;
2371 int ret;
2372
2373 /*
2374 * No ordinary (disk based) filesystem counts links as inodes;
2375 * but each new link needs a new dentry, pinning lowmem, and
2376 * tmpfs dentries cannot be pruned until they are unlinked.
2377 */
2378 ret = shmem_reserve_inode(inode->i_sb);
2379 if (ret)
2380 goto out;
2381
2382 dir->i_size += BOGO_DIRENT_SIZE;
2383 inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2384 inc_nlink(inode);
2385 ihold(inode); /* New dentry reference */
2386 dget(dentry); /* Extra pinning count for the created dentry */
2387 d_instantiate(dentry, inode);
2388 out:
2389 return ret;
2390 }
2391
2392 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
2393 {
2394 struct inode *inode = dentry->d_inode;
2395
2396 if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
2397 shmem_free_inode(inode->i_sb);
2398
2399 dir->i_size -= BOGO_DIRENT_SIZE;
2400 inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2401 drop_nlink(inode);
2402 dput(dentry); /* Undo the count from "create" - this does all the work */
2403 return 0;
2404 }
2405
2406 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
2407 {
2408 if (!simple_empty(dentry))
2409 return -ENOTEMPTY;
2410
2411 drop_nlink(dentry->d_inode);
2412 drop_nlink(dir);
2413 return shmem_unlink(dir, dentry);
2414 }
2415
2416 /*
2417 * The VFS layer already does all the dentry stuff for rename,
2418 * we just have to decrement the usage count for the target if
2419 * it exists so that the VFS layer correctly free's it when it
2420 * gets overwritten.
2421 */
2422 static int shmem_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
2423 {
2424 struct inode *inode = old_dentry->d_inode;
2425 int they_are_dirs = S_ISDIR(inode->i_mode);
2426
2427 if (!simple_empty(new_dentry))
2428 return -ENOTEMPTY;
2429
2430 if (new_dentry->d_inode) {
2431 (void) shmem_unlink(new_dir, new_dentry);
2432 if (they_are_dirs) {
2433 drop_nlink(new_dentry->d_inode);
2434 drop_nlink(old_dir);
2435 }
2436 } else if (they_are_dirs) {
2437 drop_nlink(old_dir);
2438 inc_nlink(new_dir);
2439 }
2440
2441 old_dir->i_size -= BOGO_DIRENT_SIZE;
2442 new_dir->i_size += BOGO_DIRENT_SIZE;
2443 old_dir->i_ctime = old_dir->i_mtime =
2444 new_dir->i_ctime = new_dir->i_mtime =
2445 inode->i_ctime = CURRENT_TIME;
2446 return 0;
2447 }
2448
2449 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
2450 {
2451 int error;
2452 int len;
2453 struct inode *inode;
2454 struct page *page;
2455 char *kaddr;
2456 struct shmem_inode_info *info;
2457
2458 len = strlen(symname) + 1;
2459 if (len > PAGE_CACHE_SIZE)
2460 return -ENAMETOOLONG;
2461
2462 inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
2463 if (!inode)
2464 return -ENOSPC;
2465
2466 error = security_inode_init_security(inode, dir, &dentry->d_name,
2467 shmem_initxattrs, NULL);
2468 if (error) {
2469 if (error != -EOPNOTSUPP) {
2470 iput(inode);
2471 return error;
2472 }
2473 error = 0;
2474 }
2475
2476 info = SHMEM_I(inode);
2477 inode->i_size = len-1;
2478 if (len <= SHORT_SYMLINK_LEN) {
2479 info->symlink = kmemdup(symname, len, GFP_KERNEL);
2480 if (!info->symlink) {
2481 iput(inode);
2482 return -ENOMEM;
2483 }
2484 inode->i_op = &shmem_short_symlink_operations;
2485 } else {
2486 error = shmem_getpage(inode, 0, &page, SGP_WRITE, NULL);
2487 if (error) {
2488 iput(inode);
2489 return error;
2490 }
2491 inode->i_mapping->a_ops = &shmem_aops;
2492 inode->i_op = &shmem_symlink_inode_operations;
2493 kaddr = kmap_atomic(page);
2494 memcpy(kaddr, symname, len);
2495 kunmap_atomic(kaddr);
2496 SetPageUptodate(page);
2497 set_page_dirty(page);
2498 unlock_page(page);
2499 page_cache_release(page);
2500 }
2501 dir->i_size += BOGO_DIRENT_SIZE;
2502 dir->i_ctime = dir->i_mtime = CURRENT_TIME;
2503 d_instantiate(dentry, inode);
2504 dget(dentry);
2505 return 0;
2506 }
2507
2508 static void *shmem_follow_short_symlink(struct dentry *dentry, struct nameidata *nd)
2509 {
2510 nd_set_link(nd, SHMEM_I(dentry->d_inode)->symlink);
2511 return NULL;
2512 }
2513
2514 static void *shmem_follow_link(struct dentry *dentry, struct nameidata *nd)
2515 {
2516 struct page *page = NULL;
2517 int error = shmem_getpage(dentry->d_inode, 0, &page, SGP_READ, NULL);
2518 nd_set_link(nd, error ? ERR_PTR(error) : kmap(page));
2519 if (page)
2520 unlock_page(page);
2521 return page;
2522 }
2523
2524 static void shmem_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
2525 {
2526 if (!IS_ERR(nd_get_link(nd))) {
2527 struct page *page = cookie;
2528 kunmap(page);
2529 mark_page_accessed(page);
2530 page_cache_release(page);
2531 }
2532 }
2533
2534 #ifdef CONFIG_TMPFS_XATTR
2535 /*
2536 * Superblocks without xattr inode operations may get some security.* xattr
2537 * support from the LSM "for free". As soon as we have any other xattrs
2538 * like ACLs, we also need to implement the security.* handlers at
2539 * filesystem level, though.
2540 */
2541
2542 /*
2543 * Callback for security_inode_init_security() for acquiring xattrs.
2544 */
2545 static int shmem_initxattrs(struct inode *inode,
2546 const struct xattr *xattr_array,
2547 void *fs_info)
2548 {
2549 struct shmem_inode_info *info = SHMEM_I(inode);
2550 const struct xattr *xattr;
2551 struct simple_xattr *new_xattr;
2552 size_t len;
2553
2554 for (xattr = xattr_array; xattr->name != NULL; xattr++) {
2555 new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
2556 if (!new_xattr)
2557 return -ENOMEM;
2558
2559 len = strlen(xattr->name) + 1;
2560 new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
2561 GFP_KERNEL);
2562 if (!new_xattr->name) {
2563 kfree(new_xattr);
2564 return -ENOMEM;
2565 }
2566
2567 memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
2568 XATTR_SECURITY_PREFIX_LEN);
2569 memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
2570 xattr->name, len);
2571
2572 simple_xattr_list_add(&info->xattrs, new_xattr);
2573 }
2574
2575 return 0;
2576 }
2577
2578 static const struct xattr_handler *shmem_xattr_handlers[] = {
2579 #ifdef CONFIG_TMPFS_POSIX_ACL
2580 &generic_acl_access_handler,
2581 &generic_acl_default_handler,
2582 #endif
2583 NULL
2584 };
2585
2586 static int shmem_xattr_validate(const char *name)
2587 {
2588 struct { const char *prefix; size_t len; } arr[] = {
2589 { XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN },
2590 { XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN }
2591 };
2592 int i;
2593
2594 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2595 size_t preflen = arr[i].len;
2596 if (strncmp(name, arr[i].prefix, preflen) == 0) {
2597 if (!name[preflen])
2598 return -EINVAL;
2599 return 0;
2600 }
2601 }
2602 return -EOPNOTSUPP;
2603 }
2604
2605 static ssize_t shmem_getxattr(struct dentry *dentry, const char *name,
2606 void *buffer, size_t size)
2607 {
2608 struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
2609 int err;
2610
2611 /*
2612 * If this is a request for a synthetic attribute in the system.*
2613 * namespace use the generic infrastructure to resolve a handler
2614 * for it via sb->s_xattr.
2615 */
2616 if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
2617 return generic_getxattr(dentry, name, buffer, size);
2618
2619 err = shmem_xattr_validate(name);
2620 if (err)
2621 return err;
2622
2623 return simple_xattr_get(&info->xattrs, name, buffer, size);
2624 }
2625
2626 static int shmem_setxattr(struct dentry *dentry, const char *name,
2627 const void *value, size_t size, int flags)
2628 {
2629 struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
2630 int err;
2631
2632 /*
2633 * If this is a request for a synthetic attribute in the system.*
2634 * namespace use the generic infrastructure to resolve a handler
2635 * for it via sb->s_xattr.
2636 */
2637 if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
2638 return generic_setxattr(dentry, name, value, size, flags);
2639
2640 err = shmem_xattr_validate(name);
2641 if (err)
2642 return err;
2643
2644 return simple_xattr_set(&info->xattrs, name, value, size, flags);
2645 }
2646
2647 static int shmem_removexattr(struct dentry *dentry, const char *name)
2648 {
2649 struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
2650 int err;
2651
2652 /*
2653 * If this is a request for a synthetic attribute in the system.*
2654 * namespace use the generic infrastructure to resolve a handler
2655 * for it via sb->s_xattr.
2656 */
2657 if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
2658 return generic_removexattr(dentry, name);
2659
2660 err = shmem_xattr_validate(name);
2661 if (err)
2662 return err;
2663
2664 return simple_xattr_remove(&info->xattrs, name);
2665 }
2666
2667 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
2668 {
2669 struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
2670 return simple_xattr_list(&info->xattrs, buffer, size);
2671 }
2672 #endif /* CONFIG_TMPFS_XATTR */
2673
2674 static const struct inode_operations shmem_short_symlink_operations = {
2675 .readlink = generic_readlink,
2676 .follow_link = shmem_follow_short_symlink,
2677 #ifdef CONFIG_TMPFS_XATTR
2678 .setxattr = shmem_setxattr,
2679 .getxattr = shmem_getxattr,
2680 .listxattr = shmem_listxattr,
2681 .removexattr = shmem_removexattr,
2682 #endif
2683 };
2684
2685 static const struct inode_operations shmem_symlink_inode_operations = {
2686 .readlink = generic_readlink,
2687 .follow_link = shmem_follow_link,
2688 .put_link = shmem_put_link,
2689 #ifdef CONFIG_TMPFS_XATTR
2690 .setxattr = shmem_setxattr,
2691 .getxattr = shmem_getxattr,
2692 .listxattr = shmem_listxattr,
2693 .removexattr = shmem_removexattr,
2694 #endif
2695 };
2696
2697 static struct dentry *shmem_get_parent(struct dentry *child)
2698 {
2699 return ERR_PTR(-ESTALE);
2700 }
2701
2702 static int shmem_match(struct inode *ino, void *vfh)
2703 {
2704 __u32 *fh = vfh;
2705 __u64 inum = fh[2];
2706 inum = (inum << 32) | fh[1];
2707 return ino->i_ino == inum && fh[0] == ino->i_generation;
2708 }
2709
2710 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
2711 struct fid *fid, int fh_len, int fh_type)
2712 {
2713 struct inode *inode;
2714 struct dentry *dentry = NULL;
2715 u64 inum;
2716
2717 if (fh_len < 3)
2718 return NULL;
2719
2720 inum = fid->raw[2];
2721 inum = (inum << 32) | fid->raw[1];
2722
2723 inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
2724 shmem_match, fid->raw);
2725 if (inode) {
2726 dentry = d_find_alias(inode);
2727 iput(inode);
2728 }
2729
2730 return dentry;
2731 }
2732
2733 static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
2734 struct inode *parent)
2735 {
2736 if (*len < 3) {
2737 *len = 3;
2738 return FILEID_INVALID;
2739 }
2740
2741 if (inode_unhashed(inode)) {
2742 /* Unfortunately insert_inode_hash is not idempotent,
2743 * so as we hash inodes here rather than at creation
2744 * time, we need a lock to ensure we only try
2745 * to do it once
2746 */
2747 static DEFINE_SPINLOCK(lock);
2748 spin_lock(&lock);
2749 if (inode_unhashed(inode))
2750 __insert_inode_hash(inode,
2751 inode->i_ino + inode->i_generation);
2752 spin_unlock(&lock);
2753 }
2754
2755 fh[0] = inode->i_generation;
2756 fh[1] = inode->i_ino;
2757 fh[2] = ((__u64)inode->i_ino) >> 32;
2758
2759 *len = 3;
2760 return 1;
2761 }
2762
2763 static const struct export_operations shmem_export_ops = {
2764 .get_parent = shmem_get_parent,
2765 .encode_fh = shmem_encode_fh,
2766 .fh_to_dentry = shmem_fh_to_dentry,
2767 };
2768
2769 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
2770 bool remount)
2771 {
2772 char *this_char, *value, *rest;
2773 struct mempolicy *mpol = NULL;
2774 uid_t uid;
2775 gid_t gid;
2776
2777 while (options != NULL) {
2778 this_char = options;
2779 for (;;) {
2780 /*
2781 * NUL-terminate this option: unfortunately,
2782 * mount options form a comma-separated list,
2783 * but mpol's nodelist may also contain commas.
2784 */
2785 options = strchr(options, ',');
2786 if (options == NULL)
2787 break;
2788 options++;
2789 if (!isdigit(*options)) {
2790 options[-1] = '\0';
2791 break;
2792 }
2793 }
2794 if (!*this_char)
2795 continue;
2796 if ((value = strchr(this_char,'=')) != NULL) {
2797 *value++ = 0;
2798 } else {
2799 printk(KERN_ERR
2800 "tmpfs: No value for mount option '%s'\n",
2801 this_char);
2802 goto error;
2803 }
2804
2805 if (!strcmp(this_char,"size")) {
2806 unsigned long long size;
2807 size = memparse(value,&rest);
2808 if (*rest == '%') {
2809 size <<= PAGE_SHIFT;
2810 size *= totalram_pages;
2811 do_div(size, 100);
2812 rest++;
2813 }
2814 if (*rest)
2815 goto bad_val;
2816 sbinfo->max_blocks =
2817 DIV_ROUND_UP(size, PAGE_CACHE_SIZE);
2818 } else if (!strcmp(this_char,"nr_blocks")) {
2819 sbinfo->max_blocks = memparse(value, &rest);
2820 if (*rest)
2821 goto bad_val;
2822 } else if (!strcmp(this_char,"nr_inodes")) {
2823 sbinfo->max_inodes = memparse(value, &rest);
2824 if (*rest)
2825 goto bad_val;
2826 } else if (!strcmp(this_char,"mode")) {
2827 if (remount)
2828 continue;
2829 sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
2830 if (*rest)
2831 goto bad_val;
2832 } else if (!strcmp(this_char,"uid")) {
2833 if (remount)
2834 continue;
2835 uid = simple_strtoul(value, &rest, 0);
2836 if (*rest)
2837 goto bad_val;
2838 sbinfo->uid = make_kuid(current_user_ns(), uid);
2839 if (!uid_valid(sbinfo->uid))
2840 goto bad_val;
2841 } else if (!strcmp(this_char,"gid")) {
2842 if (remount)
2843 continue;
2844 gid = simple_strtoul(value, &rest, 0);
2845 if (*rest)
2846 goto bad_val;
2847 sbinfo->gid = make_kgid(current_user_ns(), gid);
2848 if (!gid_valid(sbinfo->gid))
2849 goto bad_val;
2850 } else if (!strcmp(this_char,"mpol")) {
2851 mpol_put(mpol);
2852 mpol = NULL;
2853 if (mpol_parse_str(value, &mpol))
2854 goto bad_val;
2855 } else {
2856 printk(KERN_ERR "tmpfs: Bad mount option %s\n",
2857 this_char);
2858 goto error;
2859 }
2860 }
2861 sbinfo->mpol = mpol;
2862 return 0;
2863
2864 bad_val:
2865 printk(KERN_ERR "tmpfs: Bad value '%s' for mount option '%s'\n",
2866 value, this_char);
2867 error:
2868 mpol_put(mpol);
2869 return 1;
2870
2871 }
2872
2873 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
2874 {
2875 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2876 struct shmem_sb_info config = *sbinfo;
2877 unsigned long inodes;
2878 int error = -EINVAL;
2879
2880 config.mpol = NULL;
2881 if (shmem_parse_options(data, &config, true))
2882 return error;
2883
2884 spin_lock(&sbinfo->stat_lock);
2885 inodes = sbinfo->max_inodes - sbinfo->free_inodes;
2886 if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
2887 goto out;
2888 if (config.max_inodes < inodes)
2889 goto out;
2890 /*
2891 * Those tests disallow limited->unlimited while any are in use;
2892 * but we must separately disallow unlimited->limited, because
2893 * in that case we have no record of how much is already in use.
2894 */
2895 if (config.max_blocks && !sbinfo->max_blocks)
2896 goto out;
2897 if (config.max_inodes && !sbinfo->max_inodes)
2898 goto out;
2899
2900 error = 0;
2901 sbinfo->max_blocks = config.max_blocks;
2902 sbinfo->max_inodes = config.max_inodes;
2903 sbinfo->free_inodes = config.max_inodes - inodes;
2904
2905 /*
2906 * Preserve previous mempolicy unless mpol remount option was specified.
2907 */
2908 if (config.mpol) {
2909 mpol_put(sbinfo->mpol);
2910 sbinfo->mpol = config.mpol; /* transfers initial ref */
2911 }
2912 out:
2913 spin_unlock(&sbinfo->stat_lock);
2914 return error;
2915 }
2916
2917 static int shmem_show_options(struct seq_file *seq, struct dentry *root)
2918 {
2919 struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
2920
2921 if (sbinfo->max_blocks != shmem_default_max_blocks())
2922 seq_printf(seq, ",size=%luk",
2923 sbinfo->max_blocks << (PAGE_CACHE_SHIFT - 10));
2924 if (sbinfo->max_inodes != shmem_default_max_inodes())
2925 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
2926 if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
2927 seq_printf(seq, ",mode=%03ho", sbinfo->mode);
2928 if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
2929 seq_printf(seq, ",uid=%u",
2930 from_kuid_munged(&init_user_ns, sbinfo->uid));
2931 if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
2932 seq_printf(seq, ",gid=%u",
2933 from_kgid_munged(&init_user_ns, sbinfo->gid));
2934 shmem_show_mpol(seq, sbinfo->mpol);
2935 return 0;
2936 }
2937
2938 #define MFD_NAME_PREFIX "memfd:"
2939 #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
2940 #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
2941
2942 #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING)
2943
2944 SYSCALL_DEFINE2(memfd_create,
2945 const char __user *, uname,
2946 unsigned int, flags)
2947 {
2948 struct shmem_inode_info *info;
2949 struct file *file;
2950 int fd, error;
2951 char *name;
2952 long len;
2953
2954 if (flags & ~(unsigned int)MFD_ALL_FLAGS)
2955 return -EINVAL;
2956
2957 /* length includes terminating zero */
2958 len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
2959 if (len <= 0)
2960 return -EFAULT;
2961 if (len > MFD_NAME_MAX_LEN + 1)
2962 return -EINVAL;
2963
2964 name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_TEMPORARY);
2965 if (!name)
2966 return -ENOMEM;
2967
2968 strcpy(name, MFD_NAME_PREFIX);
2969 if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
2970 error = -EFAULT;
2971 goto err_name;
2972 }
2973
2974 /* terminating-zero may have changed after strnlen_user() returned */
2975 if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
2976 error = -EFAULT;
2977 goto err_name;
2978 }
2979
2980 fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
2981 if (fd < 0) {
2982 error = fd;
2983 goto err_name;
2984 }
2985
2986 file = shmem_file_setup(name, 0, VM_NORESERVE);
2987 if (IS_ERR(file)) {
2988 error = PTR_ERR(file);
2989 goto err_fd;
2990 }
2991 info = SHMEM_I(file->f_path.dentry->d_inode);
2992 file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
2993 file->f_flags |= O_RDWR | O_LARGEFILE;
2994
2995 fd_install(fd, file);
2996 kfree(name);
2997 return fd;
2998
2999 err_fd:
3000 put_unused_fd(fd);
3001 err_name:
3002 kfree(name);
3003 return error;
3004 }
3005
3006 #endif /* CONFIG_TMPFS */
3007
3008 static void shmem_put_super(struct super_block *sb)
3009 {
3010 struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
3011
3012 percpu_counter_destroy(&sbinfo->used_blocks);
3013 mpol_put(sbinfo->mpol);
3014 kfree(sbinfo);
3015 sb->s_fs_info = NULL;
3016 }
3017
3018 int shmem_fill_super(struct super_block *sb, void *data, int silent)
3019 {
3020 struct inode *inode;
3021 struct shmem_sb_info *sbinfo;
3022 int err = -ENOMEM;
3023
3024 /* Round up to L1_CACHE_BYTES to resist false sharing */
3025 sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
3026 L1_CACHE_BYTES), GFP_KERNEL);
3027 if (!sbinfo)
3028 return -ENOMEM;
3029
3030 sbinfo->mode = S_IRWXUGO | S_ISVTX;
3031 sbinfo->uid = current_fsuid();
3032 sbinfo->gid = current_fsgid();
3033 sb->s_fs_info = sbinfo;
3034
3035 #ifdef CONFIG_TMPFS
3036 /*
3037 * Per default we only allow half of the physical ram per
3038 * tmpfs instance, limiting inodes to one per page of lowmem;
3039 * but the internal instance is left unlimited.
3040 */
3041 if (!(sb->s_flags & MS_NOUSER)) {
3042 sbinfo->max_blocks = shmem_default_max_blocks();
3043 sbinfo->max_inodes = shmem_default_max_inodes();
3044 if (shmem_parse_options(data, sbinfo, false)) {
3045 err = -EINVAL;
3046 goto failed;
3047 }
3048 }
3049 sb->s_export_op = &shmem_export_ops;
3050 sb->s_flags |= MS_NOSEC;
3051 #else
3052 sb->s_flags |= MS_NOUSER;
3053 #endif
3054
3055 spin_lock_init(&sbinfo->stat_lock);
3056 if (percpu_counter_init(&sbinfo->used_blocks, 0))
3057 goto failed;
3058 sbinfo->free_inodes = sbinfo->max_inodes;
3059
3060 sb->s_maxbytes = MAX_LFS_FILESIZE;
3061 sb->s_blocksize = PAGE_CACHE_SIZE;
3062 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
3063 sb->s_magic = TMPFS_MAGIC;
3064 sb->s_op = &shmem_ops;
3065 sb->s_time_gran = 1;
3066 #ifdef CONFIG_TMPFS_XATTR
3067 sb->s_xattr = shmem_xattr_handlers;
3068 #endif
3069 #ifdef CONFIG_TMPFS_POSIX_ACL
3070 sb->s_flags |= MS_POSIXACL;
3071 #endif
3072
3073 inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
3074 if (!inode)
3075 goto failed;
3076 inode->i_uid = sbinfo->uid;
3077 inode->i_gid = sbinfo->gid;
3078 sb->s_root = d_make_root(inode);
3079 if (!sb->s_root)
3080 goto failed;
3081 return 0;
3082
3083 failed:
3084 shmem_put_super(sb);
3085 return err;
3086 }
3087
3088 static struct kmem_cache *shmem_inode_cachep;
3089
3090 static struct inode *shmem_alloc_inode(struct super_block *sb)
3091 {
3092 struct shmem_inode_info *info;
3093 info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
3094 if (!info)
3095 return NULL;
3096 return &info->vfs_inode;
3097 }
3098
3099 static void shmem_destroy_callback(struct rcu_head *head)
3100 {
3101 struct inode *inode = container_of(head, struct inode, i_rcu);
3102 kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
3103 }
3104
3105 static void shmem_destroy_inode(struct inode *inode)
3106 {
3107 if (S_ISREG(inode->i_mode))
3108 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
3109 call_rcu(&inode->i_rcu, shmem_destroy_callback);
3110 }
3111
3112 static void shmem_init_inode(void *foo)
3113 {
3114 struct shmem_inode_info *info = foo;
3115 inode_init_once(&info->vfs_inode);
3116 }
3117
3118 static int shmem_init_inodecache(void)
3119 {
3120 shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
3121 sizeof(struct shmem_inode_info),
3122 0, SLAB_PANIC, shmem_init_inode);
3123 return 0;
3124 }
3125
3126 static void shmem_destroy_inodecache(void)
3127 {
3128 kmem_cache_destroy(shmem_inode_cachep);
3129 }
3130
3131 static const struct address_space_operations shmem_aops = {
3132 .writepage = shmem_writepage,
3133 .set_page_dirty = __set_page_dirty_no_writeback,
3134 #ifdef CONFIG_TMPFS
3135 .write_begin = shmem_write_begin,
3136 .write_end = shmem_write_end,
3137 #endif
3138 .migratepage = migrate_page,
3139 .error_remove_page = generic_error_remove_page,
3140 };
3141
3142 static const struct file_operations shmem_file_operations = {
3143 .mmap = shmem_mmap,
3144 #ifdef CONFIG_TMPFS
3145 .llseek = shmem_file_llseek,
3146 .read = do_sync_read,
3147 .write = do_sync_write,
3148 .aio_read = shmem_file_aio_read,
3149 .aio_write = generic_file_aio_write,
3150 .fsync = noop_fsync,
3151 .splice_read = shmem_file_splice_read,
3152 .splice_write = generic_file_splice_write,
3153 .fallocate = shmem_fallocate,
3154 #endif
3155 };
3156
3157 static const struct inode_operations shmem_inode_operations = {
3158 .setattr = shmem_setattr,
3159 #ifdef CONFIG_TMPFS_XATTR
3160 .setxattr = shmem_setxattr,
3161 .getxattr = shmem_getxattr,
3162 .listxattr = shmem_listxattr,
3163 .removexattr = shmem_removexattr,
3164 #endif
3165 };
3166
3167 static const struct inode_operations shmem_dir_inode_operations = {
3168 #ifdef CONFIG_TMPFS
3169 .create = shmem_create,
3170 .lookup = simple_lookup,
3171 .link = shmem_link,
3172 .unlink = shmem_unlink,
3173 .symlink = shmem_symlink,
3174 .mkdir = shmem_mkdir,
3175 .rmdir = shmem_rmdir,
3176 .mknod = shmem_mknod,
3177 .rename = shmem_rename,
3178 .tmpfile = shmem_tmpfile,
3179 #endif
3180 #ifdef CONFIG_TMPFS_XATTR
3181 .setxattr = shmem_setxattr,
3182 .getxattr = shmem_getxattr,
3183 .listxattr = shmem_listxattr,
3184 .removexattr = shmem_removexattr,
3185 #endif
3186 #ifdef CONFIG_TMPFS_POSIX_ACL
3187 .setattr = shmem_setattr,
3188 #endif
3189 };
3190
3191 static const struct inode_operations shmem_special_inode_operations = {
3192 #ifdef CONFIG_TMPFS_XATTR
3193 .setxattr = shmem_setxattr,
3194 .getxattr = shmem_getxattr,
3195 .listxattr = shmem_listxattr,
3196 .removexattr = shmem_removexattr,
3197 #endif
3198 #ifdef CONFIG_TMPFS_POSIX_ACL
3199 .setattr = shmem_setattr,
3200 #endif
3201 };
3202
3203 static const struct super_operations shmem_ops = {
3204 .alloc_inode = shmem_alloc_inode,
3205 .destroy_inode = shmem_destroy_inode,
3206 #ifdef CONFIG_TMPFS
3207 .statfs = shmem_statfs,
3208 .remount_fs = shmem_remount_fs,
3209 .show_options = shmem_show_options,
3210 #endif
3211 .evict_inode = shmem_evict_inode,
3212 .drop_inode = generic_delete_inode,
3213 .put_super = shmem_put_super,
3214 };
3215
3216 static const struct vm_operations_struct shmem_vm_ops = {
3217 .fault = shmem_fault,
3218 #ifdef CONFIG_NUMA
3219 .set_policy = shmem_set_policy,
3220 .get_policy = shmem_get_policy,
3221 #endif
3222 .remap_pages = generic_file_remap_pages,
3223 };
3224
3225 static struct dentry *shmem_mount(struct file_system_type *fs_type,
3226 int flags, const char *dev_name, void *data)
3227 {
3228 return mount_nodev(fs_type, flags, data, shmem_fill_super);
3229 }
3230
3231 static struct file_system_type shmem_fs_type = {
3232 .owner = THIS_MODULE,
3233 .name = "tmpfs",
3234 .mount = shmem_mount,
3235 .kill_sb = kill_litter_super,
3236 .fs_flags = FS_USERNS_MOUNT,
3237 };
3238
3239 int __init shmem_init(void)
3240 {
3241 int error;
3242
3243 error = bdi_init(&shmem_backing_dev_info);
3244 if (error)
3245 goto out4;
3246
3247 error = shmem_init_inodecache();
3248 if (error)
3249 goto out3;
3250
3251 error = register_filesystem(&shmem_fs_type);
3252 if (error) {
3253 printk(KERN_ERR "Could not register tmpfs\n");
3254 goto out2;
3255 }
3256
3257 shm_mnt = vfs_kern_mount(&shmem_fs_type, MS_NOUSER,
3258 shmem_fs_type.name, NULL);
3259 if (IS_ERR(shm_mnt)) {
3260 error = PTR_ERR(shm_mnt);
3261 printk(KERN_ERR "Could not kern_mount tmpfs\n");
3262 goto out1;
3263 }
3264 return 0;
3265
3266 out1:
3267 unregister_filesystem(&shmem_fs_type);
3268 out2:
3269 shmem_destroy_inodecache();
3270 out3:
3271 bdi_destroy(&shmem_backing_dev_info);
3272 out4:
3273 shm_mnt = ERR_PTR(error);
3274 return error;
3275 }
3276
3277 #else /* !CONFIG_SHMEM */
3278
3279 /*
3280 * tiny-shmem: simple shmemfs and tmpfs using ramfs code
3281 *
3282 * This is intended for small system where the benefits of the full
3283 * shmem code (swap-backed and resource-limited) are outweighed by
3284 * their complexity. On systems without swap this code should be
3285 * effectively equivalent, but much lighter weight.
3286 */
3287
3288 static struct file_system_type shmem_fs_type = {
3289 .name = "tmpfs",
3290 .mount = ramfs_mount,
3291 .kill_sb = kill_litter_super,
3292 .fs_flags = FS_USERNS_MOUNT,
3293 };
3294
3295 int __init shmem_init(void)
3296 {
3297 BUG_ON(register_filesystem(&shmem_fs_type) != 0);
3298
3299 shm_mnt = kern_mount(&shmem_fs_type);
3300 BUG_ON(IS_ERR(shm_mnt));
3301
3302 return 0;
3303 }
3304
3305 int shmem_unuse(swp_entry_t swap, struct page *page)
3306 {
3307 return 0;
3308 }
3309
3310 int shmem_lock(struct file *file, int lock, struct user_struct *user)
3311 {
3312 return 0;
3313 }
3314
3315 void shmem_unlock_mapping(struct address_space *mapping)
3316 {
3317 }
3318
3319 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
3320 {
3321 truncate_inode_pages_range(inode->i_mapping, lstart, lend);
3322 }
3323 EXPORT_SYMBOL_GPL(shmem_truncate_range);
3324
3325 #define shmem_vm_ops generic_file_vm_ops
3326 #define shmem_file_operations ramfs_file_operations
3327 #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
3328 #define shmem_acct_size(flags, size) 0
3329 #define shmem_unacct_size(flags, size) do {} while (0)
3330
3331 #endif /* CONFIG_SHMEM */
3332
3333 /* common code */
3334
3335 static struct dentry_operations anon_ops = {
3336 .d_dname = simple_dname
3337 };
3338
3339 /**
3340 * shmem_file_setup - get an unlinked file living in tmpfs
3341 * @name: name for dentry (to be seen in /proc/<pid>/maps
3342 * @size: size to be set for the file
3343 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
3344 */
3345 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
3346 {
3347 struct file *res;
3348 struct inode *inode;
3349 struct path path;
3350 struct super_block *sb;
3351 struct qstr this;
3352
3353 if (IS_ERR(shm_mnt))
3354 return ERR_CAST(shm_mnt);
3355
3356 if (size < 0 || size > MAX_LFS_FILESIZE)
3357 return ERR_PTR(-EINVAL);
3358
3359 if (shmem_acct_size(flags, size))
3360 return ERR_PTR(-ENOMEM);
3361
3362 res = ERR_PTR(-ENOMEM);
3363 this.name = name;
3364 this.len = strlen(name);
3365 this.hash = 0; /* will go */
3366 sb = shm_mnt->mnt_sb;
3367 path.dentry = d_alloc_pseudo(sb, &this);
3368 if (!path.dentry)
3369 goto put_memory;
3370 d_set_d_op(path.dentry, &anon_ops);
3371 path.mnt = mntget(shm_mnt);
3372
3373 res = ERR_PTR(-ENOSPC);
3374 inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
3375 if (!inode)
3376 goto put_dentry;
3377
3378 d_instantiate(path.dentry, inode);
3379 inode->i_size = size;
3380 clear_nlink(inode); /* It is unlinked */
3381 res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
3382 if (IS_ERR(res))
3383 goto put_dentry;
3384
3385 res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
3386 &shmem_file_operations);
3387 if (IS_ERR(res))
3388 goto put_dentry;
3389
3390 return res;
3391
3392 put_dentry:
3393 path_put(&path);
3394 put_memory:
3395 shmem_unacct_size(flags, size);
3396 return res;
3397 }
3398 EXPORT_SYMBOL_GPL(shmem_file_setup);
3399
3400 void shmem_set_file(struct vm_area_struct *vma, struct file *file)
3401 {
3402 if (vma->vm_file)
3403 fput(vma->vm_file);
3404 vma->vm_file = file;
3405 vma->vm_ops = &shmem_vm_ops;
3406 }
3407
3408 /**
3409 * shmem_zero_setup - setup a shared anonymous mapping
3410 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
3411 */
3412 int shmem_zero_setup(struct vm_area_struct *vma)
3413 {
3414 struct file *file;
3415 loff_t size = vma->vm_end - vma->vm_start;
3416
3417 file = shmem_file_setup("dev/zero", size, vma->vm_flags);
3418 if (IS_ERR(file))
3419 return PTR_ERR(file);
3420
3421 shmem_set_file(vma, file);
3422 return 0;
3423 }
3424
3425 /**
3426 * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
3427 * @mapping: the page's address_space
3428 * @index: the page index
3429 * @gfp: the page allocator flags to use if allocating
3430 *
3431 * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
3432 * with any new page allocations done using the specified allocation flags.
3433 * But read_cache_page_gfp() uses the ->readpage() method: which does not
3434 * suit tmpfs, since it may have pages in swapcache, and needs to find those
3435 * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
3436 *
3437 * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
3438 * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
3439 */
3440 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
3441 pgoff_t index, gfp_t gfp)
3442 {
3443 #ifdef CONFIG_SHMEM
3444 struct inode *inode = mapping->host;
3445 struct page *page;
3446 int error;
3447
3448 BUG_ON(mapping->a_ops != &shmem_aops);
3449 error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE, gfp, NULL);
3450 if (error)
3451 page = ERR_PTR(error);
3452 else
3453 unlock_page(page);
3454 return page;
3455 #else
3456 /*
3457 * The tiny !SHMEM case uses ramfs without swap
3458 */
3459 return read_cache_page_gfp(mapping, index, gfp);
3460 #endif
3461 }
3462 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);