swap_state.c 14.4 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6 7 8 9
/*
 *  linux/mm/swap_state.c
 *
 *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
 *  Swap reorganised 29.12.95, Stephen Tweedie
 *
 *  Rewritten to use page cache, (C) 1998 Stephen Tweedie
 */
#include <linux/mm.h>
10
#include <linux/gfp.h>
L
Linus Torvalds 已提交
11 12
#include <linux/kernel_stat.h>
#include <linux/swap.h>
13
#include <linux/swapops.h>
L
Linus Torvalds 已提交
14 15 16
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/backing-dev.h>
17
#include <linux/blkdev.h>
18
#include <linux/pagevec.h>
C
Christoph Lameter 已提交
19
#include <linux/migrate.h>
20
#include <linux/vmalloc.h>
L
Linus Torvalds 已提交
21 22 23 24 25

#include <asm/pgtable.h>

/*
 * swapper_space is a fiction, retained to simplify the path through
J
Jens Axboe 已提交
26
 * vmscan's shrink_page_list.
L
Linus Torvalds 已提交
27
 */
28
static const struct address_space_operations swap_aops = {
L
Linus Torvalds 已提交
29
	.writepage	= swap_writepage,
30
	.set_page_dirty	= swap_set_page_dirty,
31
#ifdef CONFIG_MIGRATION
32
	.migratepage	= migrate_page,
33
#endif
L
Linus Torvalds 已提交
34 35
};

36 37
struct address_space *swapper_spaces[MAX_SWAPFILES];
static unsigned int nr_swapper_spaces[MAX_SWAPFILES];
L
Linus Torvalds 已提交
38 39 40 41 42 43 44 45 46 47

#define INC_CACHE_INFO(x)	do { swap_cache_info.x++; } while (0)

static struct {
	unsigned long add_total;
	unsigned long del_total;
	unsigned long find_success;
	unsigned long find_total;
} swap_cache_info;

48 49
unsigned long total_swapcache_pages(void)
{
50
	unsigned int i, j, nr;
51
	unsigned long ret = 0;
52
	struct address_space *spaces;
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	rcu_read_lock();
	for (i = 0; i < MAX_SWAPFILES; i++) {
		/*
		 * The corresponding entries in nr_swapper_spaces and
		 * swapper_spaces will be reused only after at least
		 * one grace period.  So it is impossible for them
		 * belongs to different usage.
		 */
		nr = nr_swapper_spaces[i];
		spaces = rcu_dereference(swapper_spaces[i]);
		if (!nr || !spaces)
			continue;
		for (j = 0; j < nr; j++)
			ret += spaces[j].nrpages;
	}
	rcu_read_unlock();
70 71 72
	return ret;
}

73 74
static atomic_t swapin_readahead_hits = ATOMIC_INIT(4);

L
Linus Torvalds 已提交
75 76
void show_swap_cache_info(void)
{
77
	printk("%lu pages in swap cache\n", total_swapcache_pages());
78
	printk("Swap cache stats: add %lu, delete %lu, find %lu/%lu\n",
L
Linus Torvalds 已提交
79
		swap_cache_info.add_total, swap_cache_info.del_total,
80
		swap_cache_info.find_success, swap_cache_info.find_total);
81 82
	printk("Free swap  = %ldkB\n",
		get_nr_swap_pages() << (PAGE_SHIFT - 10));
L
Linus Torvalds 已提交
83 84 85 86
	printk("Total swap = %lukB\n", total_swap_pages << (PAGE_SHIFT - 10));
}

/*
87
 * __add_to_swap_cache resembles add_to_page_cache_locked on swapper_space,
L
Linus Torvalds 已提交
88 89
 * but sets SwapCache flag and private instead of mapping and index.
 */
