shmem.c 64.5 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3 4 5 6 7 8
/*
 * Resizable virtual memory filesystem for Linux.
 *
 * Copyright (C) 2000 Linus Torvalds.
 *		 2000 Transmeta Corp.
 *		 2000-2001 Christoph Rohland
 *		 2000-2001 SAP AG
 *		 2002 Red Hat Inc.
9 10
 * Copyright (C) 2002-2005 Hugh Dickins.
 * Copyright (C) 2002-2005 VERITAS Software Corporation.
Linus Torvalds's avatar
Linus Torvalds committed
11 12 13 14 15 16
 * Copyright (C) 2004 Andi Kleen, SuSE Labs
 *
 * Extended attribute support for tmpfs:
 * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
 * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
 *
17 18 19
 * tiny-shmem:
 * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
 *
Linus Torvalds's avatar
Linus Torvalds committed
20 21 22
 * This file is released under the GPL.
 */

23 24 25 26
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/vfs.h>
#include <linux/mount.h>
Hugh Dickins's avatar
Hugh Dickins committed
27
#include <linux/pagemap.h>
28 29 30 31 32 33 34 35
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/swap.h>

static struct vfsmount *shm_mnt;

#ifdef CONFIG_SHMEM
Linus Torvalds's avatar
Linus Torvalds committed
36 37 38 39 40 41
/*
 * This virtual memory filesystem is heavily based on the ramfs. It
 * extends ramfs by the ability to use swap and honor resource limits
 * which makes it a completely usable filesystem.
 */

42
#include <linux/xattr.h>
43
#include <linux/exportfs.h>
44
#include <linux/posix_acl.h>
45
#include <linux/generic_acl.h>
Linus Torvalds's avatar
Linus Torvalds committed
46 47 48 49 50 51 52
#include <linux/mman.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/backing-dev.h>
#include <linux/shmem_fs.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
53
#include <linux/pagevec.h>
54
#include <linux/percpu_counter.h>
55
#include <linux/splice.h>
Linus Torvalds's avatar
Linus Torvalds committed
56 57 58 59
#include <linux/security.h>
#include <linux/swapops.h>
#include <linux/mempolicy.h>
#include <linux/namei.h>
60
#include <linux/ctype.h>
61
#include <linux/migrate.h>
62
#include <linux/highmem.h>
63
#include <linux/seq_file.h>
Mimi Zohar's avatar
Mimi Zohar committed
64
#include <linux/magic.h>
65

Linus Torvalds's avatar
Linus Torvalds committed
66 67 68
#include <asm/uaccess.h>
#include <asm/pgtable.h>

Hugh Dickins's avatar
Hugh Dickins committed
69
#define BLOCKS_PER_PAGE  (PAGE_CACHE_SIZE/512)
Linus Torvalds's avatar
Linus Torvalds committed
70 71 72 73 74
#define VM_ACCT(size)    (PAGE_CACHE_ALIGN(size) >> PAGE_SHIFT)

/* Pretend that each entry is of this size in directory's i_size */
#define BOGO_DIRENT_SIZE 20

75 76 77 78 79 80 81
struct shmem_xattr {
	struct list_head list;	/* anchored by shmem_inode_info->xattr_list */
	char *name;		/* xattr name */
	size_t size;
	char value[0];
};

82
/* Flag allocation requirements to shmem_getpage */
Linus Torvalds's avatar
Linus Torvalds committed
83 84 85
enum sgp_type {
	SGP_READ,	/* don't exceed i_size, don't allocate page */
	SGP_CACHE,	/* don't exceed i_size, may allocate page */
86
	SGP_DIRTY,	/* like SGP_CACHE, but set new page dirty */
Linus Torvalds's avatar
Linus Torvalds committed
87 88 89
	SGP_WRITE,	/* may exceed i_size, may allocate page */
};

Andrew Morton's avatar
Andrew Morton committed
90
#ifdef CONFIG_TMPFS
91 92 93 94 95 96 97 98 99
static unsigned long shmem_default_max_blocks(void)
{
	return totalram_pages / 2;
}

static unsigned long shmem_default_max_inodes(void)
{
	return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
}
Andrew Morton's avatar
Andrew Morton committed
100
#endif
101

102 103 104 105 106 107 108 109 110
static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
	struct page **pagep, enum sgp_type sgp, gfp_t gfp, int *fault_type);

static inline int shmem_getpage(struct inode *inode, pgoff_t index,
	struct page **pagep, enum sgp_type sgp, int *fault_type)
{
	return shmem_getpage_gfp(inode, index, pagep, sgp,
			mapping_gfp_mask(inode->i_mapping), fault_type);
}
Linus Torvalds's avatar
Linus Torvalds committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124

static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
{
	return sb->s_fs_info;
}

/*
 * shmem_file_setup pre-accounts the whole fixed size of a VM object,
 * for shared memory and for shared anonymous (/dev/zero) mappings
 * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
 * consistent with the pre-accounting of private mappings ...
 */
