migrate.c 76.7 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2
/*
3
 * Memory Migration functionality - linux/mm/migrate.c
4 5 6 7 8 9 10 11 12
 *
 * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
 *
 * Page migration was first developed in the context of the memory hotplug
 * project. The main authors of the migration code are:
 *
 * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
 * Hirokazu Takahashi <taka@valinux.co.jp>
 * Dave Hansen <haveblue@us.ibm.com>
Christoph Lameter's avatar
Christoph Lameter committed
13
 * Christoph Lameter
14 15 16
 */

#include <linux/migrate.h>
17
#include <linux/export.h>
18
#include <linux/swap.h>
19
#include <linux/swapops.h>
20
#include <linux/pagemap.h>
21
#include <linux/buffer_head.h>
22
#include <linux/mm_inline.h>
23
#include <linux/nsproxy.h>
24
#include <linux/pagevec.h>
25
#include <linux/ksm.h>
26 27 28 29
#include <linux/rmap.h>
#include <linux/topology.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
30
#include <linux/writeback.h>
31 32
#include <linux/mempolicy.h>
#include <linux/vmalloc.h>
33
#include <linux/security.h>
34
#include <linux/backing-dev.h>
35
#include <linux/compaction.h>
36
#include <linux/syscalls.h>
37
#include <linux/hugetlb.h>
38
#include <linux/hugetlb_cgroup.h>
39
#include <linux/gfp.h>
40
#include <linux/pfn_t.h>
41
#include <linux/memremap.h>
42
#include <linux/userfaultfd_k.h>
43
#include <linux/balloon_compaction.h>
44
#include <linux/mmu_notifier.h>
45
#include <linux/page_idle.h>
46
#include <linux/page_owner.h>
47
#include <linux/sched/mm.h>
48
#include <linux/ptrace.h>
49

50 51
#include <asm/tlbflush.h>

52 53 54
#define CREATE_TRACE_POINTS
#include <trace/events/migrate.h>

55 56 57
#include "internal.h"

/*
58
 * migrate_prep() needs to be called before we start compiling a list of pages
59 60
 * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
 * undesirable, use migrate_prep_local()
61 62 63 64 65 66 67 68 69 70 71 72 73 74
 */
int migrate_prep(void)
{
	/*
	 * Clear the LRU lists so pages can be isolated.
	 * Note that pages may be moved off the LRU after we have
	 * drained them. Those pages will fail to migrate like other
	 * pages that may be busy.
	 */
	lru_add_drain_all();

	return 0;
}

75 76 77 78 79 80 81 82
/* Do the necessary work of migrate_prep but not if it involves other CPUs */
int migrate_prep_local(void)
{
	lru_add_drain();

	return 0;
}

83
int isolate_movable_page(struct page *page, isolate_mode_t mode)
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
{
	struct address_space *mapping;

	/*
	 * Avoid burning cycles with pages that are yet under __free_pages(),
	 * or just got freed under us.
	 *
	 * In case we 'win' a race for a movable page being freed under us and
	 * raise its refcount preventing __free_pages() from doing its job
	 * the put_page() at the end of this block will take care of
	 * release this page, thus avoiding a nasty leakage.
	 */
	if (unlikely(!get_page_unless_zero(page)))
		goto out;

	/*
	 * Check PageMovable before holding a PG_lock because page's owner
	 * assumes anybody doesn't touch PG_lock of newly allocated page
	 * so unconditionally grapping the lock ruins page's owner side.
	 */
	if (unlikely(!__PageMovable(page)))
		goto out_putpage;
	/*
	 * As movable pages are not isolated from LRU lists, concurrent
	 * compaction threads can race against page migration functions
	 * as well as race against the releasing a page.
	 *
	 * In order to avoid having an already isolated movable page
	 * being (wrongly) re-isolated while it is under migration,
	 * or to avoid attempting to isolate pages being released,
	 * lets be sure we have the page lock
	 * before proceeding with the movable page isolation steps.
	 */
	if (unlikely(!trylock_page(page)))
		goto out_putpage;

	if (!PageMovable(page) || PageIsolated(page))
		goto out_no_isolated;

	mapping = page_mapping(page);
	VM_BUG_ON_PAGE(!mapping, page);

	if (!mapping->a_ops->isolate_page(page, mode))
		goto out_no_isolated;

	/* Driver shouldn't use PG_isolated bit of page->flags */
	WARN_ON_ONCE(PageIsolated(page));
	__SetPageIsolated(page);
	unlock_page(page);

134
	return 0;
135 136 137 138 139 140

out_no_isolated:
	unlock_page(page);
out_putpage:
	put_page(page);
out:
141
	return -EBUSY;
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
}

/* It should be called on page which is PG_movable */
void putback_movable_page(struct page *page)
{
	struct address_space *mapping;

	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(!PageMovable(page), page);
	VM_BUG_ON_PAGE(!PageIsolated(page), page);

	mapping = page_mapping(page);
	mapping->a_ops->putback_page(page);
	__ClearPageIsolated(page);
}

