migrate.c 75.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/compat.h>
38
#include <linux/hugetlb.h>
39
#include <linux/hugetlb_cgroup.h>
40
#include <linux/gfp.h>
41
#include <linux/pfn_t.h>
42
#include <linux/memremap.h>
43
#include <linux/userfaultfd_k.h>
44
#include <linux/balloon_compaction.h>
45
#include <linux/mmu_notifier.h>
46
#include <linux/page_idle.h>
47
#include <linux/page_owner.h>
48
#include <linux/sched/mm.h>
49
#include <linux/ptrace.h>
50

51 52
#include <asm/tlbflush.h>

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

56 57 58
#include "internal.h"

/*
59
 * migrate_prep() needs to be called before we start compiling a list of pages
60 61
 * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
 * undesirable, use migrate_prep_local()
62 63 64 65 66 67 68 69 70 71 72 73 74 75
 */
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;
}

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

	return 0;
}

84
int isolate_movable_page(struct page *page, isolate_mode_t mode)
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 134
{
	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);

135
	return 0;
136 137 138 139 140 141

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

/* 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);
}

159 160 161 162
/*
 * Put previously isolated pages back onto the appropriate lists
 * from where they were once taken off for compaction/migration.
 *
163 164 165
 * 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().
166 167 168 169 170 171
 */
void putback_movable_pages(struct list_head *l)
{
	struct page *page;
	struct page *page2;

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

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

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

224 225 226 227 228 229 230 231 232
#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

233 234 235 236
		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);
237

238 239 240 241 242 243
		/*
		 * 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);
244

245 246 247 248 249 250 251 252
		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);
			}
253 254 255
		} else
			flush_dcache_page(new);

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

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

278 279 280
		if (PageTransHuge(page) && PageMlocked(page))
			clear_page_mlock(page);

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

285
	return true;
286 287
}

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

299 300 301 302
	if (locked)
		rmap_walk_locked(new, &rwc);
	else
		rmap_walk(new, &rwc);
303 304
}

305 306 307 308 309
/*
 * 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.
 */
310
void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
311
				spinlock_t *ptl)
312
{
313
	pte_t pte;
314 315 316
	swp_entry_t entry;
	struct page *page;

317
	spin_lock(ptl);
318 319 320 321 322 323 324 325 326 327
	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);

328
	/*
329
	 * Once page cache replacement of page migration started, page_count
330 331 332 333 334 335 336
	 * *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;
337 338 339 340 341 342 343 344
	pte_unmap_unlock(ptep, ptl);
	wait_on_page_locked(page);
	put_page(page);
	return;
out:
	pte_unmap_unlock(ptep, ptl);
}

345 346 347 348 349 350 351 352
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);
}

353 354
void migration_entry_wait_huge(struct vm_area_struct *vma,
		struct mm_struct *mm, pte_t *pte)
355
{
356
	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
357 358 359
	__migration_entry_wait(mm, pte, ptl);
}

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
#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

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

	/* Simple case, sync compaction */
389
	if (mode != MIGRATE_ASYNC) {
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 421 422 423 424
		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,
425
							enum migrate_mode mode)
426 427 428 429 430
{
	return true;
}
#endif /* CONFIG_BLOCK */

431
/*
432
 * Replace the page in the mapping.
433 434 435 436
 *
 * The number of remaining references must be:
 * 1 for anonymous pages without a mapping
 * 2 for pages with a mapping
437
 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
438
 */
439
int migrate_page_move_mapping(struct address_space *mapping,
440
		struct page *newpage, struct page *page,
441 442
		struct buffer_head *head, enum migrate_mode mode,
		int extra_count)
