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