158 159 160 161
/*
 * Put previously isolated pages back onto the appropriate lists
 * from where they were once taken off for compaction/migration.
 *
162 163 164
 * This function shall be used whenever the isolated pageset has been
 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
 * and isolate_huge_page().
165 166 167 168 169 170
 */
void putback_movable_pages(struct list_head *l)
{
	struct page *page;
	struct page *page2;

171
	list_for_each_entry_safe(page, page2, l, lru) {
172 173 174 175
		if (unlikely(PageHuge(page))) {
			putback_active_hugepage(page);
			continue;
		}
176
		list_del(&page->lru);
177 178 179 180 181
		/*
		 * We isolated non-lru movable page so here we can use
		 * __PageMovable because LRU page's mapping cannot have
		 * PAGE_MAPPING_MOVABLE.
		 */
182
		if (unlikely(__PageMovable(page))) {
183 184 185 186 187 188 189 190 191
			VM_BUG_ON_PAGE(!PageIsolated(page), page);
			lock_page(page);
			if (PageMovable(page))
				putback_movable_page(page);
			else
				__ClearPageIsolated(page);
			unlock_page(page);
			put_page(page);
		} else {
192 193
			mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
					page_is_file_cache(page), -hpage_nr_pages(page));
194
			putback_lru_page(page);
195
		}
196 197 198
	}
}

199 200 201
/*
 * Restore a potential migration pte to a working pte entry
 */
202
static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
203
				 unsigned long addr, void *old)
204
{
205 206 207 208 209 210 211 212
	struct page_vma_mapped_walk pvmw = {
		.page = old,
		.vma = vma,
		.address = addr,
		.flags = PVMW_SYNC | PVMW_MIGRATION,
	};
	struct page *new;
	pte_t pte;
213 214
	swp_entry_t entry;

215 216
	VM_BUG_ON_PAGE(PageTail(page), page);
	while (page_vma_mapped_walk(&pvmw)) {
217 218 219 220 221
		if (PageKsm(page))
			new = page;
		else
			new = page - pvmw.page->index +
				linear_page_index(vma, pvmw.address);
222

223 224 225 226 227 228 229 230 231
#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
		/* PMD-mapped THP migration entry */
		if (!pvmw.pte) {
			VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
			remove_migration_pmd(&pvmw, new);
			continue;
		}
#endif

232 233 234 235
		get_page(new);
		pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
		if (pte_swp_soft_dirty(*pvmw.pte))
			pte = pte_mksoft_dirty(pte);
236

237 238 239 240 241 242
		/*
		 * Recheck VMA as permissions can change since migration started
		 */
		entry = pte_to_swp_entry(*pvmw.pte);
		if (is_write_migration_entry(entry))
			pte = maybe_mkwrite(pte, vma);
243

244 245 246 247 248 249 250 251
		if (unlikely(is_zone_device_page(new))) {
			if (is_device_private_page(new)) {
				entry = make_device_private_entry(new, pte_write(pte));
				pte = swp_entry_to_pte(entry);
			} else if (is_device_public_page(new)) {
				pte = pte_mkdevmap(pte);
				flush_dcache_page(new);
			}
252 253 254
		} else
			flush_dcache_page(new);

255
#ifdef CONFIG_HUGETLB_PAGE
256 257 258
		if (PageHuge(new)) {
			pte = pte_mkhuge(pte);
			pte = arch_make_huge_pte(pte, vma, new, 0);
259
			set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
260 261 262 263
			if (PageAnon(new))
				hugepage_add_anon_rmap(new, vma, pvmw.address);
			else
				page_dup_rmap(new, true);
264 265 266 267
		} else
#endif
		{
			set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
268

269 270 271 272 273
			if (PageAnon(new))
				page_add_anon_rmap(new, vma, pvmw.address, false);
			else
				page_add_file_rmap(new, false);
		}
274 275 276 277 278 279
		if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
			mlock_vma_page(new);

		/* No need to invalidate - it was non-present before */
		update_mmu_cache(vma, pvmw.address, pvmw.pte);
	}
280

281
	return true;
282 283
}

284 285 286 287
/*
 * Get rid of all migration entries and replace them by
 * references to the indicated page.
 */
288
void remove_migration_ptes(struct page *old, struct page *new, bool locked)
289
{
290 291 292 293 294
	struct rmap_walk_control rwc = {
		.rmap_one = remove_migration_pte,
		.arg = old,
	};

295 296 297 298
	if (locked)
		rmap_walk_locked(new, &rwc);
	else
		rmap_walk(new, &rwc);
299 300
}

301 302 303 304 305
/*
 * Something used the pte of a page under migration. We need to
 * get to the page and wait until migration is finished.
 * When we return from this function the fault will be retried.
 */
306
void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
307
				spinlock_t *ptl)
