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