static inline int shmem_acct_size(unsigned long flags, loff_t size)
{
125 126
	return (flags & VM_NORESERVE) ?
		0 : security_vm_enough_memory_kern(VM_ACCT(size));
Linus Torvalds's avatar
Linus Torvalds committed
127 128 129 130
}

static inline void shmem_unacct_size(unsigned long flags, loff_t size)
{
131
	if (!(flags & VM_NORESERVE))
Linus Torvalds's avatar
Linus Torvalds committed
132 133 134 135 136 137 138 139 140 141 142
		vm_unacct_memory(VM_ACCT(size));
}

/*
 * ... whereas tmpfs objects are accounted incrementally as
 * pages are allocated, in order to allow huge sparse files.
 * shmem_getpage reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
 * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
 */
static inline int shmem_acct_block(unsigned long flags)
{
143 144
	return (flags & VM_NORESERVE) ?
		security_vm_enough_memory_kern(VM_ACCT(PAGE_CACHE_SIZE)) : 0;
Linus Torvalds's avatar
Linus Torvalds committed
145 146 147 148
}

static inline void shmem_unacct_blocks(unsigned long flags, long pages)
{
149
	if (flags & VM_NORESERVE)
Linus Torvalds's avatar
Linus Torvalds committed
150 151 152
		vm_unacct_memory(pages * VM_ACCT(PAGE_CACHE_SIZE));
}

153
static const struct super_operations shmem_ops;
154
static const struct address_space_operations shmem_aops;
155
static const struct file_operations shmem_file_operations;
156 157 158
static const struct inode_operations shmem_inode_operations;
static const struct inode_operations shmem_dir_inode_operations;
static const struct inode_operations shmem_special_inode_operations;
159
static const struct vm_operations_struct shmem_vm_ops;
Linus Torvalds's avatar
Linus Torvalds committed
160

161
static struct backing_dev_info shmem_backing_dev_info  __read_mostly = {
Linus Torvalds's avatar
Linus Torvalds committed
162
	.ra_pages	= 0,	/* No readahead */
163
	.capabilities	= BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_SWAP_BACKED,
Linus Torvalds's avatar
Linus Torvalds committed
164 165 166
};

static LIST_HEAD(shmem_swaplist);
167
static DEFINE_MUTEX(shmem_swaplist_mutex);
Linus Torvalds's avatar
Linus Torvalds committed
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
static int shmem_reserve_inode(struct super_block *sb)
{
	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
	if (sbinfo->max_inodes) {
		spin_lock(&sbinfo->stat_lock);
		if (!sbinfo->free_inodes) {
			spin_unlock(&sbinfo->stat_lock);
			return -ENOSPC;
		}
		sbinfo->free_inodes--;
		spin_unlock(&sbinfo->stat_lock);
	}
	return 0;
}

static void shmem_free_inode(struct super_block *sb)
{
	struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
	if (sbinfo->max_inodes) {
		spin_lock(&sbinfo->stat_lock);
		sbinfo->free_inodes++;
		spin_unlock(&sbinfo->stat_lock);
	}
}

194
/**
195
 * shmem_recalc_inode - recalculate the block usage of an inode
Linus Torvalds's avatar
Linus Torvalds committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
 * @inode: inode to recalc
 *
 * We have to calculate the free blocks since the mm can drop
 * undirtied hole pages behind our back.
 *
 * But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
 * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
 *
 * It has to be called with the spinlock held.
 */
static void shmem_recalc_inode(struct inode *inode)
{
	struct shmem_inode_info *info = SHMEM_I(inode);
	long freed;

	freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
	if (freed > 0) {
213 214 215
		struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
		if (sbinfo->max_blocks)
			percpu_counter_add(&sbinfo->used_blocks, -freed);
Linus Torvalds's avatar
Linus Torvalds committed
216
		info->alloced -= freed;
217
		inode->i_blocks -= freed * BLOCKS_PER_PAGE;
Linus Torvalds's avatar
Linus Torvalds committed
218 219 220 221
		shmem_unacct_blocks(info->flags, freed);
	}
}

222 223
static void shmem_put_swap(struct shmem_inode_info *info, pgoff_t index,
			   swp_entry_t swap)
Linus Torvalds's avatar
Linus Torvalds committed
224
{
225 226
	if (index < SHMEM_NR_DIRECT)
		info->i_direct[index] = swap;
Linus Torvalds's avatar
Linus Torvalds committed
227 228
}

229
static swp_entry_t shmem_get_swap(struct shmem_inode_info *info, pgoff_t index)
Linus Torvalds's avatar
Linus Torvalds committed
230
{
231 232
	return (index < SHMEM_NR_DIRECT) ?
		info->i_direct[index] : (swp_entry_t){0};
Linus Torvalds's avatar
Linus Torvalds committed
233 234
}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
/*
 * Replace item expected in radix tree by a new item, while holding tree lock.
 */
static int shmem_radix_tree_replace(struct address_space *mapping,
			pgoff_t index, void *expected, void *replacement)
{
	void **pslot;
	void *item = NULL;

	VM_BUG_ON(!expected);
	pslot = radix_tree_lookup_slot(&mapping->page_tree, index);
	if (pslot)
		item = radix_tree_deref_slot_protected(pslot,
							&mapping->tree_lock);
	if (item != expected)
		return -ENOENT;
	if (replacement)
		radix_tree_replace_slot(pslot, replacement);
	else
		radix_tree_delete(&mapping->page_tree, index);
	return 0;
}