308
{
309
	pte_t pte;
310 311 312
	swp_entry_t entry;
	struct page *page;

313
	spin_lock(ptl);
314 315 316 317 318 319 320 321 322 323
	pte = *ptep;
	if (!is_swap_pte(pte))
		goto out;

	entry = pte_to_swp_entry(pte);
	if (!is_migration_entry(entry))
		goto out;

	page = migration_entry_to_page(entry);

Nick Piggin's avatar
Nick Piggin committed
324 325 326 327 328 329 330 331 332
	/*
	 * Once radix-tree replacement of page migration started, page_count
	 * *must* be zero. And, we don't want to call wait_on_page_locked()
	 * against a page without get_page().
	 * So, we use get_page_unless_zero(), here. Even failed, page fault
	 * will occur again.
	 */
	if (!get_page_unless_zero(page))
		goto out;
333 334 335 336 337 338 339 340
	pte_unmap_unlock(ptep, ptl);
	wait_on_page_locked(page);
	put_page(page);
	return;
out:
	pte_unmap_unlock(ptep, ptl);
}

341 342 343 344 345 346 347 348
void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
				unsigned long address)
{
	spinlock_t *ptl = pte_lockptr(mm, pmd);
	pte_t *ptep = pte_offset_map(pmd, address);
	__migration_entry_wait(mm, ptep, ptl);
}

349 350
void migration_entry_wait_huge(struct vm_area_struct *vma,
		struct mm_struct *mm, pte_t *pte)
351
{
352
	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
353 354 355
	__migration_entry_wait(mm, pte, ptl);
}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
{
	spinlock_t *ptl;
	struct page *page;

	ptl = pmd_lock(mm, pmd);
	if (!is_pmd_migration_entry(*pmd))
		goto unlock;
	page = migration_entry_to_page(pmd_to_swp_entry(*pmd));
	if (!get_page_unless_zero(page))
		goto unlock;
	spin_unlock(ptl);
	wait_on_page_locked(page);
	put_page(page);
	return;
unlock:
	spin_unlock(ptl);
}
#endif

377 378
#ifdef CONFIG_BLOCK
/* Returns true if all buffers are successfully locked */
379 380
static bool buffer_migrate_lock_buffers(struct buffer_head *head,
							enum migrate_mode mode)
381 382 383 384
{
	struct buffer_head *bh = head;

	/* Simple case, sync compaction */
385
	if (mode != MIGRATE_ASYNC) {
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 420
		do {
			get_bh(bh);
			lock_buffer(bh);
			bh = bh->b_this_page;

		} while (bh != head);

		return true;
	}

	/* async case, we cannot block on lock_buffer so use trylock_buffer */
	do {
		get_bh(bh);
		if (!trylock_buffer(bh)) {
			/*
			 * We failed to lock the buffer and cannot stall in
			 * async migration. Release the taken locks
			 */
			struct buffer_head *failed_bh = bh;
			put_bh(failed_bh);
			bh = head;
			while (bh != failed_bh) {
				unlock_buffer(bh);
				put_bh(bh);
				bh = bh->b_this_page;
			}
			return false;
		}

		bh = bh->b_this_page;
	} while (bh != head);
	return true;
}
#else
static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
421
							enum migrate_mode mode)
422 423 424 425 426
{
	return true;
}
#endif /* CONFIG_BLOCK */

427
/*
428
 * Replace the page in the mapping.
429 430 431 432
 *
 * The number of remaining references must be:
 * 1 for anonymous pages without a mapping
 * 2 for pages with a mapping
433
 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
434
 */
435
int migrate_page_move_mapping(struct address_space *mapping,
436
		struct page *newpage, struct page *page,
437 438
		struct buffer_head *head, enum migrate_mode mode,
		int extra_count)