443
{
444
	XA_STATE(xas, &mapping->i_pages, page_index(page));
445 446
	struct zone *oldzone, *newzone;
	int dirty;
447
	int expected_count = 1 + extra_count;
448

449
	/*
450 451
	 * Device public or private pages have an extra refcount as they are
	 * ZONE_DEVICE pages.
452
	 */
453 454
	expected_count += is_device_private_page(page);
	expected_count += is_device_public_page(page);
455

456
	if (!mapping) {
457
		/* Anonymous page without mapping */
458
		if (page_count(page) != expected_count)
459
			return -EAGAIN;
460 461 462 463 464

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

467
		return MIGRATEPAGE_SUCCESS;
468 469
	}

470 471 472
	oldzone = page_zone(page);
	newzone = page_zone(newpage);

473
	xas_lock_irq(&xas);
474

475
	expected_count += hpage_nr_pages(page) + page_has_private(page);
476 477
	if (page_count(page) != expected_count || xas_load(&xas) != page) {
		xas_unlock_irq(&xas);
478
		return -EAGAIN;
479 480
	}

481
	if (!page_ref_freeze(page, expected_count)) {
482
		xas_unlock_irq(&xas);
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
		xas_unlock_irq(&xas);
497 498 499
		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
	page_ref_add(newpage, hpage_nr_pages(page)); /* 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
	xas_store(&xas, newpage);
525 526 527
	if (PageTransHuge(page)) {
		int i;

528
		for (i = 1; i < HPAGE_PMD_NR; i++) {
529 530
			xas_next(&xas);
			xas_store(&xas, newpage + i);
531 532
		}
	}
533 534

	/*
535 536
	 * Drop cache reference from old page by unfreezing
	 * to one less reference.
537 538
	 * We know this isn't the last reference.
	 */
539
	page_ref_unfreeze(page, expected_count - hpage_nr_pages(page));
540

541
	xas_unlock(&xas);
542 543
	/* Leave irq disabled to prevent preemption while updating stats */

544 545 546 547 548 549 550
	/*
	 * 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
551
	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
552 553
	 * are mapped to swap space.
	 */
554
	if (newzone != oldzone) {
555 556
		__dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES);
		__inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES);
557
		if (PageSwapBacked(page) && !PageSwapCache(page)) {
558 559
			__dec_node_state(oldzone->zone_pgdat, NR_SHMEM);
			__inc_node_state(newzone->zone_pgdat, NR_SHMEM);
560 561
		}
		if (dirty && mapping_cap_account_dirty(mapping)) {
562
			__dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY);
563
			__dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING);
564
			__inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY);
565
			__inc_zone_state(newzone, NR_ZONE_WRITE_PENDING);
566
		}
567
	}
568
	local_irq_enable();
569

570
	return MIGRATEPAGE_SUCCESS;
571
}
572
EXPORT_SYMBOL(migrate_page_move_mapping);
573

574 575 576 577 578 579 580
/*
 * 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)
{
581
	XA_STATE(xas, &mapping->i_pages, page_index(page));
582 583
	int expected_count;

584
	xas_lock_irq(&xas);
585
	expected_count = 2 + page_has_private(page);
586 587
	if (page_count(page) != expected_count || xas_load(&xas) != page) {
		xas_unlock_irq(&xas);
588 589 590
		return -EAGAIN;
	}

591
	if (!page_ref_freeze(page, expected_count)) {
592
		xas_unlock_irq(&xas);
593 594 595
		return -EAGAIN;
	}

596 597
	newpage->index = page->index;
	newpage->mapping = page->mapping;
598

599 600
	get_page(newpage);

601
	xas_store(&xas, newpage);
602

603
	page_ref_unfreeze(page, expected_count - 1);
604

605
	xas_unlock_irq(&xas);
606

607
	return MIGRATEPAGE_SUCCESS;
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 655 656 657
/*
 * 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);
	}
}

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

665 666 667 668 669 670
	if (PageError(page))
		SetPageError(newpage);
	if (PageReferenced(page))
		SetPageReferenced(newpage);
	if (PageUptodate(page))
		SetPageUptodate(newpage);
671
	if (TestClearPageActive(page)) {
672
		VM_BUG_ON_PAGE(PageUnevictable(page), page);
673
		SetPageActive(newpage);
674 675
	} else if (TestClearPageUnevictable(page))
		SetPageUnevictable(newpage);
676 677
	if (PageWorkingset(page))
		SetPageWorkingset(newpage);
678 679 680 681 682
	if (PageChecked(page))
		SetPageChecked(newpage);
	if (PageMappedToDisk(page))
		SetPageMappedToDisk(newpage);

683 684 685
	/* Move dirty on pages not done by migrate_page_move_mapping() */
	if (PageDirty(page))
		SetPageDirty(newpage);
686

687 688 689 690 691
	if (page_is_young(page))
		set_page_young(newpage);
	if (page_is_idle(page))
		set_page_idle(newpage);

692 693 694 695 696 697 698
	/*
	 * 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);

699
	ksm_migrate_page(newpage, page);
700 701 702 703
	/*
	 * Please do not reorder this without considering how mm/ksm.c's
	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
	 */