258 259 260 261 262 263 264
/*
 * Like add_to_page_cache_locked, but error if expected item has gone.
 */
static int shmem_add_to_page_cache(struct page *page,
				   struct address_space *mapping,
				   pgoff_t index, gfp_t gfp, void *expected)
{
265
	int error = 0;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

	VM_BUG_ON(!PageLocked(page));
	VM_BUG_ON(!PageSwapBacked(page));

	if (!expected)
		error = radix_tree_preload(gfp & GFP_RECLAIM_MASK);
	if (!error) {
		page_cache_get(page);
		page->mapping = mapping;
		page->index = index;

		spin_lock_irq(&mapping->tree_lock);
		if (!expected)
			error = radix_tree_insert(&mapping->page_tree,
							index, page);
		else
			error = shmem_radix_tree_replace(mapping, index,
							expected, page);
		if (!error) {
			mapping->nrpages++;
			__inc_zone_page_state(page, NR_FILE_PAGES);
			__inc_zone_page_state(page, NR_SHMEM);
			spin_unlock_irq(&mapping->tree_lock);
		} else {
			page->mapping = NULL;
			spin_unlock_irq(&mapping->tree_lock);
			page_cache_release(page);
		}
		if (!expected)
			radix_tree_preload_end();
	}
	if (error)
		mem_cgroup_uncharge_cache_page(page);
	return error;
}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
/*
 * Like find_get_pages, but collecting swap entries as well as pages.
 */
static unsigned shmem_find_get_pages_and_swap(struct address_space *mapping,
					pgoff_t start, unsigned int nr_pages,
					struct page **pages, pgoff_t *indices)
{
	unsigned int i;
	unsigned int ret;
	unsigned int nr_found;

	rcu_read_lock();
restart:
	nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
				(void ***)pages, indices, start, nr_pages);
	ret = 0;
	for (i = 0; i < nr_found; i++) {
		struct page *page;
repeat:
		page = radix_tree_deref_slot((void **)pages[i]);
		if (unlikely(!page))
			continue;
		if (radix_tree_exception(page)) {
			if (radix_tree_exceptional_entry(page))
				goto export;
			/* radix_tree_deref_retry(page) */
			goto restart;
		}
		if (!page_cache_get_speculative(page))
			goto repeat;

		/* Has the page moved? */
		if (unlikely(page != *((void **)pages[i]))) {
			page_cache_release(page);
			goto repeat;
		}
export:
		indices[ret] = indices[i];
		pages[ret] = page;
		ret++;
	}
	if (unlikely(!ret && nr_found))
		goto restart;
	rcu_read_unlock();
	return ret;
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
/*
 * Lockless lookup of swap entry in radix tree, avoiding refcount on pages.
 */
static pgoff_t shmem_find_swap(struct address_space *mapping, void *radswap)
{
	void  **slots[PAGEVEC_SIZE];
	pgoff_t indices[PAGEVEC_SIZE];
	unsigned int nr_found;

restart:
	nr_found = 1;
	indices[0] = -1;
	while (nr_found) {
		pgoff_t index = indices[nr_found - 1] + 1;
		unsigned int i;

		rcu_read_lock();
		nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
					slots, indices, index, PAGEVEC_SIZE);
		for (i = 0; i < nr_found; i++) {
			void *item = radix_tree_deref_slot(slots[i]);
			if (radix_tree_deref_retry(item)) {
				rcu_read_unlock();
				goto restart;
			}
			if (item == radswap) {
				rcu_read_unlock();
				return indices[i];
			}
		}
		rcu_read_unlock();
		cond_resched();
	}
	return -1;
}

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
/*
 * Remove swap entry from radix tree, free the swap and its page cache.
 */
static int shmem_free_swap(struct address_space *mapping,
			   pgoff_t index, void *radswap)
{
	int error;

	spin_lock_irq(&mapping->tree_lock);
	error = shmem_radix_tree_replace(mapping, index, radswap, NULL);
	spin_unlock_irq(&mapping->tree_lock);
	if (!error)
		free_swap_and_cache(radix_to_swp_entry(radswap));
	return error;
}

/*
 * Pagevec may contain swap entries, so shuffle up pages before releasing.
 */
static void shmem_pagevec_release(struct pagevec *pvec)
{
	int i, j;

	for (i = 0, j = 0; i < pagevec_count(pvec); i++) {
		struct page *page = pvec->pages[i];
		if (!radix_tree_exceptional_entry(page))
			pvec->pages[j++] = page;
	}
	pvec->nr = j;
	pagevec_release(pvec);
}

/*
 * Remove range of pages and swap entries from radix tree, and free them.
 */