439
{
440 441
	struct zone *oldzone, *newzone;
	int dirty;
442
	int expected_count = 1 + extra_count;
443
	void **pslot;
444

445
	/*
446 447
	 * Device public or private pages have an extra refcount as they are
	 * ZONE_DEVICE pages.
448
	 */
449 450
	expected_count += is_device_private_page(page);
	expected_count += is_device_public_page(page);
451

452
	if (!mapping) {
453
		/* Anonymous page without mapping */
454
		if (page_count(page) != expected_count)
455
			return -EAGAIN;
456 457 458 459 460

		/* No turning back from here */
		newpage->index = page->index;
		newpage->mapping = page->mapping;
		if (PageSwapBacked(page))
461
			__SetPageSwapBacked(newpage);
462

463
		return MIGRATEPAGE_SUCCESS;
464 465
	}

466 467 468
	oldzone = page_zone(page);
	newzone = page_zone(newpage);

Nick Piggin's avatar
Nick Piggin committed
469
	spin_lock_irq(&mapping->tree_lock);
470

471 472
	pslot = radix_tree_lookup_slot(&mapping->page_tree,
 					page_index(page));
473

474
	expected_count += 1 + page_has_private(page);
Nick Piggin's avatar
Nick Piggin committed
475
	if (page_count(page) != expected_count ||
476
		radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
Nick Piggin's avatar
Nick Piggin committed
477
		spin_unlock_irq(&mapping->tree_lock);
478
		return -EAGAIN;
479 480
	}

481
	if (!page_ref_freeze(page, expected_count)) {
Nick Piggin's avatar
Nick Piggin committed
482
		spin_unlock_irq(&mapping->tree_lock);
Nick Piggin's avatar
Nick Piggin committed
483 484 485
		return -EAGAIN;
	}

486 487 488 489 490 491 492
	/*
	 * In the async migration case of moving a page with buffers, lock the
	 * buffers using trylock before the mapping is moved. If the mapping
	 * was moved, we later failed to lock the buffers and could not move
	 * the mapping back due to an elevated page count, we would have to
	 * block waiting on other references to be dropped.
	 */
493 494
	if (mode == MIGRATE_ASYNC && head &&
			!buffer_migrate_lock_buffers(head, mode)) {
495
		page_ref_unfreeze(page, expected_count);
496 497 498 499
		spin_unlock_irq(&mapping->tree_lock);
		return -EAGAIN;
	}

500
	/*
501 502
	 * Now we know that no one else is looking at the page:
	 * no turning back from here.
503
	 */
504 505
	newpage->index = page->index;
	newpage->mapping = page->mapping;
506
	get_page(newpage);	/* add cache reference */
507 508 509 510 511 512 513 514
	if (PageSwapBacked(page)) {
		__SetPageSwapBacked(newpage);
		if (PageSwapCache(page)) {
			SetPageSwapCache(newpage);
			set_page_private(newpage, page_private(page));
		}
	} else {
		VM_BUG_ON_PAGE(PageSwapCache(page), page);
515 516
	}

517 518 519 520 521 522 523
	/* Move dirty while page refs frozen and newpage not yet exposed */
	dirty = PageDirty(page);
	if (dirty) {
		ClearPageDirty(page);
		SetPageDirty(newpage);
	}

524
	radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
525 526

	/*
527 528
	 * Drop cache reference from old page by unfreezing
	 * to one less reference.
529 530
	 * We know this isn't the last reference.
	 */
531
	page_ref_unfreeze(page, expected_count - 1);
532

533 534 535
	spin_unlock(&mapping->tree_lock);
	/* Leave irq disabled to prevent preemption while updating stats */

536 537 538 539 540 541 542
	/*
	 * If moved to a different zone then also account
	 * the page for that zone. Other VM counters will be
	 * taken care of when we establish references to the
	 * new page and drop references to the old page.
	 *
	 * Note that anonymous pages are accounted for
543
	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
544 545
	 * are mapped to swap space.
	 */
546
	if (newzone != oldzone) {
547 548
		__dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES);
		__inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES);
549
		if (PageSwapBacked(page) && !PageSwapCache(page)) {
550 551
			__dec_node_state(oldzone->zone_pgdat, NR_SHMEM);
			__inc_node_state(newzone->zone_pgdat, NR_SHMEM);
552 553
		}
		if (dirty && mapping_cap_account_dirty(mapping)) {
554
			__dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY);
555
			__dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING);
556
			__inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY);
557
			__inc_zone_state(newzone, NR_ZONE_WRITE_PENDING);
558
		}
559
	}
560
	local_irq_enable();
561

562
	return MIGRATEPAGE_SUCCESS;
563
}
564
EXPORT_SYMBOL(migrate_page_move_mapping);
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/*
 * The expected number of remaining references is the same as that
 * of migrate_page_move_mapping().
 */
int migrate_huge_page_move_mapping(struct address_space *mapping,
				   struct page *newpage, struct page *page)
{
	int expected_count;
	void **pslot;

	spin_lock_irq(&mapping->tree_lock);

	pslot = radix_tree_lookup_slot(&mapping->page_tree,
					page_index(page));

	expected_count = 2 + page_has_private(page);
	if (page_count(page) != expected_count ||
583
		radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
584 585 586 587
		spin_unlock_irq(&mapping->tree_lock);
		return -EAGAIN;
	}

588
	if (!page_ref_freeze(page, expected_count)) {
589 590 591 592
		spin_unlock_irq(&mapping->tree_lock);
		return -EAGAIN;
	}

593 594
	newpage->index = page->index;
	newpage->mapping = page->mapping;
595

596 597
	get_page(newpage);

598
	radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
599

600
	page_ref_unfreeze(page, expected_count - 1);
601 602

	spin_unlock_irq(&mapping->tree_lock);
603

604
	return MIGRATEPAGE_SUCCESS;
605 606
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
/*
 * Gigantic pages are so large that we do not guarantee that page++ pointer
 * arithmetic will work across the entire page.  We need something more
 * specialized.
 */
static void __copy_gigantic_page(struct page *dst, struct page *src,
				int nr_pages)
{
	int i;
	struct page *dst_base = dst;
	struct page *src_base = src;

	for (i = 0; i < nr_pages; ) {
		cond_resched();
		copy_highpage(dst, src);

		i++;
		dst = mem_map_next(dst, dst_base, i);
		src = mem_map_next(src, src_base, i);
	}
}

static void copy_huge_page(struct page *dst, struct page *src)
{
	int i;
	int nr_pages;

	if (PageHuge(src)) {
		/* hugetlbfs page */
		struct hstate *h = page_hstate(src);
		nr_pages = pages_per_huge_page(h);

		if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) {
			__copy_gigantic_page(dst, src, nr_pages);
			return;
		}
	} else {
		/* thp page */
		BUG_ON(!PageTransHuge(src));
		nr_pages = hpage_nr_pages(src);
	}

	for (i = 0; i < nr_pages; i++) {
		cond_resched();
		copy_highpage(dst + i, src + i);
	}
}