704 705
	if (PageSwapCache(page))
		ClearPageSwapCache(page);
706 707 708 709 710 711 712 713 714
	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);
715 716

	copy_page_owner(page, newpage);
717 718

	mem_cgroup_migrate(page, newpage);
719
}
720 721 722 723 724 725 726 727 728 729 730
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);
}
731
EXPORT_SYMBOL(migrate_page_copy);
732

733 734 735 736
/************************************************************
 *                    Migration functions
 ***********************************************************/

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

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

751
	rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
752

753
	if (rc != MIGRATEPAGE_SUCCESS)
754 755
		return rc;

756 757 758 759
	if (mode != MIGRATE_SYNC_NO_COPY)
		migrate_page_copy(newpage, page);
	else
		migrate_page_states(newpage, page);
760
	return MIGRATEPAGE_SUCCESS;
761 762 763
}
EXPORT_SYMBOL(migrate_page);

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

	if (!page_has_buffers(page))
777
		return migrate_page(mapping, newpage, page, mode);
778 779 780

	head = page_buffers(page);

781
	rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0);
782

783
	if (rc != MIGRATEPAGE_SUCCESS)
784 785
		return rc;

786 787 788 789 790
	/*
	 * 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
	 */
791 792
	if (mode != MIGRATE_ASYNC)
		BUG_ON(!buffer_migrate_lock_buffers(head, mode));
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

	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);

809 810 811 812
	if (mode != MIGRATE_SYNC_NO_COPY)
		migrate_page_copy(newpage, page);
	else
		migrate_page_states(newpage, page);
813 814 815 816

	bh = head;
	do {
		unlock_buffer(bh);
817
		put_bh(bh);
818 819 820 821
		bh = bh->b_this_page;

	} while (bh != head);

822
	return MIGRATEPAGE_SUCCESS;
823 824
}
EXPORT_SYMBOL(buffer_migrate_page);
825
#endif
826

827 828 829 830
/*
 * Writeback a page to clean the dirty state
 */
static int writeout(struct address_space *mapping, struct page *page)
831
{
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
	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;

849
	/*
850 851 852 853 854 855
	 * 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.
856
	 */
857
	remove_migration_ptes(page, page, false);
858

859
	rc = mapping->a_ops->writepage(page, &wbc);
860

861 862 863 864
	if (rc != AOP_WRITEPAGE_ACTIVATE)
		/* unlocked. Relock */
		lock_page(page);

865
	return (rc < 0) ? -EIO : -EAGAIN;
866 867 868 869 870 871
}

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

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

894
	return migrate_page(mapping, newpage, page, mode);
895 896
}

897 898 899 900 901 902
/*
 * 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.
903 904 905
 *
 * Return value:
 *   < 0 - error code
906
 *  MIGRATEPAGE_SUCCESS - success
907
 */
908
static int move_to_new_page(struct page *newpage, struct page *page,
909
				enum migrate_mode mode)
910 911
{
	struct address_space *mapping;
912 913
	int rc = -EAGAIN;
	bool is_lru = !__PageMovable(page);
914

915 916
	VM_BUG_ON_PAGE(!PageLocked(page), page);
	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
917 918

	mapping = page_mapping(page);
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

	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 {
937
		/*
938 939
		 * In case of non-lru page, it could be released after
		 * isolation step. In that case, we shouldn't try migration.
940
		 */
941 942 943 944 945 946 947 948 949 950 951 952
		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));
	}
953

954 955 956 957 958
	/*
	 * 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) {
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
		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))
975
			page->mapping = NULL;
976
	}
977
out:
978 979 980
	return rc;
}

981
static int __unmap_and_move(struct page *page, struct page *newpage,
982
				int force, enum migrate_mode mode)
983
{
984
	int rc = -EAGAIN;
985
	int page_was_mapped = 0;
986
	struct anon_vma *anon_vma = NULL;
987
	bool is_lru = !__PageMovable(page);
988

Nick Piggin's avatar
Nick Piggin committed
989
	if (!trylock_page(page)) {
990
		if (!force || mode == MIGRATE_ASYNC)
991
			goto out;
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

		/*
		 * 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)
1007
			goto out;
1008

1009 1010 1011 1012
		lock_page(page);
	}

	if (PageWriteback(page)) {
1013
		/*
1014
		 * Only in the case of a full synchronous migration is it
1015 1016 1017
		 * 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
1018
		 */
