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