420
void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
Linus Torvalds's avatar
Linus Torvalds committed
421
{
422
	struct address_space *mapping = inode->i_mapping;
Linus Torvalds's avatar
Linus Torvalds committed
423
	struct shmem_inode_info *info = SHMEM_I(inode);
424
	pgoff_t start = (lstart + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
425
	unsigned partial = lstart & (PAGE_CACHE_SIZE - 1);
426
	pgoff_t end = (lend >> PAGE_CACHE_SHIFT);
427
	struct pagevec pvec;
428 429
	pgoff_t indices[PAGEVEC_SIZE];
	long nr_swaps_freed = 0;
430
	pgoff_t index;
431 432 433 434 435 436
	int i;

	BUG_ON((lend & (PAGE_CACHE_SIZE - 1)) != (PAGE_CACHE_SIZE - 1));

	pagevec_init(&pvec, 0);
	index = start;
437 438 439 440 441 442
	while (index <= end) {
		pvec.nr = shmem_find_get_pages_and_swap(mapping, index,
			min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1,
							pvec.pages, indices);
		if (!pvec.nr)
			break;
443 444 445 446
		mem_cgroup_uncharge_start();
		for (i = 0; i < pagevec_count(&pvec); i++) {
			struct page *page = pvec.pages[i];

447
			index = indices[i];
448 449 450
			if (index > end)
				break;

451 452 453
			if (radix_tree_exceptional_entry(page)) {
				nr_swaps_freed += !shmem_free_swap(mapping,
								index, page);
454
				continue;
455 456 457
			}

			if (!trylock_page(page))
458
				continue;
459 460 461
			if (page->mapping == mapping) {
				VM_BUG_ON(PageWriteback(page));
				truncate_inode_page(mapping, page);
462 463 464
			}
			unlock_page(page);
		}
465
		shmem_pagevec_release(&pvec);
466 467 468 469
		mem_cgroup_uncharge_end();
		cond_resched();
		index++;
	}
Linus Torvalds's avatar
Linus Torvalds committed
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484
	if (partial) {
		struct page *page = NULL;
		shmem_getpage(inode, start - 1, &page, SGP_READ, NULL);
		if (page) {
			zero_user_segment(page, partial, PAGE_CACHE_SIZE);
			set_page_dirty(page);
			unlock_page(page);
			page_cache_release(page);
		}
	}

	index = start;
	for ( ; ; ) {
		cond_resched();
485 486 487 488
		pvec.nr = shmem_find_get_pages_and_swap(mapping, index,
			min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1,
							pvec.pages, indices);
		if (!pvec.nr) {
489 490 491 492 493
			if (index == start)
				break;
			index = start;
			continue;
		}
494 495
		if (index == start && indices[0] > end) {
			shmem_pagevec_release(&pvec);
496 497 498 499 500 501
			break;
		}
		mem_cgroup_uncharge_start();
		for (i = 0; i < pagevec_count(&pvec); i++) {
			struct page *page = pvec.pages[i];

502
			index = indices[i];
503 504 505
			if (index > end)
				break;

506 507 508 509 510 511
			if (radix_tree_exceptional_entry(page)) {
				nr_swaps_freed += !shmem_free_swap(mapping,
								index, page);
				continue;
			}

512
			lock_page(page);
513 514 515 516
			if (page->mapping == mapping) {
				VM_BUG_ON(PageWriteback(page));
				truncate_inode_page(mapping, page);
			}
517 518
			unlock_page(page);
		}
519
		shmem_pagevec_release(&pvec);
520 521 522
		mem_cgroup_uncharge_end();
		index++;
	}
523

Linus Torvalds's avatar
Linus Torvalds committed
524
	spin_lock(&info->lock);
525
	info->swapped -= nr_swaps_freed;
Linus Torvalds's avatar
Linus Torvalds committed
526 527 528
	shmem_recalc_inode(inode);
	spin_unlock(&info->lock);

529
	inode->i_ctime = inode->i_mtime = CURRENT_TIME;
Linus Torvalds's avatar
Linus Torvalds committed
530
}
531
EXPORT_SYMBOL_GPL(shmem_truncate_range);
Linus Torvalds's avatar
Linus Torvalds committed
532

533
static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
Linus Torvalds's avatar
Linus Torvalds committed
534 535 536 537
{
	struct inode *inode = dentry->d_inode;
	int error;

538 539 540 541
	error = inode_change_ok(inode, attr);
	if (error)
		return error;

542 543 544
	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
		loff_t oldsize = inode->i_size;
		loff_t newsize = attr->ia_size;
545

546 547 548 549 550 551 552 553 554 555 556
		if (newsize != oldsize) {
			i_size_write(inode, newsize);
			inode->i_ctime = inode->i_mtime = CURRENT_TIME;
		}
		if (newsize < oldsize) {
			loff_t holebegin = round_up(newsize, PAGE_SIZE);
			unmap_mapping_range(inode->i_mapping, holebegin, 0, 1);
			shmem_truncate_range(inode, newsize, (loff_t)-1);
			/* unmap again to remove racily COWed private pages */
			unmap_mapping_range(inode->i_mapping, holebegin, 0, 1);
		}
Linus Torvalds's avatar
Linus Torvalds committed
557 558
	}

559
	setattr_copy(inode, attr);
560
#ifdef CONFIG_TMPFS_POSIX_ACL
561
	if (attr->ia_valid & ATTR_MODE)
562
		error = generic_acl_chmod(inode);
563
#endif
Linus Torvalds's avatar
Linus Torvalds committed
564 565 566
	return error;
}