1019 1020 1021 1022 1023
		switch (mode) {
		case MIGRATE_SYNC:
		case MIGRATE_SYNC_NO_COPY:
			break;
		default:
1024
			rc = -EBUSY;
1025
			goto out_unlock;
1026 1027
		}
		if (!force)
1028
			goto out_unlock;
1029 1030
		wait_on_page_writeback(page);
	}
1031

1032
	/*
1033 1034
	 * 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.
1035
	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1036
	 * of migration. File cache pages are no problem because of page_lock()
1037 1038
	 * File Caches may use write_page() or lock_page() in migration, then,
	 * just care Anon page here.
1039 1040 1041 1042 1043 1044
	 *
	 * 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).
1045
	 */
1046
	if (PageAnon(page) && !PageKsm(page))
1047
		anon_vma = page_get_anon_vma(page);
1048

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	/*
	 * 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;

1060 1061 1062 1063 1064
	if (unlikely(!is_lru)) {
		rc = move_to_new_page(newpage, page, mode);
		goto out_unlock_both;
	}

1065
	/*
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	 * 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.
1076
	 */
1077
	if (!page->mapping) {
1078
		VM_BUG_ON_PAGE(PageAnon(page), page);
1079
		if (page_has_private(page)) {
1080
			try_to_free_buffers(page);
1081
			goto out_unlock_both;
1082
		}
1083 1084
	} else if (page_mapped(page)) {
		/* Establish migration ptes */
1085 1086
		VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
				page);
1087
		try_to_unmap(page,
1088
			TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1089 1090
		page_was_mapped = 1;
	}
1091

1092
	if (!page_mapped(page))
1093
		rc = move_to_new_page(newpage, page, mode);
1094

1095 1096
	if (page_was_mapped)
		remove_migration_ptes(page,
1097
			rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1098

1099 1100 1101
out_unlock_both:
	unlock_page(newpage);
out_unlock:
1102
	/* Drop an anon_vma reference if we took one */
1103
	if (anon_vma)
1104
		put_anon_vma(anon_vma);
1105
	unlock_page(page);
1106
out:
1107 1108 1109 1110 1111 1112 1113
	/*
	 * 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) {
1114
		if (unlikely(__PageMovable(newpage)))
1115 1116 1117 1118 1119
			put_page(newpage);
		else
			putback_lru_page(newpage);
	}

1120 1121
	return rc;
}
1122

1123 1124 1125 1126
/*
 * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move().  Work
 * around it.
 */
1127 1128
#if defined(CONFIG_ARM) && \
	defined(GCC_VERSION) && GCC_VERSION < 40900 && GCC_VERSION >= 40700
1129 1130 1131 1132 1133
#define ICE_noinline noinline
#else
#define ICE_noinline
#endif

1134 1135 1136 1137
/*
 * Obtain the lock on page, remove all ptes and migrate the page
 * to the newly allocated page in newpage.
 */
1138 1139 1140
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,
1141 1142
				   int force, enum migrate_mode mode,
				   enum migrate_reason reason)
1143
{
1144 1145
	int rc = MIGRATEPAGE_SUCCESS;
	struct page *newpage;
1146

1147 1148 1149
	if (!thp_migration_supported() && PageTransHuge(page))
		return -ENOMEM;

1150
	newpage = get_new_page(page, private);
1151 1152 1153 1154 1155
	if (!newpage)
		return -ENOMEM;

	if (page_count(page) == 1) {
		/* page was freed from under us. So we are done. */
1156 1157
		ClearPageActive(page);
		ClearPageUnevictable(page);
1158 1159 1160 1161 1162 1163
		if (unlikely(__PageMovable(page))) {
			lock_page(page);
			if (!PageMovable(page))
				__ClearPageIsolated(page);
			unlock_page(page);
		}
1164 1165 1166 1167
		if (put_new_page)
			put_new_page(newpage, private);
		else
			put_page(newpage);
1168 1169 1170
		goto out;
	}

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
			if (set_hwpoison_free_buddy_page(page))
1209
				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
	return rc;
}

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
/*
 * 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,
1255 1256
				free_page_t put_new_page, unsigned long private,
				struct page *hpage, int force,
1257
				enum migrate_mode mode, int reason)
1258
{
1259
	int rc = -EAGAIN;
1260
	int page_was_mapped = 0;
1261
	struct page *new_hpage;
1262 1263
	struct anon_vma *anon_vma = NULL;

1264 1265 1266 1267 1268 1269 1270
	/*
	 * Movability of hugepages depends on architectures and hugepage size.
	 * This check is necessary because some callers of hugepage migration
	 * like soft offline and memory hotremove don't walk through page
	 * tables or check whether the hugepage is pmd-based or not before
	 * kicking migration.
	 */
