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