90
int __add_to_swap_cache(struct page *page, swp_entry_t entry)
L
Linus Torvalds 已提交
91 92
{
	int error;
93
	struct address_space *address_space;
L
Linus Torvalds 已提交
94

95 96 97
	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(PageSwapCache(page), page);
	VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
98

99
	get_page(page);
100 101 102
	SetPageSwapCache(page);
	set_page_private(page, entry.val);

103 104 105
	address_space = swap_address_space(entry);
	spin_lock_irq(&address_space->tree_lock);
	error = radix_tree_insert(&address_space->page_tree,
106
				  swp_offset(entry), page);
107
	if (likely(!error)) {
108
		address_space->nrpages++;
109
		__inc_node_page_state(page, NR_FILE_PAGES);
110 111
		INC_CACHE_INFO(add_total);
	}
112
	spin_unlock_irq(&address_space->tree_lock);
113 114

	if (unlikely(error)) {
115 116 117 118 119 120
		/*
		 * Only the context which have set SWAP_HAS_CACHE flag
		 * would call add_to_swap_cache().
		 * So add_to_swap_cache() doesn't returns -EEXIST.
		 */
		VM_BUG_ON(error == -EEXIST);
121 122
		set_page_private(page, 0UL);
		ClearPageSwapCache(page);
123
		put_page(page);
124 125 126 127 128 129 130 131 132 133
	}

	return error;
}


int add_to_swap_cache(struct page *page, swp_entry_t entry, gfp_t gfp_mask)
{
	int error;

134
	error = radix_tree_maybe_preload(gfp_mask);
B
Balbir Singh 已提交
135
	if (!error) {
136
		error = __add_to_swap_cache(page, entry);
L
Linus Torvalds 已提交
137
		radix_tree_preload_end();
H
Hugh Dickins 已提交
138
	}
L
Linus Torvalds 已提交
139 140 141 142 143 144 145 146 147
	return error;
}

/*
 * This must be called only on pages that have
 * been verified to be in the swap cache.
 */
void __delete_from_swap_cache(struct page *page)
{
148 149 150
	swp_entry_t entry;
	struct address_space *address_space;

151 152 153
	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(!PageSwapCache(page), page);
	VM_BUG_ON_PAGE(PageWriteback(page), page);
L
Linus Torvalds 已提交
154

155 156
	entry.val = page_private(page);
	address_space = swap_address_space(entry);
157
	radix_tree_delete(&address_space->page_tree, swp_offset(entry));
H
Hugh Dickins 已提交
158
	set_page_private(page, 0);
L
Linus Torvalds 已提交
159
	ClearPageSwapCache(page);
160
	address_space->nrpages--;
161
	__dec_node_page_state(page, NR_FILE_PAGES);
L
Linus Torvalds 已提交
162 163 164 165 166 167 168 169 170 171
	INC_CACHE_INFO(del_total);
}

/**
 * add_to_swap - allocate swap space for a page
 * @page: page we want to move to swap
 *
 * Allocate swap space for the page and add the page to the
 * swap cache.  Caller needs to hold the page lock. 
 */
172
int add_to_swap(struct page *page, struct list_head *list)
L
Linus Torvalds 已提交
173 174 175 176
{
	swp_entry_t entry;
	int err;

177 178
	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(!PageUptodate(page), page);
L
Linus Torvalds 已提交
179

180 181 182 183
	entry = get_swap_page();
	if (!entry.val)
		return 0;

184 185 186 187 188
	if (mem_cgroup_try_charge_swap(page, entry)) {
		swapcache_free(entry);
		return 0;
	}

A
Andrea Arcangeli 已提交
189
	if (unlikely(PageTransHuge(page)))
190
		if (unlikely(split_huge_page_to_list(page, list))) {
191
			swapcache_free(entry);
A
Andrea Arcangeli 已提交
192 193 194
			return 0;
		}

195 196 197 198 199 200 201 202 203
	/*
	 * Radix-tree node allocations from PF_MEMALLOC contexts could
	 * completely exhaust the page allocator. __GFP_NOMEMALLOC
	 * stops emergency reserves from being allocated.
	 *
	 * TODO: this could cause a theoretical memory reclaim
	 * deadlock in the swap out path.
	 */
	/*
M
Minchan Kim 已提交
204
	 * Add it to the swap cache.
205 206 207 208
	 */
	err = add_to_swap_cache(page, entry,
			__GFP_HIGH|__GFP_NOMEMALLOC|__GFP_NOWARN);

M
Minchan Kim 已提交
209
	if (!err) {
210 211
		return 1;
	} else {	/* -ENOMEM radix-tree allocation failure */
N
Nick Piggin 已提交
212
		/*
213 214
		 * add_to_swap_cache() doesn't return -EEXIST, so we can safely
		 * clear SWAP_HAS_CACHE flag.
L
Linus Torvalds 已提交
215
		 */
216
		swapcache_free(entry);
217
		return 0;
L
Linus Torvalds 已提交
218 219 220 221 222 223 224 225 226 227 228 229
	}
}

