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