655 656 657
/*
 * Copy the page to its new location
 */
658
void migrate_page_states(struct page *newpage, struct page *page)
659
{
660 661
	int cpupid;

662 663 664 665 666 667
	if (PageError(page))
		SetPageError(newpage);
	if (PageReferenced(page))
		SetPageReferenced(newpage);
	if (PageUptodate(page))
		SetPageUptodate(newpage);
668
	if (TestClearPageActive(page)) {
669
		VM_BUG_ON_PAGE(PageUnevictable(page), page);
670
		SetPageActive(newpage);
671 672
	} else if (TestClearPageUnevictable(page))
		SetPageUnevictable(newpage);
673 674 675 676 677
	if (PageChecked(page))
		SetPageChecked(newpage);
	if (PageMappedToDisk(page))
		SetPageMappedToDisk(newpage);

678 679 680
	/* Move dirty on pages not done by migrate_page_move_mapping() */
	if (PageDirty(page))
		SetPageDirty(newpage);
681

682 683 684 685 686
	if (page_is_young(page))
		set_page_young(newpage);
	if (page_is_idle(page))
		set_page_idle(newpage);

687 688 689 690 691 692 693
	/*
	 * Copy NUMA information to the new page, to prevent over-eager
	 * future migrations of this same page.
	 */
	cpupid = page_cpupid_xchg_last(page, -1);
	page_cpupid_xchg_last(newpage, cpupid);

694
	ksm_migrate_page(newpage, page);
695 696 697 698
	/*
	 * Please do not reorder this without considering how mm/ksm.c's
	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
	 */
699 700
	if (PageSwapCache(page))
		ClearPageSwapCache(page);
701 702 703 704 705 706 707 708 709
	ClearPagePrivate(page);
	set_page_private(page, 0);

	/*
	 * If any waiters have accumulated on the new page then
	 * wake them up.
	 */
	if (PageWriteback(newpage))
		end_page_writeback(newpage);
710 711

	copy_page_owner(page, newpage);
712 713

	mem_cgroup_migrate(page, newpage);
714
}
715 716 717 718 719 720 721 722 723 724 725
EXPORT_SYMBOL(migrate_page_states);

void migrate_page_copy(struct page *newpage, struct page *page)
{
	if (PageHuge(page) || PageTransHuge(page))
		copy_huge_page(newpage, page);
	else
		copy_highpage(newpage, page);

	migrate_page_states(newpage, page);
}
726
EXPORT_SYMBOL(migrate_page_copy);
727

728 729 730 731
/************************************************************
 *                    Migration functions
 ***********************************************************/

732
/*
733
 * Common logic to directly migrate a single LRU page suitable for
734
 * pages that do not use PagePrivate/PagePrivate2.
735 736 737
 *
 * Pages are locked upon entry and exit.
 */
738
int migrate_page(struct address_space *mapping,
739 740
		struct page *newpage, struct page *page,
		enum migrate_mode mode)
741 742 743 744 745
{
	int rc;

	BUG_ON(PageWriteback(page));	/* Writeback must be complete */

746
	rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
747

748
	if (rc != MIGRATEPAGE_SUCCESS)
749 750
		return rc;

751 752 753 754
	if (mode != MIGRATE_SYNC_NO_COPY)
		migrate_page_copy(newpage, page);
	else
		migrate_page_states(newpage, page);
755
	return MIGRATEPAGE_SUCCESS;
756 757 758
}
EXPORT_SYMBOL(migrate_page);

759
#ifdef CONFIG_BLOCK
760 761 762 763 764
/*
 * Migration function for pages with buffers. This function can only be used
 * if the underlying filesystem guarantees that no other references to "page"
 * exist.
 */
765
int buffer_migrate_page(struct address_space *mapping,
766
		struct page *newpage, struct page *page, enum migrate_mode mode)
767 768 769 770 771
{
	struct buffer_head *bh, *head;
	int rc;

	if (!page_has_buffers(page))
772
		return migrate_page(mapping, newpage, page, mode);
773 774 775

	head = page_buffers(page);

776
	rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0);
777

778
	if (rc != MIGRATEPAGE_SUCCESS)
779 780
		return rc;

781 782 783 784 785
	/*
	 * In the async case, migrate_page_move_mapping locked the buffers
	 * with an IRQ-safe spinlock held. In the sync case, the buffers
	 * need to be locked now
	 */
786 787
	if (mode != MIGRATE_ASYNC)
		BUG_ON(!buffer_migrate_lock_buffers(head, mode));
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

	ClearPagePrivate(page);
	set_page_private(newpage, page_private(page));
	set_page_private(page, 0);
	put_page(page);
	get_page(newpage);

	bh = head;
	do {
		set_bh_page(bh, newpage, bh_offset(bh));
		bh = bh->b_this_page;

	} while (bh != head);

	SetPagePrivate(newpage);

804 805 806 807
	if (mode != MIGRATE_SYNC_NO_COPY)
		migrate_page_copy(newpage, page);
	else
		migrate_page_states(newpage, page);
808 809 810 811

	bh = head;
	do {
		unlock_buffer(bh);
812
		put_bh(bh);
813 814 815 816
		bh = bh->b_this_page;

	} while (bh != head);