/*
 * This must be called only on pages that have
 * been verified to be in the swap cache and locked.
 * It will never put the page into the free list,
 * the caller has a reference on the page.
 */
void delete_from_swap_cache(struct page *page)
{
	swp_entry_t entry;
230
	struct address_space *address_space;
L
Linus Torvalds 已提交
231

H
Hugh Dickins 已提交
232
	entry.val = page_private(page);
L
Linus Torvalds 已提交
233

234 235
	address_space = swap_address_space(entry);
	spin_lock_irq(&address_space->tree_lock);
L
Linus Torvalds 已提交
236
	__delete_from_swap_cache(page);
237
	spin_unlock_irq(&address_space->tree_lock);
L
Linus Torvalds 已提交
238

239
	swapcache_free(entry);
240
	put_page(page);
L
Linus Torvalds 已提交
241 242 243 244 245 246
}

/* 
 * If we are the only user, then try to free up the swap cache. 
 * 
 * Its ok to check for PageSwapCache without the page lock
247 248
 * here because we are going to recheck again inside
 * try_to_free_swap() _with_ the lock.
L
Linus Torvalds 已提交
249 250 251 252
 * 					- Marcelo
 */
static inline void free_swap_cache(struct page *page)
{
253 254
	if (PageSwapCache(page) && !page_mapped(page) && trylock_page(page)) {
		try_to_free_swap(page);
L
Linus Torvalds 已提交
255 256 257 258 259 260
		unlock_page(page);
	}
}

/* 
 * Perform a free_page(), also freeing any swap cache associated with
261
 * this page if it is the last user of the page.
L
Linus Torvalds 已提交
262 263 264 265
 */
void free_page_and_swap_cache(struct page *page)
{
	free_swap_cache(page);
266
	if (!is_huge_zero_page(page))
267
		put_page(page);
L
Linus Torvalds 已提交
268 269 270 271 272 273 274 275 276
}

/*
 * Passed an array of pages, drop them all from swapcache and then release
 * them.  They are removed from the LRU and freed if this is their last use.
 */
void free_pages_and_swap_cache(struct page **pages, int nr)
{
	struct page **pagep = pages;
277
	int i;
L
Linus Torvalds 已提交
278 279

	lru_add_drain();
280 281 282
	for (i = 0; i < nr; i++)
		free_swap_cache(pagep[i]);
	release_pages(pagep, nr, false);
L
Linus Torvalds 已提交
283 284 285 286 287 288 289 290 291 292 293 294
}

/*
 * Lookup a swap entry in the swap cache. A found page will be returned
 * unlocked and with its refcount incremented - we rely on the kernel
 * lock getting page table operations atomic even if we drop the page
 * lock before returning.
 */
struct page * lookup_swap_cache(swp_entry_t entry)
{
	struct page *page;

295
	page = find_get_page(swap_address_space(entry), swp_offset(entry));
L
Linus Torvalds 已提交
296

297
	if (page) {
L
Linus Torvalds 已提交
298
		INC_CACHE_INFO(find_success);
299 300 301
		if (TestClearPageReadahead(page))
			atomic_inc(&swapin_readahead_hits);
	}
L
Linus Torvalds 已提交
302 303 304 305 306

	INC_CACHE_INFO(find_total);
	return page;
}

307 308 309
struct page *__read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
			struct vm_area_struct *vma, unsigned long addr,
			bool *new_page_allocated)