Al Viro's avatar
Al Viro committed
567
static void shmem_evict_inode(struct inode *inode)
Linus Torvalds's avatar
Linus Torvalds committed
568 569
{
	struct shmem_inode_info *info = SHMEM_I(inode);
570
	struct shmem_xattr *xattr, *nxattr;
Linus Torvalds's avatar
Linus Torvalds committed
571

572
	if (inode->i_mapping->a_ops == &shmem_aops) {
Linus Torvalds's avatar
Linus Torvalds committed
573 574
		shmem_unacct_size(info->flags, inode->i_size);
		inode->i_size = 0;
575
		shmem_truncate_range(inode, 0, (loff_t)-1);
Linus Torvalds's avatar
Linus Torvalds committed
576
		if (!list_empty(&info->swaplist)) {
577
			mutex_lock(&shmem_swaplist_mutex);
Linus Torvalds's avatar
Linus Torvalds committed
578
			list_del_init(&info->swaplist);
579
			mutex_unlock(&shmem_swaplist_mutex);
Linus Torvalds's avatar
Linus Torvalds committed
580 581
		}
	}
582 583 584 585 586

	list_for_each_entry_safe(xattr, nxattr, &info->xattr_list, list) {
		kfree(xattr->name);
		kfree(xattr);
	}
587
	BUG_ON(inode->i_blocks);
588
	shmem_free_inode(inode->i_sb);
Al Viro's avatar
Al Viro committed
589
	end_writeback(inode);
Linus Torvalds's avatar
Linus Torvalds committed
590 591
}

592 593 594
/*
 * If swap found in inode, free it and move page from swapcache to filecache.
 */
595 596
static int shmem_unuse_inode(struct shmem_inode_info *info,
			     swp_entry_t swap, struct page *page)
Linus Torvalds's avatar
Linus Torvalds committed
597
{
598
	struct address_space *mapping = info->vfs_inode.i_mapping;
599
	void *radswap;
600
	pgoff_t index;
601
	int error;
Linus Torvalds's avatar
Linus Torvalds committed
602

603 604 605
	radswap = swp_to_radix_entry(swap);
	index = shmem_find_swap(mapping, radswap);
	if (index == -1)
606
		return 0;
607

Hugh Dickins's avatar
Hugh Dickins committed
608 609
	/*
	 * Move _head_ to start search for next from here.
Al Viro's avatar
Al Viro committed
610
	 * But be careful: shmem_evict_inode checks list_empty without taking
Hugh Dickins's avatar
Hugh Dickins committed
611
	 * mutex, and there's an instant in list_move_tail when info->swaplist
612
	 * would appear empty, if it were the only one on shmem_swaplist.
Hugh Dickins's avatar
Hugh Dickins committed
613 614 615
	 */
	if (shmem_swaplist.next != &info->swaplist)
		list_move_tail(&shmem_swaplist, &info->swaplist);
616

KAMEZAWA Hiroyuki's avatar
KAMEZAWA Hiroyuki committed
617
	/*
618 619 620
	 * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
	 * but also to hold up shmem_evict_inode(): so inode cannot be freed
	 * beneath us (pagelock doesn't help until the page is in pagecache).
KAMEZAWA Hiroyuki's avatar
KAMEZAWA Hiroyuki committed
621
	 */
622 623
	error = shmem_add_to_page_cache(page, mapping, index,
						GFP_NOWAIT, radswap);
624
	/* which does mem_cgroup_uncharge_cache_page on error */
625

626
	if (error != -ENOMEM) {
627 628 629 630
		/*
		 * Truncation and eviction use free_swap_and_cache(), which
		 * only does trylock page: if we raced, best clean up here.
		 */
631 632
		delete_from_swap_cache(page);
		set_page_dirty(page);
633 634 635 636 637 638
		if (!error) {
			spin_lock(&info->lock);
			info->swapped--;
			spin_unlock(&info->lock);
			swap_free(swap);
		}
639
		error = 1;	/* not an error, but entry was found */
Linus Torvalds's avatar
Linus Torvalds committed
640
	}
641
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
642 643 644
}

/*
645
 * Search through swapped inodes to find and replace swap by page.
Linus Torvalds's avatar
Linus Torvalds committed
646
 */
