Merge branch 'stable-3.2' into pandora-3.2
[pandora-kernel.git] / mm / shmem.c
1 /*
2  * Resizable virtual memory filesystem for Linux.
3  *
4  * Copyright (C) 2000 Linus Torvalds.
5  *               2000 Transmeta Corp.
6  *               2000-2001 Christoph Rohland
7  *               2000-2001 SAP AG
8  *               2002 Red Hat Inc.
9  * Copyright (C) 2002-2011 Hugh Dickins.
10  * Copyright (C) 2011 Google Inc.
11  * Copyright (C) 2002-2005 VERITAS Software Corporation.
12  * Copyright (C) 2004 Andi Kleen, SuSE Labs
13  *
14  * Extended attribute support for tmpfs:
15  * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
16  * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
17  *
18  * tiny-shmem:
19  * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
20  *
21  * This file is released under the GPL.
22  */
23
24 #include <linux/fs.h>
25 #include <linux/init.h>
26 #include <linux/vfs.h>
27 #include <linux/mount.h>
28 #include <linux/pagemap.h>
29 #include <linux/file.h>
30 #include <linux/mm.h>
31 #include <linux/export.h>
32 #include <linux/swap.h>
33
34 static struct vfsmount *shm_mnt;
35
36 #ifdef CONFIG_SHMEM
37 /*
38  * This virtual memory filesystem is heavily based on the ramfs. It
39  * extends ramfs by the ability to use swap and honor resource limits
40  * which makes it a completely usable filesystem.
41  */
42
43 #include <linux/xattr.h>
44 #include <linux/exportfs.h>
45 #include <linux/posix_acl.h>
46 #include <linux/generic_acl.h>
47 #include <linux/mman.h>
48 #include <linux/string.h>
49 #include <linux/slab.h>
50 #include <linux/backing-dev.h>
51 #include <linux/shmem_fs.h>
52 #include <linux/writeback.h>
53 #include <linux/blkdev.h>
54 #include <linux/pagevec.h>
55 #include <linux/percpu_counter.h>
56 #include <linux/splice.h>
57 #include <linux/security.h>
58 #include <linux/swapops.h>
59 #include <linux/mempolicy.h>
60 #include <linux/namei.h>
61 #include <linux/ctype.h>
62 #include <linux/migrate.h>
63 #include <linux/highmem.h>
64 #include <linux/seq_file.h>
65 #include <linux/magic.h>
66
67 #include <asm/uaccess.h>
68 #include <asm/pgtable.h>
69
70 #define BLOCKS_PER_PAGE  (PAGE_CACHE_SIZE/512)
71 #define VM_ACCT(size)    (PAGE_CACHE_ALIGN(size) >> PAGE_SHIFT)
72
73 /* Pretend that each entry is of this size in directory's i_size */
74 #define BOGO_DIRENT_SIZE 20
75
76 /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
77 #define SHORT_SYMLINK_LEN 128
78
79 /*
80  * vmtruncate_range() communicates with shmem_fault via
81  * inode->i_private (with i_mutex making sure that it has only one user at
82  * a time): we would prefer not to enlarge the shmem inode just for that.
83  */
84 struct shmem_falloc {
85         wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
86         pgoff_t start;          /* start of range currently being fallocated */
87         pgoff_t next;           /* the next page offset to be fallocated */
88 };
89
90 struct shmem_xattr {
91         struct list_head list;  /* anchored by shmem_inode_info->xattr_list */
92         char *name;             /* xattr name */
93         size_t size;
94         char value[0];
95 };
96
97 /* Flag allocation requirements to shmem_getpage */
98 enum sgp_type {
99         SGP_READ,       /* don't exceed i_size, don't allocate page */
100         SGP_CACHE,      /* don't exceed i_size, may allocate page */
101         SGP_DIRTY,      /* like SGP_CACHE, but set new page dirty */
102         SGP_WRITE,      /* may exceed i_size, may allocate page */
103 };
104
105 #ifdef CONFIG_TMPFS
106 static unsigned long shmem_default_max_blocks(void)
107 {
108         return totalram_pages / 2;
109 }
110
111 static unsigned long shmem_default_max_inodes(void)
112 {
113         return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
114 }
115 #endif
116
117 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
118         struct page **pagep, enum sgp_type sgp, gfp_t gfp, int *fault_type);
119
120 static inline int shmem_getpage(struct inode *inode, pgoff_t index,
121         struct page **pagep, enum sgp_type sgp, int *fault_type)
122 {
123         return shmem_getpage_gfp(inode, index, pagep, sgp,
124                         mapping_gfp_mask(inode->i_mapping), fault_type);
125 }
126
127 static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
128 {
129         return sb->s_fs_info;
130 }
131
132 /*
133  * shmem_file_setup pre-accounts the whole fixed size of a VM object,
134  * for shared memory and for shared anonymous (/dev/zero) mappings
135  * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
136  * consistent with the pre-accounting of private mappings ...
137  */
138 static inline int shmem_acct_size(unsigned long flags, loff_t size)
139 {
140         return (flags & VM_NORESERVE) ?
141                 0 : security_vm_enough_memory_kern(VM_ACCT(size));
142 }
143
144 static inline void shmem_unacct_size(unsigned long flags, loff_t size)
145 {
146         if (!(flags & VM_NORESERVE))
147                 vm_unacct_memory(VM_ACCT(size));
148 }
149
150 /*
151  * ... whereas tmpfs objects are accounted incrementally as
152  * pages are allocated, in order to allow huge sparse files.
153  * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
154  * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
155  */
156 static inline int shmem_acct_block(unsigned long flags)
157 {
158         return (flags & VM_NORESERVE) ?
159                 security_vm_enough_memory_kern(VM_ACCT(PAGE_CACHE_SIZE)) : 0;
160 }
161
162 static inline void shmem_unacct_blocks(unsigned long flags, long pages)
163 {
164         if (flags & VM_NORESERVE)
165                 vm_unacct_memory(pages * VM_ACCT(PAGE_CACHE_SIZE));
166 }
167
168 static const struct super_operations shmem_ops;
169 static const struct address_space_operations shmem_aops;
170 static const struct file_operations shmem_file_operations;
171 static const struct inode_operations shmem_inode_operations;
172 static const struct inode_operations shmem_dir_inode_operations;
173 static const struct inode_operations shmem_special_inode_operations;
174 static const struct vm_operations_struct shmem_vm_ops;
175
176 static struct backing_dev_info shmem_backing_dev_info  __read_mostly = {
177         .ra_pages       = 0,    /* No readahead */
178         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_SWAP_BACKED,
179 };
180
181 static LIST_HEAD(shmem_swaplist);
182 static DEFINE_MUTEX(shmem_swaplist_mutex);
183
184 static int shmem_reserve_inode(struct super_block *sb)
185 {
186         struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
187         if (sbinfo->max_inodes) {
188                 spin_lock(&sbinfo->stat_lock);
189                 if (!sbinfo->free_inodes) {
190                         spin_unlock(&sbinfo->stat_lock);
191                         return -ENOSPC;
192                 }
193                 sbinfo->free_inodes--;
194                 spin_unlock(&sbinfo->stat_lock);
195         }
196         return 0;
197 }
198
199 static void shmem_free_inode(struct super_block *sb)
200 {
201         struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
202         if (sbinfo->max_inodes) {
203                 spin_lock(&sbinfo->stat_lock);
204                 sbinfo->free_inodes++;
205                 spin_unlock(&sbinfo->stat_lock);
206         }
207 }
208
209 /**
210  * shmem_recalc_inode - recalculate the block usage of an inode
211  * @inode: inode to recalc
212  *
213  * We have to calculate the free blocks since the mm can drop
214  * undirtied hole pages behind our back.
215  *
216  * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
217  * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
218  *
219  * It has to be called with the spinlock held.
220  */
221 static void shmem_recalc_inode(struct inode *inode)
222 {
223         struct shmem_inode_info *info = SHMEM_I(inode);
224         long freed;
225
226         freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
227         if (freed > 0) {
228                 struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
229                 if (sbinfo->max_blocks)
230                         percpu_counter_add(&sbinfo->used_blocks, -freed);
231                 info->alloced -= freed;
232                 inode->i_blocks -= freed * BLOCKS_PER_PAGE;
233                 shmem_unacct_blocks(info->flags, freed);
234         }
235 }
236
237 /*
238  * Replace item expected in radix tree by a new item, while holding tree lock.
239  */
240 static int shmem_radix_tree_replace(struct address_space *mapping,
241                         pgoff_t index, void *expected, void *replacement)
242 {
243         void **pslot;
244         void *item = NULL;
245
246         VM_BUG_ON(!expected);
247         pslot = radix_tree_lookup_slot(&mapping->page_tree, index);
248         if (pslot)
249                 item = radix_tree_deref_slot_protected(pslot,
250                                                         &mapping->tree_lock);
251         if (item != expected)
252                 return -ENOENT;
253         if (replacement)
254                 radix_tree_replace_slot(pslot, replacement);
255         else
256                 radix_tree_delete(&mapping->page_tree, index);
257         return 0;
258 }
259
260 /*
261  * Like add_to_page_cache_locked, but error if expected item has gone.
262  */
263 static int shmem_add_to_page_cache(struct page *page,
264                                    struct address_space *mapping,
265                                    pgoff_t index, gfp_t gfp, void *expected)
266 {
267         int error = 0;
268
269         VM_BUG_ON(!PageLocked(page));
270         VM_BUG_ON(!PageSwapBacked(page));
271
272         if (!expected)
273                 error = radix_tree_preload(gfp & GFP_RECLAIM_MASK);
274         if (!error) {
275                 page_cache_get(page);
276                 page->mapping = mapping;
277                 page->index = index;
278
279                 spin_lock_irq(&mapping->tree_lock);
280                 if (!expected)
281                         error = radix_tree_insert(&mapping->page_tree,
282                                                         index, page);
283                 else
284                         error = shmem_radix_tree_replace(mapping, index,
285                                                         expected, page);
286                 if (!error) {
287                         mapping->nrpages++;
288                         __inc_zone_page_state(page, NR_FILE_PAGES);
289                         __inc_zone_page_state(page, NR_SHMEM);
290                         spin_unlock_irq(&mapping->tree_lock);
291                 } else {
292                         page->mapping = NULL;
293                         spin_unlock_irq(&mapping->tree_lock);
294                         page_cache_release(page);
295                 }
296                 if (!expected)
297                         radix_tree_preload_end();
298         }
299         if (error)
300                 mem_cgroup_uncharge_cache_page(page);
301         return error;
302 }
303
304 /*
305  * Like delete_from_page_cache, but substitutes swap for page.
306  */
307 static void shmem_delete_from_page_cache(struct page *page, void *radswap)
308 {
309         struct address_space *mapping = page->mapping;
310         int error;
311
312         spin_lock_irq(&mapping->tree_lock);
313         error = shmem_radix_tree_replace(mapping, page->index, page, radswap);
314         page->mapping = NULL;
315         mapping->nrpages--;
316         __dec_zone_page_state(page, NR_FILE_PAGES);
317         __dec_zone_page_state(page, NR_SHMEM);
318         spin_unlock_irq(&mapping->tree_lock);
319         page_cache_release(page);
320         BUG_ON(error);
321 }
322
323 /*
324  * Like find_get_pages, but collecting swap entries as well as pages.
325  */
326 static unsigned shmem_find_get_pages_and_swap(struct address_space *mapping,
327                                         pgoff_t start, unsigned int nr_pages,
328                                         struct page **pages, pgoff_t *indices)
329 {
330         unsigned int i;
331         unsigned int ret;
332         unsigned int nr_found;
333
334         rcu_read_lock();
335 restart:
336         nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
337                                 (void ***)pages, indices, start, nr_pages);
338         ret = 0;
339         for (i = 0; i < nr_found; i++) {
340                 struct page *page;
341 repeat:
342                 page = radix_tree_deref_slot((void **)pages[i]);
343                 if (unlikely(!page))
344                         continue;
345                 if (radix_tree_exception(page)) {
346                         if (radix_tree_deref_retry(page))
347                                 goto restart;
348                         /*
349                          * Otherwise, we must be storing a swap entry
350                          * here as an exceptional entry: so return it
351                          * without attempting to raise page count.
352                          */
353                         goto export;
354                 }
355                 if (!page_cache_get_speculative(page))
356                         goto repeat;
357
358                 /* Has the page moved? */
359                 if (unlikely(page != *((void **)pages[i]))) {
360                         page_cache_release(page);
361                         goto repeat;
362                 }
363 export:
364                 indices[ret] = indices[i];
365                 pages[ret] = page;
366                 ret++;
367         }
368         if (unlikely(!ret && nr_found))
369                 goto restart;
370         rcu_read_unlock();
371         return ret;
372 }
373
374 /*
375  * Remove swap entry from radix tree, free the swap and its page cache.
376  */
377 static int shmem_free_swap(struct address_space *mapping,
378                            pgoff_t index, void *radswap)
379 {
380         int error;
381
382         spin_lock_irq(&mapping->tree_lock);
383         error = shmem_radix_tree_replace(mapping, index, radswap, NULL);
384         spin_unlock_irq(&mapping->tree_lock);
385         if (!error)
386                 free_swap_and_cache(radix_to_swp_entry(radswap));
387         return error;
388 }
389
390 /*
391  * Pagevec may contain swap entries, so shuffle up pages before releasing.
392  */
393 static void shmem_deswap_pagevec(struct pagevec *pvec)
394 {
395         int i, j;
396
397         for (i = 0, j = 0; i < pagevec_count(pvec); i++) {
398                 struct page *page = pvec->pages[i];
399                 if (!radix_tree_exceptional_entry(page))
400                         pvec->pages[j++] = page;
401         }
402         pvec->nr = j;
403 }
404
405 /*
406  * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
407  */
408 void shmem_unlock_mapping(struct address_space *mapping)
409 {
410         struct pagevec pvec;
411         pgoff_t indices[PAGEVEC_SIZE];
412         pgoff_t index = 0;
413
414         pagevec_init(&pvec, 0);
415         /*
416          * Minor point, but we might as well stop if someone else SHM_LOCKs it.
417          */
418         while (!mapping_unevictable(mapping)) {
419                 /*
420                  * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
421                  * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
422                  */
423                 pvec.nr = shmem_find_get_pages_and_swap(mapping, index,
424                                         PAGEVEC_SIZE, pvec.pages, indices);
425                 if (!pvec.nr)
426                         break;
427                 index = indices[pvec.nr - 1] + 1;
428                 shmem_deswap_pagevec(&pvec);
429                 check_move_unevictable_pages(pvec.pages, pvec.nr);
430                 pagevec_release(&pvec);
431                 cond_resched();
432         }
433 }
434
435 /*
436  * Remove range of pages and swap entries from radix tree, and free them.
437  */
438 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
439 {
440         struct address_space *mapping = inode->i_mapping;
441         struct shmem_inode_info *info = SHMEM_I(inode);
442         pgoff_t start = (lstart + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
443         unsigned partial = lstart & (PAGE_CACHE_SIZE - 1);
444         pgoff_t end = (lend >> PAGE_CACHE_SHIFT);
445         struct pagevec pvec;
446         pgoff_t indices[PAGEVEC_SIZE];
447         long nr_swaps_freed = 0;
448         pgoff_t index;
449         int i;
450
451         BUG_ON((lend & (PAGE_CACHE_SIZE - 1)) != (PAGE_CACHE_SIZE - 1));
452
453         pagevec_init(&pvec, 0);
454         index = start;
455         while (index <= end) {
456                 pvec.nr = shmem_find_get_pages_and_swap(mapping, index,
457                         min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1,
458                                                         pvec.pages, indices);
459                 if (!pvec.nr)
460                         break;
461                 mem_cgroup_uncharge_start();
462                 for (i = 0; i < pagevec_count(&pvec); i++) {
463                         struct page *page = pvec.pages[i];
464
465                         index = indices[i];
466                         if (index > end)
467                                 break;
468
469                         if (radix_tree_exceptional_entry(page)) {
470                                 nr_swaps_freed += !shmem_free_swap(mapping,
471                                                                 index, page);
472                                 continue;
473                         }
474
475                         if (!trylock_page(page))
476                                 continue;
477                         if (page->mapping == mapping) {
478                                 VM_BUG_ON(PageWriteback(page));
479                                 truncate_inode_page(mapping, page);
480                         }
481                         unlock_page(page);
482                 }
483                 shmem_deswap_pagevec(&pvec);
484                 pagevec_release(&pvec);
485                 mem_cgroup_uncharge_end();
486                 cond_resched();
487                 index++;
488         }
489
490         if (partial) {
491                 struct page *page = NULL;
492                 shmem_getpage(inode, start - 1, &page, SGP_READ, NULL);
493                 if (page) {
494                         zero_user_segment(page, partial, PAGE_CACHE_SIZE);
495                         set_page_dirty(page);
496                         unlock_page(page);
497                         page_cache_release(page);
498                 }
499         }
500
501         index = start;
502         while (index <= end) {
503                 cond_resched();
504                 pvec.nr = shmem_find_get_pages_and_swap(mapping, index,
505                         min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1,
506                                                         pvec.pages, indices);
507                 if (!pvec.nr) {
508                         /* If all gone or hole-punch, we're done */
509                         if (index == start || end != -1)
510                                 break;
511                         /* But if truncating, restart to make sure all gone */
512                         index = start;
513                         continue;
514                 }
515                 mem_cgroup_uncharge_start();
516                 for (i = 0; i < pagevec_count(&pvec); i++) {
517                         struct page *page = pvec.pages[i];
518
519                         index = indices[i];
520                         if (index > end)
521                                 break;
522
523                         if (radix_tree_exceptional_entry(page)) {
524                                 if (shmem_free_swap(mapping, index, page)) {
525                                         /* Swap was replaced by page: retry */
526                                         index--;
527                                         break;
528                                 }
529                                 nr_swaps_freed++;
530                                 continue;
531                         }
532
533                         lock_page(page);
534                         if (page->mapping == mapping) {
535                                 VM_BUG_ON(PageWriteback(page));
536                                 truncate_inode_page(mapping, page);
537                         } else {
538                                 /* Page was replaced by swap: retry */
539                                 unlock_page(page);
540                                 index--;
541                                 break;
542                         }
543                         unlock_page(page);
544                 }
545                 shmem_deswap_pagevec(&pvec);
546                 pagevec_release(&pvec);
547                 mem_cgroup_uncharge_end();
548                 index++;
549         }
550
551         spin_lock(&info->lock);
552         info->swapped -= nr_swaps_freed;
553         shmem_recalc_inode(inode);
554         spin_unlock(&info->lock);
555
556         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
557 }
558 EXPORT_SYMBOL_GPL(shmem_truncate_range);
559
560 static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
561 {
562         struct inode *inode = dentry->d_inode;
563         int error;
564
565         error = inode_change_ok(inode, attr);
566         if (error)
567                 return error;
568
569         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
570                 loff_t oldsize = inode->i_size;
571                 loff_t newsize = attr->ia_size;
572
573                 if (newsize != oldsize) {
574                         i_size_write(inode, newsize);
575                         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
576                 }
577                 if (newsize < oldsize) {
578                         loff_t holebegin = round_up(newsize, PAGE_SIZE);
579                         unmap_mapping_range(inode->i_mapping, holebegin, 0, 1);
580                         shmem_truncate_range(inode, newsize, (loff_t)-1);
581                         /* unmap again to remove racily COWed private pages */
582                         unmap_mapping_range(inode->i_mapping, holebegin, 0, 1);
583                 }
584         }
585
586         setattr_copy(inode, attr);
587 #ifdef CONFIG_TMPFS_POSIX_ACL
588         if (attr->ia_valid & ATTR_MODE)
589                 error = generic_acl_chmod(inode);
590 #endif
591         return error;
592 }
593
594 static void shmem_evict_inode(struct inode *inode)
595 {
596         struct shmem_inode_info *info = SHMEM_I(inode);
597         struct shmem_xattr *xattr, *nxattr;
598
599         if (inode->i_mapping->a_ops == &shmem_aops) {
600                 shmem_unacct_size(info->flags, inode->i_size);
601                 inode->i_size = 0;
602                 shmem_truncate_range(inode, 0, (loff_t)-1);
603                 if (!list_empty(&info->swaplist)) {
604                         mutex_lock(&shmem_swaplist_mutex);
605                         list_del_init(&info->swaplist);
606                         mutex_unlock(&shmem_swaplist_mutex);
607                 }
608         } else
609                 kfree(info->symlink);
610
611         list_for_each_entry_safe(xattr, nxattr, &info->xattr_list, list) {
612                 kfree(xattr->name);
613                 kfree(xattr);
614         }
615         WARN_ON(inode->i_blocks);
616         shmem_free_inode(inode->i_sb);
617         end_writeback(inode);
618 }
619
620 /*
621  * If swap found in inode, free it and move page from swapcache to filecache.
622  */
623 static int shmem_unuse_inode(struct shmem_inode_info *info,
624                              swp_entry_t swap, struct page *page)
625 {
626         struct address_space *mapping = info->vfs_inode.i_mapping;
627         void *radswap;
628         pgoff_t index;
629         int error;
630
631         radswap = swp_to_radix_entry(swap);
632         index = radix_tree_locate_item(&mapping->page_tree, radswap);
633         if (index == -1)
634                 return 0;
635
636         /*
637          * Move _head_ to start search for next from here.
638          * But be careful: shmem_evict_inode checks list_empty without taking
639          * mutex, and there's an instant in list_move_tail when info->swaplist
640          * would appear empty, if it were the only one on shmem_swaplist.
641          */
642         if (shmem_swaplist.next != &info->swaplist)
643                 list_move_tail(&shmem_swaplist, &info->swaplist);
644
645         /*
646          * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
647          * but also to hold up shmem_evict_inode(): so inode cannot be freed
648          * beneath us (pagelock doesn't help until the page is in pagecache).
649          */
650         error = shmem_add_to_page_cache(page, mapping, index,
651                                                 GFP_NOWAIT, radswap);
652         /* which does mem_cgroup_uncharge_cache_page on error */
653
654         if (error != -ENOMEM) {
655                 /*
656                  * Truncation and eviction use free_swap_and_cache(), which
657                  * only does trylock page: if we raced, best clean up here.
658                  */
659                 delete_from_swap_cache(page);
660                 set_page_dirty(page);
661                 if (!error) {
662                         spin_lock(&info->lock);
663                         info->swapped--;
664                         spin_unlock(&info->lock);
665                         swap_free(swap);
666                 }
667                 error = 1;      /* not an error, but entry was found */
668         }
669         return error;
670 }
671
672 /*
673  * Search through swapped inodes to find and replace swap by page.
674  */
675 int shmem_unuse(swp_entry_t swap, struct page *page)
676 {
677         struct list_head *this, *next;
678         struct shmem_inode_info *info;
679         int found = 0;
680         int error;
681
682         /*
683          * Charge page using GFP_KERNEL while we can wait, before taking
684          * the shmem_swaplist_mutex which might hold up shmem_writepage().
685          * Charged back to the user (not to caller) when swap account is used.
686          */
687         error = mem_cgroup_cache_charge(page, current->mm, GFP_KERNEL);
688         if (error)
689                 goto out;
690         /* No radix_tree_preload: swap entry keeps a place for page in tree */
691
692         mutex_lock(&shmem_swaplist_mutex);
693         list_for_each_safe(this, next, &shmem_swaplist) {
694                 info = list_entry(this, struct shmem_inode_info, swaplist);
695                 if (info->swapped)
696                         found = shmem_unuse_inode(info, swap, page);
697                 else
698                         list_del_init(&info->swaplist);
699                 cond_resched();
700                 if (found)
701                         break;
702         }
703         mutex_unlock(&shmem_swaplist_mutex);
704
705         if (!found)
706                 mem_cgroup_uncharge_cache_page(page);
707         if (found < 0)
708                 error = found;
709 out:
710         unlock_page(page);
711         page_cache_release(page);
712         return error;
713 }
714
715 /*
716  * Move the page from the page cache to the swap cache.
717  */
718 static int shmem_writepage(struct page *page, struct writeback_control *wbc)
719 {
720         struct shmem_inode_info *info;
721         struct address_space *mapping;
722         struct inode *inode;
723         swp_entry_t swap;
724         pgoff_t index;
725
726         BUG_ON(!PageLocked(page));
727         mapping = page->mapping;
728         index = page->index;
729         inode = mapping->host;
730         info = SHMEM_I(inode);
731         if (info->flags & VM_LOCKED)
732                 goto redirty;
733         if (!total_swap_pages)
734                 goto redirty;
735
736         /*
737          * shmem_backing_dev_info's capabilities prevent regular writeback or
738          * sync from ever calling shmem_writepage; but a stacking filesystem
739          * might use ->writepage of its underlying filesystem, in which case
740          * tmpfs should write out to swap only in response to memory pressure,
741          * and not for the writeback threads or sync.
742          */
743         if (!wbc->for_reclaim) {
744                 WARN_ON_ONCE(1);        /* Still happens? Tell us about it! */
745                 goto redirty;
746         }
747         swap = get_swap_page();
748         if (!swap.val)
749                 goto redirty;
750
751         /*
752          * Add inode to shmem_unuse()'s list of swapped-out inodes,
753          * if it's not already there.  Do it now before the page is
754          * moved to swap cache, when its pagelock no longer protects
755          * the inode from eviction.  But don't unlock the mutex until
756          * we've incremented swapped, because shmem_unuse_inode() will
757          * prune a !swapped inode from the swaplist under this mutex.
758          */
759         mutex_lock(&shmem_swaplist_mutex);
760         if (list_empty(&info->swaplist))
761                 list_add_tail(&info->swaplist, &shmem_swaplist);
762
763         if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
764                 swap_shmem_alloc(swap);
765                 shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
766
767                 spin_lock(&info->lock);
768                 info->swapped++;
769                 shmem_recalc_inode(inode);
770                 spin_unlock(&info->lock);
771
772                 mutex_unlock(&shmem_swaplist_mutex);
773                 BUG_ON(page_mapped(page));
774                 swap_writepage(page, wbc);
775                 return 0;
776         }
777
778         mutex_unlock(&shmem_swaplist_mutex);
779         swapcache_free(swap, NULL);
780 redirty:
781         set_page_dirty(page);
782         if (wbc->for_reclaim)
783                 return AOP_WRITEPAGE_ACTIVATE;  /* Return with page locked */
784         unlock_page(page);
785         return 0;
786 }
787
788 #ifdef CONFIG_NUMA
789 #ifdef CONFIG_TMPFS
790 static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
791 {
792         char buffer[64];
793
794         if (!mpol || mpol->mode == MPOL_DEFAULT)
795                 return;         /* show nothing */
796
797         mpol_to_str(buffer, sizeof(buffer), mpol, 1);
798
799         seq_printf(seq, ",mpol=%s", buffer);
800 }
801
802 static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
803 {
804         struct mempolicy *mpol = NULL;
805         if (sbinfo->mpol) {
806                 spin_lock(&sbinfo->stat_lock);  /* prevent replace/use races */
807                 mpol = sbinfo->mpol;
808                 mpol_get(mpol);
809                 spin_unlock(&sbinfo->stat_lock);
810         }
811         return mpol;
812 }
813 #endif /* CONFIG_TMPFS */
814
815 static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
816                         struct shmem_inode_info *info, pgoff_t index)
817 {
818         struct vm_area_struct pvma;
819         struct page *page;
820
821         /* Create a pseudo vma that just contains the policy */
822         pvma.vm_start = 0;
823         pvma.vm_pgoff = index;
824         pvma.vm_ops = NULL;
825         pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, index);
826
827         page = swapin_readahead(swap, gfp, &pvma, 0);
828
829         /* Drop reference taken by mpol_shared_policy_lookup() */
830         mpol_cond_put(pvma.vm_policy);
831
832         return page;
833 }
834
835 static struct page *shmem_alloc_page(gfp_t gfp,
836                         struct shmem_inode_info *info, pgoff_t index)
837 {
838         struct vm_area_struct pvma;
839         struct page *page;
840
841         /* Create a pseudo vma that just contains the policy */
842         pvma.vm_start = 0;
843         pvma.vm_pgoff = index;
844         pvma.vm_ops = NULL;
845         pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, index);
846
847         page = alloc_page_vma(gfp, &pvma, 0);
848
849         /* Drop reference taken by mpol_shared_policy_lookup() */
850         mpol_cond_put(pvma.vm_policy);
851
852         return page;
853 }
854 #else /* !CONFIG_NUMA */
855 #ifdef CONFIG_TMPFS
856 static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
857 {
858 }
859 #endif /* CONFIG_TMPFS */
860
861 static inline struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
862                         struct shmem_inode_info *info, pgoff_t index)
863 {
864         return swapin_readahead(swap, gfp, NULL, 0);
865 }
866
867 static inline struct page *shmem_alloc_page(gfp_t gfp,
868                         struct shmem_inode_info *info, pgoff_t index)
869 {
870         return alloc_page(gfp);
871 }
872 #endif /* CONFIG_NUMA */
873
874 #if !defined(CONFIG_NUMA) || !defined(CONFIG_TMPFS)
875 static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
876 {
877         return NULL;
878 }
879 #endif
880
881 /*
882  * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
883  *
884  * If we allocate a new one we do not mark it dirty. That's up to the
885  * vm. If we swap it in we mark it dirty since we also free the swap
886  * entry since a page cannot live in both the swap and page cache
887  */
888 static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
889         struct page **pagep, enum sgp_type sgp, gfp_t gfp, int *fault_type)
890 {
891         struct address_space *mapping = inode->i_mapping;
892         struct shmem_inode_info *info;
893         struct shmem_sb_info *sbinfo;
894         struct page *page;
895         swp_entry_t swap;
896         int error;
897         int once = 0;
898
899         if (index > (MAX_LFS_FILESIZE >> PAGE_CACHE_SHIFT))
900                 return -EFBIG;
901 repeat:
902         swap.val = 0;
903         page = find_lock_page(mapping, index);
904         if (radix_tree_exceptional_entry(page)) {
905                 swap = radix_to_swp_entry(page);
906                 page = NULL;
907         }
908
909         if (sgp != SGP_WRITE &&
910             ((loff_t)index << PAGE_CACHE_SHIFT) >= i_size_read(inode)) {
911                 error = -EINVAL;
912                 goto failed;
913         }
914
915         if (page || (sgp == SGP_READ && !swap.val)) {
916                 /*
917                  * Once we can get the page lock, it must be uptodate:
918                  * if there were an error in reading back from swap,
919                  * the page would not be inserted into the filecache.
920                  */
921                 BUG_ON(page && !PageUptodate(page));
922                 *pagep = page;
923                 return 0;
924         }
925
926         /*
927          * Fast cache lookup did not find it:
928          * bring it back from swap or allocate.
929          */
930         info = SHMEM_I(inode);
931         sbinfo = SHMEM_SB(inode->i_sb);
932
933         if (swap.val) {
934                 /* Look it up and read it in.. */
935                 page = lookup_swap_cache(swap);
936                 if (!page) {
937                         /* here we actually do the io */
938                         if (fault_type)
939                                 *fault_type |= VM_FAULT_MAJOR;
940                         page = shmem_swapin(swap, gfp, info, index);
941                         if (!page) {
942                                 error = -ENOMEM;
943                                 goto failed;
944                         }
945                 }
946
947                 /* We have to do this with page locked to prevent races */
948                 lock_page(page);
949                 if (!PageUptodate(page)) {
950                         error = -EIO;
951                         goto failed;
952                 }
953                 wait_on_page_writeback(page);
954
955                 /* Someone may have already done it for us */
956                 if (page->mapping) {
957                         if (page->mapping == mapping &&
958                             page->index == index)
959                                 goto done;
960                         error = -EEXIST;
961                         goto failed;
962                 }
963
964                 error = mem_cgroup_cache_charge(page, current->mm,
965                                                 gfp & GFP_RECLAIM_MASK);
966                 if (!error)
967                         error = shmem_add_to_page_cache(page, mapping, index,
968                                                 gfp, swp_to_radix_entry(swap));
969                 if (error)
970                         goto failed;
971
972                 spin_lock(&info->lock);
973                 info->swapped--;
974                 shmem_recalc_inode(inode);
975                 spin_unlock(&info->lock);
976
977                 delete_from_swap_cache(page);
978                 set_page_dirty(page);
979                 swap_free(swap);
980
981         } else {
982                 if (shmem_acct_block(info->flags)) {
983                         error = -ENOSPC;
984                         goto failed;
985                 }
986                 if (sbinfo->max_blocks) {
987                         if (percpu_counter_compare(&sbinfo->used_blocks,
988                                                 sbinfo->max_blocks) >= 0) {
989                                 error = -ENOSPC;
990                                 goto unacct;
991                         }
992                         percpu_counter_inc(&sbinfo->used_blocks);
993                 }
994
995                 page = shmem_alloc_page(gfp, info, index);
996                 if (!page) {
997                         error = -ENOMEM;
998                         goto decused;
999                 }
1000
1001                 SetPageSwapBacked(page);
1002                 __set_page_locked(page);
1003                 error = mem_cgroup_cache_charge(page, current->mm,
1004                                                 gfp & GFP_RECLAIM_MASK);
1005                 if (!error)
1006                         error = shmem_add_to_page_cache(page, mapping, index,
1007                                                 gfp, NULL);
1008                 if (error)
1009                         goto decused;
1010                 lru_cache_add_anon(page);
1011
1012                 spin_lock(&info->lock);
1013                 info->alloced++;
1014                 inode->i_blocks += BLOCKS_PER_PAGE;
1015                 shmem_recalc_inode(inode);
1016                 spin_unlock(&info->lock);
1017
1018                 clear_highpage(page);
1019                 flush_dcache_page(page);
1020                 SetPageUptodate(page);
1021                 if (sgp == SGP_DIRTY)
1022                         set_page_dirty(page);
1023         }
1024 done:
1025         /* Perhaps the file has been truncated since we checked */
1026         if (sgp != SGP_WRITE &&
1027             ((loff_t)index << PAGE_CACHE_SHIFT) >= i_size_read(inode)) {
1028                 error = -EINVAL;
1029                 goto trunc;
1030         }
1031         *pagep = page;
1032         return 0;
1033
1034         /*
1035          * Error recovery.
1036          */
1037 trunc:
1038         ClearPageDirty(page);
1039         delete_from_page_cache(page);
1040         spin_lock(&info->lock);
1041         info->alloced--;
1042         inode->i_blocks -= BLOCKS_PER_PAGE;
1043         spin_unlock(&info->lock);
1044 decused:
1045         if (sbinfo->max_blocks)
1046                 percpu_counter_add(&sbinfo->used_blocks, -1);
1047 unacct:
1048         shmem_unacct_blocks(info->flags, 1);
1049 failed:
1050         if (swap.val && error != -EINVAL) {
1051                 struct page *test = find_get_page(mapping, index);
1052                 if (test && !radix_tree_exceptional_entry(test))
1053                         page_cache_release(test);
1054                 /* Have another try if the entry has changed */
1055                 if (test != swp_to_radix_entry(swap))
1056                         error = -EEXIST;
1057         }
1058         if (page) {
1059                 unlock_page(page);
1060                 page_cache_release(page);
1061         }
1062         if (error == -ENOSPC && !once++) {
1063                 info = SHMEM_I(inode);
1064                 spin_lock(&info->lock);
1065                 shmem_recalc_inode(inode);
1066                 spin_unlock(&info->lock);
1067                 goto repeat;
1068         }
1069         if (error == -EEXIST)
1070                 goto repeat;
1071         return error;
1072 }
1073
1074 static int shmem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1075 {
1076         struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1077         int error;
1078         int ret = VM_FAULT_LOCKED;
1079
1080         /*
1081          * Trinity finds that probing a hole which tmpfs is punching can
1082          * prevent the hole-punch from ever completing: which in turn
1083          * locks writers out with its hold on i_mutex.  So refrain from
1084          * faulting pages into the hole while it's being punched.  Although
1085          * shmem_truncate_range() does remove the additions, it may be unable to
1086          * keep up, as each new page needs its own unmap_mapping_range() call,
1087          * and the i_mmap tree grows ever slower to scan if new vmas are added.
1088          *
1089          * It does not matter if we sometimes reach this check just before the
1090          * hole-punch begins, so that one fault then races with the punch:
1091          * we just need to make racing faults a rare case.
1092          *
1093          * The implementation below would be much simpler if we just used a
1094          * standard mutex or completion: but we cannot take i_mutex in fault,
1095          * and bloating every shmem inode for this unlikely case would be sad.
1096          */
1097         if (unlikely(inode->i_private)) {
1098                 struct shmem_falloc *shmem_falloc;
1099
1100                 spin_lock(&inode->i_lock);
1101                 shmem_falloc = inode->i_private;
1102                 if (shmem_falloc &&
1103                     vmf->pgoff >= shmem_falloc->start &&
1104                     vmf->pgoff < shmem_falloc->next) {
1105                         wait_queue_head_t *shmem_falloc_waitq;
1106                         DEFINE_WAIT(shmem_fault_wait);
1107
1108                         ret = VM_FAULT_NOPAGE;
1109                         if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
1110                            !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
1111                                 /* It's polite to up mmap_sem if we can */
1112                                 up_read(&vma->vm_mm->mmap_sem);
1113                                 ret = VM_FAULT_RETRY;
1114                         }
1115
1116                         shmem_falloc_waitq = shmem_falloc->waitq;
1117                         prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
1118                                         TASK_UNINTERRUPTIBLE);
1119                         spin_unlock(&inode->i_lock);
1120                         schedule();
1121
1122                         /*
1123                          * shmem_falloc_waitq points into the vmtruncate_range()
1124                          * stack of the hole-punching task: shmem_falloc_waitq
1125                          * is usually invalid by the time we reach here, but
1126                          * finish_wait() does not dereference it in that case;
1127                          * though i_lock needed lest racing with wake_up_all().
1128                          */
1129                         spin_lock(&inode->i_lock);
1130                         finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
1131                         spin_unlock(&inode->i_lock);
1132                         return ret;
1133                 }
1134                 spin_unlock(&inode->i_lock);
1135         }
1136
1137         error = shmem_getpage(inode, vmf->pgoff, &vmf->page, SGP_CACHE, &ret);
1138         if (error)
1139                 return ((error == -ENOMEM) ? VM_FAULT_OOM : VM_FAULT_SIGBUS);
1140
1141         if (ret & VM_FAULT_MAJOR) {
1142                 count_vm_event(PGMAJFAULT);
1143                 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
1144         }
1145         return ret;
1146 }
1147
1148 int vmtruncate_range(struct inode *inode, loff_t lstart, loff_t lend)
1149 {
1150         /*
1151          * If the underlying filesystem is not going to provide
1152          * a way to truncate a range of blocks (punch a hole) -
1153          * we should return failure right now.
1154          * Only CONFIG_SHMEM shmem.c ever supported i_op->truncate_range().
1155          */
1156         if (inode->i_op->truncate_range != shmem_truncate_range)
1157                 return -ENOSYS;
1158
1159         mutex_lock(&inode->i_mutex);
1160         {
1161                 struct shmem_falloc shmem_falloc;
1162                 struct address_space *mapping = inode->i_mapping;
1163                 loff_t unmap_start = round_up(lstart, PAGE_SIZE);
1164                 loff_t unmap_end = round_down(1 + lend, PAGE_SIZE) - 1;
1165                 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
1166
1167                 shmem_falloc.waitq = &shmem_falloc_waitq;
1168                 shmem_falloc.start = unmap_start >> PAGE_SHIFT;
1169                 shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
1170                 spin_lock(&inode->i_lock);
1171                 inode->i_private = &shmem_falloc;
1172                 spin_unlock(&inode->i_lock);
1173
1174                 if ((u64)unmap_end > (u64)unmap_start)
1175                         unmap_mapping_range(mapping, unmap_start,
1176                                             1 + unmap_end - unmap_start, 0);
1177                 shmem_truncate_range(inode, lstart, lend);
1178                 /* No need to unmap again: hole-punching leaves COWed pages */
1179
1180                 spin_lock(&inode->i_lock);
1181                 inode->i_private = NULL;
1182                 wake_up_all(&shmem_falloc_waitq);
1183                 spin_unlock(&inode->i_lock);
1184         }
1185         mutex_unlock(&inode->i_mutex);
1186         return 0;
1187 }
1188 EXPORT_SYMBOL_GPL(vmtruncate_range);
1189
1190 #ifdef CONFIG_NUMA
1191 static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
1192 {
1193         struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1194         return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
1195 }
1196
1197 static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
1198                                           unsigned long addr)
1199 {
1200         struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1201         pgoff_t index;
1202
1203         index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
1204         return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
1205 }
1206 #endif
1207
1208 int shmem_lock(struct file *file, int lock, struct user_struct *user)
1209 {
1210         struct inode *inode = file->f_path.dentry->d_inode;
1211         struct shmem_inode_info *info = SHMEM_I(inode);
1212         int retval = -ENOMEM;
1213
1214         spin_lock(&info->lock);
1215         if (lock && !(info->flags & VM_LOCKED)) {
1216                 if (!user_shm_lock(inode->i_size, user))
1217                         goto out_nomem;
1218                 info->flags |= VM_LOCKED;
1219                 mapping_set_unevictable(file->f_mapping);
1220         }
1221         if (!lock && (info->flags & VM_LOCKED) && user) {
1222                 user_shm_unlock(inode->i_size, user);
1223                 info->flags &= ~VM_LOCKED;
1224                 mapping_clear_unevictable(file->f_mapping);
1225         }
1226         retval = 0;
1227
1228 out_nomem:
1229         spin_unlock(&info->lock);
1230         return retval;
1231 }
1232
1233 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
1234 {
1235         file_accessed(file);
1236         vma->vm_ops = &shmem_vm_ops;
1237         vma->vm_flags |= VM_CAN_NONLINEAR;
1238         return 0;
1239 }
1240
1241 static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
1242                                      int mode, dev_t dev, unsigned long flags)
1243 {
1244         struct inode *inode;
1245         struct shmem_inode_info *info;
1246         struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
1247
1248         if (shmem_reserve_inode(sb))
1249                 return NULL;
1250
1251         inode = new_inode(sb);
1252         if (inode) {
1253                 inode->i_ino = get_next_ino();
1254                 inode_init_owner(inode, dir, mode);
1255                 inode->i_blocks = 0;
1256                 inode->i_mapping->backing_dev_info = &shmem_backing_dev_info;
1257                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1258                 inode->i_generation = get_seconds();
1259                 info = SHMEM_I(inode);
1260                 memset(info, 0, (char *)inode - (char *)info);
1261                 spin_lock_init(&info->lock);
1262                 info->flags = flags & VM_NORESERVE;
1263                 INIT_LIST_HEAD(&info->swaplist);
1264                 INIT_LIST_HEAD(&info->xattr_list);
1265                 cache_no_acl(inode);
1266
1267                 switch (mode & S_IFMT) {
1268                 default:
1269                         inode->i_op = &shmem_special_inode_operations;
1270                         init_special_inode(inode, mode, dev);
1271                         break;
1272                 case S_IFREG:
1273                         inode->i_mapping->a_ops = &shmem_aops;
1274                         inode->i_op = &shmem_inode_operations;
1275                         inode->i_fop = &shmem_file_operations;
1276                         mpol_shared_policy_init(&info->policy,
1277                                                  shmem_get_sbmpol(sbinfo));
1278                         break;
1279                 case S_IFDIR:
1280                         inc_nlink(inode);
1281                         /* Some things misbehave if size == 0 on a directory */
1282                         inode->i_size = 2 * BOGO_DIRENT_SIZE;
1283                         inode->i_op = &shmem_dir_inode_operations;
1284                         inode->i_fop = &simple_dir_operations;
1285                         break;
1286                 case S_IFLNK:
1287                         /*
1288                          * Must not load anything in the rbtree,
1289                          * mpol_free_shared_policy will not be called.
1290                          */
1291                         mpol_shared_policy_init(&info->policy, NULL);
1292                         break;
1293                 }
1294         } else
1295                 shmem_free_inode(sb);
1296         return inode;
1297 }
1298
1299 #ifdef CONFIG_TMPFS
1300 static const struct inode_operations shmem_symlink_inode_operations;
1301 static const struct inode_operations shmem_short_symlink_operations;
1302
1303 static int
1304 shmem_write_begin(struct file *file, struct address_space *mapping,
1305                         loff_t pos, unsigned len, unsigned flags,
1306                         struct page **pagep, void **fsdata)
1307 {
1308         struct inode *inode = mapping->host;
1309         pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1310         return shmem_getpage(inode, index, pagep, SGP_WRITE, NULL);
1311 }
1312
1313 static int
1314 shmem_write_end(struct file *file, struct address_space *mapping,
1315                         loff_t pos, unsigned len, unsigned copied,
1316                         struct page *page, void *fsdata)
1317 {
1318         struct inode *inode = mapping->host;
1319
1320         if (pos + copied > inode->i_size)
1321                 i_size_write(inode, pos + copied);
1322
1323         set_page_dirty(page);
1324         unlock_page(page);
1325         page_cache_release(page);
1326
1327         return copied;
1328 }
1329
1330 static void do_shmem_file_read(struct file *filp, loff_t *ppos, read_descriptor_t *desc, read_actor_t actor)
1331 {
1332         struct inode *inode = filp->f_path.dentry->d_inode;
1333         struct address_space *mapping = inode->i_mapping;
1334         pgoff_t index;
1335         unsigned long offset;
1336         enum sgp_type sgp = SGP_READ;
1337
1338         /*
1339          * Might this read be for a stacking filesystem?  Then when reading
1340          * holes of a sparse file, we actually need to allocate those pages,
1341          * and even mark them dirty, so it cannot exceed the max_blocks limit.
1342          */
1343         if (segment_eq(get_fs(), KERNEL_DS))
1344                 sgp = SGP_DIRTY;
1345
1346         index = *ppos >> PAGE_CACHE_SHIFT;
1347         offset = *ppos & ~PAGE_CACHE_MASK;
1348
1349         for (;;) {
1350                 struct page *page = NULL;
1351                 pgoff_t end_index;
1352                 unsigned long nr, ret;
1353                 loff_t i_size = i_size_read(inode);
1354
1355                 end_index = i_size >> PAGE_CACHE_SHIFT;
1356                 if (index > end_index)
1357                         break;
1358                 if (index == end_index) {
1359                         nr = i_size & ~PAGE_CACHE_MASK;
1360                         if (nr <= offset)
1361                                 break;
1362                 }
1363
1364                 desc->error = shmem_getpage(inode, index, &page, sgp, NULL);
1365                 if (desc->error) {
1366                         if (desc->error == -EINVAL)
1367                                 desc->error = 0;
1368                         break;
1369                 }
1370                 if (page)
1371                         unlock_page(page);
1372
1373                 /*
1374                  * We must evaluate after, since reads (unlike writes)
1375                  * are called without i_mutex protection against truncate
1376                  */
1377                 nr = PAGE_CACHE_SIZE;
1378                 i_size = i_size_read(inode);
1379                 end_index = i_size >> PAGE_CACHE_SHIFT;
1380                 if (index == end_index) {
1381                         nr = i_size & ~PAGE_CACHE_MASK;
1382                         if (nr <= offset) {
1383                                 if (page)
1384                                         page_cache_release(page);
1385                                 break;
1386                         }
1387                 }
1388                 nr -= offset;
1389
1390                 if (page) {
1391                         /*
1392                          * If users can be writing to this page using arbitrary
1393                          * virtual addresses, take care about potential aliasing
1394                          * before reading the page on the kernel side.
1395                          */
1396                         if (mapping_writably_mapped(mapping))
1397                                 flush_dcache_page(page);
1398                         /*
1399                          * Mark the page accessed if we read the beginning.
1400                          */
1401                         if (!offset)
1402                                 mark_page_accessed(page);
1403                 } else {
1404                         page = ZERO_PAGE(0);
1405                         page_cache_get(page);
1406                 }
1407
1408                 /*
1409                  * Ok, we have the page, and it's up-to-date, so
1410                  * now we can copy it to user space...
1411                  *
1412                  * The actor routine returns how many bytes were actually used..
1413                  * NOTE! This may not be the same as how much of a user buffer
1414                  * we filled up (we may be padding etc), so we can only update
1415                  * "pos" here (the actor routine has to update the user buffer
1416                  * pointers and the remaining count).
1417                  */
1418                 ret = actor(desc, page, offset, nr);
1419                 offset += ret;
1420                 index += offset >> PAGE_CACHE_SHIFT;
1421                 offset &= ~PAGE_CACHE_MASK;
1422
1423                 page_cache_release(page);
1424                 if (ret != nr || !desc->count)
1425                         break;
1426
1427                 cond_resched();
1428         }
1429
1430         *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
1431         file_accessed(filp);
1432 }
1433
1434 static ssize_t shmem_file_aio_read(struct kiocb *iocb,
1435                 const struct iovec *iov, unsigned long nr_segs, loff_t pos)
1436 {
1437         struct file *filp = iocb->ki_filp;
1438         ssize_t retval;
1439         unsigned long seg;
1440         size_t count;
1441         loff_t *ppos = &iocb->ki_pos;
1442
1443         retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1444         if (retval)
1445                 return retval;
1446
1447         for (seg = 0; seg < nr_segs; seg++) {
1448                 read_descriptor_t desc;
1449
1450                 desc.written = 0;
1451                 desc.arg.buf = iov[seg].iov_base;
1452                 desc.count = iov[seg].iov_len;
1453                 if (desc.count == 0)
1454                         continue;
1455                 desc.error = 0;
1456                 do_shmem_file_read(filp, ppos, &desc, file_read_actor);
1457                 retval += desc.written;
1458                 if (desc.error) {
1459                         retval = retval ?: desc.error;
1460                         break;
1461                 }
1462                 if (desc.count > 0)
1463                         break;
1464         }
1465         return retval;
1466 }
1467
1468 static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
1469                                 struct pipe_inode_info *pipe, size_t len,
1470                                 unsigned int flags)
1471 {
1472         struct address_space *mapping = in->f_mapping;
1473         struct inode *inode = mapping->host;
1474         unsigned int loff, nr_pages, req_pages;
1475         struct page *pages[PIPE_DEF_BUFFERS];
1476         struct partial_page partial[PIPE_DEF_BUFFERS];
1477         struct page *page;
1478         pgoff_t index, end_index;
1479         loff_t isize, left;
1480         int error, page_nr;
1481         struct splice_pipe_desc spd = {
1482                 .pages = pages,
1483                 .partial = partial,
1484                 .nr_pages_max = PIPE_DEF_BUFFERS,
1485                 .flags = flags,
1486                 .ops = &page_cache_pipe_buf_ops,
1487                 .spd_release = spd_release_page,
1488         };
1489
1490         isize = i_size_read(inode);
1491         if (unlikely(*ppos >= isize))
1492                 return 0;
1493
1494         left = isize - *ppos;
1495         if (unlikely(left < len))
1496                 len = left;
1497
1498         if (splice_grow_spd(pipe, &spd))
1499                 return -ENOMEM;
1500
1501         index = *ppos >> PAGE_CACHE_SHIFT;
1502         loff = *ppos & ~PAGE_CACHE_MASK;
1503         req_pages = (len + loff + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1504         nr_pages = min(req_pages, pipe->buffers);
1505
1506         spd.nr_pages = find_get_pages_contig(mapping, index,
1507                                                 nr_pages, spd.pages);
1508         index += spd.nr_pages;
1509         error = 0;
1510
1511         while (spd.nr_pages < nr_pages) {
1512                 error = shmem_getpage(inode, index, &page, SGP_CACHE, NULL);
1513                 if (error)
1514                         break;
1515                 unlock_page(page);
1516                 spd.pages[spd.nr_pages++] = page;
1517                 index++;
1518         }
1519
1520         index = *ppos >> PAGE_CACHE_SHIFT;
1521         nr_pages = spd.nr_pages;
1522         spd.nr_pages = 0;
1523
1524         for (page_nr = 0; page_nr < nr_pages; page_nr++) {
1525                 unsigned int this_len;
1526
1527                 if (!len)
1528                         break;
1529
1530                 this_len = min_t(unsigned long, len, PAGE_CACHE_SIZE - loff);
1531                 page = spd.pages[page_nr];
1532
1533                 if (!PageUptodate(page) || page->mapping != mapping) {
1534                         error = shmem_getpage(inode, index, &page,
1535                                                         SGP_CACHE, NULL);
1536                         if (error)
1537                                 break;
1538                         unlock_page(page);
1539                         page_cache_release(spd.pages[page_nr]);
1540                         spd.pages[page_nr] = page;
1541                 }
1542
1543                 isize = i_size_read(inode);
1544                 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1545                 if (unlikely(!isize || index > end_index))
1546                         break;
1547
1548                 if (end_index == index) {
1549                         unsigned int plen;
1550
1551                         plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1552                         if (plen <= loff)
1553                                 break;
1554
1555                         this_len = min(this_len, plen - loff);
1556                         len = this_len;
1557                 }
1558
1559                 spd.partial[page_nr].offset = loff;
1560                 spd.partial[page_nr].len = this_len;
1561                 len -= this_len;
1562                 loff = 0;
1563                 spd.nr_pages++;
1564                 index++;
1565         }
1566
1567         while (page_nr < nr_pages)
1568                 page_cache_release(spd.pages[page_nr++]);
1569
1570         if (spd.nr_pages)
1571                 error = splice_to_pipe(pipe, &spd);
1572
1573         splice_shrink_spd(&spd);
1574
1575         if (error > 0) {
1576                 *ppos += error;
1577                 file_accessed(in);
1578         }
1579         return error;
1580 }
1581
1582 static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
1583 {
1584         struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
1585
1586         buf->f_type = TMPFS_MAGIC;
1587         buf->f_bsize = PAGE_CACHE_SIZE;
1588         buf->f_namelen = NAME_MAX;
1589         if (sbinfo->max_blocks) {
1590                 buf->f_blocks = sbinfo->max_blocks;
1591                 buf->f_bavail =
1592                 buf->f_bfree  = sbinfo->max_blocks -
1593                                 percpu_counter_sum(&sbinfo->used_blocks);
1594         }
1595         if (sbinfo->max_inodes) {
1596                 buf->f_files = sbinfo->max_inodes;
1597                 buf->f_ffree = sbinfo->free_inodes;
1598         }
1599         /* else leave those fields 0 like simple_statfs */
1600         return 0;
1601 }
1602
1603 /*
1604  * File creation. Allocate an inode, and we're done..
1605  */
1606 static int
1607 shmem_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
1608 {
1609         struct inode *inode;
1610         int error = -ENOSPC;
1611
1612         inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
1613         if (inode) {
1614                 error = security_inode_init_security(inode, dir,
1615                                                      &dentry->d_name,
1616                                                      NULL, NULL);
1617                 if (error) {
1618                         if (error != -EOPNOTSUPP) {
1619                                 iput(inode);
1620                                 return error;
1621                         }
1622                 }
1623 #ifdef CONFIG_TMPFS_POSIX_ACL
1624                 error = generic_acl_init(inode, dir);
1625                 if (error) {
1626                         iput(inode);
1627                         return error;
1628                 }
1629 #else
1630                 error = 0;
1631 #endif
1632                 dir->i_size += BOGO_DIRENT_SIZE;
1633                 dir->i_ctime = dir->i_mtime = CURRENT_TIME;
1634                 d_instantiate(dentry, inode);
1635                 dget(dentry); /* Extra count - pin the dentry in core */
1636         }
1637         return error;
1638 }
1639
1640 static int shmem_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1641 {
1642         int error;
1643
1644         if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
1645                 return error;
1646         inc_nlink(dir);
1647         return 0;
1648 }
1649
1650 static int shmem_create(struct inode *dir, struct dentry *dentry, int mode,
1651                 struct nameidata *nd)
1652 {
1653         return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
1654 }
1655
1656 /*
1657  * Link a file..
1658  */
1659 static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
1660 {
1661         struct inode *inode = old_dentry->d_inode;
1662         int ret;
1663
1664         /*
1665          * No ordinary (disk based) filesystem counts links as inodes;
1666          * but each new link needs a new dentry, pinning lowmem, and
1667          * tmpfs dentries cannot be pruned until they are unlinked.
1668          */
1669         ret = shmem_reserve_inode(inode->i_sb);
1670         if (ret)
1671                 goto out;
1672
1673         dir->i_size += BOGO_DIRENT_SIZE;
1674         inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
1675         inc_nlink(inode);
1676         ihold(inode);   /* New dentry reference */
1677         dget(dentry);           /* Extra pinning count for the created dentry */
1678         d_instantiate(dentry, inode);
1679 out:
1680         return ret;
1681 }
1682
1683 static int shmem_unlink(struct inode *dir, struct dentry *dentry)
1684 {
1685         struct inode *inode = dentry->d_inode;
1686
1687         if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
1688                 shmem_free_inode(inode->i_sb);
1689
1690         dir->i_size -= BOGO_DIRENT_SIZE;
1691         inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
1692         drop_nlink(inode);
1693         dput(dentry);   /* Undo the count from "create" - this does all the work */
1694         return 0;
1695 }
1696
1697 static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
1698 {
1699         if (!simple_empty(dentry))
1700                 return -ENOTEMPTY;
1701
1702         drop_nlink(dentry->d_inode);
1703         drop_nlink(dir);
1704         return shmem_unlink(dir, dentry);
1705 }
1706
1707 /*
1708  * The VFS layer already does all the dentry stuff for rename,
1709  * we just have to decrement the usage count for the target if
1710  * it exists so that the VFS layer correctly free's it when it
1711  * gets overwritten.
1712  */
1713 static int shmem_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
1714 {
1715         struct inode *inode = old_dentry->d_inode;
1716         int they_are_dirs = S_ISDIR(inode->i_mode);
1717
1718         if (!simple_empty(new_dentry))
1719                 return -ENOTEMPTY;
1720
1721         if (new_dentry->d_inode) {
1722                 (void) shmem_unlink(new_dir, new_dentry);
1723                 if (they_are_dirs) {
1724                         drop_nlink(new_dentry->d_inode);
1725                         drop_nlink(old_dir);
1726                 }
1727         } else if (they_are_dirs) {
1728                 drop_nlink(old_dir);
1729                 inc_nlink(new_dir);
1730         }
1731
1732         old_dir->i_size -= BOGO_DIRENT_SIZE;
1733         new_dir->i_size += BOGO_DIRENT_SIZE;
1734         old_dir->i_ctime = old_dir->i_mtime =
1735         new_dir->i_ctime = new_dir->i_mtime =
1736         inode->i_ctime = CURRENT_TIME;
1737         return 0;
1738 }
1739
1740 static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1741 {
1742         int error;
1743         int len;
1744         struct inode *inode;
1745         struct page *page;
1746         char *kaddr;
1747         struct shmem_inode_info *info;
1748
1749         len = strlen(symname) + 1;
1750         if (len > PAGE_CACHE_SIZE)
1751                 return -ENAMETOOLONG;
1752
1753         inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
1754         if (!inode)
1755                 return -ENOSPC;
1756
1757         error = security_inode_init_security(inode, dir, &dentry->d_name,
1758                                              NULL, NULL);
1759         if (error) {
1760                 if (error != -EOPNOTSUPP) {
1761                         iput(inode);
1762                         return error;
1763                 }
1764                 error = 0;
1765         }
1766
1767         info = SHMEM_I(inode);
1768         inode->i_size = len-1;
1769         if (len <= SHORT_SYMLINK_LEN) {
1770                 info->symlink = kmemdup(symname, len, GFP_KERNEL);
1771                 if (!info->symlink) {
1772                         iput(inode);
1773                         return -ENOMEM;
1774                 }
1775                 inode->i_op = &shmem_short_symlink_operations;
1776         } else {
1777                 error = shmem_getpage(inode, 0, &page, SGP_WRITE, NULL);
1778                 if (error) {
1779                         iput(inode);
1780                         return error;
1781                 }
1782                 inode->i_mapping->a_ops = &shmem_aops;
1783                 inode->i_op = &shmem_symlink_inode_operations;
1784                 kaddr = kmap_atomic(page, KM_USER0);
1785                 memcpy(kaddr, symname, len);
1786                 kunmap_atomic(kaddr, KM_USER0);
1787                 set_page_dirty(page);
1788                 unlock_page(page);
1789                 page_cache_release(page);
1790         }
1791         dir->i_size += BOGO_DIRENT_SIZE;
1792         dir->i_ctime = dir->i_mtime = CURRENT_TIME;
1793         d_instantiate(dentry, inode);
1794         dget(dentry);
1795         return 0;
1796 }
1797
1798 static void *shmem_follow_short_symlink(struct dentry *dentry, struct nameidata *nd)
1799 {
1800         nd_set_link(nd, SHMEM_I(dentry->d_inode)->symlink);
1801         return NULL;
1802 }
1803
1804 static void *shmem_follow_link(struct dentry *dentry, struct nameidata *nd)
1805 {
1806         struct page *page = NULL;
1807         int error = shmem_getpage(dentry->d_inode, 0, &page, SGP_READ, NULL);
1808         nd_set_link(nd, error ? ERR_PTR(error) : kmap(page));
1809         if (page)
1810                 unlock_page(page);
1811         return page;
1812 }
1813
1814 static void shmem_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
1815 {
1816         if (!IS_ERR(nd_get_link(nd))) {
1817                 struct page *page = cookie;
1818                 kunmap(page);
1819                 mark_page_accessed(page);
1820                 page_cache_release(page);
1821         }
1822 }
1823
1824 #ifdef CONFIG_TMPFS_XATTR
1825 /*
1826  * Superblocks without xattr inode operations may get some security.* xattr
1827  * support from the LSM "for free". As soon as we have any other xattrs
1828  * like ACLs, we also need to implement the security.* handlers at
1829  * filesystem level, though.
1830  */
1831
1832 static int shmem_xattr_get(struct dentry *dentry, const char *name,
1833                            void *buffer, size_t size)
1834 {
1835         struct shmem_inode_info *info;
1836         struct shmem_xattr *xattr;
1837         int ret = -ENODATA;
1838
1839         info = SHMEM_I(dentry->d_inode);
1840
1841         spin_lock(&info->lock);
1842         list_for_each_entry(xattr, &info->xattr_list, list) {
1843                 if (strcmp(name, xattr->name))
1844                         continue;
1845
1846                 ret = xattr->size;
1847                 if (buffer) {
1848                         if (size < xattr->size)
1849                                 ret = -ERANGE;
1850                         else
1851                                 memcpy(buffer, xattr->value, xattr->size);
1852                 }
1853                 break;
1854         }
1855         spin_unlock(&info->lock);
1856         return ret;
1857 }
1858
1859 static int shmem_xattr_set(struct dentry *dentry, const char *name,
1860                            const void *value, size_t size, int flags)
1861 {
1862         struct inode *inode = dentry->d_inode;
1863         struct shmem_inode_info *info = SHMEM_I(inode);
1864         struct shmem_xattr *xattr;
1865         struct shmem_xattr *new_xattr = NULL;
1866         size_t len;
1867         int err = 0;
1868
1869         /* value == NULL means remove */
1870         if (value) {
1871                 /* wrap around? */
1872                 len = sizeof(*new_xattr) + size;
1873                 if (len <= sizeof(*new_xattr))
1874                         return -ENOMEM;
1875
1876                 new_xattr = kmalloc(len, GFP_KERNEL);
1877                 if (!new_xattr)
1878                         return -ENOMEM;
1879
1880                 new_xattr->name = kstrdup(name, GFP_KERNEL);
1881                 if (!new_xattr->name) {
1882                         kfree(new_xattr);
1883                         return -ENOMEM;
1884                 }
1885
1886                 new_xattr->size = size;
1887                 memcpy(new_xattr->value, value, size);
1888         }
1889
1890         spin_lock(&info->lock);
1891         list_for_each_entry(xattr, &info->xattr_list, list) {
1892                 if (!strcmp(name, xattr->name)) {
1893                         if (flags & XATTR_CREATE) {
1894                                 xattr = new_xattr;
1895                                 err = -EEXIST;
1896                         } else if (new_xattr) {
1897                                 list_replace(&xattr->list, &new_xattr->list);
1898                         } else {
1899                                 list_del(&xattr->list);
1900                         }
1901                         goto out;
1902                 }
1903         }
1904         if (flags & XATTR_REPLACE) {
1905                 xattr = new_xattr;
1906                 err = -ENODATA;
1907         } else {
1908                 list_add(&new_xattr->list, &info->xattr_list);
1909                 xattr = NULL;
1910         }
1911 out:
1912         spin_unlock(&info->lock);
1913         if (xattr)
1914                 kfree(xattr->name);
1915         kfree(xattr);
1916         return err;
1917 }
1918
1919 static const struct xattr_handler *shmem_xattr_handlers[] = {
1920 #ifdef CONFIG_TMPFS_POSIX_ACL
1921         &generic_acl_access_handler,
1922         &generic_acl_default_handler,
1923 #endif
1924         NULL
1925 };
1926
1927 static int shmem_xattr_validate(const char *name)
1928 {
1929         struct { const char *prefix; size_t len; } arr[] = {
1930                 { XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN },
1931                 { XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN }
1932         };
1933         int i;
1934
1935         for (i = 0; i < ARRAY_SIZE(arr); i++) {
1936                 size_t preflen = arr[i].len;
1937                 if (strncmp(name, arr[i].prefix, preflen) == 0) {
1938                         if (!name[preflen])
1939                                 return -EINVAL;
1940                         return 0;
1941                 }
1942         }
1943         return -EOPNOTSUPP;
1944 }
1945
1946 static ssize_t shmem_getxattr(struct dentry *dentry, const char *name,
1947                               void *buffer, size_t size)
1948 {
1949         int err;
1950
1951         /*
1952          * If this is a request for a synthetic attribute in the system.*
1953          * namespace use the generic infrastructure to resolve a handler
1954          * for it via sb->s_xattr.
1955          */
1956         if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
1957                 return generic_getxattr(dentry, name, buffer, size);
1958
1959         err = shmem_xattr_validate(name);
1960         if (err)
1961                 return err;
1962
1963         return shmem_xattr_get(dentry, name, buffer, size);
1964 }
1965
1966 static int shmem_setxattr(struct dentry *dentry, const char *name,
1967                           const void *value, size_t size, int flags)
1968 {
1969         int err;
1970
1971         /*
1972          * If this is a request for a synthetic attribute in the system.*
1973          * namespace use the generic infrastructure to resolve a handler
1974          * for it via sb->s_xattr.
1975          */
1976         if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
1977                 return generic_setxattr(dentry, name, value, size, flags);
1978
1979         err = shmem_xattr_validate(name);
1980         if (err)
1981                 return err;
1982
1983         if (size == 0)
1984                 value = "";  /* empty EA, do not remove */
1985
1986         return shmem_xattr_set(dentry, name, value, size, flags);
1987
1988 }
1989
1990 static int shmem_removexattr(struct dentry *dentry, const char *name)
1991 {
1992         int err;
1993
1994         /*
1995          * If this is a request for a synthetic attribute in the system.*
1996          * namespace use the generic infrastructure to resolve a handler
1997          * for it via sb->s_xattr.
1998          */
1999         if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
2000                 return generic_removexattr(dentry, name);
2001
2002         err = shmem_xattr_validate(name);
2003         if (err)
2004                 return err;
2005
2006         return shmem_xattr_set(dentry, name, NULL, 0, XATTR_REPLACE);
2007 }
2008
2009 static bool xattr_is_trusted(const char *name)
2010 {
2011         return !strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN);
2012 }
2013
2014 static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
2015 {
2016         bool trusted = capable(CAP_SYS_ADMIN);
2017         struct shmem_xattr *xattr;
2018         struct shmem_inode_info *info;
2019         size_t used = 0;
2020
2021         info = SHMEM_I(dentry->d_inode);
2022
2023         spin_lock(&info->lock);
2024         list_for_each_entry(xattr, &info->xattr_list, list) {
2025                 size_t len;
2026
2027                 /* skip "trusted." attributes for unprivileged callers */
2028                 if (!trusted && xattr_is_trusted(xattr->name))
2029                         continue;
2030
2031                 len = strlen(xattr->name) + 1;
2032                 used += len;
2033                 if (buffer) {
2034                         if (size < used) {
2035                                 used = -ERANGE;
2036                                 break;
2037                         }
2038                         memcpy(buffer, xattr->name, len);
2039                         buffer += len;
2040                 }
2041         }
2042         spin_unlock(&info->lock);
2043
2044         return used;
2045 }
2046 #endif /* CONFIG_TMPFS_XATTR */
2047
2048 static const struct inode_operations shmem_short_symlink_operations = {
2049         .readlink       = generic_readlink,
2050         .follow_link    = shmem_follow_short_symlink,
2051 #ifdef CONFIG_TMPFS_XATTR
2052         .setxattr       = shmem_setxattr,
2053         .getxattr       = shmem_getxattr,
2054         .listxattr      = shmem_listxattr,
2055         .removexattr    = shmem_removexattr,
2056 #endif
2057 };
2058
2059 static const struct inode_operations shmem_symlink_inode_operations = {
2060         .readlink       = generic_readlink,
2061         .follow_link    = shmem_follow_link,
2062         .put_link       = shmem_put_link,
2063 #ifdef CONFIG_TMPFS_XATTR
2064         .setxattr       = shmem_setxattr,
2065         .getxattr       = shmem_getxattr,
2066         .listxattr      = shmem_listxattr,
2067         .removexattr    = shmem_removexattr,
2068 #endif
2069 };
2070
2071 static struct dentry *shmem_get_parent(struct dentry *child)
2072 {
2073         return ERR_PTR(-ESTALE);
2074 }
2075
2076 static int shmem_match(struct inode *ino, void *vfh)
2077 {
2078         __u32 *fh = vfh;
2079         __u64 inum = fh[2];
2080         inum = (inum << 32) | fh[1];
2081         return ino->i_ino == inum && fh[0] == ino->i_generation;
2082 }
2083
2084 static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
2085                 struct fid *fid, int fh_len, int fh_type)
2086 {
2087         struct inode *inode;
2088         struct dentry *dentry = NULL;
2089         u64 inum;
2090
2091         if (fh_len < 3)
2092                 return NULL;
2093
2094         inum = fid->raw[2];
2095         inum = (inum << 32) | fid->raw[1];
2096
2097         inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
2098                         shmem_match, fid->raw);
2099         if (inode) {
2100                 dentry = d_find_alias(inode);
2101                 iput(inode);
2102         }
2103
2104         return dentry;
2105 }
2106
2107 static int shmem_encode_fh(struct dentry *dentry, __u32 *fh, int *len,
2108                                 int connectable)
2109 {
2110         struct inode *inode = dentry->d_inode;
2111
2112         if (*len < 3) {
2113                 *len = 3;
2114                 return 255;
2115         }
2116
2117         if (inode_unhashed(inode)) {
2118                 /* Unfortunately insert_inode_hash is not idempotent,
2119                  * so as we hash inodes here rather than at creation
2120                  * time, we need a lock to ensure we only try
2121                  * to do it once
2122                  */
2123                 static DEFINE_SPINLOCK(lock);
2124                 spin_lock(&lock);
2125                 if (inode_unhashed(inode))
2126                         __insert_inode_hash(inode,
2127                                             inode->i_ino + inode->i_generation);
2128                 spin_unlock(&lock);
2129         }
2130
2131         fh[0] = inode->i_generation;
2132         fh[1] = inode->i_ino;
2133         fh[2] = ((__u64)inode->i_ino) >> 32;
2134
2135         *len = 3;
2136         return 1;
2137 }
2138
2139 static const struct export_operations shmem_export_ops = {
2140         .get_parent     = shmem_get_parent,
2141         .encode_fh      = shmem_encode_fh,
2142         .fh_to_dentry   = shmem_fh_to_dentry,
2143 };
2144
2145 static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
2146                                bool remount)
2147 {
2148         char *this_char, *value, *rest;
2149
2150         while (options != NULL) {
2151                 this_char = options;
2152                 for (;;) {
2153                         /*
2154                          * NUL-terminate this option: unfortunately,
2155                          * mount options form a comma-separated list,
2156                          * but mpol's nodelist may also contain commas.
2157                          */
2158                         options = strchr(options, ',');
2159                         if (options == NULL)
2160                                 break;
2161                         options++;
2162                         if (!isdigit(*options)) {
2163                                 options[-1] = '\0';
2164                                 break;
2165                         }
2166                 }
2167                 if (!*this_char)
2168                         continue;
2169                 if ((value = strchr(this_char,'=')) != NULL) {
2170                         *value++ = 0;
2171                 } else {
2172                         printk(KERN_ERR
2173                             "tmpfs: No value for mount option '%s'\n",
2174                             this_char);
2175                         return 1;
2176                 }
2177
2178                 if (!strcmp(this_char,"size")) {
2179                         unsigned long long size;
2180                         size = memparse(value,&rest);
2181                         if (*rest == '%') {
2182                                 size <<= PAGE_SHIFT;
2183                                 size *= totalram_pages;
2184                                 do_div(size, 100);
2185                                 rest++;
2186                         }
2187                         if (*rest)
2188                                 goto bad_val;
2189                         sbinfo->max_blocks =
2190                                 DIV_ROUND_UP(size, PAGE_CACHE_SIZE);
2191                 } else if (!strcmp(this_char,"nr_blocks")) {
2192                         sbinfo->max_blocks = memparse(value, &rest);
2193                         if (*rest)
2194                                 goto bad_val;
2195                 } else if (!strcmp(this_char,"nr_inodes")) {
2196                         sbinfo->max_inodes = memparse(value, &rest);
2197                         if (*rest)
2198                                 goto bad_val;
2199                 } else if (!strcmp(this_char,"mode")) {
2200                         if (remount)
2201                                 continue;
2202                         sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
2203                         if (*rest)
2204                                 goto bad_val;
2205                 } else if (!strcmp(this_char,"uid")) {
2206                         if (remount)
2207                                 continue;
2208                         sbinfo->uid = simple_strtoul(value, &rest, 0);
2209                         if (*rest)
2210                                 goto bad_val;
2211                 } else if (!strcmp(this_char,"gid")) {
2212                         if (remount)
2213                                 continue;
2214                         sbinfo->gid = simple_strtoul(value, &rest, 0);
2215                         if (*rest)
2216                                 goto bad_val;
2217                 } else if (!strcmp(this_char,"mpol")) {
2218                         if (mpol_parse_str(value, &sbinfo->mpol, 1))
2219                                 goto bad_val;
2220                 } else {
2221                         printk(KERN_ERR "tmpfs: Bad mount option %s\n",
2222                                this_char);
2223                         return 1;
2224                 }
2225         }
2226         return 0;
2227
2228 bad_val:
2229         printk(KERN_ERR "tmpfs: Bad value '%s' for mount option '%s'\n",
2230                value, this_char);
2231         return 1;
2232
2233 }
2234
2235 static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
2236 {
2237         struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2238         struct shmem_sb_info config = *sbinfo;
2239         unsigned long inodes;
2240         int error = -EINVAL;
2241
2242         config.mpol = NULL;
2243         if (shmem_parse_options(data, &config, true))
2244                 return error;
2245
2246         spin_lock(&sbinfo->stat_lock);
2247         inodes = sbinfo->max_inodes - sbinfo->free_inodes;
2248         if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
2249                 goto out;
2250         if (config.max_inodes < inodes)
2251                 goto out;
2252         /*
2253          * Those tests disallow limited->unlimited while any are in use;
2254          * but we must separately disallow unlimited->limited, because
2255          * in that case we have no record of how much is already in use.
2256          */
2257         if (config.max_blocks && !sbinfo->max_blocks)
2258                 goto out;
2259         if (config.max_inodes && !sbinfo->max_inodes)
2260                 goto out;
2261
2262         error = 0;
2263         sbinfo->max_blocks  = config.max_blocks;
2264         sbinfo->max_inodes  = config.max_inodes;
2265         sbinfo->free_inodes = config.max_inodes - inodes;
2266
2267         /*
2268          * Preserve previous mempolicy unless mpol remount option was specified.
2269          */
2270         if (config.mpol) {
2271                 mpol_put(sbinfo->mpol);
2272                 sbinfo->mpol = config.mpol;     /* transfers initial ref */
2273         }
2274 out:
2275         spin_unlock(&sbinfo->stat_lock);
2276         return error;
2277 }
2278
2279 static int shmem_show_options(struct seq_file *seq, struct vfsmount *vfs)
2280 {
2281         struct shmem_sb_info *sbinfo = SHMEM_SB(vfs->mnt_sb);
2282
2283         if (sbinfo->max_blocks != shmem_default_max_blocks())
2284                 seq_printf(seq, ",size=%luk",
2285                         sbinfo->max_blocks << (PAGE_CACHE_SHIFT - 10));
2286         if (sbinfo->max_inodes != shmem_default_max_inodes())
2287                 seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
2288         if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
2289                 seq_printf(seq, ",mode=%03o", sbinfo->mode);
2290         if (sbinfo->uid != 0)
2291                 seq_printf(seq, ",uid=%u", sbinfo->uid);
2292         if (sbinfo->gid != 0)
2293                 seq_printf(seq, ",gid=%u", sbinfo->gid);
2294         shmem_show_mpol(seq, sbinfo->mpol);
2295         return 0;
2296 }
2297 #endif /* CONFIG_TMPFS */
2298
2299 static void shmem_put_super(struct super_block *sb)
2300 {
2301         struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
2302
2303         percpu_counter_destroy(&sbinfo->used_blocks);
2304         kfree(sbinfo);
2305         sb->s_fs_info = NULL;
2306 }
2307
2308 int shmem_fill_super(struct super_block *sb, void *data, int silent)
2309 {
2310         struct inode *inode;
2311         struct dentry *root;
2312         struct shmem_sb_info *sbinfo;
2313         int err = -ENOMEM;
2314
2315         /* Round up to L1_CACHE_BYTES to resist false sharing */
2316         sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
2317                                 L1_CACHE_BYTES), GFP_KERNEL);
2318         if (!sbinfo)
2319                 return -ENOMEM;
2320
2321         sbinfo->mode = S_IRWXUGO | S_ISVTX;
2322         sbinfo->uid = current_fsuid();
2323         sbinfo->gid = current_fsgid();
2324         sb->s_fs_info = sbinfo;
2325
2326 #ifdef CONFIG_TMPFS
2327         /*
2328          * Per default we only allow half of the physical ram per
2329          * tmpfs instance, limiting inodes to one per page of lowmem;
2330          * but the internal instance is left unlimited.
2331          */
2332         if (!(sb->s_flags & MS_NOUSER)) {
2333                 sbinfo->max_blocks = shmem_default_max_blocks();
2334                 sbinfo->max_inodes = shmem_default_max_inodes();
2335                 if (shmem_parse_options(data, sbinfo, false)) {
2336                         err = -EINVAL;
2337                         goto failed;
2338                 }
2339         }
2340         sb->s_export_op = &shmem_export_ops;
2341 #else
2342         sb->s_flags |= MS_NOUSER;
2343 #endif
2344
2345         spin_lock_init(&sbinfo->stat_lock);
2346         if (percpu_counter_init(&sbinfo->used_blocks, 0))
2347                 goto failed;
2348         sbinfo->free_inodes = sbinfo->max_inodes;
2349
2350         sb->s_maxbytes = MAX_LFS_FILESIZE;
2351         sb->s_blocksize = PAGE_CACHE_SIZE;
2352         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2353         sb->s_magic = TMPFS_MAGIC;
2354         sb->s_op = &shmem_ops;
2355         sb->s_time_gran = 1;
2356 #ifdef CONFIG_TMPFS_XATTR
2357         sb->s_xattr = shmem_xattr_handlers;
2358 #endif
2359 #ifdef CONFIG_TMPFS_POSIX_ACL
2360         sb->s_flags |= MS_POSIXACL;
2361 #endif
2362
2363         inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
2364         if (!inode)
2365                 goto failed;
2366         inode->i_uid = sbinfo->uid;
2367         inode->i_gid = sbinfo->gid;
2368         root = d_alloc_root(inode);
2369         if (!root)
2370                 goto failed_iput;
2371         sb->s_root = root;
2372         return 0;
2373
2374 failed_iput:
2375         iput(inode);
2376 failed:
2377         shmem_put_super(sb);
2378         return err;
2379 }
2380
2381 static struct kmem_cache *shmem_inode_cachep;
2382
2383 static struct inode *shmem_alloc_inode(struct super_block *sb)
2384 {
2385         struct shmem_inode_info *info;
2386         info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
2387         if (!info)
2388                 return NULL;
2389         return &info->vfs_inode;
2390 }
2391
2392 static void shmem_destroy_callback(struct rcu_head *head)
2393 {
2394         struct inode *inode = container_of(head, struct inode, i_rcu);
2395         INIT_LIST_HEAD(&inode->i_dentry);
2396         kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
2397 }
2398
2399 static void shmem_destroy_inode(struct inode *inode)
2400 {
2401         if ((inode->i_mode & S_IFMT) == S_IFREG)
2402                 mpol_free_shared_policy(&SHMEM_I(inode)->policy);
2403         call_rcu(&inode->i_rcu, shmem_destroy_callback);
2404 }
2405
2406 static void shmem_init_inode(void *foo)
2407 {
2408         struct shmem_inode_info *info = foo;
2409         inode_init_once(&info->vfs_inode);
2410 }
2411
2412 static int shmem_init_inodecache(void)
2413 {
2414         shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
2415                                 sizeof(struct shmem_inode_info),
2416                                 0, SLAB_PANIC, shmem_init_inode);
2417         return 0;
2418 }
2419
2420 static void shmem_destroy_inodecache(void)
2421 {
2422         kmem_cache_destroy(shmem_inode_cachep);
2423 }
2424
2425 static const struct address_space_operations shmem_aops = {
2426         .writepage      = shmem_writepage,
2427         .set_page_dirty = __set_page_dirty_no_writeback,
2428 #ifdef CONFIG_TMPFS
2429         .write_begin    = shmem_write_begin,
2430         .write_end      = shmem_write_end,
2431 #endif
2432         .migratepage    = migrate_page,
2433         .error_remove_page = generic_error_remove_page,
2434 };
2435
2436 static const struct file_operations shmem_file_operations = {
2437         .mmap           = shmem_mmap,
2438 #ifdef CONFIG_TMPFS
2439         .llseek         = generic_file_llseek,
2440         .read           = do_sync_read,
2441         .write          = do_sync_write,
2442         .aio_read       = shmem_file_aio_read,
2443         .aio_write      = generic_file_aio_write,
2444         .fsync          = noop_fsync,
2445         .splice_read    = shmem_file_splice_read,
2446         .splice_write   = generic_file_splice_write,
2447 #endif
2448 };
2449
2450 static const struct inode_operations shmem_inode_operations = {
2451         .setattr        = shmem_setattr,
2452         .truncate_range = shmem_truncate_range,
2453 #ifdef CONFIG_TMPFS_XATTR
2454         .setxattr       = shmem_setxattr,
2455         .getxattr       = shmem_getxattr,
2456         .listxattr      = shmem_listxattr,
2457         .removexattr    = shmem_removexattr,
2458 #endif
2459 };
2460
2461 static const struct inode_operations shmem_dir_inode_operations = {
2462 #ifdef CONFIG_TMPFS
2463         .create         = shmem_create,
2464         .lookup         = simple_lookup,
2465         .link           = shmem_link,
2466         .unlink         = shmem_unlink,
2467         .symlink        = shmem_symlink,
2468         .mkdir          = shmem_mkdir,
2469         .rmdir          = shmem_rmdir,
2470         .mknod          = shmem_mknod,
2471         .rename         = shmem_rename,
2472 #endif
2473 #ifdef CONFIG_TMPFS_XATTR
2474         .setxattr       = shmem_setxattr,
2475         .getxattr       = shmem_getxattr,
2476         .listxattr      = shmem_listxattr,
2477         .removexattr    = shmem_removexattr,
2478 #endif
2479 #ifdef CONFIG_TMPFS_POSIX_ACL
2480         .setattr        = shmem_setattr,
2481 #endif
2482 };
2483
2484 static const struct inode_operations shmem_special_inode_operations = {
2485 #ifdef CONFIG_TMPFS_XATTR
2486         .setxattr       = shmem_setxattr,
2487         .getxattr       = shmem_getxattr,
2488         .listxattr      = shmem_listxattr,
2489         .removexattr    = shmem_removexattr,
2490 #endif
2491 #ifdef CONFIG_TMPFS_POSIX_ACL
2492         .setattr        = shmem_setattr,
2493 #endif
2494 };
2495
2496 static const struct super_operations shmem_ops = {
2497         .alloc_inode    = shmem_alloc_inode,
2498         .destroy_inode  = shmem_destroy_inode,
2499 #ifdef CONFIG_TMPFS
2500         .statfs         = shmem_statfs,
2501         .remount_fs     = shmem_remount_fs,
2502         .show_options   = shmem_show_options,
2503 #endif
2504         .evict_inode    = shmem_evict_inode,
2505         .drop_inode     = generic_delete_inode,
2506         .put_super      = shmem_put_super,
2507 };
2508
2509 static const struct vm_operations_struct shmem_vm_ops = {
2510         .fault          = shmem_fault,
2511 #ifdef CONFIG_NUMA
2512         .set_policy     = shmem_set_policy,
2513         .get_policy     = shmem_get_policy,
2514 #endif
2515 };
2516
2517 static struct dentry *shmem_mount(struct file_system_type *fs_type,
2518         int flags, const char *dev_name, void *data)
2519 {
2520         return mount_nodev(fs_type, flags, data, shmem_fill_super);
2521 }
2522
2523 static struct file_system_type shmem_fs_type = {
2524         .owner          = THIS_MODULE,
2525         .name           = "tmpfs",
2526         .mount          = shmem_mount,
2527         .kill_sb        = kill_litter_super,
2528 };
2529
2530 int __init shmem_init(void)
2531 {
2532         int error;
2533
2534         error = bdi_init(&shmem_backing_dev_info);
2535         if (error)
2536                 goto out4;
2537
2538         error = shmem_init_inodecache();
2539         if (error)
2540                 goto out3;
2541
2542         error = register_filesystem(&shmem_fs_type);
2543         if (error) {
2544                 printk(KERN_ERR "Could not register tmpfs\n");
2545                 goto out2;
2546         }
2547
2548         shm_mnt = vfs_kern_mount(&shmem_fs_type, MS_NOUSER,
2549                                  shmem_fs_type.name, NULL);
2550         if (IS_ERR(shm_mnt)) {
2551                 error = PTR_ERR(shm_mnt);
2552                 printk(KERN_ERR "Could not kern_mount tmpfs\n");
2553                 goto out1;
2554         }
2555         return 0;
2556
2557 out1:
2558         unregister_filesystem(&shmem_fs_type);
2559 out2:
2560         shmem_destroy_inodecache();
2561 out3:
2562         bdi_destroy(&shmem_backing_dev_info);
2563 out4:
2564         shm_mnt = ERR_PTR(error);
2565         return error;
2566 }
2567
2568 #else /* !CONFIG_SHMEM */
2569
2570 /*
2571  * tiny-shmem: simple shmemfs and tmpfs using ramfs code
2572  *
2573  * This is intended for small system where the benefits of the full
2574  * shmem code (swap-backed and resource-limited) are outweighed by
2575  * their complexity. On systems without swap this code should be
2576  * effectively equivalent, but much lighter weight.
2577  */
2578
2579 #include <linux/ramfs.h>
2580
2581 static struct file_system_type shmem_fs_type = {
2582         .name           = "tmpfs",
2583         .mount          = ramfs_mount,
2584         .kill_sb        = kill_litter_super,
2585 };
2586
2587 int __init shmem_init(void)
2588 {
2589         BUG_ON(register_filesystem(&shmem_fs_type) != 0);
2590
2591         shm_mnt = kern_mount(&shmem_fs_type);
2592         BUG_ON(IS_ERR(shm_mnt));
2593
2594         return 0;
2595 }
2596
2597 int shmem_unuse(swp_entry_t swap, struct page *page)
2598 {
2599         return 0;
2600 }
2601
2602 int shmem_lock(struct file *file, int lock, struct user_struct *user)
2603 {
2604         return 0;
2605 }
2606
2607 void shmem_unlock_mapping(struct address_space *mapping)
2608 {
2609 }
2610
2611 void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
2612 {
2613         truncate_inode_pages_range(inode->i_mapping, lstart, lend);
2614 }
2615 EXPORT_SYMBOL_GPL(shmem_truncate_range);
2616
2617 int vmtruncate_range(struct inode *inode, loff_t lstart, loff_t lend)
2618 {
2619         /* Only CONFIG_SHMEM shmem.c ever supported i_op->truncate_range(). */
2620         return -ENOSYS;
2621 }
2622
2623 #define shmem_vm_ops                            generic_file_vm_ops
2624 #define shmem_file_operations                   ramfs_file_operations
2625 #define shmem_get_inode(sb, dir, mode, dev, flags)      ramfs_get_inode(sb, dir, mode, dev)
2626 #define shmem_acct_size(flags, size)            0
2627 #define shmem_unacct_size(flags, size)          do {} while (0)
2628
2629 #endif /* CONFIG_SHMEM */
2630
2631 /* common code */
2632
2633 /**
2634  * shmem_file_setup - get an unlinked file living in tmpfs
2635  * @name: name for dentry (to be seen in /proc/<pid>/maps
2636  * @size: size to be set for the file
2637  * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
2638  */
2639 struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
2640 {
2641         int error;
2642         struct file *file;
2643         struct inode *inode;
2644         struct path path;
2645         struct dentry *root;
2646         struct qstr this;
2647
2648         if (IS_ERR(shm_mnt))
2649                 return (void *)shm_mnt;
2650
2651         if (size < 0 || size > MAX_LFS_FILESIZE)
2652                 return ERR_PTR(-EINVAL);
2653
2654         if (shmem_acct_size(flags, size))
2655                 return ERR_PTR(-ENOMEM);
2656
2657         error = -ENOMEM;
2658         this.name = name;
2659         this.len = strlen(name);
2660         this.hash = 0; /* will go */
2661         root = shm_mnt->mnt_root;
2662         path.dentry = d_alloc(root, &this);
2663         if (!path.dentry)
2664                 goto put_memory;
2665         path.mnt = mntget(shm_mnt);
2666
2667         error = -ENOSPC;
2668         inode = shmem_get_inode(root->d_sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
2669         if (!inode)
2670                 goto put_dentry;
2671
2672         d_instantiate(path.dentry, inode);
2673         inode->i_size = size;
2674         clear_nlink(inode);     /* It is unlinked */
2675 #ifndef CONFIG_MMU
2676         error = ramfs_nommu_expand_for_mapping(inode, size);
2677         if (error)
2678                 goto put_dentry;
2679 #endif
2680
2681         error = -ENFILE;
2682         file = alloc_file(&path, FMODE_WRITE | FMODE_READ,
2683                   &shmem_file_operations);
2684         if (!file)
2685                 goto put_dentry;
2686
2687         return file;
2688
2689 put_dentry:
2690         path_put(&path);
2691 put_memory:
2692         shmem_unacct_size(flags, size);
2693         return ERR_PTR(error);
2694 }
2695 EXPORT_SYMBOL_GPL(shmem_file_setup);
2696
2697 /**
2698  * shmem_zero_setup - setup a shared anonymous mapping
2699  * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
2700  */
2701 int shmem_zero_setup(struct vm_area_struct *vma)
2702 {
2703         struct file *file;
2704         loff_t size = vma->vm_end - vma->vm_start;
2705
2706         file = shmem_file_setup("dev/zero", size, vma->vm_flags);
2707         if (IS_ERR(file))
2708                 return PTR_ERR(file);
2709
2710         if (vma->vm_file)
2711                 fput(vma->vm_file);
2712         vma->vm_file = file;
2713         vma->vm_ops = &shmem_vm_ops;
2714         vma->vm_flags |= VM_CAN_NONLINEAR;
2715         return 0;
2716 }
2717 EXPORT_SYMBOL_GPL(shmem_zero_setup);
2718
2719 /**
2720  * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
2721  * @mapping:    the page's address_space
2722  * @index:      the page index
2723  * @gfp:        the page allocator flags to use if allocating
2724  *
2725  * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
2726  * with any new page allocations done using the specified allocation flags.
2727  * But read_cache_page_gfp() uses the ->readpage() method: which does not
2728  * suit tmpfs, since it may have pages in swapcache, and needs to find those
2729  * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
2730  *
2731  * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
2732  * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
2733  */
2734 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
2735                                          pgoff_t index, gfp_t gfp)
2736 {
2737 #ifdef CONFIG_SHMEM
2738         struct inode *inode = mapping->host;
2739         struct page *page;
2740         int error;
2741
2742         BUG_ON(mapping->a_ops != &shmem_aops);
2743         error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE, gfp, NULL);
2744         if (error)
2745                 page = ERR_PTR(error);
2746         else
2747                 unlock_page(page);
2748         return page;
2749 #else
2750         /*
2751          * The tiny !SHMEM case uses ramfs without swap
2752          */
2753         return read_cache_page_gfp(mapping, index, gfp);
2754 #endif
2755 }
2756 EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);