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