647
int shmem_unuse(swp_entry_t swap, struct page *page)
Linus Torvalds's avatar
Linus Torvalds committed
648
{
649
	struct list_head *this, *next;
Linus Torvalds's avatar
Linus Torvalds committed
650 651
	struct shmem_inode_info *info;
	int found = 0;
652 653 654 655 656 657 658 659 660 661
	int error;

	/*
	 * Charge page using GFP_KERNEL while we can wait, before taking
	 * the shmem_swaplist_mutex which might hold up shmem_writepage().
	 * Charged back to the user (not to caller) when swap account is used.
	 */
	error = mem_cgroup_cache_charge(page, current->mm, GFP_KERNEL);
	if (error)
		goto out;
662
	/* No radix_tree_preload: swap entry keeps a place for page in tree */
Linus Torvalds's avatar
Linus Torvalds committed
663

664
	mutex_lock(&shmem_swaplist_mutex);
665 666
	list_for_each_safe(this, next, &shmem_swaplist) {
		info = list_entry(this, struct shmem_inode_info, swaplist);
667 668 669 670 671 672 673
		if (!info->swapped) {
			spin_lock(&info->lock);
			if (!info->swapped)
				list_del_init(&info->swaplist);
			spin_unlock(&info->lock);
		}
		if (info->swapped)
674
			found = shmem_unuse_inode(info, swap, page);
675
		cond_resched();
676
		if (found)
677
			break;
Linus Torvalds's avatar
Linus Torvalds committed
678
	}
679
	mutex_unlock(&shmem_swaplist_mutex);
680 681 682 683 684 685

	if (!found)
		mem_cgroup_uncharge_cache_page(page);
	if (found < 0)
		error = found;
out:
Hugh Dickins's avatar
Hugh Dickins committed
686 687
	unlock_page(page);
	page_cache_release(page);
688
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
689 690 691 692 693 694 695 696
}

/*
 * Move the page from the page cache to the swap cache.
 */
static int shmem_writepage(struct page *page, struct writeback_control *wbc)
{
	struct shmem_inode_info *info;
697
	swp_entry_t swap, oswap;
Linus Torvalds's avatar
Linus Torvalds committed
698
	struct address_space *mapping;
699
	pgoff_t index;
Linus Torvalds's avatar
Linus Torvalds committed
700 701 702 703 704 705 706 707 708
	struct inode *inode;

	BUG_ON(!PageLocked(page));
	mapping = page->mapping;
	index = page->index;
	inode = mapping->host;
	info = SHMEM_I(inode);
	if (info->flags & VM_LOCKED)
		goto redirty;
709
	if (!total_swap_pages)
Linus Torvalds's avatar
Linus Torvalds committed
710 711
		goto redirty;

712 713 714
	/*
	 * shmem_backing_dev_info's capabilities prevent regular writeback or
	 * sync from ever calling shmem_writepage; but a stacking filesystem
715
	 * might use ->writepage of its underlying filesystem, in which case
716
	 * tmpfs should write out to swap only in response to memory pressure,
717
	 * and not for the writeback threads or sync.
718
	 */
719 720 721 722
	if (!wbc->for_reclaim) {
		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
		goto redirty;
	}
723 724

	/*
725 726
	 * Disable even the toy swapping implementation, while we convert
	 * functions one by one to having swap entries in the radix tree.
727
	 */
728
	if (index < ULONG_MAX)
729 730
		goto redirty;

731 732 733
	swap = get_swap_page();
	if (!swap.val)
		goto redirty;
734

735 736 737 738 739 740 741 742 743
	/*
	 * Add inode to shmem_unuse()'s list of swapped-out inodes,
	 * if it's not already there.  Do it now because we cannot take
	 * mutex while holding spinlock, and must do so before the page
	 * is moved to swap cache, when its pagelock no longer protects
	 * the inode from eviction.  But don't unlock the mutex until
	 * we've taken the spinlock, because shmem_unuse_inode() will
	 * prune a !swapped inode from the swaplist under both locks.
	 */
744 745 746
	mutex_lock(&shmem_swaplist_mutex);
	if (list_empty(&info->swaplist))
		list_add_tail(&info->swaplist, &shmem_swaplist);
747

Linus Torvalds's avatar
Linus Torvalds committed
748
	spin_lock(&info->lock);
749
	mutex_unlock(&shmem_swaplist_mutex);
750

751 752
	oswap = shmem_get_swap(info, index);
	if (oswap.val) {
753
		WARN_ON_ONCE(1);	/* Still happens? Tell us about it! */
754 755 756
		free_swap_and_cache(oswap);
		shmem_put_swap(info, index, (swp_entry_t){0});
		info->swapped--;
757 758
	}
	shmem_recalc_inode(inode);
Linus Torvalds's avatar
Linus Torvalds committed
759

760
	if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
761
		delete_from_page_cache(page);
762 763
		shmem_put_swap(info, index, swap);
		info->swapped++;
Hugh Dickins's avatar
Hugh Dickins committed
764
		swap_shmem_alloc(swap);
765
		spin_unlock(&info->lock);
766
		BUG_ON(page_mapped(page));
767
		swap_writepage(page, wbc);
Linus Torvalds's avatar
Linus Torvalds committed
768 769 770 771
		return 0;
	}

	spin_unlock(&info->lock);
772
	swapcache_free(swap, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
773 774
redirty:
	set_page_dirty(page);
775 776 777 778
	if (wbc->for_reclaim)
		return AOP_WRITEPAGE_ACTIVATE;	/* Return with page locked */
	unlock_page(page);
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
779 780 781
}