1271
	if (!hugepage_migration_supported(page_hstate(hpage))) {
1272
		putback_active_hugepage(hpage);
1273
		return -ENOSYS;
1274
	}
1275

1276
	new_hpage = get_new_page(hpage, private);
1277 1278 1279 1280
	if (!new_hpage)
		return -ENOMEM;

	if (!trylock_page(hpage)) {
1281
		if (!force)
1282
			goto out;
1283 1284 1285 1286 1287 1288 1289
		switch (mode) {
		case MIGRATE_SYNC:
		case MIGRATE_SYNC_NO_COPY:
			break;
		default:
			goto out;
		}
1290 1291 1292
		lock_page(hpage);
	}

1293 1294
	if (PageAnon(hpage))
		anon_vma = page_get_anon_vma(hpage);
1295

1296 1297 1298
	if (unlikely(!trylock_page(new_hpage)))
		goto put_anon;

1299 1300 1301 1302 1303
	if (page_mapped(hpage)) {
		try_to_unmap(hpage,
			TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
		page_was_mapped = 1;
	}
1304 1305

	if (!page_mapped(hpage))
1306
		rc = move_to_new_page(new_hpage, hpage, mode);
1307

1308 1309
	if (page_was_mapped)
		remove_migration_ptes(hpage,
1310
			rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1311

1312 1313 1314
	unlock_page(new_hpage);

put_anon:
1315
	if (anon_vma)
1316
		put_anon_vma(anon_vma);
1317

1318
	if (rc == MIGRATEPAGE_SUCCESS) {
1319
		move_hugetlb_state(hpage, new_hpage, reason);
1320 1321
		put_new_page = NULL;
	}
1322

1323
	unlock_page(hpage);
1324
out:
1325 1326
	if (rc != -EAGAIN)
		putback_active_hugepage(hpage);
1327 1328 1329 1330 1331 1332

	/*
	 * If migration was not successful and there's a freeing callback, use
	 * it.  Otherwise, put_page() will drop the reference grabbed during
	 * isolation.
	 */
1333
	if (put_new_page)
1334 1335
		put_new_page(new_hpage, private);
	else
1336
		putback_active_hugepage(new_hpage);
1337

1338 1339 1340
	return rc;
}

1341
/*
1342 1343
 * migrate_pages - migrate the pages specified in a list, to the free pages
 *		   supplied as the target for the page migration
1344
 *
1345 1346 1347
 * @from:		The list of pages to be migrated.
 * @get_new_page:	The function used to allocate free pages to be used
 *			as the target of the page migration.
1348 1349
 * @put_new_page:	The function used to free target pages if migration
 *			fails, or NULL if no special handling is necessary.
1350 1351 1352 1353
 * @private:		Private data to be passed on to get_new_page()
 * @mode:		The migration mode that specifies the constraints for
 *			page migration, if any.
 * @reason:		The reason for page migration.
1354
 *
1355 1356
 * The function returns after 10 attempts or if no pages are movable any more
 * because the list has become empty or no retryable pages exist any more.
1357
 * The caller should call putback_movable_pages() to return pages to the LRU
1358
 * or free list only if ret != 0.
1359
 *
1360
 * Returns the number of pages that were not migrated, or an error code.
1361
 */
1362
int migrate_pages(struct list_head *from, new_page_t get_new_page,
1363 1364
		free_page_t put_new_page, unsigned long private,
		enum migrate_mode mode, int reason)
1365
{
1366
	int retry = 1;
1367
	int nr_failed = 0;
1368
	int nr_succeeded = 0;
1369 1370 1371 1372 1373 1374 1375 1376 1377
	int pass = 0;
	struct page *page;
	struct page *page2;
	int swapwrite = current->flags & PF_SWAPWRITE;
	int rc;

	if (!swapwrite)
		current->flags |= PF_SWAPWRITE;

1378 1379
	for(pass = 0; pass < 10 && retry; pass++) {
		retry = 0;
1380

1381
		list_for_each_entry_safe(page, page2, from, lru) {
1382
retry:
1383
			cond_resched();