817
	return MIGRATEPAGE_SUCCESS;
818 819
}
EXPORT_SYMBOL(buffer_migrate_page);
820
#endif
821

822 823 824 825
/*
 * Writeback a page to clean the dirty state
 */
static int writeout(struct address_space *mapping, struct page *page)
826
{
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
	struct writeback_control wbc = {
		.sync_mode = WB_SYNC_NONE,
		.nr_to_write = 1,
		.range_start = 0,
		.range_end = LLONG_MAX,
		.for_reclaim = 1
	};
	int rc;

	if (!mapping->a_ops->writepage)
		/* No write method for the address space */
		return -EINVAL;

	if (!clear_page_dirty_for_io(page))
		/* Someone else already triggered a write */
		return -EAGAIN;

844
	/*
845 846 847 848 849 850
	 * A dirty page may imply that the underlying filesystem has
	 * the page on some queue. So the page must be clean for
	 * migration. Writeout may mean we loose the lock and the
	 * page state is no longer what we checked for earlier.
	 * At this point we know that the migration attempt cannot
	 * be successful.
851
	 */
852
	remove_migration_ptes(page, page, false);
853

854
	rc = mapping->a_ops->writepage(page, &wbc);
855

856 857 858 859
	if (rc != AOP_WRITEPAGE_ACTIVATE)
		/* unlocked. Relock */
		lock_page(page);

Hugh Dickins's avatar
Hugh Dickins committed
860
	return (rc < 0) ? -EIO : -EAGAIN;
861 862 863 864 865 866
}

/*
 * Default handling if a filesystem does not provide a migration function.
 */
static int fallback_migrate_page(struct address_space *mapping,
867
	struct page *newpage, struct page *page, enum migrate_mode mode)
868
{
869
	if (PageDirty(page)) {
870
		/* Only writeback pages in full synchronous migration */
871 872 873 874 875
		switch (mode) {
		case MIGRATE_SYNC:
		case MIGRATE_SYNC_NO_COPY:
			break;
		default:
876
			return -EBUSY;
877
		}
878
		return writeout(mapping, page);
879
	}
880 881 882 883 884

	/*
	 * Buffers may be managed in a filesystem specific way.
	 * We must have no buffers or drop them.
	 */
885
	if (page_has_private(page) &&
886 887 888
	    !try_to_release_page(page, GFP_KERNEL))
		return -EAGAIN;

889
	return migrate_page(mapping, newpage, page, mode);
890 891
}

892 893 894 895 896 897
/*
 * Move a page to a newly allocated page
 * The page is locked and all ptes have been successfully removed.
 *
 * The new page will have replaced the old page if this function
 * is successful.
898 899 900
 *
 * Return value:
 *   < 0 - error code
901
 *  MIGRATEPAGE_SUCCESS - success
902
 */
903
static int move_to_new_page(struct page *newpage, struct page *page,
904
				enum migrate_mode mode)
905 906
{
	struct address_space *mapping;
907 908
	int rc = -EAGAIN;
	bool is_lru = !__PageMovable(page);
909

910 911
	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
912 913

	mapping = page_mapping(page);
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

	if (likely(is_lru)) {
		if (!mapping)
			rc = migrate_page(mapping, newpage, page, mode);
		else if (mapping->a_ops->migratepage)
			/*
			 * Most pages have a mapping and most filesystems
			 * provide a migratepage callback. Anonymous pages
			 * are part of swap space which also has its own
			 * migratepage callback. This is the most common path
			 * for page migration.
			 */
			rc = mapping->a_ops->migratepage(mapping, newpage,
							page, mode);
		else
			rc = fallback_migrate_page(mapping, newpage,
							page, mode);
	} else {
932
		/*
933 934
		 * In case of non-lru page, it could be released after
		 * isolation step. In that case, we shouldn't try migration.
935
		 */
936 937 938 939 940 941 942 943 944 945 946 947
		VM_BUG_ON_PAGE(!PageIsolated(page), page);
		if (!PageMovable(page)) {
			rc = MIGRATEPAGE_SUCCESS;
			__ClearPageIsolated(page);
			goto out;
		}

		rc = mapping->a_ops->migratepage(mapping, newpage,
						page, mode);
		WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
			!PageIsolated(page));
	}
948

949 950 951 952 953
	/*
	 * When successful, old pagecache page->mapping must be cleared before
	 * page is freed; but stats require that PageAnon be left as PageAnon.
	 */
	if (rc == MIGRATEPAGE_SUCCESS) {
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
		if (__PageMovable(page)) {
			VM_BUG_ON_PAGE(!PageIsolated(page), page);

			/*
			 * We clear PG_movable under page_lock so any compactor
			 * cannot try to migrate this page.
			 */
			__ClearPageIsolated(page);
		}

		/*
		 * Anonymous and movable page->mapping will be cleard by
		 * free_pages_prepare so don't reset it here for keeping
		 * the type to work PageAnon, for example.
		 */
		if (!PageMappingFlags(page))
970
			page->mapping = NULL;
971
	}
972
out:
973 974 975
	return rc;
}