#ifdef CONFIG_NUMA
782
#ifdef CONFIG_TMPFS
783
static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
784
{
785
	char buffer[64];
786

787
	if (!mpol || mpol->mode == MPOL_DEFAULT)
788
		return;		/* show nothing */
789

790
	mpol_to_str(buffer, sizeof(buffer), mpol, 1);
791 792

	seq_printf(seq, ",mpol=%s", buffer);
793
}
794 795 796 797 798 799 800 801 802 803 804 805

static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
{
	struct mempolicy *mpol = NULL;
	if (sbinfo->mpol) {
		spin_lock(&sbinfo->stat_lock);	/* prevent replace/use races */
		mpol = sbinfo->mpol;
		mpol_get(mpol);
		spin_unlock(&sbinfo->stat_lock);
	}
	return mpol;
}
806 807
#endif /* CONFIG_TMPFS */

808 809
static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
			struct shmem_inode_info *info, pgoff_t index)
Linus Torvalds's avatar
Linus Torvalds committed
810
{
811
	struct mempolicy mpol, *spol;
Linus Torvalds's avatar
Linus Torvalds committed
812 813
	struct vm_area_struct pvma;

814
	spol = mpol_cond_copy(&mpol,
815
			mpol_shared_policy_lookup(&info->policy, index));
816

Linus Torvalds's avatar
Linus Torvalds committed
817
	/* Create a pseudo vma that just contains the policy */
818
	pvma.vm_start = 0;
819
	pvma.vm_pgoff = index;
820
	pvma.vm_ops = NULL;
821
	pvma.vm_policy = spol;
822
	return swapin_readahead(swap, gfp, &pvma, 0);
Linus Torvalds's avatar
Linus Torvalds committed
823 824
}

825
static struct page *shmem_alloc_page(gfp_t gfp,
826
			struct shmem_inode_info *info, pgoff_t index)
Linus Torvalds's avatar
Linus Torvalds committed
827 828 829
{
	struct vm_area_struct pvma;

830 831
	/* Create a pseudo vma that just contains the policy */
	pvma.vm_start = 0;
832
	pvma.vm_pgoff = index;
833
	pvma.vm_ops = NULL;
834
	pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, index);
835 836 837 838 839

	/*
	 * alloc_page_vma() will drop the shared policy reference
	 */
	return alloc_page_vma(gfp, &pvma, 0);
Linus Torvalds's avatar
Linus Torvalds committed
840
}
841 842
#else /* !CONFIG_NUMA */
#ifdef CONFIG_TMPFS
843
static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
844 845 846 847
{
}
#endif /* CONFIG_TMPFS */

848 849
static inline struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
			struct shmem_inode_info *info, pgoff_t index)
Linus Torvalds's avatar
Linus Torvalds committed
850
{
851
	return swapin_readahead(swap, gfp, NULL, 0);
Linus Torvalds's avatar
Linus Torvalds committed
852 853
}

854
static inline struct page *shmem_alloc_page(gfp_t gfp,
855
			struct shmem_inode_info *info, pgoff_t index)
Linus Torvalds's avatar
Linus Torvalds committed
856
{
857
	return alloc_page(gfp);
Linus Torvalds's avatar
Linus Torvalds committed
858
}
859
#endif /* CONFIG_NUMA */
Linus Torvalds's avatar
Linus Torvalds committed
860

861 862 863 864 865 866 867
#if !defined(CONFIG_NUMA) || !defined(CONFIG_TMPFS)
static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
{
	return NULL;
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
868
/*
869
 * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
Linus Torvalds's avatar
Linus Torvalds committed
870 871 872 873 874
 *
 * If we allocate a new one we do not mark it dirty. That's up to the
 * vm. If we swap it in we mark it dirty since we also free the swap
 * entry since a page cannot live in both the swap and page cache
 */
875
static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
876
	struct page **pagep, enum sgp_type sgp, gfp_t gfp, int *fault_type)