L
Linus Torvalds 已提交
310 311
{
	struct page *found_page, *new_page = NULL;
312
	struct address_space *swapper_space = swap_address_space(entry);
L
Linus Torvalds 已提交
313
	int err;
314
	*new_page_allocated = false;
L
Linus Torvalds 已提交
315 316 317 318 319 320 321

	do {
		/*
		 * First check the swap cache.  Since this is normally
		 * called after lookup_swap_cache() failed, re-calling
		 * that would confuse statistics.
		 */
322
		found_page = find_get_page(swapper_space, swp_offset(entry));
L
Linus Torvalds 已提交
323 324 325
		if (found_page)
			break;

326 327 328 329
		/* Just skip read ahead for unused swap slot */
		if (!__swp_swapcount(entry))
			return NULL;

L
Linus Torvalds 已提交
330 331 332 333
		/*
		 * Get a new page to read into from swap.
		 */
		if (!new_page) {
334
			new_page = alloc_page_vma(gfp_mask, vma, addr);
L
Linus Torvalds 已提交
335 336 337 338
			if (!new_page)
				break;		/* Out of memory */
		}

339 340 341
		/*
		 * call radix_tree_preload() while we can wait.
		 */
342
		err = radix_tree_maybe_preload(gfp_mask & GFP_KERNEL);
343 344 345
		if (err)
			break;

H
Hugh Dickins 已提交
346 347 348
		/*
		 * Swap entry may have been freed since our caller observed it.
		 */
349
		err = swapcache_prepare(entry);
350
		if (err == -EEXIST) {
351
			radix_tree_preload_end();
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
			/*
			 * We might race against get_swap_page() and stumble
			 * across a SWAP_HAS_CACHE swap_map entry whose page
			 * has not been brought into the swapcache yet, while
			 * the other end is scheduled away waiting on discard
			 * I/O completion at scan_swap_map().
			 *
			 * In order to avoid turning this transitory state
			 * into a permanent loop around this -EEXIST case
			 * if !CONFIG_PREEMPT and the I/O completion happens
			 * to be waiting on the CPU waitqueue where we are now
			 * busy looping, we just conditionally invoke the
			 * scheduler here, if there are some more important
			 * tasks to run.
			 */
			cond_resched();
368
			continue;
369 370 371
		}
		if (err) {		/* swp entry is obsolete ? */
			radix_tree_preload_end();
H
Hugh Dickins 已提交
372
			break;
373
		}
H
Hugh Dickins 已提交
374

375
		/* May fail (-ENOMEM) if radix-tree node allocation failed. */
376
		__SetPageLocked(new_page);
377
		__SetPageSwapBacked(new_page);
378
		err = __add_to_swap_cache(new_page, entry);
N
Nick Piggin 已提交
379
		if (likely(!err)) {
380
			radix_tree_preload_end();
L
Linus Torvalds 已提交
381 382 383
			/*
			 * Initiate read into locked page and return.
			 */
384
			lru_cache_add_anon(new_page);
385
			*new_page_allocated = true;
L
Linus Torvalds 已提交
386 387
			return new_page;
		}
388
		radix_tree_preload_end();
389
		__ClearPageLocked(new_page);
390 391 392 393
		/*
		 * add_to_swap_cache() doesn't return -EEXIST, so we can safely
		 * clear SWAP_HAS_CACHE flag.
		 */
394
		swapcache_free(entry);
H
Hugh Dickins 已提交
395
	} while (err != -ENOMEM);
L
Linus Torvalds 已提交
396 397

	if (new_page)
398
		put_page(new_page);
L
Linus Torvalds 已提交
399 400
	return found_page;
}
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
/*
 * Locate a page of swap in physical memory, reserving swap cache space
 * and reading the disk if it is not already cached.
 * A failure return means that either the page allocation failed or that
 * the swap entry is no longer in use.
 */
struct page *read_swap_cache_async(swp_entry_t entry, gfp_t gfp_mask,
			struct vm_area_struct *vma, unsigned long addr)
{
	bool page_was_allocated;
	struct page *retpage = __read_swap_cache_async(entry, gfp_mask,
			vma, addr, &page_was_allocated);

	if (page_was_allocated)
		swap_readpage(retpage);

	return retpage;
}