976
static int __unmap_and_move(struct page *page, struct page *newpage,
977
				int force, enum migrate_mode mode)
978
{
979
	int rc = -EAGAIN;
980
	int page_was_mapped = 0;
981
	struct anon_vma *anon_vma = NULL;
982
	bool is_lru = !__PageMovable(page);
983

Nick Piggin's avatar
Nick Piggin committed
984
	if (!trylock_page(page)) {
985
		if (!force || mode == MIGRATE_ASYNC)
986
			goto out;
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

		/*
		 * It's not safe for direct compaction to call lock_page.
		 * For example, during page readahead pages are added locked
		 * to the LRU. Later, when the IO completes the pages are
		 * marked uptodate and unlocked. However, the queueing
		 * could be merging multiple pages for one bio (e.g.
		 * mpage_readpages). If an allocation happens for the
		 * second or third page, the process can end up locking
		 * the same page twice and deadlocking. Rather than
		 * trying to be clever about what pages can be locked,
		 * avoid the use of lock_page for direct compaction
		 * altogether.
		 */
		if (current->flags & PF_MEMALLOC)
1002
			goto out;
1003

1004 1005 1006 1007
		lock_page(page);
	}

	if (PageWriteback(page)) {
1008
		/*
1009
		 * Only in the case of a full synchronous migration is it
1010 1011 1012
		 * necessary to wait for PageWriteback. In the async case,
		 * the retry loop is too short and in the sync-light case,
		 * the overhead of stalling is too much
1013
		 */
1014 1015 1016 1017 1018
		switch (mode) {
		case MIGRATE_SYNC:
		case MIGRATE_SYNC_NO_COPY:
			break;
		default:
1019
			rc = -EBUSY;
1020
			goto out_unlock;
1021 1022
		}
		if (!force)
1023
			goto out_unlock;
1024 1025
		wait_on_page_writeback(page);
	}
1026

1027
	/*
1028 1029
	 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
	 * we cannot notice that anon_vma is freed while we migrates a page.
1030
	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1031
	 * of migration. File cache pages are no problem because of page_lock()
1032 1033
	 * File Caches may use write_page() or lock_page() in migration, then,
	 * just care Anon page here.
1034 1035 1036 1037 1038 1039
	 *
	 * Only page_get_anon_vma() understands the subtleties of
	 * getting a hold on an anon_vma from outside one of its mms.
	 * But if we cannot get anon_vma, then we won't need it anyway,
	 * because that implies that the anon page is no longer mapped
	 * (and cannot be remapped so long as we hold the page lock).
1040
	 */
1041
	if (PageAnon(page) && !PageKsm(page))
1042
		anon_vma = page_get_anon_vma(page);
1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
	/*
	 * Block others from accessing the new page when we get around to
	 * establishing additional references. We are usually the only one
	 * holding a reference to newpage at this point. We used to have a BUG
	 * here if trylock_page(newpage) fails, but would like to allow for
	 * cases where there might be a race with the previous use of newpage.
	 * This is much like races on refcount of oldpage: just don't BUG().
	 */
	if (unlikely(!trylock_page(newpage)))
		goto out_unlock;

1055 1056 1057 1058 1059
	if (unlikely(!is_lru)) {
		rc = move_to_new_page(newpage, page, mode);
		goto out_unlock_both;
	}

1060
	/*
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	 * Corner case handling:
	 * 1. When a new swap-cache page is read into, it is added to the LRU
	 * and treated as swapcache but it has no rmap yet.
	 * Calling try_to_unmap() against a page->mapping==NULL page will
	 * trigger a BUG.  So handle it here.
	 * 2. An orphaned page (see truncate_complete_page) might have
	 * fs-private metadata. The page can be picked up due to memory
	 * offlining.  Everywhere else except page reclaim, the page is
	 * invisible to the vm, so the page can not be migrated.  So try to
	 * free the metadata, so the page can be freed.
1071
	 */
1072
	if (!page->mapping) {
1073
		VM_BUG_ON_PAGE(PageAnon(page), page);
1074
		if (page_has_private(page)) {
1075
			try_to_free_buffers(page);
1076
			goto out_unlock_both;
1077
		}
1078 1079
	} else if (page_mapped(page)) {
		/* Establish migration ptes */
1080 1081
		VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
				page);
1082
		try_to_unmap(page,
1083
			TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1084 1085
		page_was_mapped = 1;
	}
1086

1087
	if (!page_mapped(page))
1088
		rc = move_to_new_page(newpage, page, mode);
1089

1090 1091
	if (page_was_mapped)
		remove_migration_ptes(page,
1092
			rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1093

1094 1095 1096
out_unlock_both:
	unlock_page(newpage);
out_unlock:
1097
	/* Drop an anon_vma reference if we took one */
1098
	if (anon_vma)
1099
		put_anon_vma(anon_vma);
1100
	unlock_page(page);
1101
out:
1102 1103 1104 1105 1106 1107 1108
	/*
	 * If migration is successful, decrease refcount of the newpage
	 * which will not free the page because new page owner increased
	 * refcounter. As well, if it is LRU page, add the page to LRU
	 * list in here.
	 */
	if (rc == MIGRATEPAGE_SUCCESS) {
1109
		if (unlikely(__PageMovable(newpage)))
1110 1111 1112 1113 1114
			put_page(newpage);
		else
			putback_lru_page(newpage);
	}

1115 1116
	return rc;
}
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
/*
 * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move().  Work
 * around it.
 */
#if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM)
#define ICE_noinline noinline
#else
#define ICE_noinline
#endif

1128 1129 1130 1131
/*
 * Obtain the lock on page, remove all ptes and migrate the page
 * to the newly allocated page in newpage.
 */
1132 1133 1134
static ICE_noinline int unmap_and_move(new_page_t get_new_page,
				   free_page_t put_new_page,
				   unsigned long private, struct page *page,
1135 1136
				   int force, enum migrate_mode mode,
				   enum migrate_reason reason)
1137
{
1138
	int rc = MIGRATEPAGE_SUCCESS;
1139
	int *result = NULL;
1140
	struct page *newpage;
1141

1142
	newpage = get_new_page(page, private, &result);
1143 1144 1145 1146 1147
	if (!newpage)
		return -ENOMEM;

	if (page_count(page) == 1) {
		/* page was freed from under us. So we are done. */
1148 1149
		ClearPageActive(page);
		ClearPageUnevictable(page);
1150 1151 1152 1153 1154 1155
		if (unlikely(__PageMovable(page))) {
			lock_page(page);
			if (!PageMovable(page))
				__ClearPageIsolated(page);
			unlock_page(page);
		}
1156 1157 1158 1159
		if (put_new_page)
			put_new_page(newpage, private);
		else
			put_page(newpage);
1160 1161 1162
		goto out;
	}

1163
	if (unlikely(PageTransHuge(page) && !PageTransHuge(newpage))) {
1164 1165 1166 1167
		lock_page(page);
		rc = split_huge_page(page);
		unlock_page(page);
		if (rc)
1168
			goto out;
1169
	}
1170

1171
	rc = __unmap_and_move(page, newpage, force, mode);
1172
	if (rc == MIGRATEPAGE_SUCCESS)
1173
		set_page_owner_migrate_reason(newpage, reason);
1174

1175
out:
1176
	if (rc != -EAGAIN) {
1177 1178 1179 1180 1181 1182 1183
		/*
		 * A page that has been migrated has all references
		 * removed and will be freed. A page that has not been
		 * migrated will have kepts its references and be
		 * restored.
		 */
		list_del(&page->lru);
1184 1185 1186 1187 1188 1189 1190

		/*
		 * Compaction can migrate also non-LRU pages which are
		 * not accounted to NR_ISOLATED_*. They can be recognized
		 * as __PageMovable
		 */
		if (likely(!__PageMovable(page)))
1191 1192
			mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
					page_is_file_cache(page), -hpage_nr_pages(page));
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	}

	/*
	 * If migration is successful, releases reference grabbed during
	 * isolation. Otherwise, restore the page to right list unless
	 * we want to retry.
	 */
	if (rc == MIGRATEPAGE_SUCCESS) {
		put_page(page);
		if (reason == MR_MEMORY_FAILURE) {
1203
			/*
1204 1205 1206
			 * Set PG_HWPoison on just freed page
			 * intentionally. Although it's rather weird,
			 * it's how HWPoison flag works at the moment.
1207
			 */
1208 1209
			if (!test_set_page_hwpoison(page))
				num_poisoned_pages_inc();
1210 1211
		}
	} else {
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
		if (rc != -EAGAIN) {
			if (likely(!__PageMovable(page))) {
				putback_lru_page(page);
				goto put_new;
			}

			lock_page(page);
			if (PageMovable(page))
				putback_movable_page(page);
			else
				__ClearPageIsolated(page);
			unlock_page(page);
			put_page(page);
		}
put_new:
1227 1228 1229 1230
		if (put_new_page)
			put_new_page(newpage, private);
		else
			put_page(newpage);
1231
	}
1232

1233 1234 1235 1236 1237 1238
	if (result) {
		if (rc)
			*result = rc;
		else
			*result = page_to_nid(newpage);
	}
1239 1240 1241
	return rc;
}

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
/*
 * Counterpart of unmap_and_move_page() for hugepage migration.
 *
 * This function doesn't wait the completion of hugepage I/O
 * because there is no race between I/O and migration for hugepage.
 * Note that currently hugepage I/O occurs only in direct I/O
 * where no lock is held and PG_writeback is irrelevant,
 * and writeback status of all subpages are counted in the reference
 * count of the head page (i.e. if all subpages of a 2MB hugepage are
 * under direct I/O, the reference of the head page is 512 and a bit more.)
 * This means that when we try to migrate hugepage whose subpages are
 * doing direct I/O, some references remain after try_to_unmap() and
 * hugepage migration fails without data corruption.
 *
 * There is also no race when direct I/O is issued on the page under migration,
 * because then pte is replaced with migration swap entry and direct I/O code
 * will wait in the page fault for migration to complete.
 */
static int unmap_and_move_huge_page(new_page_t get_new_page,
1261 1262
				free_page_t put_new_page, unsigned long private,
				struct page *hpage, int force,
Vlastimil Babka's avatar