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