421 422 423 424 425 426
static unsigned long swapin_nr_pages(unsigned long offset)
{
	static unsigned long prev_offset;
	unsigned int pages, max_pages, last_ra;
	static atomic_t last_readahead_pages;

427
	max_pages = 1 << READ_ONCE(page_cluster);
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
	if (max_pages <= 1)
		return 1;

	/*
	 * This heuristic has been found to work well on both sequential and
	 * random loads, swapping to hard disk or to SSD: please don't ask
	 * what the "+ 2" means, it just happens to work well, that's all.
	 */
	pages = atomic_xchg(&swapin_readahead_hits, 0) + 2;
	if (pages == 2) {
		/*
		 * We can have no readahead hits to judge by: but must not get
		 * stuck here forever, so check for an adjacent offset instead
		 * (and don't even bother to check whether swap type is same).
		 */
		if (offset != prev_offset + 1 && offset != prev_offset - 1)
			pages = 1;
		prev_offset = offset;
	} else {
		unsigned int roundup = 4;
		while (roundup < pages)
			roundup <<= 1;
		pages = roundup;
	}

	if (pages > max_pages)
		pages = max_pages;

	/* Don't shrink readahead too fast */
	last_ra = atomic_read(&last_readahead_pages) / 2;
	if (pages < last_ra)
		pages = last_ra;
	atomic_set(&last_readahead_pages, pages);

	return pages;
}

465 466 467
/**
 * swapin_readahead - swap in pages in hope we need them soon
 * @entry: swap entry of this memory
468
 * @gfp_mask: memory allocation flags
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
 * @vma: user vma this address belongs to
 * @addr: target address for mempolicy
 *
 * Returns the struct page for entry and addr, after queueing swapin.
 *
 * Primitive swap readahead code. We simply read an aligned block of
 * (1 << page_cluster) entries in the swap area. This method is chosen
 * because it doesn't cost us any seek time.  We also make sure to queue
 * the 'original' request together with the readahead ones...
 *
 * This has been extended to use the NUMA policies from the mm triggering
 * the readahead.
 *
 * Caller must hold down_read on the vma->vm_mm if vma is not NULL.
 */
484
struct page *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask,
485 486 487
			struct vm_area_struct *vma, unsigned long addr)
{
	struct page *page;
488 489
	unsigned long entry_offset = swp_offset(entry);
	unsigned long offset = entry_offset;
490
	unsigned long start_offset, end_offset;
491
	unsigned long mask;
492
	struct blk_plug plug;
493

494 495 496 497
	mask = swapin_nr_pages(offset) - 1;
	if (!mask)
		goto skip;

498 499 500 501 502 503
	/* Read a page_cluster sized and aligned cluster around offset. */
	start_offset = offset & ~mask;
	end_offset = offset | mask;
	if (!start_offset)	/* First page is swap header. */
		start_offset++;

504
	blk_start_plug(&plug);
505
	for (offset = start_offset; offset <= end_offset ; offset++) {
506 507
		/* Ok, do the async read-ahead now */
		page = read_swap_cache_async(swp_entry(swp_type(entry), offset),
508
						gfp_mask, vma, addr);
509
		if (!page)
510
			continue;
511 512
		if (offset != entry_offset)
			SetPageReadahead(page);
513
		put_page(page);
514
	}
515 516
	blk_finish_plug(&plug);

517
	lru_add_drain();	/* Push any new pages onto the LRU now */
518
skip:
519
	return read_swap_cache_async(entry, gfp_mask, vma, addr);
520
}
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

int init_swap_address_space(unsigned int type, unsigned long nr_pages)
{
	struct address_space *spaces, *space;
	unsigned int i, nr;

	nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
	spaces = vzalloc(sizeof(struct address_space) * nr);
	if (!spaces)
		return -ENOMEM;
	for (i = 0; i < nr; i++) {
		space = spaces + i;
		INIT_RADIX_TREE(&space->page_tree, GFP_ATOMIC|__GFP_NOWARN);
		atomic_set(&space->i_mmap_writable, 0);
		space->a_ops = &swap_aops;
		/* swap cache doesn't use writeback related tags */
		mapping_set_no_writeback_tags(space);
		spin_lock_init(&space->tree_lock);
	}
	nr_swapper_spaces[type] = nr;
	rcu_assign_pointer(swapper_spaces[type], spaces);

	return 0;
}

void exit_swap_address_space(unsigned int type)
{
	struct address_space *spaces;

	spaces = swapper_spaces[type];
	nr_swapper_spaces[type] = 0;
	rcu_assign_pointer(swapper_spaces[type], NULL);
	synchronize_rcu();
	kvfree(spaces);
}