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