Linus Torvalds's avatar
Linus Torvalds committed
877 878
{
	struct address_space *mapping = inode->i_mapping;
879
	struct shmem_inode_info *info;
Linus Torvalds's avatar
Linus Torvalds committed
880
	struct shmem_sb_info *sbinfo;
881
	struct page *page;
Linus Torvalds's avatar
Linus Torvalds committed
882 883
	swp_entry_t swap;
	int error;
884
	int once = 0;
Linus Torvalds's avatar
Linus Torvalds committed
885

886
	if (index > (MAX_LFS_FILESIZE >> PAGE_CACHE_SHIFT))
Linus Torvalds's avatar
Linus Torvalds committed
887 888
		return -EFBIG;
repeat:
889
	swap.val = 0;
890
	page = find_lock_page(mapping, index);
891 892 893 894 895 896 897 898 899 900 901 902
	if (radix_tree_exceptional_entry(page)) {
		swap = radix_to_swp_entry(page);
		page = NULL;
	}

	if (sgp != SGP_WRITE &&
	    ((loff_t)index << PAGE_CACHE_SHIFT) >= i_size_read(inode)) {
		error = -EINVAL;
		goto failed;
	}

	if (page || (sgp == SGP_READ && !swap.val)) {
Hugh Dickins's avatar
Hugh Dickins committed
903
		/*
904 905 906
		 * Once we can get the page lock, it must be uptodate:
		 * if there were an error in reading back from swap,
		 * the page would not be inserted into the filecache.
Hugh Dickins's avatar
Hugh Dickins committed
907
		 */
908 909 910
		BUG_ON(page && !PageUptodate(page));
		*pagep = page;
		return 0;
911 912 913
	}

	/*
914 915
	 * Fast cache lookup did not find it:
	 * bring it back from swap or allocate.
916
	 */
917 918
	info = SHMEM_I(inode);
	sbinfo = SHMEM_SB(inode->i_sb);
Linus Torvalds's avatar
Linus Torvalds committed
919 920 921

	if (swap.val) {
		/* Look it up and read it in.. */
922 923
		page = lookup_swap_cache(swap);
		if (!page) {
Linus Torvalds's avatar
Linus Torvalds committed
924
			/* here we actually do the io */
925 926
			if (fault_type)
				*fault_type |= VM_FAULT_MAJOR;
927
			page = shmem_swapin(swap, gfp, info, index);
928
			if (!page) {
929 930
				error = -ENOMEM;
				goto failed;
Linus Torvalds's avatar
Linus Torvalds committed
931 932 933 934
			}
		}

		/* We have to do this with page locked to prevent races */
935
		lock_page(page);
936
		if (!PageUptodate(page)) {
Linus Torvalds's avatar
Linus Torvalds committed
937
			error = -EIO;
938
			goto failed;
Linus Torvalds's avatar
Linus Torvalds committed
939
		}
940 941 942 943 944 945 946 947 948
		wait_on_page_writeback(page);

		/* Someone may have already done it for us */
		if (page->mapping) {
			if (page->mapping == mapping &&
			    page->index == index)
				goto done;
			error = -EEXIST;
			goto failed;
Linus Torvalds's avatar
Linus Torvalds committed
949
		}
950

951 952 953 954 955
		error = mem_cgroup_cache_charge(page, current->mm,
						gfp & GFP_RECLAIM_MASK);
		if (!error)
			error = shmem_add_to_page_cache(page, mapping, index,
						gfp, swp_to_radix_entry(swap));
956 957 958 959
		if (error)
			goto failed;

		spin_lock(&info->lock);
960
		info->swapped--;
961
		shmem_recalc_inode(inode);
962
		spin_unlock(&info->lock);
963 964

		delete_from_swap_cache(page);
965 966 967
		set_page_dirty(page);
		swap_free(swap);

968 969 970 971
	} else {
		if (shmem_acct_block(info->flags)) {
			error = -ENOSPC;
			goto failed;
Linus Torvalds's avatar
Linus Torvalds committed
972
		}
973
		if (sbinfo->max_blocks) {
974
			if (percpu_counter_compare(&sbinfo->used_blocks,
975 976 977 978
						sbinfo->max_blocks) >= 0) {
				error = -ENOSPC;
				goto unacct;
			}
979
			percpu_counter_inc(&sbinfo->used_blocks);
980
		}
Linus Torvalds's avatar
Linus Torvalds committed
981

982 983 984 985
		page = shmem_alloc_page(gfp, info, index);
		if (!page) {
			error = -ENOMEM;
			goto decused;
Linus Torvalds's avatar
Linus Torvalds committed
986 987
		}

988 989
		SetPageSwapBacked(page);
		__set_page_locked(page);
990 991 992 993 994
		error = mem_cgroup_cache_charge(page, current->mm,
						gfp & GFP_RECLAIM_MASK);
		if (!error)
			error = shmem_add_to_page_cache(page, mapping, index,
						gfp, NULL);
995 996 997 998 999
		if (error)
			goto decused;
		lru_cache_add_anon(page);

		spin_lock(&info->lock);
Linus Torvalds's avatar
Linus Torvalds committed
1000
		info->alloced++;
1001 1002
		inode->i_blocks += BLOCKS_PER_PAGE;
		shmem_recalc_inode(inode);
Linus Torvalds's avatar
Linus Torvalds committed
1003
		spin_unlock(&info->lock);
1004

1005 1006 1007
		clear_highpage(page);
		flush_dcache_page(page);
		SetPageUptodate(page);
1008
		if (sgp == SGP_DIRTY)
1009
			set_page_dirty(page);
Linus Torvalds's avatar
Linus Torvalds committed
1010 1011
	}
done:
1012 1013 1014 1015 1016
	/* Perhaps the file has been truncated since we checked */
	if (sgp != SGP_WRITE &&
	    ((loff_t)index << PAGE_CACHE_SHIFT) >= i_size_read(inode)) {
		error = -EINVAL;
		goto trunc;
Hugh Dickins's avatar
Hugh Dickins committed
1017
	}
1018 1019
	*pagep = page;
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
1020

1021
	/*
1022
	 * Error recovery.
1023
	 */
1024 1025 1026 1027 1028 1029
trunc:
	ClearPageDirty(page);
	delete_from_page_cache(page);
	spin_lock(&info->lock);
	info->alloced--;
	inode->i_blocks -= BLOCKS_PER_PAGE;