• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Memory Migration functionality - linux/mm/migrate.c
4  *
5  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
6  *
7  * Page migration was first developed in the context of the memory hotplug
8  * project. The main authors of the migration code are:
9  *
10  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11  * Hirokazu Takahashi <taka@valinux.co.jp>
12  * Dave Hansen <haveblue@us.ibm.com>
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 #include <linux/rmap.h>
27 #include <linux/topology.h>
28 #include <linux/cpu.h>
29 #include <linux/cpuset.h>
30 #include <linux/writeback.h>
31 #include <linux/mempolicy.h>
32 #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/pagewalk.h>
42 #include <linux/pfn_t.h>
43 #include <linux/memremap.h>
44 #include <linux/userfaultfd_k.h>
45 #include <linux/balloon_compaction.h>
46 #include <linux/mmu_notifier.h>
47 #include <linux/page_idle.h>
48 #include <linux/page_owner.h>
49 #include <linux/sched/mm.h>
50 #include <linux/ptrace.h>
51 #include <linux/oom.h>
52 #include <linux/memory.h>
53 
54 #include <asm/tlbflush.h>
55 
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/migrate.h>
58 
59 #include "internal.h"
60 
isolate_movable_page(struct page * page,isolate_mode_t mode)61 int isolate_movable_page(struct page *page, isolate_mode_t mode)
62 {
63 	struct address_space *mapping;
64 
65 	/*
66 	 * Avoid burning cycles with pages that are yet under __free_pages(),
67 	 * or just got freed under us.
68 	 *
69 	 * In case we 'win' a race for a movable page being freed under us and
70 	 * raise its refcount preventing __free_pages() from doing its job
71 	 * the put_page() at the end of this block will take care of
72 	 * release this page, thus avoiding a nasty leakage.
73 	 */
74 	if (unlikely(!get_page_unless_zero(page)))
75 		goto out;
76 
77 	/*
78 	 * Check PageMovable before holding a PG_lock because page's owner
79 	 * assumes anybody doesn't touch PG_lock of newly allocated page
80 	 * so unconditionally grabbing the lock ruins page's owner side.
81 	 */
82 	if (unlikely(!__PageMovable(page)))
83 		goto out_putpage;
84 	/*
85 	 * As movable pages are not isolated from LRU lists, concurrent
86 	 * compaction threads can race against page migration functions
87 	 * as well as race against the releasing a page.
88 	 *
89 	 * In order to avoid having an already isolated movable page
90 	 * being (wrongly) re-isolated while it is under migration,
91 	 * or to avoid attempting to isolate pages being released,
92 	 * lets be sure we have the page lock
93 	 * before proceeding with the movable page isolation steps.
94 	 */
95 	if (unlikely(!trylock_page(page)))
96 		goto out_putpage;
97 
98 	if (!PageMovable(page) || PageIsolated(page))
99 		goto out_no_isolated;
100 
101 	mapping = page_mapping(page);
102 	VM_BUG_ON_PAGE(!mapping, page);
103 
104 	if (!mapping->a_ops->isolate_page(page, mode))
105 		goto out_no_isolated;
106 
107 	/* Driver shouldn't use PG_isolated bit of page->flags */
108 	WARN_ON_ONCE(PageIsolated(page));
109 	SetPageIsolated(page);
110 	unlock_page(page);
111 
112 	return 0;
113 
114 out_no_isolated:
115 	unlock_page(page);
116 out_putpage:
117 	put_page(page);
118 out:
119 	return -EBUSY;
120 }
121 
putback_movable_page(struct page * page)122 static void putback_movable_page(struct page *page)
123 {
124 	struct address_space *mapping;
125 
126 	mapping = page_mapping(page);
127 	mapping->a_ops->putback_page(page);
128 	ClearPageIsolated(page);
129 }
130 
131 /*
132  * Put previously isolated pages back onto the appropriate lists
133  * from where they were once taken off for compaction/migration.
134  *
135  * This function shall be used whenever the isolated pageset has been
136  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
137  * and isolate_hugetlb().
138  */
putback_movable_pages(struct list_head * l)139 void putback_movable_pages(struct list_head *l)
140 {
141 	struct page *page;
142 	struct page *page2;
143 
144 	list_for_each_entry_safe(page, page2, l, lru) {
145 		if (unlikely(PageHuge(page))) {
146 			putback_active_hugepage(page);
147 			continue;
148 		}
149 		list_del(&page->lru);
150 		/*
151 		 * We isolated non-lru movable page so here we can use
152 		 * __PageMovable because LRU page's mapping cannot have
153 		 * PAGE_MAPPING_MOVABLE.
154 		 */
155 		if (unlikely(__PageMovable(page))) {
156 			VM_BUG_ON_PAGE(!PageIsolated(page), page);
157 			lock_page(page);
158 			if (PageMovable(page))
159 				putback_movable_page(page);
160 			else
161 				ClearPageIsolated(page);
162 			unlock_page(page);
163 			put_page(page);
164 		} else {
165 			mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
166 					page_is_file_lru(page), -thp_nr_pages(page));
167 			putback_lru_page(page);
168 		}
169 	}
170 }
171 EXPORT_SYMBOL_GPL(putback_movable_pages);
172 
173 /*
174  * Restore a potential migration pte to a working pte entry
175  */
remove_migration_pte(struct page * page,struct vm_area_struct * vma,unsigned long addr,void * old)176 static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
177 				 unsigned long addr, void *old)
178 {
179 	struct page_vma_mapped_walk pvmw = {
180 		.page = old,
181 		.vma = vma,
182 		.address = addr,
183 		.flags = PVMW_SYNC | PVMW_MIGRATION,
184 	};
185 	struct page *new;
186 	pte_t pte;
187 	swp_entry_t entry;
188 
189 	VM_BUG_ON_PAGE(PageTail(page), page);
190 	while (page_vma_mapped_walk(&pvmw)) {
191 		if (PageKsm(page))
192 			new = page;
193 		else
194 			new = page - pvmw.page->index +
195 				linear_page_index(vma, pvmw.address);
196 
197 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
198 		/* PMD-mapped THP migration entry */
199 		if (!pvmw.pte) {
200 			VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
201 			remove_migration_pmd(&pvmw, new);
202 			continue;
203 		}
204 #endif
205 
206 		get_page(new);
207 		pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
208 		if (pte_swp_soft_dirty(*pvmw.pte))
209 			pte = pte_mksoft_dirty(pte);
210 
211 		/*
212 		 * Recheck VMA as permissions can change since migration started
213 		 */
214 		entry = pte_to_swp_entry(*pvmw.pte);
215 		if (is_writable_migration_entry(entry))
216 			pte = maybe_mkwrite(pte, vma);
217 		else if (pte_swp_uffd_wp(*pvmw.pte))
218 			pte = pte_mkuffd_wp(pte);
219 
220 		if (unlikely(is_device_private_page(new))) {
221 			if (pte_write(pte))
222 				entry = make_writable_device_private_entry(
223 							page_to_pfn(new));
224 			else
225 				entry = make_readable_device_private_entry(
226 							page_to_pfn(new));
227 			pte = swp_entry_to_pte(entry);
228 			if (pte_swp_soft_dirty(*pvmw.pte))
229 				pte = pte_swp_mksoft_dirty(pte);
230 			if (pte_swp_uffd_wp(*pvmw.pte))
231 				pte = pte_swp_mkuffd_wp(pte);
232 		}
233 
234 #ifdef CONFIG_HUGETLB_PAGE
235 		if (PageHuge(new)) {
236 			unsigned int shift = huge_page_shift(hstate_vma(vma));
237 
238 			pte = pte_mkhuge(pte);
239 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
240 			set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
241 			if (PageAnon(new))
242 				hugepage_add_anon_rmap(new, vma, pvmw.address);
243 			else
244 				page_dup_rmap(new, true);
245 		} else
246 #endif
247 		{
248 			set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
249 
250 			if (PageAnon(new))
251 				page_add_anon_rmap(new, vma, pvmw.address, false);
252 			else
253 				page_add_file_rmap(new, false);
254 		}
255 		if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
256 			mlock_vma_page(new);
257 
258 		if (PageTransHuge(page) && PageMlocked(page))
259 			clear_page_mlock(page);
260 
261 		/* No need to invalidate - it was non-present before */
262 		update_mmu_cache(vma, pvmw.address, pvmw.pte);
263 	}
264 
265 	return true;
266 }
267 
268 /*
269  * Get rid of all migration entries and replace them by
270  * references to the indicated page.
271  */
remove_migration_ptes(struct page * old,struct page * new,bool locked)272 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
273 {
274 	struct rmap_walk_control rwc = {
275 		.rmap_one = remove_migration_pte,
276 		.arg = old,
277 	};
278 
279 	if (locked)
280 		rmap_walk_locked(new, &rwc);
281 	else
282 		rmap_walk(new, &rwc);
283 }
284 
285 /*
286  * Something used the pte of a page under migration. We need to
287  * get to the page and wait until migration is finished.
288  * When we return from this function the fault will be retried.
289  */
__migration_entry_wait(struct mm_struct * mm,pte_t * ptep,spinlock_t * ptl)290 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
291 				spinlock_t *ptl)
292 {
293 	pte_t pte;
294 	swp_entry_t entry;
295 	struct page *page;
296 
297 	spin_lock(ptl);
298 	pte = *ptep;
299 	if (!is_swap_pte(pte))
300 		goto out;
301 
302 	entry = pte_to_swp_entry(pte);
303 	if (!is_migration_entry(entry))
304 		goto out;
305 
306 	page = pfn_swap_entry_to_page(entry);
307 	page = compound_head(page);
308 
309 	/*
310 	 * Once page cache replacement of page migration started, page_count
311 	 * is zero; but we must not call put_and_wait_on_page_locked() without
312 	 * a ref. Use get_page_unless_zero(), and just fault again if it fails.
313 	 */
314 	if (!get_page_unless_zero(page))
315 		goto out;
316 	pte_unmap_unlock(ptep, ptl);
317 	put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
318 	return;
319 out:
320 	pte_unmap_unlock(ptep, ptl);
321 }
322 
migration_entry_wait(struct mm_struct * mm,pmd_t * pmd,unsigned long address)323 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
324 				unsigned long address)
325 {
326 	spinlock_t *ptl = pte_lockptr(mm, pmd);
327 	pte_t *ptep = pte_offset_map(pmd, address);
328 	__migration_entry_wait(mm, ptep, ptl);
329 }
330 
migration_entry_wait_huge(struct vm_area_struct * vma,struct mm_struct * mm,pte_t * pte)331 void migration_entry_wait_huge(struct vm_area_struct *vma,
332 		struct mm_struct *mm, pte_t *pte)
333 {
334 	spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
335 	__migration_entry_wait(mm, pte, ptl);
336 }
337 
338 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
pmd_migration_entry_wait(struct mm_struct * mm,pmd_t * pmd)339 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
340 {
341 	spinlock_t *ptl;
342 	struct page *page;
343 
344 	ptl = pmd_lock(mm, pmd);
345 	if (!is_pmd_migration_entry(*pmd))
346 		goto unlock;
347 	page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
348 	if (!get_page_unless_zero(page))
349 		goto unlock;
350 	spin_unlock(ptl);
351 	put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE);
352 	return;
353 unlock:
354 	spin_unlock(ptl);
355 }
356 #endif
357 
expected_page_refs(struct address_space * mapping,struct page * page)358 static int expected_page_refs(struct address_space *mapping, struct page *page)
359 {
360 	int expected_count = 1;
361 
362 	/*
363 	 * Device private pages have an extra refcount as they are
364 	 * ZONE_DEVICE pages.
365 	 */
366 	expected_count += is_device_private_page(page);
367 	if (mapping)
368 		expected_count += thp_nr_pages(page) + page_has_private(page);
369 
370 	return expected_count;
371 }
372 
373 /*
374  * Replace the page in the mapping.
375  *
376  * The number of remaining references must be:
377  * 1 for anonymous pages without a mapping
378  * 2 for pages with a mapping
379  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
380  */
migrate_page_move_mapping(struct address_space * mapping,struct page * newpage,struct page * page,int extra_count)381 int migrate_page_move_mapping(struct address_space *mapping,
382 		struct page *newpage, struct page *page, int extra_count)
383 {
384 	XA_STATE(xas, &mapping->i_pages, page_index(page));
385 	struct zone *oldzone, *newzone;
386 	int dirty;
387 	int expected_count = expected_page_refs(mapping, page) + extra_count;
388 	int nr = thp_nr_pages(page);
389 
390 	if (!mapping) {
391 		/* Anonymous page without mapping */
392 		if (page_count(page) != expected_count)
393 			return -EAGAIN;
394 
395 		/* No turning back from here */
396 		newpage->index = page->index;
397 		newpage->mapping = page->mapping;
398 		if (PageSwapBacked(page))
399 			__SetPageSwapBacked(newpage);
400 
401 		return MIGRATEPAGE_SUCCESS;
402 	}
403 
404 	oldzone = page_zone(page);
405 	newzone = page_zone(newpage);
406 
407 	xas_lock_irq(&xas);
408 	if (page_count(page) != expected_count || xas_load(&xas) != page) {
409 		xas_unlock_irq(&xas);
410 		return -EAGAIN;
411 	}
412 
413 	if (!page_ref_freeze(page, expected_count)) {
414 		xas_unlock_irq(&xas);
415 		return -EAGAIN;
416 	}
417 
418 	/*
419 	 * Now we know that no one else is looking at the page:
420 	 * no turning back from here.
421 	 */
422 	newpage->index = page->index;
423 	newpage->mapping = page->mapping;
424 	page_ref_add(newpage, nr); /* add cache reference */
425 	if (PageSwapBacked(page)) {
426 		__SetPageSwapBacked(newpage);
427 		if (PageSwapCache(page)) {
428 			SetPageSwapCache(newpage);
429 			set_page_private(newpage, page_private(page));
430 		}
431 	} else {
432 		VM_BUG_ON_PAGE(PageSwapCache(page), page);
433 	}
434 
435 	/* Move dirty while page refs frozen and newpage not yet exposed */
436 	dirty = PageDirty(page);
437 	if (dirty) {
438 		ClearPageDirty(page);
439 		SetPageDirty(newpage);
440 	}
441 
442 	xas_store(&xas, newpage);
443 	if (PageTransHuge(page)) {
444 		int i;
445 
446 		for (i = 1; i < nr; i++) {
447 			xas_next(&xas);
448 			xas_store(&xas, newpage);
449 		}
450 	}
451 
452 	/*
453 	 * Drop cache reference from old page by unfreezing
454 	 * to one less reference.
455 	 * We know this isn't the last reference.
456 	 */
457 	page_ref_unfreeze(page, expected_count - nr);
458 
459 	xas_unlock(&xas);
460 	/* Leave irq disabled to prevent preemption while updating stats */
461 
462 	/*
463 	 * If moved to a different zone then also account
464 	 * the page for that zone. Other VM counters will be
465 	 * taken care of when we establish references to the
466 	 * new page and drop references to the old page.
467 	 *
468 	 * Note that anonymous pages are accounted for
469 	 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
470 	 * are mapped to swap space.
471 	 */
472 	if (newzone != oldzone) {
473 		struct lruvec *old_lruvec, *new_lruvec;
474 		struct mem_cgroup *memcg;
475 
476 		memcg = page_memcg(page);
477 		old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
478 		new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
479 
480 		__mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
481 		__mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
482 		if (PageSwapBacked(page) && !PageSwapCache(page)) {
483 			__mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
484 			__mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
485 		}
486 #ifdef CONFIG_SWAP
487 		if (PageSwapCache(page)) {
488 			__mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
489 			__mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
490 		}
491 #endif
492 		if (dirty && mapping_can_writeback(mapping)) {
493 			__mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
494 			__mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
495 			__mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
496 			__mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
497 		}
498 	}
499 	local_irq_enable();
500 
501 	return MIGRATEPAGE_SUCCESS;
502 }
503 EXPORT_SYMBOL(migrate_page_move_mapping);
504 
505 /*
506  * The expected number of remaining references is the same as that
507  * of migrate_page_move_mapping().
508  */
migrate_huge_page_move_mapping(struct address_space * mapping,struct page * newpage,struct page * page)509 int migrate_huge_page_move_mapping(struct address_space *mapping,
510 				   struct page *newpage, struct page *page)
511 {
512 	XA_STATE(xas, &mapping->i_pages, page_index(page));
513 	int expected_count;
514 
515 	xas_lock_irq(&xas);
516 	expected_count = 2 + page_has_private(page);
517 	if (page_count(page) != expected_count || xas_load(&xas) != page) {
518 		xas_unlock_irq(&xas);
519 		return -EAGAIN;
520 	}
521 
522 	if (!page_ref_freeze(page, expected_count)) {
523 		xas_unlock_irq(&xas);
524 		return -EAGAIN;
525 	}
526 
527 	newpage->index = page->index;
528 	newpage->mapping = page->mapping;
529 
530 	get_page(newpage);
531 
532 	xas_store(&xas, newpage);
533 
534 	page_ref_unfreeze(page, expected_count - 1);
535 
536 	xas_unlock_irq(&xas);
537 
538 	return MIGRATEPAGE_SUCCESS;
539 }
540 
541 /*
542  * Copy the page to its new location
543  */
migrate_page_states(struct page * newpage,struct page * page)544 void migrate_page_states(struct page *newpage, struct page *page)
545 {
546 	int cpupid;
547 
548 	if (PageError(page))
549 		SetPageError(newpage);
550 	if (PageReferenced(page))
551 		SetPageReferenced(newpage);
552 	if (PageUptodate(page))
553 		SetPageUptodate(newpage);
554 	if (TestClearPageActive(page)) {
555 		VM_BUG_ON_PAGE(PageUnevictable(page), page);
556 		SetPageActive(newpage);
557 	} else if (TestClearPageUnevictable(page))
558 		SetPageUnevictable(newpage);
559 	if (PageWorkingset(page))
560 		SetPageWorkingset(newpage);
561 	if (PageChecked(page))
562 		SetPageChecked(newpage);
563 	if (PageMappedToDisk(page))
564 		SetPageMappedToDisk(newpage);
565 
566 	/* Move dirty on pages not done by migrate_page_move_mapping() */
567 	if (PageDirty(page))
568 		SetPageDirty(newpage);
569 
570 	if (page_is_young(page))
571 		set_page_young(newpage);
572 	if (page_is_idle(page))
573 		set_page_idle(newpage);
574 
575 	/*
576 	 * Copy NUMA information to the new page, to prevent over-eager
577 	 * future migrations of this same page.
578 	 */
579 	cpupid = page_cpupid_xchg_last(page, -1);
580 	page_cpupid_xchg_last(newpage, cpupid);
581 
582 	ksm_migrate_page(newpage, page);
583 	/*
584 	 * Please do not reorder this without considering how mm/ksm.c's
585 	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
586 	 */
587 	if (PageSwapCache(page))
588 		ClearPageSwapCache(page);
589 	ClearPagePrivate(page);
590 
591 	/* page->private contains hugetlb specific flags */
592 	if (!PageHuge(page))
593 		set_page_private(page, 0);
594 
595 	/*
596 	 * If any waiters have accumulated on the new page then
597 	 * wake them up.
598 	 */
599 	if (PageWriteback(newpage))
600 		end_page_writeback(newpage);
601 
602 	/*
603 	 * PG_readahead shares the same bit with PG_reclaim.  The above
604 	 * end_page_writeback() may clear PG_readahead mistakenly, so set the
605 	 * bit after that.
606 	 */
607 	if (PageReadahead(page))
608 		SetPageReadahead(newpage);
609 
610 	copy_page_owner(page, newpage);
611 
612 	if (!PageHuge(page))
613 		mem_cgroup_migrate(page, newpage);
614 }
615 EXPORT_SYMBOL(migrate_page_states);
616 
migrate_page_copy(struct page * newpage,struct page * page)617 void migrate_page_copy(struct page *newpage, struct page *page)
618 {
619 	if (PageHuge(page) || PageTransHuge(page))
620 		copy_huge_page(newpage, page);
621 	else
622 		copy_highpage(newpage, page);
623 
624 	migrate_page_states(newpage, page);
625 }
626 EXPORT_SYMBOL(migrate_page_copy);
627 
628 /************************************************************
629  *                    Migration functions
630  ***********************************************************/
631 
632 /*
633  * Common logic to directly migrate a single LRU page suitable for
634  * pages that do not use PagePrivate/PagePrivate2.
635  *
636  * Pages are locked upon entry and exit.
637  */
migrate_page(struct address_space * mapping,struct page * newpage,struct page * page,enum migrate_mode mode)638 int migrate_page(struct address_space *mapping,
639 		struct page *newpage, struct page *page,
640 		enum migrate_mode mode)
641 {
642 	int rc;
643 
644 	BUG_ON(PageWriteback(page));	/* Writeback must be complete */
645 
646 	rc = migrate_page_move_mapping(mapping, newpage, page, 0);
647 
648 	if (rc != MIGRATEPAGE_SUCCESS)
649 		return rc;
650 
651 	if (mode != MIGRATE_SYNC_NO_COPY)
652 		migrate_page_copy(newpage, page);
653 	else
654 		migrate_page_states(newpage, page);
655 	return MIGRATEPAGE_SUCCESS;
656 }
657 EXPORT_SYMBOL(migrate_page);
658 
659 #ifdef CONFIG_BLOCK
660 /* Returns true if all buffers are successfully locked */
buffer_migrate_lock_buffers(struct buffer_head * head,enum migrate_mode mode)661 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
662 							enum migrate_mode mode)
663 {
664 	struct buffer_head *bh = head;
665 
666 	/* Simple case, sync compaction */
667 	if (mode != MIGRATE_ASYNC) {
668 		do {
669 			lock_buffer(bh);
670 			bh = bh->b_this_page;
671 
672 		} while (bh != head);
673 
674 		return true;
675 	}
676 
677 	/* async case, we cannot block on lock_buffer so use trylock_buffer */
678 	do {
679 		if (!trylock_buffer(bh)) {
680 			/*
681 			 * We failed to lock the buffer and cannot stall in
682 			 * async migration. Release the taken locks
683 			 */
684 			struct buffer_head *failed_bh = bh;
685 			bh = head;
686 			while (bh != failed_bh) {
687 				unlock_buffer(bh);
688 				bh = bh->b_this_page;
689 			}
690 			return false;
691 		}
692 
693 		bh = bh->b_this_page;
694 	} while (bh != head);
695 	return true;
696 }
697 
__buffer_migrate_page(struct address_space * mapping,struct page * newpage,struct page * page,enum migrate_mode mode,bool check_refs)698 static int __buffer_migrate_page(struct address_space *mapping,
699 		struct page *newpage, struct page *page, enum migrate_mode mode,
700 		bool check_refs)
701 {
702 	struct buffer_head *bh, *head;
703 	int rc;
704 	int expected_count;
705 
706 	if (!page_has_buffers(page))
707 		return migrate_page(mapping, newpage, page, mode);
708 
709 	/* Check whether page does not have extra refs before we do more work */
710 	expected_count = expected_page_refs(mapping, page);
711 	if (page_count(page) != expected_count)
712 		return -EAGAIN;
713 
714 	head = page_buffers(page);
715 	if (!buffer_migrate_lock_buffers(head, mode))
716 		return -EAGAIN;
717 
718 	if (check_refs) {
719 		bool busy;
720 		bool invalidated = false;
721 
722 recheck_buffers:
723 		busy = false;
724 		spin_lock(&mapping->private_lock);
725 		bh = head;
726 		do {
727 			if (atomic_read(&bh->b_count)) {
728 				busy = true;
729 				break;
730 			}
731 			bh = bh->b_this_page;
732 		} while (bh != head);
733 		if (busy) {
734 			if (invalidated) {
735 				rc = -EAGAIN;
736 				goto unlock_buffers;
737 			}
738 			spin_unlock(&mapping->private_lock);
739 			invalidate_bh_lrus();
740 			invalidated = true;
741 			goto recheck_buffers;
742 		}
743 	}
744 
745 	rc = migrate_page_move_mapping(mapping, newpage, page, 0);
746 	if (rc != MIGRATEPAGE_SUCCESS)
747 		goto unlock_buffers;
748 
749 	attach_page_private(newpage, detach_page_private(page));
750 
751 	bh = head;
752 	do {
753 		set_bh_page(bh, newpage, bh_offset(bh));
754 		bh = bh->b_this_page;
755 
756 	} while (bh != head);
757 
758 	if (mode != MIGRATE_SYNC_NO_COPY)
759 		migrate_page_copy(newpage, page);
760 	else
761 		migrate_page_states(newpage, page);
762 
763 	rc = MIGRATEPAGE_SUCCESS;
764 unlock_buffers:
765 	if (check_refs)
766 		spin_unlock(&mapping->private_lock);
767 	bh = head;
768 	do {
769 		unlock_buffer(bh);
770 		bh = bh->b_this_page;
771 
772 	} while (bh != head);
773 
774 	return rc;
775 }
776 
777 /*
778  * Migration function for pages with buffers. This function can only be used
779  * if the underlying filesystem guarantees that no other references to "page"
780  * exist. For example attached buffer heads are accessed only under page lock.
781  */
buffer_migrate_page(struct address_space * mapping,struct page * newpage,struct page * page,enum migrate_mode mode)782 int buffer_migrate_page(struct address_space *mapping,
783 		struct page *newpage, struct page *page, enum migrate_mode mode)
784 {
785 	return __buffer_migrate_page(mapping, newpage, page, mode, false);
786 }
787 EXPORT_SYMBOL(buffer_migrate_page);
788 
789 /*
790  * Same as above except that this variant is more careful and checks that there
791  * are also no buffer head references. This function is the right one for
792  * mappings where buffer heads are directly looked up and referenced (such as
793  * block device mappings).
794  */
buffer_migrate_page_norefs(struct address_space * mapping,struct page * newpage,struct page * page,enum migrate_mode mode)795 int buffer_migrate_page_norefs(struct address_space *mapping,
796 		struct page *newpage, struct page *page, enum migrate_mode mode)
797 {
798 	return __buffer_migrate_page(mapping, newpage, page, mode, true);
799 }
800 #endif
801 
802 /*
803  * Writeback a page to clean the dirty state
804  */
writeout(struct address_space * mapping,struct page * page)805 static int writeout(struct address_space *mapping, struct page *page)
806 {
807 	struct writeback_control wbc = {
808 		.sync_mode = WB_SYNC_NONE,
809 		.nr_to_write = 1,
810 		.range_start = 0,
811 		.range_end = LLONG_MAX,
812 		.for_reclaim = 1
813 	};
814 	int rc;
815 
816 	if (!mapping->a_ops->writepage)
817 		/* No write method for the address space */
818 		return -EINVAL;
819 
820 	if (!clear_page_dirty_for_io(page))
821 		/* Someone else already triggered a write */
822 		return -EAGAIN;
823 
824 	/*
825 	 * A dirty page may imply that the underlying filesystem has
826 	 * the page on some queue. So the page must be clean for
827 	 * migration. Writeout may mean we loose the lock and the
828 	 * page state is no longer what we checked for earlier.
829 	 * At this point we know that the migration attempt cannot
830 	 * be successful.
831 	 */
832 	remove_migration_ptes(page, page, false);
833 
834 	rc = mapping->a_ops->writepage(page, &wbc);
835 
836 	if (rc != AOP_WRITEPAGE_ACTIVATE)
837 		/* unlocked. Relock */
838 		lock_page(page);
839 
840 	return (rc < 0) ? -EIO : -EAGAIN;
841 }
842 
843 /*
844  * Default handling if a filesystem does not provide a migration function.
845  */
fallback_migrate_page(struct address_space * mapping,struct page * newpage,struct page * page,enum migrate_mode mode)846 static int fallback_migrate_page(struct address_space *mapping,
847 	struct page *newpage, struct page *page, enum migrate_mode mode)
848 {
849 	if (PageDirty(page)) {
850 		/* Only writeback pages in full synchronous migration */
851 		switch (mode) {
852 		case MIGRATE_SYNC:
853 		case MIGRATE_SYNC_NO_COPY:
854 			break;
855 		default:
856 			return -EBUSY;
857 		}
858 		return writeout(mapping, page);
859 	}
860 
861 	/*
862 	 * Buffers may be managed in a filesystem specific way.
863 	 * We must have no buffers or drop them.
864 	 */
865 	if (page_has_private(page) &&
866 	    !try_to_release_page(page, GFP_KERNEL))
867 		return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
868 
869 	return migrate_page(mapping, newpage, page, mode);
870 }
871 
872 /*
873  * Move a page to a newly allocated page
874  * The page is locked and all ptes have been successfully removed.
875  *
876  * The new page will have replaced the old page if this function
877  * is successful.
878  *
879  * Return value:
880  *   < 0 - error code
881  *  MIGRATEPAGE_SUCCESS - success
882  */
move_to_new_page(struct page * newpage,struct page * page,enum migrate_mode mode)883 static int move_to_new_page(struct page *newpage, struct page *page,
884 				enum migrate_mode mode)
885 {
886 	struct address_space *mapping;
887 	int rc = -EAGAIN;
888 	bool is_lru = !__PageMovable(page);
889 
890 	VM_BUG_ON_PAGE(!PageLocked(page), page);
891 	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
892 
893 	mapping = page_mapping(page);
894 
895 	if (likely(is_lru)) {
896 		if (!mapping)
897 			rc = migrate_page(mapping, newpage, page, mode);
898 		else if (mapping->a_ops->migratepage)
899 			/*
900 			 * Most pages have a mapping and most filesystems
901 			 * provide a migratepage callback. Anonymous pages
902 			 * are part of swap space which also has its own
903 			 * migratepage callback. This is the most common path
904 			 * for page migration.
905 			 */
906 			rc = mapping->a_ops->migratepage(mapping, newpage,
907 							page, mode);
908 		else
909 			rc = fallback_migrate_page(mapping, newpage,
910 							page, mode);
911 	} else {
912 		/*
913 		 * In case of non-lru page, it could be released after
914 		 * isolation step. In that case, we shouldn't try migration.
915 		 */
916 		VM_BUG_ON_PAGE(!PageIsolated(page), page);
917 		if (!PageMovable(page)) {
918 			rc = MIGRATEPAGE_SUCCESS;
919 			ClearPageIsolated(page);
920 			goto out;
921 		}
922 
923 		rc = mapping->a_ops->migratepage(mapping, newpage,
924 						page, mode);
925 		WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
926 			!PageIsolated(page));
927 	}
928 
929 	/*
930 	 * When successful, old pagecache page->mapping must be cleared before
931 	 * page is freed; but stats require that PageAnon be left as PageAnon.
932 	 */
933 	if (rc == MIGRATEPAGE_SUCCESS) {
934 		if (__PageMovable(page)) {
935 			VM_BUG_ON_PAGE(!PageIsolated(page), page);
936 
937 			/*
938 			 * We clear PG_movable under page_lock so any compactor
939 			 * cannot try to migrate this page.
940 			 */
941 			ClearPageIsolated(page);
942 		}
943 
944 		/*
945 		 * Anonymous and movable page->mapping will be cleared by
946 		 * free_pages_prepare so don't reset it here for keeping
947 		 * the type to work PageAnon, for example.
948 		 */
949 		if (!PageMappingFlags(page))
950 			page->mapping = NULL;
951 
952 		if (likely(!is_zone_device_page(newpage))) {
953 			int i, nr = compound_nr(newpage);
954 
955 			for (i = 0; i < nr; i++)
956 				flush_dcache_page(newpage + i);
957 		}
958 	}
959 out:
960 	return rc;
961 }
962 
__unmap_and_move(struct page * page,struct page * newpage,int force,enum migrate_mode mode)963 static int __unmap_and_move(struct page *page, struct page *newpage,
964 				int force, enum migrate_mode mode)
965 {
966 	int rc = -EAGAIN;
967 	bool page_was_mapped = false;
968 	struct anon_vma *anon_vma = NULL;
969 	bool is_lru = !__PageMovable(page);
970 
971 	if (!trylock_page(page)) {
972 		if (!force || mode == MIGRATE_ASYNC)
973 			goto out;
974 
975 		/*
976 		 * It's not safe for direct compaction to call lock_page.
977 		 * For example, during page readahead pages are added locked
978 		 * to the LRU. Later, when the IO completes the pages are
979 		 * marked uptodate and unlocked. However, the queueing
980 		 * could be merging multiple pages for one bio (e.g.
981 		 * mpage_readahead). If an allocation happens for the
982 		 * second or third page, the process can end up locking
983 		 * the same page twice and deadlocking. Rather than
984 		 * trying to be clever about what pages can be locked,
985 		 * avoid the use of lock_page for direct compaction
986 		 * altogether.
987 		 */
988 		if (current->flags & PF_MEMALLOC)
989 			goto out;
990 
991 		lock_page(page);
992 	}
993 
994 	if (PageWriteback(page)) {
995 		/*
996 		 * Only in the case of a full synchronous migration is it
997 		 * necessary to wait for PageWriteback. In the async case,
998 		 * the retry loop is too short and in the sync-light case,
999 		 * the overhead of stalling is too much
1000 		 */
1001 		switch (mode) {
1002 		case MIGRATE_SYNC:
1003 		case MIGRATE_SYNC_NO_COPY:
1004 			break;
1005 		default:
1006 			rc = -EBUSY;
1007 			goto out_unlock;
1008 		}
1009 		if (!force)
1010 			goto out_unlock;
1011 		wait_on_page_writeback(page);
1012 	}
1013 
1014 	/*
1015 	 * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1016 	 * we cannot notice that anon_vma is freed while we migrates a page.
1017 	 * This get_anon_vma() delays freeing anon_vma pointer until the end
1018 	 * of migration. File cache pages are no problem because of page_lock()
1019 	 * File Caches may use write_page() or lock_page() in migration, then,
1020 	 * just care Anon page here.
1021 	 *
1022 	 * Only page_get_anon_vma() understands the subtleties of
1023 	 * getting a hold on an anon_vma from outside one of its mms.
1024 	 * But if we cannot get anon_vma, then we won't need it anyway,
1025 	 * because that implies that the anon page is no longer mapped
1026 	 * (and cannot be remapped so long as we hold the page lock).
1027 	 */
1028 	if (PageAnon(page) && !PageKsm(page))
1029 		anon_vma = page_get_anon_vma(page);
1030 
1031 	/*
1032 	 * Block others from accessing the new page when we get around to
1033 	 * establishing additional references. We are usually the only one
1034 	 * holding a reference to newpage at this point. We used to have a BUG
1035 	 * here if trylock_page(newpage) fails, but would like to allow for
1036 	 * cases where there might be a race with the previous use of newpage.
1037 	 * This is much like races on refcount of oldpage: just don't BUG().
1038 	 */
1039 	if (unlikely(!trylock_page(newpage)))
1040 		goto out_unlock;
1041 
1042 	if (unlikely(!is_lru)) {
1043 		rc = move_to_new_page(newpage, page, mode);
1044 		goto out_unlock_both;
1045 	}
1046 
1047 	/*
1048 	 * Corner case handling:
1049 	 * 1. When a new swap-cache page is read into, it is added to the LRU
1050 	 * and treated as swapcache but it has no rmap yet.
1051 	 * Calling try_to_unmap() against a page->mapping==NULL page will
1052 	 * trigger a BUG.  So handle it here.
1053 	 * 2. An orphaned page (see truncate_cleanup_page) might have
1054 	 * fs-private metadata. The page can be picked up due to memory
1055 	 * offlining.  Everywhere else except page reclaim, the page is
1056 	 * invisible to the vm, so the page can not be migrated.  So try to
1057 	 * free the metadata, so the page can be freed.
1058 	 */
1059 	if (!page->mapping) {
1060 		VM_BUG_ON_PAGE(PageAnon(page), page);
1061 		if (page_has_private(page)) {
1062 			try_to_free_buffers(page);
1063 			goto out_unlock_both;
1064 		}
1065 	} else if (page_mapped(page)) {
1066 		/* Establish migration ptes */
1067 		VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1068 				page);
1069 		try_to_migrate(page, 0);
1070 		page_was_mapped = true;
1071 	}
1072 
1073 	if (!page_mapped(page))
1074 		rc = move_to_new_page(newpage, page, mode);
1075 
1076 	if (page_was_mapped)
1077 		remove_migration_ptes(page,
1078 			rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1079 
1080 out_unlock_both:
1081 	unlock_page(newpage);
1082 out_unlock:
1083 	/* Drop an anon_vma reference if we took one */
1084 	if (anon_vma)
1085 		put_anon_vma(anon_vma);
1086 	unlock_page(page);
1087 out:
1088 	/*
1089 	 * If migration is successful, decrease refcount of the newpage
1090 	 * which will not free the page because new page owner increased
1091 	 * refcounter. As well, if it is LRU page, add the page to LRU
1092 	 * list in here. Use the old state of the isolated source page to
1093 	 * determine if we migrated a LRU page. newpage was already unlocked
1094 	 * and possibly modified by its owner - don't rely on the page
1095 	 * state.
1096 	 */
1097 	if (rc == MIGRATEPAGE_SUCCESS) {
1098 		if (unlikely(!is_lru))
1099 			put_page(newpage);
1100 		else
1101 			putback_lru_page(newpage);
1102 	}
1103 
1104 	return rc;
1105 }
1106 
1107 
1108 /*
1109  * node_demotion[] example:
1110  *
1111  * Consider a system with two sockets.  Each socket has
1112  * three classes of memory attached: fast, medium and slow.
1113  * Each memory class is placed in its own NUMA node.  The
1114  * CPUs are placed in the node with the "fast" memory.  The
1115  * 6 NUMA nodes (0-5) might be split among the sockets like
1116  * this:
1117  *
1118  *	Socket A: 0, 1, 2
1119  *	Socket B: 3, 4, 5
1120  *
1121  * When Node 0 fills up, its memory should be migrated to
1122  * Node 1.  When Node 1 fills up, it should be migrated to
1123  * Node 2.  The migration path start on the nodes with the
1124  * processors (since allocations default to this node) and
1125  * fast memory, progress through medium and end with the
1126  * slow memory:
1127  *
1128  *	0 -> 1 -> 2 -> stop
1129  *	3 -> 4 -> 5 -> stop
1130  *
1131  * This is represented in the node_demotion[] like this:
1132  *
1133  *	{  1, // Node 0 migrates to 1
1134  *	   2, // Node 1 migrates to 2
1135  *	  -1, // Node 2 does not migrate
1136  *	   4, // Node 3 migrates to 4
1137  *	   5, // Node 4 migrates to 5
1138  *	  -1} // Node 5 does not migrate
1139  */
1140 
1141 /*
1142  * Writes to this array occur without locking.  Cycles are
1143  * not allowed: Node X demotes to Y which demotes to X...
1144  *
1145  * If multiple reads are performed, a single rcu_read_lock()
1146  * must be held over all reads to ensure that no cycles are
1147  * observed.
1148  */
1149 static int node_demotion[MAX_NUMNODES] __read_mostly =
1150 	{[0 ...  MAX_NUMNODES - 1] = NUMA_NO_NODE};
1151 
1152 /**
1153  * next_demotion_node() - Get the next node in the demotion path
1154  * @node: The starting node to lookup the next node
1155  *
1156  * Return: node id for next memory node in the demotion path hierarchy
1157  * from @node; NUMA_NO_NODE if @node is terminal.  This does not keep
1158  * @node online or guarantee that it *continues* to be the next demotion
1159  * target.
1160  */
next_demotion_node(int node)1161 int next_demotion_node(int node)
1162 {
1163 	int target;
1164 
1165 	/*
1166 	 * node_demotion[] is updated without excluding this
1167 	 * function from running.  RCU doesn't provide any
1168 	 * compiler barriers, so the READ_ONCE() is required
1169 	 * to avoid compiler reordering or read merging.
1170 	 *
1171 	 * Make sure to use RCU over entire code blocks if
1172 	 * node_demotion[] reads need to be consistent.
1173 	 */
1174 	rcu_read_lock();
1175 	target = READ_ONCE(node_demotion[node]);
1176 	rcu_read_unlock();
1177 
1178 	return target;
1179 }
1180 
1181 /*
1182  * Obtain the lock on page, remove all ptes and migrate the page
1183  * to the newly allocated page in newpage.
1184  */
unmap_and_move(new_page_t get_new_page,free_page_t put_new_page,unsigned long private,struct page * page,int force,enum migrate_mode mode,enum migrate_reason reason,struct list_head * ret)1185 static int unmap_and_move(new_page_t get_new_page,
1186 				   free_page_t put_new_page,
1187 				   unsigned long private, struct page *page,
1188 				   int force, enum migrate_mode mode,
1189 				   enum migrate_reason reason,
1190 				   struct list_head *ret)
1191 {
1192 	int rc = MIGRATEPAGE_SUCCESS;
1193 	struct page *newpage = NULL;
1194 
1195 	if (!thp_migration_supported() && PageTransHuge(page))
1196 		return -ENOSYS;
1197 
1198 	if (page_count(page) == 1) {
1199 		/* page was freed from under us. So we are done. */
1200 		ClearPageActive(page);
1201 		ClearPageUnevictable(page);
1202 		if (unlikely(__PageMovable(page))) {
1203 			lock_page(page);
1204 			if (!PageMovable(page))
1205 				ClearPageIsolated(page);
1206 			unlock_page(page);
1207 		}
1208 		goto out;
1209 	}
1210 
1211 	newpage = get_new_page(page, private);
1212 	if (!newpage)
1213 		return -ENOMEM;
1214 
1215 	rc = __unmap_and_move(page, newpage, force, mode);
1216 	if (rc == MIGRATEPAGE_SUCCESS)
1217 		set_page_owner_migrate_reason(newpage, reason);
1218 
1219 out:
1220 	if (rc != -EAGAIN) {
1221 		/*
1222 		 * A page that has been migrated has all references
1223 		 * removed and will be freed. A page that has not been
1224 		 * migrated will have kept its references and be restored.
1225 		 */
1226 		list_del(&page->lru);
1227 	}
1228 
1229 	/*
1230 	 * If migration is successful, releases reference grabbed during
1231 	 * isolation. Otherwise, restore the page to right list unless
1232 	 * we want to retry.
1233 	 */
1234 	if (rc == MIGRATEPAGE_SUCCESS) {
1235 		/*
1236 		 * Compaction can migrate also non-LRU pages which are
1237 		 * not accounted to NR_ISOLATED_*. They can be recognized
1238 		 * as __PageMovable
1239 		 */
1240 		if (likely(!__PageMovable(page)))
1241 			mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1242 					page_is_file_lru(page), -thp_nr_pages(page));
1243 
1244 		if (reason != MR_MEMORY_FAILURE)
1245 			/*
1246 			 * We release the page in page_handle_poison.
1247 			 */
1248 			put_page(page);
1249 	} else {
1250 		if (rc != -EAGAIN)
1251 			list_add_tail(&page->lru, ret);
1252 
1253 		if (put_new_page)
1254 			put_new_page(newpage, private);
1255 		else
1256 			put_page(newpage);
1257 	}
1258 
1259 	return rc;
1260 }
1261 
1262 /*
1263  * Counterpart of unmap_and_move_page() for hugepage migration.
1264  *
1265  * This function doesn't wait the completion of hugepage I/O
1266  * because there is no race between I/O and migration for hugepage.
1267  * Note that currently hugepage I/O occurs only in direct I/O
1268  * where no lock is held and PG_writeback is irrelevant,
1269  * and writeback status of all subpages are counted in the reference
1270  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1271  * under direct I/O, the reference of the head page is 512 and a bit more.)
1272  * This means that when we try to migrate hugepage whose subpages are
1273  * doing direct I/O, some references remain after try_to_unmap() and
1274  * hugepage migration fails without data corruption.
1275  *
1276  * There is also no race when direct I/O is issued on the page under migration,
1277  * because then pte is replaced with migration swap entry and direct I/O code
1278  * will wait in the page fault for migration to complete.
1279  */
unmap_and_move_huge_page(new_page_t get_new_page,free_page_t put_new_page,unsigned long private,struct page * hpage,int force,enum migrate_mode mode,int reason,struct list_head * ret)1280 static int unmap_and_move_huge_page(new_page_t get_new_page,
1281 				free_page_t put_new_page, unsigned long private,
1282 				struct page *hpage, int force,
1283 				enum migrate_mode mode, int reason,
1284 				struct list_head *ret)
1285 {
1286 	int rc = -EAGAIN;
1287 	int page_was_mapped = 0;
1288 	struct page *new_hpage;
1289 	struct anon_vma *anon_vma = NULL;
1290 	struct address_space *mapping = NULL;
1291 
1292 	/*
1293 	 * Migratability of hugepages depends on architectures and their size.
1294 	 * This check is necessary because some callers of hugepage migration
1295 	 * like soft offline and memory hotremove don't walk through page
1296 	 * tables or check whether the hugepage is pmd-based or not before
1297 	 * kicking migration.
1298 	 */
1299 	if (!hugepage_migration_supported(page_hstate(hpage))) {
1300 		list_move_tail(&hpage->lru, ret);
1301 		return -ENOSYS;
1302 	}
1303 
1304 	if (page_count(hpage) == 1) {
1305 		/* page was freed from under us. So we are done. */
1306 		putback_active_hugepage(hpage);
1307 		return MIGRATEPAGE_SUCCESS;
1308 	}
1309 
1310 	new_hpage = get_new_page(hpage, private);
1311 	if (!new_hpage)
1312 		return -ENOMEM;
1313 
1314 	if (!trylock_page(hpage)) {
1315 		if (!force)
1316 			goto out;
1317 		switch (mode) {
1318 		case MIGRATE_SYNC:
1319 		case MIGRATE_SYNC_NO_COPY:
1320 			break;
1321 		default:
1322 			goto out;
1323 		}
1324 		lock_page(hpage);
1325 	}
1326 
1327 	/*
1328 	 * Check for pages which are in the process of being freed.  Without
1329 	 * page_mapping() set, hugetlbfs specific move page routine will not
1330 	 * be called and we could leak usage counts for subpools.
1331 	 */
1332 	if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1333 		rc = -EBUSY;
1334 		goto out_unlock;
1335 	}
1336 
1337 	if (PageAnon(hpage))
1338 		anon_vma = page_get_anon_vma(hpage);
1339 
1340 	if (unlikely(!trylock_page(new_hpage)))
1341 		goto put_anon;
1342 
1343 	if (page_mapped(hpage)) {
1344 		bool mapping_locked = false;
1345 		enum ttu_flags ttu = 0;
1346 
1347 		if (!PageAnon(hpage)) {
1348 			/*
1349 			 * In shared mappings, try_to_unmap could potentially
1350 			 * call huge_pmd_unshare.  Because of this, take
1351 			 * semaphore in write mode here and set TTU_RMAP_LOCKED
1352 			 * to let lower levels know we have taken the lock.
1353 			 */
1354 			mapping = hugetlb_page_mapping_lock_write(hpage);
1355 			if (unlikely(!mapping))
1356 				goto unlock_put_anon;
1357 
1358 			mapping_locked = true;
1359 			ttu |= TTU_RMAP_LOCKED;
1360 		}
1361 
1362 		try_to_migrate(hpage, ttu);
1363 		page_was_mapped = 1;
1364 
1365 		if (mapping_locked)
1366 			i_mmap_unlock_write(mapping);
1367 	}
1368 
1369 	if (!page_mapped(hpage))
1370 		rc = move_to_new_page(new_hpage, hpage, mode);
1371 
1372 	if (page_was_mapped)
1373 		remove_migration_ptes(hpage,
1374 			rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1375 
1376 unlock_put_anon:
1377 	unlock_page(new_hpage);
1378 
1379 put_anon:
1380 	if (anon_vma)
1381 		put_anon_vma(anon_vma);
1382 
1383 	if (rc == MIGRATEPAGE_SUCCESS) {
1384 		move_hugetlb_state(hpage, new_hpage, reason);
1385 		put_new_page = NULL;
1386 	}
1387 
1388 out_unlock:
1389 	unlock_page(hpage);
1390 out:
1391 	if (rc == MIGRATEPAGE_SUCCESS)
1392 		putback_active_hugepage(hpage);
1393 	else if (rc != -EAGAIN)
1394 		list_move_tail(&hpage->lru, ret);
1395 
1396 	/*
1397 	 * If migration was not successful and there's a freeing callback, use
1398 	 * it.  Otherwise, put_page() will drop the reference grabbed during
1399 	 * isolation.
1400 	 */
1401 	if (put_new_page)
1402 		put_new_page(new_hpage, private);
1403 	else
1404 		putback_active_hugepage(new_hpage);
1405 
1406 	return rc;
1407 }
1408 
try_split_thp(struct page * page,struct page ** page2,struct list_head * from)1409 static inline int try_split_thp(struct page *page, struct page **page2,
1410 				struct list_head *from)
1411 {
1412 	int rc = 0;
1413 
1414 	lock_page(page);
1415 	rc = split_huge_page_to_list(page, from);
1416 	unlock_page(page);
1417 	if (!rc)
1418 		list_safe_reset_next(page, *page2, lru);
1419 
1420 	return rc;
1421 }
1422 
1423 /*
1424  * migrate_pages - migrate the pages specified in a list, to the free pages
1425  *		   supplied as the target for the page migration
1426  *
1427  * @from:		The list of pages to be migrated.
1428  * @get_new_page:	The function used to allocate free pages to be used
1429  *			as the target of the page migration.
1430  * @put_new_page:	The function used to free target pages if migration
1431  *			fails, or NULL if no special handling is necessary.
1432  * @private:		Private data to be passed on to get_new_page()
1433  * @mode:		The migration mode that specifies the constraints for
1434  *			page migration, if any.
1435  * @reason:		The reason for page migration.
1436  * @ret_succeeded:	Set to the number of pages migrated successfully if
1437  *			the caller passes a non-NULL pointer.
1438  *
1439  * The function returns after 10 attempts or if no pages are movable any more
1440  * because the list has become empty or no retryable pages exist any more.
1441  * It is caller's responsibility to call putback_movable_pages() to return pages
1442  * to the LRU or free list only if ret != 0.
1443  *
1444  * Returns the number of pages that were not migrated, or an error code.
1445  */
migrate_pages(struct list_head * from,new_page_t get_new_page,free_page_t put_new_page,unsigned long private,enum migrate_mode mode,int reason,unsigned int * ret_succeeded)1446 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1447 		free_page_t put_new_page, unsigned long private,
1448 		enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1449 {
1450 	int retry = 1;
1451 	int thp_retry = 1;
1452 	int nr_failed = 0;
1453 	int nr_succeeded = 0;
1454 	int nr_thp_succeeded = 0;
1455 	int nr_thp_failed = 0;
1456 	int nr_thp_split = 0;
1457 	int pass = 0;
1458 	bool is_thp = false;
1459 	struct page *page;
1460 	struct page *page2;
1461 	int swapwrite = current->flags & PF_SWAPWRITE;
1462 	int rc, nr_subpages;
1463 	LIST_HEAD(ret_pages);
1464 	bool nosplit = (reason == MR_NUMA_MISPLACED);
1465 
1466 	trace_mm_migrate_pages_start(mode, reason);
1467 
1468 	if (!swapwrite)
1469 		current->flags |= PF_SWAPWRITE;
1470 
1471 	for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1472 		retry = 0;
1473 		thp_retry = 0;
1474 
1475 		list_for_each_entry_safe(page, page2, from, lru) {
1476 retry:
1477 			/*
1478 			 * THP statistics is based on the source huge page.
1479 			 * Capture required information that might get lost
1480 			 * during migration.
1481 			 */
1482 			is_thp = PageTransHuge(page) && !PageHuge(page);
1483 			nr_subpages = thp_nr_pages(page);
1484 			cond_resched();
1485 
1486 			if (PageHuge(page))
1487 				rc = unmap_and_move_huge_page(get_new_page,
1488 						put_new_page, private, page,
1489 						pass > 2, mode, reason,
1490 						&ret_pages);
1491 			else
1492 				rc = unmap_and_move(get_new_page, put_new_page,
1493 						private, page, pass > 2, mode,
1494 						reason, &ret_pages);
1495 			/*
1496 			 * The rules are:
1497 			 *	Success: non hugetlb page will be freed, hugetlb
1498 			 *		 page will be put back
1499 			 *	-EAGAIN: stay on the from list
1500 			 *	-ENOMEM: stay on the from list
1501 			 *	Other errno: put on ret_pages list then splice to
1502 			 *		     from list
1503 			 */
1504 			switch(rc) {
1505 			/*
1506 			 * THP migration might be unsupported or the
1507 			 * allocation could've failed so we should
1508 			 * retry on the same page with the THP split
1509 			 * to base pages.
1510 			 *
1511 			 * Head page is retried immediately and tail
1512 			 * pages are added to the tail of the list so
1513 			 * we encounter them after the rest of the list
1514 			 * is processed.
1515 			 */
1516 			case -ENOSYS:
1517 				/* THP migration is unsupported */
1518 				if (is_thp) {
1519 					if (!try_split_thp(page, &page2, from)) {
1520 						nr_thp_split++;
1521 						goto retry;
1522 					}
1523 
1524 					nr_thp_failed++;
1525 					nr_failed += nr_subpages;
1526 					break;
1527 				}
1528 
1529 				/* Hugetlb migration is unsupported */
1530 				nr_failed++;
1531 				break;
1532 			case -ENOMEM:
1533 				/*
1534 				 * When memory is low, don't bother to try to migrate
1535 				 * other pages, just exit.
1536 				 * THP NUMA faulting doesn't split THP to retry.
1537 				 */
1538 				if (is_thp && !nosplit) {
1539 					if (!try_split_thp(page, &page2, from)) {
1540 						nr_thp_split++;
1541 						goto retry;
1542 					}
1543 
1544 					nr_thp_failed++;
1545 					nr_failed += nr_subpages;
1546 					goto out;
1547 				}
1548 				nr_failed++;
1549 				goto out;
1550 			case -EAGAIN:
1551 				if (is_thp) {
1552 					thp_retry++;
1553 					break;
1554 				}
1555 				retry++;
1556 				break;
1557 			case MIGRATEPAGE_SUCCESS:
1558 				if (is_thp) {
1559 					nr_thp_succeeded++;
1560 					nr_succeeded += nr_subpages;
1561 					break;
1562 				}
1563 				nr_succeeded++;
1564 				break;
1565 			default:
1566 				/*
1567 				 * Permanent failure (-EBUSY, etc.):
1568 				 * unlike -EAGAIN case, the failed page is
1569 				 * removed from migration page list and not
1570 				 * retried in the next outer loop.
1571 				 */
1572 				if (is_thp) {
1573 					nr_thp_failed++;
1574 					nr_failed += nr_subpages;
1575 					break;
1576 				}
1577 				nr_failed++;
1578 				break;
1579 			}
1580 		}
1581 	}
1582 	nr_failed += retry + thp_retry;
1583 	nr_thp_failed += thp_retry;
1584 	rc = nr_failed;
1585 out:
1586 	/*
1587 	 * Put the permanent failure page back to migration list, they
1588 	 * will be put back to the right list by the caller.
1589 	 */
1590 	list_splice(&ret_pages, from);
1591 
1592 	count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1593 	count_vm_events(PGMIGRATE_FAIL, nr_failed);
1594 	count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1595 	count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1596 	count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1597 	trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1598 			       nr_thp_failed, nr_thp_split, mode, reason);
1599 
1600 	if (!swapwrite)
1601 		current->flags &= ~PF_SWAPWRITE;
1602 
1603 	if (ret_succeeded)
1604 		*ret_succeeded = nr_succeeded;
1605 
1606 	return rc;
1607 }
1608 EXPORT_SYMBOL_GPL(migrate_pages);
1609 
alloc_migration_target(struct page * page,unsigned long private)1610 struct page *alloc_migration_target(struct page *page, unsigned long private)
1611 {
1612 	struct migration_target_control *mtc;
1613 	gfp_t gfp_mask;
1614 	unsigned int order = 0;
1615 	struct page *new_page = NULL;
1616 	int nid;
1617 	int zidx;
1618 
1619 	mtc = (struct migration_target_control *)private;
1620 	gfp_mask = mtc->gfp_mask;
1621 	nid = mtc->nid;
1622 	if (nid == NUMA_NO_NODE)
1623 		nid = page_to_nid(page);
1624 
1625 	if (PageHuge(page)) {
1626 		struct hstate *h = page_hstate(compound_head(page));
1627 
1628 		gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1629 		return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1630 	}
1631 
1632 	if (PageTransHuge(page)) {
1633 		/*
1634 		 * clear __GFP_RECLAIM to make the migration callback
1635 		 * consistent with regular THP allocations.
1636 		 */
1637 		gfp_mask &= ~__GFP_RECLAIM;
1638 		gfp_mask |= GFP_TRANSHUGE;
1639 		order = HPAGE_PMD_ORDER;
1640 	}
1641 	zidx = zone_idx(page_zone(page));
1642 	if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1643 		gfp_mask |= __GFP_HIGHMEM;
1644 
1645 	new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1646 
1647 	if (new_page && PageTransHuge(new_page))
1648 		prep_transhuge_page(new_page);
1649 
1650 	return new_page;
1651 }
1652 
1653 #ifdef CONFIG_NUMA
1654 
store_status(int __user * status,int start,int value,int nr)1655 static int store_status(int __user *status, int start, int value, int nr)
1656 {
1657 	while (nr-- > 0) {
1658 		if (put_user(value, status + start))
1659 			return -EFAULT;
1660 		start++;
1661 	}
1662 
1663 	return 0;
1664 }
1665 
do_move_pages_to_node(struct mm_struct * mm,struct list_head * pagelist,int node)1666 static int do_move_pages_to_node(struct mm_struct *mm,
1667 		struct list_head *pagelist, int node)
1668 {
1669 	int err;
1670 	struct migration_target_control mtc = {
1671 		.nid = node,
1672 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1673 	};
1674 
1675 	err = migrate_pages(pagelist, alloc_migration_target, NULL,
1676 		(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1677 	if (err)
1678 		putback_movable_pages(pagelist);
1679 	return err;
1680 }
1681 
1682 /*
1683  * Resolves the given address to a struct page, isolates it from the LRU and
1684  * puts it to the given pagelist.
1685  * Returns:
1686  *     errno - if the page cannot be found/isolated
1687  *     0 - when it doesn't have to be migrated because it is already on the
1688  *         target node
1689  *     1 - when it has been queued
1690  */
add_page_for_migration(struct mm_struct * mm,unsigned long addr,int node,struct list_head * pagelist,bool migrate_all)1691 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1692 		int node, struct list_head *pagelist, bool migrate_all)
1693 {
1694 	struct vm_area_struct *vma;
1695 	struct page *page;
1696 	unsigned int follflags;
1697 	int err;
1698 
1699 	mmap_read_lock(mm);
1700 	err = -EFAULT;
1701 	vma = find_vma(mm, addr);
1702 	if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1703 		goto out;
1704 
1705 	/* FOLL_DUMP to ignore special (like zero) pages */
1706 	follflags = FOLL_GET | FOLL_DUMP;
1707 	page = follow_page(vma, addr, follflags);
1708 
1709 	err = PTR_ERR(page);
1710 	if (IS_ERR(page))
1711 		goto out;
1712 
1713 	err = -ENOENT;
1714 	if (!page)
1715 		goto out;
1716 
1717 	err = 0;
1718 	if (page_to_nid(page) == node)
1719 		goto out_putpage;
1720 
1721 	err = -EACCES;
1722 	if (page_mapcount(page) > 1 && !migrate_all)
1723 		goto out_putpage;
1724 
1725 	if (PageHuge(page)) {
1726 		if (PageHead(page)) {
1727 			err = isolate_hugetlb(page, pagelist);
1728 			if (!err)
1729 				err = 1;
1730 		}
1731 	} else {
1732 		struct page *head;
1733 
1734 		head = compound_head(page);
1735 		err = isolate_lru_page(head);
1736 		if (err)
1737 			goto out_putpage;
1738 
1739 		err = 1;
1740 		list_add_tail(&head->lru, pagelist);
1741 		mod_node_page_state(page_pgdat(head),
1742 			NR_ISOLATED_ANON + page_is_file_lru(head),
1743 			thp_nr_pages(head));
1744 	}
1745 out_putpage:
1746 	/*
1747 	 * Either remove the duplicate refcount from
1748 	 * isolate_lru_page() or drop the page ref if it was
1749 	 * not isolated.
1750 	 */
1751 	put_page(page);
1752 out:
1753 	mmap_read_unlock(mm);
1754 	return err;
1755 }
1756 
move_pages_and_store_status(struct mm_struct * mm,int node,struct list_head * pagelist,int __user * status,int start,int i,unsigned long nr_pages)1757 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1758 		struct list_head *pagelist, int __user *status,
1759 		int start, int i, unsigned long nr_pages)
1760 {
1761 	int err;
1762 
1763 	if (list_empty(pagelist))
1764 		return 0;
1765 
1766 	err = do_move_pages_to_node(mm, pagelist, node);
1767 	if (err) {
1768 		/*
1769 		 * Positive err means the number of failed
1770 		 * pages to migrate.  Since we are going to
1771 		 * abort and return the number of non-migrated
1772 		 * pages, so need to include the rest of the
1773 		 * nr_pages that have not been attempted as
1774 		 * well.
1775 		 */
1776 		if (err > 0)
1777 			err += nr_pages - i - 1;
1778 		return err;
1779 	}
1780 	return store_status(status, start, node, i - start);
1781 }
1782 
1783 /*
1784  * Migrate an array of page address onto an array of nodes and fill
1785  * the corresponding array of status.
1786  */
do_pages_move(struct mm_struct * mm,nodemask_t task_nodes,unsigned long nr_pages,const void __user * __user * pages,const int __user * nodes,int __user * status,int flags)1787 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1788 			 unsigned long nr_pages,
1789 			 const void __user * __user *pages,
1790 			 const int __user *nodes,
1791 			 int __user *status, int flags)
1792 {
1793 	compat_uptr_t __user *compat_pages = (void __user *)pages;
1794 	int current_node = NUMA_NO_NODE;
1795 	LIST_HEAD(pagelist);
1796 	int start, i;
1797 	int err = 0, err1;
1798 
1799 	lru_cache_disable();
1800 
1801 	for (i = start = 0; i < nr_pages; i++) {
1802 		const void __user *p;
1803 		unsigned long addr;
1804 		int node;
1805 
1806 		err = -EFAULT;
1807 		if (in_compat_syscall()) {
1808 			compat_uptr_t cp;
1809 
1810 			if (get_user(cp, compat_pages + i))
1811 				goto out_flush;
1812 
1813 			p = compat_ptr(cp);
1814 		} else {
1815 			if (get_user(p, pages + i))
1816 				goto out_flush;
1817 		}
1818 		if (get_user(node, nodes + i))
1819 			goto out_flush;
1820 		addr = (unsigned long)untagged_addr(p);
1821 
1822 		err = -ENODEV;
1823 		if (node < 0 || node >= MAX_NUMNODES)
1824 			goto out_flush;
1825 		if (!node_state(node, N_MEMORY))
1826 			goto out_flush;
1827 
1828 		err = -EACCES;
1829 		if (!node_isset(node, task_nodes))
1830 			goto out_flush;
1831 
1832 		if (current_node == NUMA_NO_NODE) {
1833 			current_node = node;
1834 			start = i;
1835 		} else if (node != current_node) {
1836 			err = move_pages_and_store_status(mm, current_node,
1837 					&pagelist, status, start, i, nr_pages);
1838 			if (err)
1839 				goto out;
1840 			start = i;
1841 			current_node = node;
1842 		}
1843 
1844 		/*
1845 		 * Errors in the page lookup or isolation are not fatal and we simply
1846 		 * report them via status
1847 		 */
1848 		err = add_page_for_migration(mm, addr, current_node,
1849 				&pagelist, flags & MPOL_MF_MOVE_ALL);
1850 
1851 		if (err > 0) {
1852 			/* The page is successfully queued for migration */
1853 			continue;
1854 		}
1855 
1856 		/*
1857 		 * If the page is already on the target node (!err), store the
1858 		 * node, otherwise, store the err.
1859 		 */
1860 		err = store_status(status, i, err ? : current_node, 1);
1861 		if (err)
1862 			goto out_flush;
1863 
1864 		err = move_pages_and_store_status(mm, current_node, &pagelist,
1865 				status, start, i, nr_pages);
1866 		if (err)
1867 			goto out;
1868 		current_node = NUMA_NO_NODE;
1869 	}
1870 out_flush:
1871 	/* Make sure we do not overwrite the existing error */
1872 	err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1873 				status, start, i, nr_pages);
1874 	if (err >= 0)
1875 		err = err1;
1876 out:
1877 	lru_cache_enable();
1878 	return err;
1879 }
1880 
1881 /*
1882  * Determine the nodes of an array of pages and store it in an array of status.
1883  */
do_pages_stat_array(struct mm_struct * mm,unsigned long nr_pages,const void __user ** pages,int * status)1884 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1885 				const void __user **pages, int *status)
1886 {
1887 	unsigned long i;
1888 
1889 	mmap_read_lock(mm);
1890 
1891 	for (i = 0; i < nr_pages; i++) {
1892 		unsigned long addr = (unsigned long)(*pages);
1893 		struct vm_area_struct *vma;
1894 		struct page *page;
1895 		int err = -EFAULT;
1896 
1897 		vma = vma_lookup(mm, addr);
1898 		if (!vma)
1899 			goto set_status;
1900 
1901 		/* FOLL_DUMP to ignore special (like zero) pages */
1902 		page = follow_page(vma, addr, FOLL_DUMP);
1903 
1904 		err = PTR_ERR(page);
1905 		if (IS_ERR(page))
1906 			goto set_status;
1907 
1908 		err = page ? page_to_nid(page) : -ENOENT;
1909 set_status:
1910 		*status = err;
1911 
1912 		pages++;
1913 		status++;
1914 	}
1915 
1916 	mmap_read_unlock(mm);
1917 }
1918 
get_compat_pages_array(const void __user * chunk_pages[],const void __user * __user * pages,unsigned long chunk_nr)1919 static int get_compat_pages_array(const void __user *chunk_pages[],
1920 				  const void __user * __user *pages,
1921 				  unsigned long chunk_nr)
1922 {
1923 	compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1924 	compat_uptr_t p;
1925 	int i;
1926 
1927 	for (i = 0; i < chunk_nr; i++) {
1928 		if (get_user(p, pages32 + i))
1929 			return -EFAULT;
1930 		chunk_pages[i] = compat_ptr(p);
1931 	}
1932 
1933 	return 0;
1934 }
1935 
1936 /*
1937  * Determine the nodes of a user array of pages and store it in
1938  * a user array of status.
1939  */
do_pages_stat(struct mm_struct * mm,unsigned long nr_pages,const void __user * __user * pages,int __user * status)1940 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1941 			 const void __user * __user *pages,
1942 			 int __user *status)
1943 {
1944 #define DO_PAGES_STAT_CHUNK_NR 16
1945 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1946 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1947 
1948 	while (nr_pages) {
1949 		unsigned long chunk_nr;
1950 
1951 		chunk_nr = nr_pages;
1952 		if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1953 			chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1954 
1955 		if (in_compat_syscall()) {
1956 			if (get_compat_pages_array(chunk_pages, pages,
1957 						   chunk_nr))
1958 				break;
1959 		} else {
1960 			if (copy_from_user(chunk_pages, pages,
1961 				      chunk_nr * sizeof(*chunk_pages)))
1962 				break;
1963 		}
1964 
1965 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1966 
1967 		if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1968 			break;
1969 
1970 		pages += chunk_nr;
1971 		status += chunk_nr;
1972 		nr_pages -= chunk_nr;
1973 	}
1974 	return nr_pages ? -EFAULT : 0;
1975 }
1976 
find_mm_struct(pid_t pid,nodemask_t * mem_nodes)1977 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1978 {
1979 	struct task_struct *task;
1980 	struct mm_struct *mm;
1981 
1982 	/*
1983 	 * There is no need to check if current process has the right to modify
1984 	 * the specified process when they are same.
1985 	 */
1986 	if (!pid) {
1987 		mmget(current->mm);
1988 		*mem_nodes = cpuset_mems_allowed(current);
1989 		return current->mm;
1990 	}
1991 
1992 	/* Find the mm_struct */
1993 	rcu_read_lock();
1994 	task = find_task_by_vpid(pid);
1995 	if (!task) {
1996 		rcu_read_unlock();
1997 		return ERR_PTR(-ESRCH);
1998 	}
1999 	get_task_struct(task);
2000 
2001 	/*
2002 	 * Check if this process has the right to modify the specified
2003 	 * process. Use the regular "ptrace_may_access()" checks.
2004 	 */
2005 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
2006 		rcu_read_unlock();
2007 		mm = ERR_PTR(-EPERM);
2008 		goto out;
2009 	}
2010 	rcu_read_unlock();
2011 
2012 	mm = ERR_PTR(security_task_movememory(task));
2013 	if (IS_ERR(mm))
2014 		goto out;
2015 	*mem_nodes = cpuset_mems_allowed(task);
2016 	mm = get_task_mm(task);
2017 out:
2018 	put_task_struct(task);
2019 	if (!mm)
2020 		mm = ERR_PTR(-EINVAL);
2021 	return mm;
2022 }
2023 
2024 /*
2025  * Move a list of pages in the address space of the currently executing
2026  * process.
2027  */
kernel_move_pages(pid_t pid,unsigned long nr_pages,const void __user * __user * pages,const int __user * nodes,int __user * status,int flags)2028 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2029 			     const void __user * __user *pages,
2030 			     const int __user *nodes,
2031 			     int __user *status, int flags)
2032 {
2033 	struct mm_struct *mm;
2034 	int err;
2035 	nodemask_t task_nodes;
2036 
2037 	/* Check flags */
2038 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2039 		return -EINVAL;
2040 
2041 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2042 		return -EPERM;
2043 
2044 	mm = find_mm_struct(pid, &task_nodes);
2045 	if (IS_ERR(mm))
2046 		return PTR_ERR(mm);
2047 
2048 	if (nodes)
2049 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
2050 				    nodes, status, flags);
2051 	else
2052 		err = do_pages_stat(mm, nr_pages, pages, status);
2053 
2054 	mmput(mm);
2055 	return err;
2056 }
2057 
SYSCALL_DEFINE6(move_pages,pid_t,pid,unsigned long,nr_pages,const void __user * __user *,pages,const int __user *,nodes,int __user *,status,int,flags)2058 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2059 		const void __user * __user *, pages,
2060 		const int __user *, nodes,
2061 		int __user *, status, int, flags)
2062 {
2063 	return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2064 }
2065 
2066 #ifdef CONFIG_NUMA_BALANCING
2067 /*
2068  * Returns true if this is a safe migration target node for misplaced NUMA
2069  * pages. Currently it only checks the watermarks which crude
2070  */
migrate_balanced_pgdat(struct pglist_data * pgdat,unsigned long nr_migrate_pages)2071 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2072 				   unsigned long nr_migrate_pages)
2073 {
2074 	int z;
2075 
2076 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2077 		struct zone *zone = pgdat->node_zones + z;
2078 
2079 		if (!populated_zone(zone))
2080 			continue;
2081 
2082 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
2083 		if (!zone_watermark_ok(zone, 0,
2084 				       high_wmark_pages(zone) +
2085 				       nr_migrate_pages,
2086 				       ZONE_MOVABLE, 0))
2087 			continue;
2088 		return true;
2089 	}
2090 	return false;
2091 }
2092 
alloc_misplaced_dst_page(struct page * page,unsigned long data)2093 static struct page *alloc_misplaced_dst_page(struct page *page,
2094 					   unsigned long data)
2095 {
2096 	int nid = (int) data;
2097 	struct page *newpage;
2098 
2099 	newpage = __alloc_pages_node(nid,
2100 					 (GFP_HIGHUSER_MOVABLE |
2101 					  __GFP_THISNODE | __GFP_NOMEMALLOC |
2102 					  __GFP_NORETRY | __GFP_NOWARN) &
2103 					 ~__GFP_RECLAIM, 0);
2104 
2105 	return newpage;
2106 }
2107 
alloc_misplaced_dst_page_thp(struct page * page,unsigned long data)2108 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2109 						 unsigned long data)
2110 {
2111 	int nid = (int) data;
2112 	struct page *newpage;
2113 
2114 	newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2115 				   HPAGE_PMD_ORDER);
2116 	if (!newpage)
2117 		goto out;
2118 
2119 	prep_transhuge_page(newpage);
2120 
2121 out:
2122 	return newpage;
2123 }
2124 
numamigrate_isolate_page(pg_data_t * pgdat,struct page * page)2125 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2126 {
2127 	int page_lru;
2128 	int nr_pages = thp_nr_pages(page);
2129 
2130 	VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2131 
2132 	/* Do not migrate THP mapped by multiple processes */
2133 	if (PageTransHuge(page) && total_mapcount(page) > 1)
2134 		return 0;
2135 
2136 	/* Avoid migrating to a node that is nearly full */
2137 	if (!migrate_balanced_pgdat(pgdat, nr_pages))
2138 		return 0;
2139 
2140 	if (isolate_lru_page(page))
2141 		return 0;
2142 
2143 	page_lru = page_is_file_lru(page);
2144 	mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2145 			    nr_pages);
2146 
2147 	/*
2148 	 * Isolating the page has taken another reference, so the
2149 	 * caller's reference can be safely dropped without the page
2150 	 * disappearing underneath us during migration.
2151 	 */
2152 	put_page(page);
2153 	return 1;
2154 }
2155 
2156 /*
2157  * Attempt to migrate a misplaced page to the specified destination
2158  * node. Caller is expected to have an elevated reference count on
2159  * the page that will be dropped by this function before returning.
2160  */
migrate_misplaced_page(struct page * page,struct vm_area_struct * vma,int node)2161 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2162 			   int node)
2163 {
2164 	pg_data_t *pgdat = NODE_DATA(node);
2165 	int isolated;
2166 	int nr_remaining;
2167 	LIST_HEAD(migratepages);
2168 	new_page_t *new;
2169 	bool compound;
2170 	int nr_pages = thp_nr_pages(page);
2171 
2172 	/*
2173 	 * PTE mapped THP or HugeTLB page can't reach here so the page could
2174 	 * be either base page or THP.  And it must be head page if it is
2175 	 * THP.
2176 	 */
2177 	compound = PageTransHuge(page);
2178 
2179 	if (compound)
2180 		new = alloc_misplaced_dst_page_thp;
2181 	else
2182 		new = alloc_misplaced_dst_page;
2183 
2184 	/*
2185 	 * Don't migrate file pages that are mapped in multiple processes
2186 	 * with execute permissions as they are probably shared libraries.
2187 	 */
2188 	if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2189 	    (vma->vm_flags & VM_EXEC))
2190 		goto out;
2191 
2192 	/*
2193 	 * Also do not migrate dirty pages as not all filesystems can move
2194 	 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2195 	 */
2196 	if (page_is_file_lru(page) && PageDirty(page))
2197 		goto out;
2198 
2199 	isolated = numamigrate_isolate_page(pgdat, page);
2200 	if (!isolated)
2201 		goto out;
2202 
2203 	list_add(&page->lru, &migratepages);
2204 	nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2205 				     MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2206 	if (nr_remaining) {
2207 		if (!list_empty(&migratepages)) {
2208 			list_del(&page->lru);
2209 			mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2210 					page_is_file_lru(page), -nr_pages);
2211 			putback_lru_page(page);
2212 		}
2213 		isolated = 0;
2214 	} else
2215 		count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2216 	BUG_ON(!list_empty(&migratepages));
2217 	return isolated;
2218 
2219 out:
2220 	put_page(page);
2221 	return 0;
2222 }
2223 #endif /* CONFIG_NUMA_BALANCING */
2224 #endif /* CONFIG_NUMA */
2225 
2226 #ifdef CONFIG_DEVICE_PRIVATE
migrate_vma_collect_skip(unsigned long start,unsigned long end,struct mm_walk * walk)2227 static int migrate_vma_collect_skip(unsigned long start,
2228 				    unsigned long end,
2229 				    struct mm_walk *walk)
2230 {
2231 	struct migrate_vma *migrate = walk->private;
2232 	unsigned long addr;
2233 
2234 	for (addr = start; addr < end; addr += PAGE_SIZE) {
2235 		migrate->dst[migrate->npages] = 0;
2236 		migrate->src[migrate->npages++] = 0;
2237 	}
2238 
2239 	return 0;
2240 }
2241 
migrate_vma_collect_hole(unsigned long start,unsigned long end,__always_unused int depth,struct mm_walk * walk)2242 static int migrate_vma_collect_hole(unsigned long start,
2243 				    unsigned long end,
2244 				    __always_unused int depth,
2245 				    struct mm_walk *walk)
2246 {
2247 	struct migrate_vma *migrate = walk->private;
2248 	unsigned long addr;
2249 
2250 	/* Only allow populating anonymous memory. */
2251 	if (!vma_is_anonymous(walk->vma))
2252 		return migrate_vma_collect_skip(start, end, walk);
2253 
2254 	for (addr = start; addr < end; addr += PAGE_SIZE) {
2255 		migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2256 		migrate->dst[migrate->npages] = 0;
2257 		migrate->npages++;
2258 		migrate->cpages++;
2259 	}
2260 
2261 	return 0;
2262 }
2263 
migrate_vma_collect_pmd(pmd_t * pmdp,unsigned long start,unsigned long end,struct mm_walk * walk)2264 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2265 				   unsigned long start,
2266 				   unsigned long end,
2267 				   struct mm_walk *walk)
2268 {
2269 	struct migrate_vma *migrate = walk->private;
2270 	struct vm_area_struct *vma = walk->vma;
2271 	struct mm_struct *mm = vma->vm_mm;
2272 	unsigned long addr = start, unmapped = 0;
2273 	spinlock_t *ptl;
2274 	pte_t *ptep;
2275 
2276 again:
2277 	if (pmd_none(*pmdp))
2278 		return migrate_vma_collect_hole(start, end, -1, walk);
2279 
2280 	if (pmd_trans_huge(*pmdp)) {
2281 		struct page *page;
2282 
2283 		ptl = pmd_lock(mm, pmdp);
2284 		if (unlikely(!pmd_trans_huge(*pmdp))) {
2285 			spin_unlock(ptl);
2286 			goto again;
2287 		}
2288 
2289 		page = pmd_page(*pmdp);
2290 		if (is_huge_zero_page(page)) {
2291 			spin_unlock(ptl);
2292 			split_huge_pmd(vma, pmdp, addr);
2293 			if (pmd_trans_unstable(pmdp))
2294 				return migrate_vma_collect_skip(start, end,
2295 								walk);
2296 		} else {
2297 			int ret;
2298 
2299 			get_page(page);
2300 			spin_unlock(ptl);
2301 			if (unlikely(!trylock_page(page)))
2302 				return migrate_vma_collect_skip(start, end,
2303 								walk);
2304 			ret = split_huge_page(page);
2305 			unlock_page(page);
2306 			put_page(page);
2307 			if (ret)
2308 				return migrate_vma_collect_skip(start, end,
2309 								walk);
2310 			if (pmd_none(*pmdp))
2311 				return migrate_vma_collect_hole(start, end, -1,
2312 								walk);
2313 		}
2314 	}
2315 
2316 	if (unlikely(pmd_bad(*pmdp)))
2317 		return migrate_vma_collect_skip(start, end, walk);
2318 
2319 	ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2320 	arch_enter_lazy_mmu_mode();
2321 
2322 	for (; addr < end; addr += PAGE_SIZE, ptep++) {
2323 		unsigned long mpfn = 0, pfn;
2324 		struct page *page;
2325 		swp_entry_t entry;
2326 		pte_t pte;
2327 
2328 		pte = *ptep;
2329 
2330 		if (pte_none(pte)) {
2331 			if (vma_is_anonymous(vma)) {
2332 				mpfn = MIGRATE_PFN_MIGRATE;
2333 				migrate->cpages++;
2334 			}
2335 			goto next;
2336 		}
2337 
2338 		if (!pte_present(pte)) {
2339 			/*
2340 			 * Only care about unaddressable device page special
2341 			 * page table entry. Other special swap entries are not
2342 			 * migratable, and we ignore regular swapped page.
2343 			 */
2344 			entry = pte_to_swp_entry(pte);
2345 			if (!is_device_private_entry(entry))
2346 				goto next;
2347 
2348 			page = pfn_swap_entry_to_page(entry);
2349 			if (!(migrate->flags &
2350 				MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2351 			    page->pgmap->owner != migrate->pgmap_owner)
2352 				goto next;
2353 
2354 			mpfn = migrate_pfn(page_to_pfn(page)) |
2355 					MIGRATE_PFN_MIGRATE;
2356 			if (is_writable_device_private_entry(entry))
2357 				mpfn |= MIGRATE_PFN_WRITE;
2358 		} else {
2359 			if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2360 				goto next;
2361 			pfn = pte_pfn(pte);
2362 			if (is_zero_pfn(pfn)) {
2363 				mpfn = MIGRATE_PFN_MIGRATE;
2364 				migrate->cpages++;
2365 				goto next;
2366 			}
2367 			page = vm_normal_page(migrate->vma, addr, pte);
2368 			mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2369 			mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2370 		}
2371 
2372 		/* FIXME support THP */
2373 		if (!page || !page->mapping || PageTransCompound(page)) {
2374 			mpfn = 0;
2375 			goto next;
2376 		}
2377 
2378 		/*
2379 		 * By getting a reference on the page we pin it and that blocks
2380 		 * any kind of migration. Side effect is that it "freezes" the
2381 		 * pte.
2382 		 *
2383 		 * We drop this reference after isolating the page from the lru
2384 		 * for non device page (device page are not on the lru and thus
2385 		 * can't be dropped from it).
2386 		 */
2387 		get_page(page);
2388 		migrate->cpages++;
2389 
2390 		/*
2391 		 * Optimize for the common case where page is only mapped once
2392 		 * in one process. If we can lock the page, then we can safely
2393 		 * set up a special migration page table entry now.
2394 		 */
2395 		if (trylock_page(page)) {
2396 			pte_t swp_pte;
2397 
2398 			mpfn |= MIGRATE_PFN_LOCKED;
2399 			ptep_get_and_clear(mm, addr, ptep);
2400 
2401 			/* Setup special migration page table entry */
2402 			if (mpfn & MIGRATE_PFN_WRITE)
2403 				entry = make_writable_migration_entry(
2404 							page_to_pfn(page));
2405 			else
2406 				entry = make_readable_migration_entry(
2407 							page_to_pfn(page));
2408 			swp_pte = swp_entry_to_pte(entry);
2409 			if (pte_present(pte)) {
2410 				if (pte_soft_dirty(pte))
2411 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2412 				if (pte_uffd_wp(pte))
2413 					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2414 			} else {
2415 				if (pte_swp_soft_dirty(pte))
2416 					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2417 				if (pte_swp_uffd_wp(pte))
2418 					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2419 			}
2420 			set_pte_at(mm, addr, ptep, swp_pte);
2421 
2422 			/*
2423 			 * This is like regular unmap: we remove the rmap and
2424 			 * drop page refcount. Page won't be freed, as we took
2425 			 * a reference just above.
2426 			 */
2427 			page_remove_rmap(page, false);
2428 			put_page(page);
2429 
2430 			if (pte_present(pte))
2431 				unmapped++;
2432 		}
2433 
2434 next:
2435 		migrate->dst[migrate->npages] = 0;
2436 		migrate->src[migrate->npages++] = mpfn;
2437 	}
2438 
2439 	/* Only flush the TLB if we actually modified any entries */
2440 	if (unmapped)
2441 		flush_tlb_range(walk->vma, start, end);
2442 
2443 	arch_leave_lazy_mmu_mode();
2444 	pte_unmap_unlock(ptep - 1, ptl);
2445 
2446 	return 0;
2447 }
2448 
2449 static const struct mm_walk_ops migrate_vma_walk_ops = {
2450 	.pmd_entry		= migrate_vma_collect_pmd,
2451 	.pte_hole		= migrate_vma_collect_hole,
2452 };
2453 
2454 /*
2455  * migrate_vma_collect() - collect pages over a range of virtual addresses
2456  * @migrate: migrate struct containing all migration information
2457  *
2458  * This will walk the CPU page table. For each virtual address backed by a
2459  * valid page, it updates the src array and takes a reference on the page, in
2460  * order to pin the page until we lock it and unmap it.
2461  */
migrate_vma_collect(struct migrate_vma * migrate)2462 static void migrate_vma_collect(struct migrate_vma *migrate)
2463 {
2464 	struct mmu_notifier_range range;
2465 
2466 	/*
2467 	 * Note that the pgmap_owner is passed to the mmu notifier callback so
2468 	 * that the registered device driver can skip invalidating device
2469 	 * private page mappings that won't be migrated.
2470 	 */
2471 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2472 		migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2473 		migrate->pgmap_owner);
2474 	mmu_notifier_invalidate_range_start(&range);
2475 
2476 	walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2477 			&migrate_vma_walk_ops, migrate);
2478 
2479 	mmu_notifier_invalidate_range_end(&range);
2480 	migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2481 }
2482 
2483 /*
2484  * migrate_vma_check_page() - check if page is pinned or not
2485  * @page: struct page to check
2486  *
2487  * Pinned pages cannot be migrated. This is the same test as in
2488  * migrate_page_move_mapping(), except that here we allow migration of a
2489  * ZONE_DEVICE page.
2490  */
migrate_vma_check_page(struct page * page)2491 static bool migrate_vma_check_page(struct page *page)
2492 {
2493 	/*
2494 	 * One extra ref because caller holds an extra reference, either from
2495 	 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2496 	 * a device page.
2497 	 */
2498 	int extra = 1;
2499 
2500 	/*
2501 	 * FIXME support THP (transparent huge page), it is bit more complex to
2502 	 * check them than regular pages, because they can be mapped with a pmd
2503 	 * or with a pte (split pte mapping).
2504 	 */
2505 	if (PageCompound(page))
2506 		return false;
2507 
2508 	/* Page from ZONE_DEVICE have one extra reference */
2509 	if (is_zone_device_page(page)) {
2510 		/*
2511 		 * Private page can never be pin as they have no valid pte and
2512 		 * GUP will fail for those. Yet if there is a pending migration
2513 		 * a thread might try to wait on the pte migration entry and
2514 		 * will bump the page reference count. Sadly there is no way to
2515 		 * differentiate a regular pin from migration wait. Hence to
2516 		 * avoid 2 racing thread trying to migrate back to CPU to enter
2517 		 * infinite loop (one stopping migration because the other is
2518 		 * waiting on pte migration entry). We always return true here.
2519 		 *
2520 		 * FIXME proper solution is to rework migration_entry_wait() so
2521 		 * it does not need to take a reference on page.
2522 		 */
2523 		return is_device_private_page(page);
2524 	}
2525 
2526 	/* For file back page */
2527 	if (page_mapping(page))
2528 		extra += 1 + page_has_private(page);
2529 
2530 	if ((page_count(page) - extra) > page_mapcount(page))
2531 		return false;
2532 
2533 	return true;
2534 }
2535 
2536 /*
2537  * migrate_vma_prepare() - lock pages and isolate them from the lru
2538  * @migrate: migrate struct containing all migration information
2539  *
2540  * This locks pages that have been collected by migrate_vma_collect(). Once each
2541  * page is locked it is isolated from the lru (for non-device pages). Finally,
2542  * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2543  * migrated by concurrent kernel threads.
2544  */
migrate_vma_prepare(struct migrate_vma * migrate)2545 static void migrate_vma_prepare(struct migrate_vma *migrate)
2546 {
2547 	const unsigned long npages = migrate->npages;
2548 	const unsigned long start = migrate->start;
2549 	unsigned long addr, i, restore = 0;
2550 	bool allow_drain = true;
2551 
2552 	lru_add_drain();
2553 
2554 	for (i = 0; (i < npages) && migrate->cpages; i++) {
2555 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
2556 		bool remap = true;
2557 
2558 		if (!page)
2559 			continue;
2560 
2561 		if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2562 			/*
2563 			 * Because we are migrating several pages there can be
2564 			 * a deadlock between 2 concurrent migration where each
2565 			 * are waiting on each other page lock.
2566 			 *
2567 			 * Make migrate_vma() a best effort thing and backoff
2568 			 * for any page we can not lock right away.
2569 			 */
2570 			if (!trylock_page(page)) {
2571 				migrate->src[i] = 0;
2572 				migrate->cpages--;
2573 				put_page(page);
2574 				continue;
2575 			}
2576 			remap = false;
2577 			migrate->src[i] |= MIGRATE_PFN_LOCKED;
2578 		}
2579 
2580 		/* ZONE_DEVICE pages are not on LRU */
2581 		if (!is_zone_device_page(page)) {
2582 			if (!PageLRU(page) && allow_drain) {
2583 				/* Drain CPU's pagevec */
2584 				lru_add_drain_all();
2585 				allow_drain = false;
2586 			}
2587 
2588 			if (isolate_lru_page(page)) {
2589 				if (remap) {
2590 					migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2591 					migrate->cpages--;
2592 					restore++;
2593 				} else {
2594 					migrate->src[i] = 0;
2595 					unlock_page(page);
2596 					migrate->cpages--;
2597 					put_page(page);
2598 				}
2599 				continue;
2600 			}
2601 
2602 			/* Drop the reference we took in collect */
2603 			put_page(page);
2604 		}
2605 
2606 		if (!migrate_vma_check_page(page)) {
2607 			if (remap) {
2608 				migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2609 				migrate->cpages--;
2610 				restore++;
2611 
2612 				if (!is_zone_device_page(page)) {
2613 					get_page(page);
2614 					putback_lru_page(page);
2615 				}
2616 			} else {
2617 				migrate->src[i] = 0;
2618 				unlock_page(page);
2619 				migrate->cpages--;
2620 
2621 				if (!is_zone_device_page(page))
2622 					putback_lru_page(page);
2623 				else
2624 					put_page(page);
2625 			}
2626 		}
2627 	}
2628 
2629 	for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2630 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
2631 
2632 		if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2633 			continue;
2634 
2635 		remove_migration_pte(page, migrate->vma, addr, page);
2636 
2637 		migrate->src[i] = 0;
2638 		unlock_page(page);
2639 		put_page(page);
2640 		restore--;
2641 	}
2642 }
2643 
2644 /*
2645  * migrate_vma_unmap() - replace page mapping with special migration pte entry
2646  * @migrate: migrate struct containing all migration information
2647  *
2648  * Replace page mapping (CPU page table pte) with a special migration pte entry
2649  * and check again if it has been pinned. Pinned pages are restored because we
2650  * cannot migrate them.
2651  *
2652  * This is the last step before we call the device driver callback to allocate
2653  * destination memory and copy contents of original page over to new page.
2654  */
migrate_vma_unmap(struct migrate_vma * migrate)2655 static void migrate_vma_unmap(struct migrate_vma *migrate)
2656 {
2657 	const unsigned long npages = migrate->npages;
2658 	const unsigned long start = migrate->start;
2659 	unsigned long addr, i, restore = 0;
2660 
2661 	for (i = 0; i < npages; i++) {
2662 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
2663 
2664 		if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2665 			continue;
2666 
2667 		if (page_mapped(page)) {
2668 			try_to_migrate(page, 0);
2669 			if (page_mapped(page))
2670 				goto restore;
2671 		}
2672 
2673 		if (migrate_vma_check_page(page))
2674 			continue;
2675 
2676 restore:
2677 		migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2678 		migrate->cpages--;
2679 		restore++;
2680 	}
2681 
2682 	for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2683 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
2684 
2685 		if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2686 			continue;
2687 
2688 		remove_migration_ptes(page, page, false);
2689 
2690 		migrate->src[i] = 0;
2691 		unlock_page(page);
2692 		restore--;
2693 
2694 		if (is_zone_device_page(page))
2695 			put_page(page);
2696 		else
2697 			putback_lru_page(page);
2698 	}
2699 }
2700 
2701 /**
2702  * migrate_vma_setup() - prepare to migrate a range of memory
2703  * @args: contains the vma, start, and pfns arrays for the migration
2704  *
2705  * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2706  * without an error.
2707  *
2708  * Prepare to migrate a range of memory virtual address range by collecting all
2709  * the pages backing each virtual address in the range, saving them inside the
2710  * src array.  Then lock those pages and unmap them. Once the pages are locked
2711  * and unmapped, check whether each page is pinned or not.  Pages that aren't
2712  * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2713  * corresponding src array entry.  Then restores any pages that are pinned, by
2714  * remapping and unlocking those pages.
2715  *
2716  * The caller should then allocate destination memory and copy source memory to
2717  * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2718  * flag set).  Once these are allocated and copied, the caller must update each
2719  * corresponding entry in the dst array with the pfn value of the destination
2720  * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2721  * (destination pages must have their struct pages locked, via lock_page()).
2722  *
2723  * Note that the caller does not have to migrate all the pages that are marked
2724  * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2725  * device memory to system memory.  If the caller cannot migrate a device page
2726  * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2727  * consequences for the userspace process, so it must be avoided if at all
2728  * possible.
2729  *
2730  * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2731  * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2732  * allowing the caller to allocate device memory for those unbacked virtual
2733  * addresses.  For this the caller simply has to allocate device memory and
2734  * properly set the destination entry like for regular migration.  Note that
2735  * this can still fail, and thus inside the device driver you must check if the
2736  * migration was successful for those entries after calling migrate_vma_pages(),
2737  * just like for regular migration.
2738  *
2739  * After that, the callers must call migrate_vma_pages() to go over each entry
2740  * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2741  * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2742  * then migrate_vma_pages() to migrate struct page information from the source
2743  * struct page to the destination struct page.  If it fails to migrate the
2744  * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2745  * src array.
2746  *
2747  * At this point all successfully migrated pages have an entry in the src
2748  * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2749  * array entry with MIGRATE_PFN_VALID flag set.
2750  *
2751  * Once migrate_vma_pages() returns the caller may inspect which pages were
2752  * successfully migrated, and which were not.  Successfully migrated pages will
2753  * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2754  *
2755  * It is safe to update device page table after migrate_vma_pages() because
2756  * both destination and source page are still locked, and the mmap_lock is held
2757  * in read mode (hence no one can unmap the range being migrated).
2758  *
2759  * Once the caller is done cleaning up things and updating its page table (if it
2760  * chose to do so, this is not an obligation) it finally calls
2761  * migrate_vma_finalize() to update the CPU page table to point to new pages
2762  * for successfully migrated pages or otherwise restore the CPU page table to
2763  * point to the original source pages.
2764  */
migrate_vma_setup(struct migrate_vma * args)2765 int migrate_vma_setup(struct migrate_vma *args)
2766 {
2767 	long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2768 
2769 	args->start &= PAGE_MASK;
2770 	args->end &= PAGE_MASK;
2771 	if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2772 	    (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2773 		return -EINVAL;
2774 	if (nr_pages <= 0)
2775 		return -EINVAL;
2776 	if (args->start < args->vma->vm_start ||
2777 	    args->start >= args->vma->vm_end)
2778 		return -EINVAL;
2779 	if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2780 		return -EINVAL;
2781 	if (!args->src || !args->dst)
2782 		return -EINVAL;
2783 
2784 	memset(args->src, 0, sizeof(*args->src) * nr_pages);
2785 	args->cpages = 0;
2786 	args->npages = 0;
2787 
2788 	migrate_vma_collect(args);
2789 
2790 	if (args->cpages)
2791 		migrate_vma_prepare(args);
2792 	if (args->cpages)
2793 		migrate_vma_unmap(args);
2794 
2795 	/*
2796 	 * At this point pages are locked and unmapped, and thus they have
2797 	 * stable content and can safely be copied to destination memory that
2798 	 * is allocated by the drivers.
2799 	 */
2800 	return 0;
2801 
2802 }
2803 EXPORT_SYMBOL(migrate_vma_setup);
2804 
2805 /*
2806  * This code closely matches the code in:
2807  *   __handle_mm_fault()
2808  *     handle_pte_fault()
2809  *       do_anonymous_page()
2810  * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2811  * private page.
2812  */
migrate_vma_insert_page(struct migrate_vma * migrate,unsigned long addr,struct page * page,unsigned long * src)2813 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2814 				    unsigned long addr,
2815 				    struct page *page,
2816 				    unsigned long *src)
2817 {
2818 	struct vm_area_struct *vma = migrate->vma;
2819 	struct mm_struct *mm = vma->vm_mm;
2820 	bool flush = false;
2821 	spinlock_t *ptl;
2822 	pte_t entry;
2823 	pgd_t *pgdp;
2824 	p4d_t *p4dp;
2825 	pud_t *pudp;
2826 	pmd_t *pmdp;
2827 	pte_t *ptep;
2828 
2829 	/* Only allow populating anonymous memory */
2830 	if (!vma_is_anonymous(vma))
2831 		goto abort;
2832 
2833 	pgdp = pgd_offset(mm, addr);
2834 	p4dp = p4d_alloc(mm, pgdp, addr);
2835 	if (!p4dp)
2836 		goto abort;
2837 	pudp = pud_alloc(mm, p4dp, addr);
2838 	if (!pudp)
2839 		goto abort;
2840 	pmdp = pmd_alloc(mm, pudp, addr);
2841 	if (!pmdp)
2842 		goto abort;
2843 
2844 	if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2845 		goto abort;
2846 
2847 	/*
2848 	 * Use pte_alloc() instead of pte_alloc_map().  We can't run
2849 	 * pte_offset_map() on pmds where a huge pmd might be created
2850 	 * from a different thread.
2851 	 *
2852 	 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2853 	 * parallel threads are excluded by other means.
2854 	 *
2855 	 * Here we only have mmap_read_lock(mm).
2856 	 */
2857 	if (pte_alloc(mm, pmdp))
2858 		goto abort;
2859 
2860 	/* See the comment in pte_alloc_one_map() */
2861 	if (unlikely(pmd_trans_unstable(pmdp)))
2862 		goto abort;
2863 
2864 	if (unlikely(anon_vma_prepare(vma)))
2865 		goto abort;
2866 	if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
2867 		goto abort;
2868 
2869 	/*
2870 	 * The memory barrier inside __SetPageUptodate makes sure that
2871 	 * preceding stores to the page contents become visible before
2872 	 * the set_pte_at() write.
2873 	 */
2874 	__SetPageUptodate(page);
2875 
2876 	if (is_zone_device_page(page)) {
2877 		if (is_device_private_page(page)) {
2878 			swp_entry_t swp_entry;
2879 
2880 			if (vma->vm_flags & VM_WRITE)
2881 				swp_entry = make_writable_device_private_entry(
2882 							page_to_pfn(page));
2883 			else
2884 				swp_entry = make_readable_device_private_entry(
2885 							page_to_pfn(page));
2886 			entry = swp_entry_to_pte(swp_entry);
2887 		} else {
2888 			/*
2889 			 * For now we only support migrating to un-addressable
2890 			 * device memory.
2891 			 */
2892 			pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2893 			goto abort;
2894 		}
2895 	} else {
2896 		entry = mk_pte(page, vma->vm_page_prot);
2897 		if (vma->vm_flags & VM_WRITE)
2898 			entry = pte_mkwrite(pte_mkdirty(entry));
2899 	}
2900 
2901 	ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2902 
2903 	if (check_stable_address_space(mm))
2904 		goto unlock_abort;
2905 
2906 	if (pte_present(*ptep)) {
2907 		unsigned long pfn = pte_pfn(*ptep);
2908 
2909 		if (!is_zero_pfn(pfn))
2910 			goto unlock_abort;
2911 		flush = true;
2912 	} else if (!pte_none(*ptep))
2913 		goto unlock_abort;
2914 
2915 	/*
2916 	 * Check for userfaultfd but do not deliver the fault. Instead,
2917 	 * just back off.
2918 	 */
2919 	if (userfaultfd_missing(vma))
2920 		goto unlock_abort;
2921 
2922 	inc_mm_counter(mm, MM_ANONPAGES);
2923 	page_add_new_anon_rmap(page, vma, addr, false);
2924 	if (!is_zone_device_page(page))
2925 		lru_cache_add_inactive_or_unevictable(page, vma);
2926 	get_page(page);
2927 
2928 	if (flush) {
2929 		flush_cache_page(vma, addr, pte_pfn(*ptep));
2930 		ptep_clear_flush_notify(vma, addr, ptep);
2931 		set_pte_at_notify(mm, addr, ptep, entry);
2932 		update_mmu_cache(vma, addr, ptep);
2933 	} else {
2934 		/* No need to invalidate - it was non-present before */
2935 		set_pte_at(mm, addr, ptep, entry);
2936 		update_mmu_cache(vma, addr, ptep);
2937 	}
2938 
2939 	pte_unmap_unlock(ptep, ptl);
2940 	*src = MIGRATE_PFN_MIGRATE;
2941 	return;
2942 
2943 unlock_abort:
2944 	pte_unmap_unlock(ptep, ptl);
2945 abort:
2946 	*src &= ~MIGRATE_PFN_MIGRATE;
2947 }
2948 
2949 /**
2950  * migrate_vma_pages() - migrate meta-data from src page to dst page
2951  * @migrate: migrate struct containing all migration information
2952  *
2953  * This migrates struct page meta-data from source struct page to destination
2954  * struct page. This effectively finishes the migration from source page to the
2955  * destination page.
2956  */
migrate_vma_pages(struct migrate_vma * migrate)2957 void migrate_vma_pages(struct migrate_vma *migrate)
2958 {
2959 	const unsigned long npages = migrate->npages;
2960 	const unsigned long start = migrate->start;
2961 	struct mmu_notifier_range range;
2962 	unsigned long addr, i;
2963 	bool notified = false;
2964 
2965 	for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2966 		struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2967 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
2968 		struct address_space *mapping;
2969 		int r;
2970 
2971 		if (!newpage) {
2972 			migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2973 			continue;
2974 		}
2975 
2976 		if (!page) {
2977 			if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2978 				continue;
2979 			if (!notified) {
2980 				notified = true;
2981 
2982 				mmu_notifier_range_init_owner(&range,
2983 					MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2984 					migrate->vma->vm_mm, addr, migrate->end,
2985 					migrate->pgmap_owner);
2986 				mmu_notifier_invalidate_range_start(&range);
2987 			}
2988 			migrate_vma_insert_page(migrate, addr, newpage,
2989 						&migrate->src[i]);
2990 			continue;
2991 		}
2992 
2993 		mapping = page_mapping(page);
2994 
2995 		if (is_zone_device_page(newpage)) {
2996 			if (is_device_private_page(newpage)) {
2997 				/*
2998 				 * For now only support private anonymous when
2999 				 * migrating to un-addressable device memory.
3000 				 */
3001 				if (mapping) {
3002 					migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3003 					continue;
3004 				}
3005 			} else {
3006 				/*
3007 				 * Other types of ZONE_DEVICE page are not
3008 				 * supported.
3009 				 */
3010 				migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3011 				continue;
3012 			}
3013 		}
3014 
3015 		r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
3016 		if (r != MIGRATEPAGE_SUCCESS)
3017 			migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3018 	}
3019 
3020 	/*
3021 	 * No need to double call mmu_notifier->invalidate_range() callback as
3022 	 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3023 	 * did already call it.
3024 	 */
3025 	if (notified)
3026 		mmu_notifier_invalidate_range_only_end(&range);
3027 }
3028 EXPORT_SYMBOL(migrate_vma_pages);
3029 
3030 /**
3031  * migrate_vma_finalize() - restore CPU page table entry
3032  * @migrate: migrate struct containing all migration information
3033  *
3034  * This replaces the special migration pte entry with either a mapping to the
3035  * new page if migration was successful for that page, or to the original page
3036  * otherwise.
3037  *
3038  * This also unlocks the pages and puts them back on the lru, or drops the extra
3039  * refcount, for device pages.
3040  */
migrate_vma_finalize(struct migrate_vma * migrate)3041 void migrate_vma_finalize(struct migrate_vma *migrate)
3042 {
3043 	const unsigned long npages = migrate->npages;
3044 	unsigned long i;
3045 
3046 	for (i = 0; i < npages; i++) {
3047 		struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3048 		struct page *page = migrate_pfn_to_page(migrate->src[i]);
3049 
3050 		if (!page) {
3051 			if (newpage) {
3052 				unlock_page(newpage);
3053 				put_page(newpage);
3054 			}
3055 			continue;
3056 		}
3057 
3058 		if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3059 			if (newpage) {
3060 				unlock_page(newpage);
3061 				put_page(newpage);
3062 			}
3063 			newpage = page;
3064 		}
3065 
3066 		remove_migration_ptes(page, newpage, false);
3067 		unlock_page(page);
3068 
3069 		if (is_zone_device_page(page))
3070 			put_page(page);
3071 		else
3072 			putback_lru_page(page);
3073 
3074 		if (newpage != page) {
3075 			unlock_page(newpage);
3076 			if (is_zone_device_page(newpage))
3077 				put_page(newpage);
3078 			else
3079 				putback_lru_page(newpage);
3080 		}
3081 	}
3082 }
3083 EXPORT_SYMBOL(migrate_vma_finalize);
3084 #endif /* CONFIG_DEVICE_PRIVATE */
3085 
3086 #if defined(CONFIG_HOTPLUG_CPU)
3087 /* Disable reclaim-based migration. */
__disable_all_migrate_targets(void)3088 static void __disable_all_migrate_targets(void)
3089 {
3090 	int node;
3091 
3092 	for_each_online_node(node)
3093 		node_demotion[node] = NUMA_NO_NODE;
3094 }
3095 
disable_all_migrate_targets(void)3096 static void disable_all_migrate_targets(void)
3097 {
3098 	__disable_all_migrate_targets();
3099 
3100 	/*
3101 	 * Ensure that the "disable" is visible across the system.
3102 	 * Readers will see either a combination of before+disable
3103 	 * state or disable+after.  They will never see before and
3104 	 * after state together.
3105 	 *
3106 	 * The before+after state together might have cycles and
3107 	 * could cause readers to do things like loop until this
3108 	 * function finishes.  This ensures they can only see a
3109 	 * single "bad" read and would, for instance, only loop
3110 	 * once.
3111 	 */
3112 	synchronize_rcu();
3113 }
3114 
3115 /*
3116  * Find an automatic demotion target for 'node'.
3117  * Failing here is OK.  It might just indicate
3118  * being at the end of a chain.
3119  */
establish_migrate_target(int node,nodemask_t * used)3120 static int establish_migrate_target(int node, nodemask_t *used)
3121 {
3122 	int migration_target;
3123 
3124 	/*
3125 	 * Can not set a migration target on a
3126 	 * node with it already set.
3127 	 *
3128 	 * No need for READ_ONCE() here since this
3129 	 * in the write path for node_demotion[].
3130 	 * This should be the only thread writing.
3131 	 */
3132 	if (node_demotion[node] != NUMA_NO_NODE)
3133 		return NUMA_NO_NODE;
3134 
3135 	migration_target = find_next_best_node(node, used);
3136 	if (migration_target == NUMA_NO_NODE)
3137 		return NUMA_NO_NODE;
3138 
3139 	node_demotion[node] = migration_target;
3140 
3141 	return migration_target;
3142 }
3143 
3144 /*
3145  * When memory fills up on a node, memory contents can be
3146  * automatically migrated to another node instead of
3147  * discarded at reclaim.
3148  *
3149  * Establish a "migration path" which will start at nodes
3150  * with CPUs and will follow the priorities used to build the
3151  * page allocator zonelists.
3152  *
3153  * The difference here is that cycles must be avoided.  If
3154  * node0 migrates to node1, then neither node1, nor anything
3155  * node1 migrates to can migrate to node0.
3156  *
3157  * This function can run simultaneously with readers of
3158  * node_demotion[].  However, it can not run simultaneously
3159  * with itself.  Exclusion is provided by memory hotplug events
3160  * being single-threaded.
3161  */
__set_migration_target_nodes(void)3162 static void __set_migration_target_nodes(void)
3163 {
3164 	nodemask_t next_pass	= NODE_MASK_NONE;
3165 	nodemask_t this_pass	= NODE_MASK_NONE;
3166 	nodemask_t used_targets = NODE_MASK_NONE;
3167 	int node;
3168 
3169 	/*
3170 	 * Avoid any oddities like cycles that could occur
3171 	 * from changes in the topology.  This will leave
3172 	 * a momentary gap when migration is disabled.
3173 	 */
3174 	disable_all_migrate_targets();
3175 
3176 	/*
3177 	 * Allocations go close to CPUs, first.  Assume that
3178 	 * the migration path starts at the nodes with CPUs.
3179 	 */
3180 	next_pass = node_states[N_CPU];
3181 again:
3182 	this_pass = next_pass;
3183 	next_pass = NODE_MASK_NONE;
3184 	/*
3185 	 * To avoid cycles in the migration "graph", ensure
3186 	 * that migration sources are not future targets by
3187 	 * setting them in 'used_targets'.  Do this only
3188 	 * once per pass so that multiple source nodes can
3189 	 * share a target node.
3190 	 *
3191 	 * 'used_targets' will become unavailable in future
3192 	 * passes.  This limits some opportunities for
3193 	 * multiple source nodes to share a destination.
3194 	 */
3195 	nodes_or(used_targets, used_targets, this_pass);
3196 	for_each_node_mask(node, this_pass) {
3197 		int target_node = establish_migrate_target(node, &used_targets);
3198 
3199 		if (target_node == NUMA_NO_NODE)
3200 			continue;
3201 
3202 		/*
3203 		 * Visit targets from this pass in the next pass.
3204 		 * Eventually, every node will have been part of
3205 		 * a pass, and will become set in 'used_targets'.
3206 		 */
3207 		node_set(target_node, next_pass);
3208 	}
3209 	/*
3210 	 * 'next_pass' contains nodes which became migration
3211 	 * targets in this pass.  Make additional passes until
3212 	 * no more migrations targets are available.
3213 	 */
3214 	if (!nodes_empty(next_pass))
3215 		goto again;
3216 }
3217 
3218 /*
3219  * For callers that do not hold get_online_mems() already.
3220  */
set_migration_target_nodes(void)3221 static void set_migration_target_nodes(void)
3222 {
3223 	get_online_mems();
3224 	__set_migration_target_nodes();
3225 	put_online_mems();
3226 }
3227 
3228 /*
3229  * This leaves migrate-on-reclaim transiently disabled between
3230  * the MEM_GOING_OFFLINE and MEM_OFFLINE events.  This runs
3231  * whether reclaim-based migration is enabled or not, which
3232  * ensures that the user can turn reclaim-based migration at
3233  * any time without needing to recalculate migration targets.
3234  *
3235  * These callbacks already hold get_online_mems().  That is why
3236  * __set_migration_target_nodes() can be used as opposed to
3237  * set_migration_target_nodes().
3238  */
migrate_on_reclaim_callback(struct notifier_block * self,unsigned long action,void * _arg)3239 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3240 						 unsigned long action, void *_arg)
3241 {
3242 	struct memory_notify *arg = _arg;
3243 
3244 	/*
3245 	 * Only update the node migration order when a node is
3246 	 * changing status, like online->offline.  This avoids
3247 	 * the overhead of synchronize_rcu() in most cases.
3248 	 */
3249 	if (arg->status_change_nid < 0)
3250 		return notifier_from_errno(0);
3251 
3252 	switch (action) {
3253 	case MEM_GOING_OFFLINE:
3254 		/*
3255 		 * Make sure there are not transient states where
3256 		 * an offline node is a migration target.  This
3257 		 * will leave migration disabled until the offline
3258 		 * completes and the MEM_OFFLINE case below runs.
3259 		 */
3260 		disable_all_migrate_targets();
3261 		break;
3262 	case MEM_OFFLINE:
3263 	case MEM_ONLINE:
3264 		/*
3265 		 * Recalculate the target nodes once the node
3266 		 * reaches its final state (online or offline).
3267 		 */
3268 		__set_migration_target_nodes();
3269 		break;
3270 	case MEM_CANCEL_OFFLINE:
3271 		/*
3272 		 * MEM_GOING_OFFLINE disabled all the migration
3273 		 * targets.  Reenable them.
3274 		 */
3275 		__set_migration_target_nodes();
3276 		break;
3277 	case MEM_GOING_ONLINE:
3278 	case MEM_CANCEL_ONLINE:
3279 		break;
3280 	}
3281 
3282 	return notifier_from_errno(0);
3283 }
3284 
3285 /*
3286  * React to hotplug events that might affect the migration targets
3287  * like events that online or offline NUMA nodes.
3288  *
3289  * The ordering is also currently dependent on which nodes have
3290  * CPUs.  That means we need CPU on/offline notification too.
3291  */
migration_online_cpu(unsigned int cpu)3292 static int migration_online_cpu(unsigned int cpu)
3293 {
3294 	set_migration_target_nodes();
3295 	return 0;
3296 }
3297 
migration_offline_cpu(unsigned int cpu)3298 static int migration_offline_cpu(unsigned int cpu)
3299 {
3300 	set_migration_target_nodes();
3301 	return 0;
3302 }
3303 
migrate_on_reclaim_init(void)3304 static int __init migrate_on_reclaim_init(void)
3305 {
3306 	int ret;
3307 
3308 	ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3309 					NULL, migration_offline_cpu);
3310 	/*
3311 	 * In the unlikely case that this fails, the automatic
3312 	 * migration targets may become suboptimal for nodes
3313 	 * where N_CPU changes.  With such a small impact in a
3314 	 * rare case, do not bother trying to do anything special.
3315 	 */
3316 	WARN_ON(ret < 0);
3317 	ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3318 				migration_online_cpu, NULL);
3319 	WARN_ON(ret < 0);
3320 
3321 	hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3322 	return 0;
3323 }
3324 late_initcall(migrate_on_reclaim_init);
3325 #endif /* CONFIG_HOTPLUG_CPU */
3326