xref: /openbmc/linux/mm/migrate.c (revision e23feb16)
1 /*
2  * Memory Migration functionality - linux/mm/migration.c
3  *
4  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
5  *
6  * Page migration was first developed in the context of the memory hotplug
7  * project. The main authors of the migration code are:
8  *
9  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
10  * Hirokazu Takahashi <taka@valinux.co.jp>
11  * Dave Hansen <haveblue@us.ibm.com>
12  * Christoph Lameter
13  */
14 
15 #include <linux/migrate.h>
16 #include <linux/export.h>
17 #include <linux/swap.h>
18 #include <linux/swapops.h>
19 #include <linux/pagemap.h>
20 #include <linux/buffer_head.h>
21 #include <linux/mm_inline.h>
22 #include <linux/nsproxy.h>
23 #include <linux/pagevec.h>
24 #include <linux/ksm.h>
25 #include <linux/rmap.h>
26 #include <linux/topology.h>
27 #include <linux/cpu.h>
28 #include <linux/cpuset.h>
29 #include <linux/writeback.h>
30 #include <linux/mempolicy.h>
31 #include <linux/vmalloc.h>
32 #include <linux/security.h>
33 #include <linux/memcontrol.h>
34 #include <linux/syscalls.h>
35 #include <linux/hugetlb.h>
36 #include <linux/hugetlb_cgroup.h>
37 #include <linux/gfp.h>
38 #include <linux/balloon_compaction.h>
39 
40 #include <asm/tlbflush.h>
41 
42 #define CREATE_TRACE_POINTS
43 #include <trace/events/migrate.h>
44 
45 #include "internal.h"
46 
47 /*
48  * migrate_prep() needs to be called before we start compiling a list of pages
49  * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
50  * undesirable, use migrate_prep_local()
51  */
52 int migrate_prep(void)
53 {
54 	/*
55 	 * Clear the LRU lists so pages can be isolated.
56 	 * Note that pages may be moved off the LRU after we have
57 	 * drained them. Those pages will fail to migrate like other
58 	 * pages that may be busy.
59 	 */
60 	lru_add_drain_all();
61 
62 	return 0;
63 }
64 
65 /* Do the necessary work of migrate_prep but not if it involves other CPUs */
66 int migrate_prep_local(void)
67 {
68 	lru_add_drain();
69 
70 	return 0;
71 }
72 
73 /*
74  * Add isolated pages on the list back to the LRU under page lock
75  * to avoid leaking evictable pages back onto unevictable list.
76  */
77 void putback_lru_pages(struct list_head *l)
78 {
79 	struct page *page;
80 	struct page *page2;
81 
82 	list_for_each_entry_safe(page, page2, l, lru) {
83 		list_del(&page->lru);
84 		dec_zone_page_state(page, NR_ISOLATED_ANON +
85 				page_is_file_cache(page));
86 			putback_lru_page(page);
87 	}
88 }
89 
90 /*
91  * Put previously isolated pages back onto the appropriate lists
92  * from where they were once taken off for compaction/migration.
93  *
94  * This function shall be used instead of putback_lru_pages(),
95  * whenever the isolated pageset has been built by isolate_migratepages_range()
96  */
97 void putback_movable_pages(struct list_head *l)
98 {
99 	struct page *page;
100 	struct page *page2;
101 
102 	list_for_each_entry_safe(page, page2, l, lru) {
103 		if (unlikely(PageHuge(page))) {
104 			putback_active_hugepage(page);
105 			continue;
106 		}
107 		list_del(&page->lru);
108 		dec_zone_page_state(page, NR_ISOLATED_ANON +
109 				page_is_file_cache(page));
110 		if (unlikely(isolated_balloon_page(page)))
111 			balloon_page_putback(page);
112 		else
113 			putback_lru_page(page);
114 	}
115 }
116 
117 /*
118  * Restore a potential migration pte to a working pte entry
119  */
120 static int remove_migration_pte(struct page *new, struct vm_area_struct *vma,
121 				 unsigned long addr, void *old)
122 {
123 	struct mm_struct *mm = vma->vm_mm;
124 	swp_entry_t entry;
125  	pmd_t *pmd;
126 	pte_t *ptep, pte;
127  	spinlock_t *ptl;
128 
129 	if (unlikely(PageHuge(new))) {
130 		ptep = huge_pte_offset(mm, addr);
131 		if (!ptep)
132 			goto out;
133 		ptl = &mm->page_table_lock;
134 	} else {
135 		pmd = mm_find_pmd(mm, addr);
136 		if (!pmd)
137 			goto out;
138 		if (pmd_trans_huge(*pmd))
139 			goto out;
140 
141 		ptep = pte_offset_map(pmd, addr);
142 
143 		/*
144 		 * Peek to check is_swap_pte() before taking ptlock?  No, we
145 		 * can race mremap's move_ptes(), which skips anon_vma lock.
146 		 */
147 
148 		ptl = pte_lockptr(mm, pmd);
149 	}
150 
151  	spin_lock(ptl);
152 	pte = *ptep;
153 	if (!is_swap_pte(pte))
154 		goto unlock;
155 
156 	entry = pte_to_swp_entry(pte);
157 
158 	if (!is_migration_entry(entry) ||
159 	    migration_entry_to_page(entry) != old)
160 		goto unlock;
161 
162 	get_page(new);
163 	pte = pte_mkold(mk_pte(new, vma->vm_page_prot));
164 	if (is_write_migration_entry(entry))
165 		pte = pte_mkwrite(pte);
166 #ifdef CONFIG_HUGETLB_PAGE
167 	if (PageHuge(new)) {
168 		pte = pte_mkhuge(pte);
169 		pte = arch_make_huge_pte(pte, vma, new, 0);
170 	}
171 #endif
172 	flush_dcache_page(new);
173 	set_pte_at(mm, addr, ptep, pte);
174 
175 	if (PageHuge(new)) {
176 		if (PageAnon(new))
177 			hugepage_add_anon_rmap(new, vma, addr);
178 		else
179 			page_dup_rmap(new);
180 	} else if (PageAnon(new))
181 		page_add_anon_rmap(new, vma, addr);
182 	else
183 		page_add_file_rmap(new);
184 
185 	/* No need to invalidate - it was non-present before */
186 	update_mmu_cache(vma, addr, ptep);
187 unlock:
188 	pte_unmap_unlock(ptep, ptl);
189 out:
190 	return SWAP_AGAIN;
191 }
192 
193 /*
194  * Get rid of all migration entries and replace them by
195  * references to the indicated page.
196  */
197 static void remove_migration_ptes(struct page *old, struct page *new)
198 {
199 	rmap_walk(new, remove_migration_pte, old);
200 }
201 
202 /*
203  * Something used the pte of a page under migration. We need to
204  * get to the page and wait until migration is finished.
205  * When we return from this function the fault will be retried.
206  */
207 static void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
208 				spinlock_t *ptl)
209 {
210 	pte_t pte;
211 	swp_entry_t entry;
212 	struct page *page;
213 
214 	spin_lock(ptl);
215 	pte = *ptep;
216 	if (!is_swap_pte(pte))
217 		goto out;
218 
219 	entry = pte_to_swp_entry(pte);
220 	if (!is_migration_entry(entry))
221 		goto out;
222 
223 	page = migration_entry_to_page(entry);
224 
225 	/*
226 	 * Once radix-tree replacement of page migration started, page_count
227 	 * *must* be zero. And, we don't want to call wait_on_page_locked()
228 	 * against a page without get_page().
229 	 * So, we use get_page_unless_zero(), here. Even failed, page fault
230 	 * will occur again.
231 	 */
232 	if (!get_page_unless_zero(page))
233 		goto out;
234 	pte_unmap_unlock(ptep, ptl);
235 	wait_on_page_locked(page);
236 	put_page(page);
237 	return;
238 out:
239 	pte_unmap_unlock(ptep, ptl);
240 }
241 
242 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
243 				unsigned long address)
244 {
245 	spinlock_t *ptl = pte_lockptr(mm, pmd);
246 	pte_t *ptep = pte_offset_map(pmd, address);
247 	__migration_entry_wait(mm, ptep, ptl);
248 }
249 
250 void migration_entry_wait_huge(struct mm_struct *mm, pte_t *pte)
251 {
252 	spinlock_t *ptl = &(mm)->page_table_lock;
253 	__migration_entry_wait(mm, pte, ptl);
254 }
255 
256 #ifdef CONFIG_BLOCK
257 /* Returns true if all buffers are successfully locked */
258 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
259 							enum migrate_mode mode)
260 {
261 	struct buffer_head *bh = head;
262 
263 	/* Simple case, sync compaction */
264 	if (mode != MIGRATE_ASYNC) {
265 		do {
266 			get_bh(bh);
267 			lock_buffer(bh);
268 			bh = bh->b_this_page;
269 
270 		} while (bh != head);
271 
272 		return true;
273 	}
274 
275 	/* async case, we cannot block on lock_buffer so use trylock_buffer */
276 	do {
277 		get_bh(bh);
278 		if (!trylock_buffer(bh)) {
279 			/*
280 			 * We failed to lock the buffer and cannot stall in
281 			 * async migration. Release the taken locks
282 			 */
283 			struct buffer_head *failed_bh = bh;
284 			put_bh(failed_bh);
285 			bh = head;
286 			while (bh != failed_bh) {
287 				unlock_buffer(bh);
288 				put_bh(bh);
289 				bh = bh->b_this_page;
290 			}
291 			return false;
292 		}
293 
294 		bh = bh->b_this_page;
295 	} while (bh != head);
296 	return true;
297 }
298 #else
299 static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
300 							enum migrate_mode mode)
301 {
302 	return true;
303 }
304 #endif /* CONFIG_BLOCK */
305 
306 /*
307  * Replace the page in the mapping.
308  *
309  * The number of remaining references must be:
310  * 1 for anonymous pages without a mapping
311  * 2 for pages with a mapping
312  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
313  */
314 int migrate_page_move_mapping(struct address_space *mapping,
315 		struct page *newpage, struct page *page,
316 		struct buffer_head *head, enum migrate_mode mode)
317 {
318 	int expected_count = 0;
319 	void **pslot;
320 
321 	if (!mapping) {
322 		/* Anonymous page without mapping */
323 		if (page_count(page) != 1)
324 			return -EAGAIN;
325 		return MIGRATEPAGE_SUCCESS;
326 	}
327 
328 	spin_lock_irq(&mapping->tree_lock);
329 
330 	pslot = radix_tree_lookup_slot(&mapping->page_tree,
331  					page_index(page));
332 
333 	expected_count = 2 + page_has_private(page);
334 	if (page_count(page) != expected_count ||
335 		radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
336 		spin_unlock_irq(&mapping->tree_lock);
337 		return -EAGAIN;
338 	}
339 
340 	if (!page_freeze_refs(page, expected_count)) {
341 		spin_unlock_irq(&mapping->tree_lock);
342 		return -EAGAIN;
343 	}
344 
345 	/*
346 	 * In the async migration case of moving a page with buffers, lock the
347 	 * buffers using trylock before the mapping is moved. If the mapping
348 	 * was moved, we later failed to lock the buffers and could not move
349 	 * the mapping back due to an elevated page count, we would have to
350 	 * block waiting on other references to be dropped.
351 	 */
352 	if (mode == MIGRATE_ASYNC && head &&
353 			!buffer_migrate_lock_buffers(head, mode)) {
354 		page_unfreeze_refs(page, expected_count);
355 		spin_unlock_irq(&mapping->tree_lock);
356 		return -EAGAIN;
357 	}
358 
359 	/*
360 	 * Now we know that no one else is looking at the page.
361 	 */
362 	get_page(newpage);	/* add cache reference */
363 	if (PageSwapCache(page)) {
364 		SetPageSwapCache(newpage);
365 		set_page_private(newpage, page_private(page));
366 	}
367 
368 	radix_tree_replace_slot(pslot, newpage);
369 
370 	/*
371 	 * Drop cache reference from old page by unfreezing
372 	 * to one less reference.
373 	 * We know this isn't the last reference.
374 	 */
375 	page_unfreeze_refs(page, expected_count - 1);
376 
377 	/*
378 	 * If moved to a different zone then also account
379 	 * the page for that zone. Other VM counters will be
380 	 * taken care of when we establish references to the
381 	 * new page and drop references to the old page.
382 	 *
383 	 * Note that anonymous pages are accounted for
384 	 * via NR_FILE_PAGES and NR_ANON_PAGES if they
385 	 * are mapped to swap space.
386 	 */
387 	__dec_zone_page_state(page, NR_FILE_PAGES);
388 	__inc_zone_page_state(newpage, NR_FILE_PAGES);
389 	if (!PageSwapCache(page) && PageSwapBacked(page)) {
390 		__dec_zone_page_state(page, NR_SHMEM);
391 		__inc_zone_page_state(newpage, NR_SHMEM);
392 	}
393 	spin_unlock_irq(&mapping->tree_lock);
394 
395 	return MIGRATEPAGE_SUCCESS;
396 }
397 
398 /*
399  * The expected number of remaining references is the same as that
400  * of migrate_page_move_mapping().
401  */
402 int migrate_huge_page_move_mapping(struct address_space *mapping,
403 				   struct page *newpage, struct page *page)
404 {
405 	int expected_count;
406 	void **pslot;
407 
408 	if (!mapping) {
409 		if (page_count(page) != 1)
410 			return -EAGAIN;
411 		return MIGRATEPAGE_SUCCESS;
412 	}
413 
414 	spin_lock_irq(&mapping->tree_lock);
415 
416 	pslot = radix_tree_lookup_slot(&mapping->page_tree,
417 					page_index(page));
418 
419 	expected_count = 2 + page_has_private(page);
420 	if (page_count(page) != expected_count ||
421 		radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
422 		spin_unlock_irq(&mapping->tree_lock);
423 		return -EAGAIN;
424 	}
425 
426 	if (!page_freeze_refs(page, expected_count)) {
427 		spin_unlock_irq(&mapping->tree_lock);
428 		return -EAGAIN;
429 	}
430 
431 	get_page(newpage);
432 
433 	radix_tree_replace_slot(pslot, newpage);
434 
435 	page_unfreeze_refs(page, expected_count - 1);
436 
437 	spin_unlock_irq(&mapping->tree_lock);
438 	return MIGRATEPAGE_SUCCESS;
439 }
440 
441 /*
442  * Copy the page to its new location
443  */
444 void migrate_page_copy(struct page *newpage, struct page *page)
445 {
446 	if (PageHuge(page) || PageTransHuge(page))
447 		copy_huge_page(newpage, page);
448 	else
449 		copy_highpage(newpage, page);
450 
451 	if (PageError(page))
452 		SetPageError(newpage);
453 	if (PageReferenced(page))
454 		SetPageReferenced(newpage);
455 	if (PageUptodate(page))
456 		SetPageUptodate(newpage);
457 	if (TestClearPageActive(page)) {
458 		VM_BUG_ON(PageUnevictable(page));
459 		SetPageActive(newpage);
460 	} else if (TestClearPageUnevictable(page))
461 		SetPageUnevictable(newpage);
462 	if (PageChecked(page))
463 		SetPageChecked(newpage);
464 	if (PageMappedToDisk(page))
465 		SetPageMappedToDisk(newpage);
466 
467 	if (PageDirty(page)) {
468 		clear_page_dirty_for_io(page);
469 		/*
470 		 * Want to mark the page and the radix tree as dirty, and
471 		 * redo the accounting that clear_page_dirty_for_io undid,
472 		 * but we can't use set_page_dirty because that function
473 		 * is actually a signal that all of the page has become dirty.
474 		 * Whereas only part of our page may be dirty.
475 		 */
476 		if (PageSwapBacked(page))
477 			SetPageDirty(newpage);
478 		else
479 			__set_page_dirty_nobuffers(newpage);
480  	}
481 
482 	mlock_migrate_page(newpage, page);
483 	ksm_migrate_page(newpage, page);
484 	/*
485 	 * Please do not reorder this without considering how mm/ksm.c's
486 	 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
487 	 */
488 	ClearPageSwapCache(page);
489 	ClearPagePrivate(page);
490 	set_page_private(page, 0);
491 
492 	/*
493 	 * If any waiters have accumulated on the new page then
494 	 * wake them up.
495 	 */
496 	if (PageWriteback(newpage))
497 		end_page_writeback(newpage);
498 }
499 
500 /************************************************************
501  *                    Migration functions
502  ***********************************************************/
503 
504 /* Always fail migration. Used for mappings that are not movable */
505 int fail_migrate_page(struct address_space *mapping,
506 			struct page *newpage, struct page *page)
507 {
508 	return -EIO;
509 }
510 EXPORT_SYMBOL(fail_migrate_page);
511 
512 /*
513  * Common logic to directly migrate a single page suitable for
514  * pages that do not use PagePrivate/PagePrivate2.
515  *
516  * Pages are locked upon entry and exit.
517  */
518 int migrate_page(struct address_space *mapping,
519 		struct page *newpage, struct page *page,
520 		enum migrate_mode mode)
521 {
522 	int rc;
523 
524 	BUG_ON(PageWriteback(page));	/* Writeback must be complete */
525 
526 	rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode);
527 
528 	if (rc != MIGRATEPAGE_SUCCESS)
529 		return rc;
530 
531 	migrate_page_copy(newpage, page);
532 	return MIGRATEPAGE_SUCCESS;
533 }
534 EXPORT_SYMBOL(migrate_page);
535 
536 #ifdef CONFIG_BLOCK
537 /*
538  * Migration function for pages with buffers. This function can only be used
539  * if the underlying filesystem guarantees that no other references to "page"
540  * exist.
541  */
542 int buffer_migrate_page(struct address_space *mapping,
543 		struct page *newpage, struct page *page, enum migrate_mode mode)
544 {
545 	struct buffer_head *bh, *head;
546 	int rc;
547 
548 	if (!page_has_buffers(page))
549 		return migrate_page(mapping, newpage, page, mode);
550 
551 	head = page_buffers(page);
552 
553 	rc = migrate_page_move_mapping(mapping, newpage, page, head, mode);
554 
555 	if (rc != MIGRATEPAGE_SUCCESS)
556 		return rc;
557 
558 	/*
559 	 * In the async case, migrate_page_move_mapping locked the buffers
560 	 * with an IRQ-safe spinlock held. In the sync case, the buffers
561 	 * need to be locked now
562 	 */
563 	if (mode != MIGRATE_ASYNC)
564 		BUG_ON(!buffer_migrate_lock_buffers(head, mode));
565 
566 	ClearPagePrivate(page);
567 	set_page_private(newpage, page_private(page));
568 	set_page_private(page, 0);
569 	put_page(page);
570 	get_page(newpage);
571 
572 	bh = head;
573 	do {
574 		set_bh_page(bh, newpage, bh_offset(bh));
575 		bh = bh->b_this_page;
576 
577 	} while (bh != head);
578 
579 	SetPagePrivate(newpage);
580 
581 	migrate_page_copy(newpage, page);
582 
583 	bh = head;
584 	do {
585 		unlock_buffer(bh);
586  		put_bh(bh);
587 		bh = bh->b_this_page;
588 
589 	} while (bh != head);
590 
591 	return MIGRATEPAGE_SUCCESS;
592 }
593 EXPORT_SYMBOL(buffer_migrate_page);
594 #endif
595 
596 /*
597  * Writeback a page to clean the dirty state
598  */
599 static int writeout(struct address_space *mapping, struct page *page)
600 {
601 	struct writeback_control wbc = {
602 		.sync_mode = WB_SYNC_NONE,
603 		.nr_to_write = 1,
604 		.range_start = 0,
605 		.range_end = LLONG_MAX,
606 		.for_reclaim = 1
607 	};
608 	int rc;
609 
610 	if (!mapping->a_ops->writepage)
611 		/* No write method for the address space */
612 		return -EINVAL;
613 
614 	if (!clear_page_dirty_for_io(page))
615 		/* Someone else already triggered a write */
616 		return -EAGAIN;
617 
618 	/*
619 	 * A dirty page may imply that the underlying filesystem has
620 	 * the page on some queue. So the page must be clean for
621 	 * migration. Writeout may mean we loose the lock and the
622 	 * page state is no longer what we checked for earlier.
623 	 * At this point we know that the migration attempt cannot
624 	 * be successful.
625 	 */
626 	remove_migration_ptes(page, page);
627 
628 	rc = mapping->a_ops->writepage(page, &wbc);
629 
630 	if (rc != AOP_WRITEPAGE_ACTIVATE)
631 		/* unlocked. Relock */
632 		lock_page(page);
633 
634 	return (rc < 0) ? -EIO : -EAGAIN;
635 }
636 
637 /*
638  * Default handling if a filesystem does not provide a migration function.
639  */
640 static int fallback_migrate_page(struct address_space *mapping,
641 	struct page *newpage, struct page *page, enum migrate_mode mode)
642 {
643 	if (PageDirty(page)) {
644 		/* Only writeback pages in full synchronous migration */
645 		if (mode != MIGRATE_SYNC)
646 			return -EBUSY;
647 		return writeout(mapping, page);
648 	}
649 
650 	/*
651 	 * Buffers may be managed in a filesystem specific way.
652 	 * We must have no buffers or drop them.
653 	 */
654 	if (page_has_private(page) &&
655 	    !try_to_release_page(page, GFP_KERNEL))
656 		return -EAGAIN;
657 
658 	return migrate_page(mapping, newpage, page, mode);
659 }
660 
661 /*
662  * Move a page to a newly allocated page
663  * The page is locked and all ptes have been successfully removed.
664  *
665  * The new page will have replaced the old page if this function
666  * is successful.
667  *
668  * Return value:
669  *   < 0 - error code
670  *  MIGRATEPAGE_SUCCESS - success
671  */
672 static int move_to_new_page(struct page *newpage, struct page *page,
673 				int remap_swapcache, enum migrate_mode mode)
674 {
675 	struct address_space *mapping;
676 	int rc;
677 
678 	/*
679 	 * Block others from accessing the page when we get around to
680 	 * establishing additional references. We are the only one
681 	 * holding a reference to the new page at this point.
682 	 */
683 	if (!trylock_page(newpage))
684 		BUG();
685 
686 	/* Prepare mapping for the new page.*/
687 	newpage->index = page->index;
688 	newpage->mapping = page->mapping;
689 	if (PageSwapBacked(page))
690 		SetPageSwapBacked(newpage);
691 
692 	mapping = page_mapping(page);
693 	if (!mapping)
694 		rc = migrate_page(mapping, newpage, page, mode);
695 	else if (mapping->a_ops->migratepage)
696 		/*
697 		 * Most pages have a mapping and most filesystems provide a
698 		 * migratepage callback. Anonymous pages are part of swap
699 		 * space which also has its own migratepage callback. This
700 		 * is the most common path for page migration.
701 		 */
702 		rc = mapping->a_ops->migratepage(mapping,
703 						newpage, page, mode);
704 	else
705 		rc = fallback_migrate_page(mapping, newpage, page, mode);
706 
707 	if (rc != MIGRATEPAGE_SUCCESS) {
708 		newpage->mapping = NULL;
709 	} else {
710 		if (remap_swapcache)
711 			remove_migration_ptes(page, newpage);
712 		page->mapping = NULL;
713 	}
714 
715 	unlock_page(newpage);
716 
717 	return rc;
718 }
719 
720 static int __unmap_and_move(struct page *page, struct page *newpage,
721 				int force, enum migrate_mode mode)
722 {
723 	int rc = -EAGAIN;
724 	int remap_swapcache = 1;
725 	struct mem_cgroup *mem;
726 	struct anon_vma *anon_vma = NULL;
727 
728 	if (!trylock_page(page)) {
729 		if (!force || mode == MIGRATE_ASYNC)
730 			goto out;
731 
732 		/*
733 		 * It's not safe for direct compaction to call lock_page.
734 		 * For example, during page readahead pages are added locked
735 		 * to the LRU. Later, when the IO completes the pages are
736 		 * marked uptodate and unlocked. However, the queueing
737 		 * could be merging multiple pages for one bio (e.g.
738 		 * mpage_readpages). If an allocation happens for the
739 		 * second or third page, the process can end up locking
740 		 * the same page twice and deadlocking. Rather than
741 		 * trying to be clever about what pages can be locked,
742 		 * avoid the use of lock_page for direct compaction
743 		 * altogether.
744 		 */
745 		if (current->flags & PF_MEMALLOC)
746 			goto out;
747 
748 		lock_page(page);
749 	}
750 
751 	/* charge against new page */
752 	mem_cgroup_prepare_migration(page, newpage, &mem);
753 
754 	if (PageWriteback(page)) {
755 		/*
756 		 * Only in the case of a full synchronous migration is it
757 		 * necessary to wait for PageWriteback. In the async case,
758 		 * the retry loop is too short and in the sync-light case,
759 		 * the overhead of stalling is too much
760 		 */
761 		if (mode != MIGRATE_SYNC) {
762 			rc = -EBUSY;
763 			goto uncharge;
764 		}
765 		if (!force)
766 			goto uncharge;
767 		wait_on_page_writeback(page);
768 	}
769 	/*
770 	 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
771 	 * we cannot notice that anon_vma is freed while we migrates a page.
772 	 * This get_anon_vma() delays freeing anon_vma pointer until the end
773 	 * of migration. File cache pages are no problem because of page_lock()
774 	 * File Caches may use write_page() or lock_page() in migration, then,
775 	 * just care Anon page here.
776 	 */
777 	if (PageAnon(page) && !PageKsm(page)) {
778 		/*
779 		 * Only page_lock_anon_vma_read() understands the subtleties of
780 		 * getting a hold on an anon_vma from outside one of its mms.
781 		 */
782 		anon_vma = page_get_anon_vma(page);
783 		if (anon_vma) {
784 			/*
785 			 * Anon page
786 			 */
787 		} else if (PageSwapCache(page)) {
788 			/*
789 			 * We cannot be sure that the anon_vma of an unmapped
790 			 * swapcache page is safe to use because we don't
791 			 * know in advance if the VMA that this page belonged
792 			 * to still exists. If the VMA and others sharing the
793 			 * data have been freed, then the anon_vma could
794 			 * already be invalid.
795 			 *
796 			 * To avoid this possibility, swapcache pages get
797 			 * migrated but are not remapped when migration
798 			 * completes
799 			 */
800 			remap_swapcache = 0;
801 		} else {
802 			goto uncharge;
803 		}
804 	}
805 
806 	if (unlikely(balloon_page_movable(page))) {
807 		/*
808 		 * A ballooned page does not need any special attention from
809 		 * physical to virtual reverse mapping procedures.
810 		 * Skip any attempt to unmap PTEs or to remap swap cache,
811 		 * in order to avoid burning cycles at rmap level, and perform
812 		 * the page migration right away (proteced by page lock).
813 		 */
814 		rc = balloon_page_migrate(newpage, page, mode);
815 		goto uncharge;
816 	}
817 
818 	/*
819 	 * Corner case handling:
820 	 * 1. When a new swap-cache page is read into, it is added to the LRU
821 	 * and treated as swapcache but it has no rmap yet.
822 	 * Calling try_to_unmap() against a page->mapping==NULL page will
823 	 * trigger a BUG.  So handle it here.
824 	 * 2. An orphaned page (see truncate_complete_page) might have
825 	 * fs-private metadata. The page can be picked up due to memory
826 	 * offlining.  Everywhere else except page reclaim, the page is
827 	 * invisible to the vm, so the page can not be migrated.  So try to
828 	 * free the metadata, so the page can be freed.
829 	 */
830 	if (!page->mapping) {
831 		VM_BUG_ON(PageAnon(page));
832 		if (page_has_private(page)) {
833 			try_to_free_buffers(page);
834 			goto uncharge;
835 		}
836 		goto skip_unmap;
837 	}
838 
839 	/* Establish migration ptes or remove ptes */
840 	try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
841 
842 skip_unmap:
843 	if (!page_mapped(page))
844 		rc = move_to_new_page(newpage, page, remap_swapcache, mode);
845 
846 	if (rc && remap_swapcache)
847 		remove_migration_ptes(page, page);
848 
849 	/* Drop an anon_vma reference if we took one */
850 	if (anon_vma)
851 		put_anon_vma(anon_vma);
852 
853 uncharge:
854 	mem_cgroup_end_migration(mem, page, newpage,
855 				 (rc == MIGRATEPAGE_SUCCESS ||
856 				  rc == MIGRATEPAGE_BALLOON_SUCCESS));
857 	unlock_page(page);
858 out:
859 	return rc;
860 }
861 
862 /*
863  * Obtain the lock on page, remove all ptes and migrate the page
864  * to the newly allocated page in newpage.
865  */
866 static int unmap_and_move(new_page_t get_new_page, unsigned long private,
867 			struct page *page, int force, enum migrate_mode mode)
868 {
869 	int rc = 0;
870 	int *result = NULL;
871 	struct page *newpage = get_new_page(page, private, &result);
872 
873 	if (!newpage)
874 		return -ENOMEM;
875 
876 	if (page_count(page) == 1) {
877 		/* page was freed from under us. So we are done. */
878 		goto out;
879 	}
880 
881 	if (unlikely(PageTransHuge(page)))
882 		if (unlikely(split_huge_page(page)))
883 			goto out;
884 
885 	rc = __unmap_and_move(page, newpage, force, mode);
886 
887 	if (unlikely(rc == MIGRATEPAGE_BALLOON_SUCCESS)) {
888 		/*
889 		 * A ballooned page has been migrated already.
890 		 * Now, it's the time to wrap-up counters,
891 		 * handle the page back to Buddy and return.
892 		 */
893 		dec_zone_page_state(page, NR_ISOLATED_ANON +
894 				    page_is_file_cache(page));
895 		balloon_page_free(page);
896 		return MIGRATEPAGE_SUCCESS;
897 	}
898 out:
899 	if (rc != -EAGAIN) {
900 		/*
901 		 * A page that has been migrated has all references
902 		 * removed and will be freed. A page that has not been
903 		 * migrated will have kepts its references and be
904 		 * restored.
905 		 */
906 		list_del(&page->lru);
907 		dec_zone_page_state(page, NR_ISOLATED_ANON +
908 				page_is_file_cache(page));
909 		putback_lru_page(page);
910 	}
911 	/*
912 	 * Move the new page to the LRU. If migration was not successful
913 	 * then this will free the page.
914 	 */
915 	putback_lru_page(newpage);
916 	if (result) {
917 		if (rc)
918 			*result = rc;
919 		else
920 			*result = page_to_nid(newpage);
921 	}
922 	return rc;
923 }
924 
925 /*
926  * Counterpart of unmap_and_move_page() for hugepage migration.
927  *
928  * This function doesn't wait the completion of hugepage I/O
929  * because there is no race between I/O and migration for hugepage.
930  * Note that currently hugepage I/O occurs only in direct I/O
931  * where no lock is held and PG_writeback is irrelevant,
932  * and writeback status of all subpages are counted in the reference
933  * count of the head page (i.e. if all subpages of a 2MB hugepage are
934  * under direct I/O, the reference of the head page is 512 and a bit more.)
935  * This means that when we try to migrate hugepage whose subpages are
936  * doing direct I/O, some references remain after try_to_unmap() and
937  * hugepage migration fails without data corruption.
938  *
939  * There is also no race when direct I/O is issued on the page under migration,
940  * because then pte is replaced with migration swap entry and direct I/O code
941  * will wait in the page fault for migration to complete.
942  */
943 static int unmap_and_move_huge_page(new_page_t get_new_page,
944 				unsigned long private, struct page *hpage,
945 				int force, enum migrate_mode mode)
946 {
947 	int rc = 0;
948 	int *result = NULL;
949 	struct page *new_hpage = get_new_page(hpage, private, &result);
950 	struct anon_vma *anon_vma = NULL;
951 
952 	/*
953 	 * Movability of hugepages depends on architectures and hugepage size.
954 	 * This check is necessary because some callers of hugepage migration
955 	 * like soft offline and memory hotremove don't walk through page
956 	 * tables or check whether the hugepage is pmd-based or not before
957 	 * kicking migration.
958 	 */
959 	if (!hugepage_migration_support(page_hstate(hpage)))
960 		return -ENOSYS;
961 
962 	if (!new_hpage)
963 		return -ENOMEM;
964 
965 	rc = -EAGAIN;
966 
967 	if (!trylock_page(hpage)) {
968 		if (!force || mode != MIGRATE_SYNC)
969 			goto out;
970 		lock_page(hpage);
971 	}
972 
973 	if (PageAnon(hpage))
974 		anon_vma = page_get_anon_vma(hpage);
975 
976 	try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
977 
978 	if (!page_mapped(hpage))
979 		rc = move_to_new_page(new_hpage, hpage, 1, mode);
980 
981 	if (rc)
982 		remove_migration_ptes(hpage, hpage);
983 
984 	if (anon_vma)
985 		put_anon_vma(anon_vma);
986 
987 	if (!rc)
988 		hugetlb_cgroup_migrate(hpage, new_hpage);
989 
990 	unlock_page(hpage);
991 out:
992 	if (rc != -EAGAIN)
993 		putback_active_hugepage(hpage);
994 	put_page(new_hpage);
995 	if (result) {
996 		if (rc)
997 			*result = rc;
998 		else
999 			*result = page_to_nid(new_hpage);
1000 	}
1001 	return rc;
1002 }
1003 
1004 /*
1005  * migrate_pages - migrate the pages specified in a list, to the free pages
1006  *		   supplied as the target for the page migration
1007  *
1008  * @from:		The list of pages to be migrated.
1009  * @get_new_page:	The function used to allocate free pages to be used
1010  *			as the target of the page migration.
1011  * @private:		Private data to be passed on to get_new_page()
1012  * @mode:		The migration mode that specifies the constraints for
1013  *			page migration, if any.
1014  * @reason:		The reason for page migration.
1015  *
1016  * The function returns after 10 attempts or if no pages are movable any more
1017  * because the list has become empty or no retryable pages exist any more.
1018  * The caller should call putback_lru_pages() to return pages to the LRU
1019  * or free list only if ret != 0.
1020  *
1021  * Returns the number of pages that were not migrated, or an error code.
1022  */
1023 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1024 		unsigned long private, enum migrate_mode mode, int reason)
1025 {
1026 	int retry = 1;
1027 	int nr_failed = 0;
1028 	int nr_succeeded = 0;
1029 	int pass = 0;
1030 	struct page *page;
1031 	struct page *page2;
1032 	int swapwrite = current->flags & PF_SWAPWRITE;
1033 	int rc;
1034 
1035 	if (!swapwrite)
1036 		current->flags |= PF_SWAPWRITE;
1037 
1038 	for(pass = 0; pass < 10 && retry; pass++) {
1039 		retry = 0;
1040 
1041 		list_for_each_entry_safe(page, page2, from, lru) {
1042 			cond_resched();
1043 
1044 			if (PageHuge(page))
1045 				rc = unmap_and_move_huge_page(get_new_page,
1046 						private, page, pass > 2, mode);
1047 			else
1048 				rc = unmap_and_move(get_new_page, private,
1049 						page, pass > 2, mode);
1050 
1051 			switch(rc) {
1052 			case -ENOMEM:
1053 				goto out;
1054 			case -EAGAIN:
1055 				retry++;
1056 				break;
1057 			case MIGRATEPAGE_SUCCESS:
1058 				nr_succeeded++;
1059 				break;
1060 			default:
1061 				/* Permanent failure */
1062 				nr_failed++;
1063 				break;
1064 			}
1065 		}
1066 	}
1067 	rc = nr_failed + retry;
1068 out:
1069 	if (nr_succeeded)
1070 		count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1071 	if (nr_failed)
1072 		count_vm_events(PGMIGRATE_FAIL, nr_failed);
1073 	trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
1074 
1075 	if (!swapwrite)
1076 		current->flags &= ~PF_SWAPWRITE;
1077 
1078 	return rc;
1079 }
1080 
1081 #ifdef CONFIG_NUMA
1082 /*
1083  * Move a list of individual pages
1084  */
1085 struct page_to_node {
1086 	unsigned long addr;
1087 	struct page *page;
1088 	int node;
1089 	int status;
1090 };
1091 
1092 static struct page *new_page_node(struct page *p, unsigned long private,
1093 		int **result)
1094 {
1095 	struct page_to_node *pm = (struct page_to_node *)private;
1096 
1097 	while (pm->node != MAX_NUMNODES && pm->page != p)
1098 		pm++;
1099 
1100 	if (pm->node == MAX_NUMNODES)
1101 		return NULL;
1102 
1103 	*result = &pm->status;
1104 
1105 	if (PageHuge(p))
1106 		return alloc_huge_page_node(page_hstate(compound_head(p)),
1107 					pm->node);
1108 	else
1109 		return alloc_pages_exact_node(pm->node,
1110 				GFP_HIGHUSER_MOVABLE | GFP_THISNODE, 0);
1111 }
1112 
1113 /*
1114  * Move a set of pages as indicated in the pm array. The addr
1115  * field must be set to the virtual address of the page to be moved
1116  * and the node number must contain a valid target node.
1117  * The pm array ends with node = MAX_NUMNODES.
1118  */
1119 static int do_move_page_to_node_array(struct mm_struct *mm,
1120 				      struct page_to_node *pm,
1121 				      int migrate_all)
1122 {
1123 	int err;
1124 	struct page_to_node *pp;
1125 	LIST_HEAD(pagelist);
1126 
1127 	down_read(&mm->mmap_sem);
1128 
1129 	/*
1130 	 * Build a list of pages to migrate
1131 	 */
1132 	for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
1133 		struct vm_area_struct *vma;
1134 		struct page *page;
1135 
1136 		err = -EFAULT;
1137 		vma = find_vma(mm, pp->addr);
1138 		if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
1139 			goto set_status;
1140 
1141 		page = follow_page(vma, pp->addr, FOLL_GET|FOLL_SPLIT);
1142 
1143 		err = PTR_ERR(page);
1144 		if (IS_ERR(page))
1145 			goto set_status;
1146 
1147 		err = -ENOENT;
1148 		if (!page)
1149 			goto set_status;
1150 
1151 		/* Use PageReserved to check for zero page */
1152 		if (PageReserved(page))
1153 			goto put_and_set;
1154 
1155 		pp->page = page;
1156 		err = page_to_nid(page);
1157 
1158 		if (err == pp->node)
1159 			/*
1160 			 * Node already in the right place
1161 			 */
1162 			goto put_and_set;
1163 
1164 		err = -EACCES;
1165 		if (page_mapcount(page) > 1 &&
1166 				!migrate_all)
1167 			goto put_and_set;
1168 
1169 		if (PageHuge(page)) {
1170 			isolate_huge_page(page, &pagelist);
1171 			goto put_and_set;
1172 		}
1173 
1174 		err = isolate_lru_page(page);
1175 		if (!err) {
1176 			list_add_tail(&page->lru, &pagelist);
1177 			inc_zone_page_state(page, NR_ISOLATED_ANON +
1178 					    page_is_file_cache(page));
1179 		}
1180 put_and_set:
1181 		/*
1182 		 * Either remove the duplicate refcount from
1183 		 * isolate_lru_page() or drop the page ref if it was
1184 		 * not isolated.
1185 		 */
1186 		put_page(page);
1187 set_status:
1188 		pp->status = err;
1189 	}
1190 
1191 	err = 0;
1192 	if (!list_empty(&pagelist)) {
1193 		err = migrate_pages(&pagelist, new_page_node,
1194 				(unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL);
1195 		if (err)
1196 			putback_movable_pages(&pagelist);
1197 	}
1198 
1199 	up_read(&mm->mmap_sem);
1200 	return err;
1201 }
1202 
1203 /*
1204  * Migrate an array of page address onto an array of nodes and fill
1205  * the corresponding array of status.
1206  */
1207 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1208 			 unsigned long nr_pages,
1209 			 const void __user * __user *pages,
1210 			 const int __user *nodes,
1211 			 int __user *status, int flags)
1212 {
1213 	struct page_to_node *pm;
1214 	unsigned long chunk_nr_pages;
1215 	unsigned long chunk_start;
1216 	int err;
1217 
1218 	err = -ENOMEM;
1219 	pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
1220 	if (!pm)
1221 		goto out;
1222 
1223 	migrate_prep();
1224 
1225 	/*
1226 	 * Store a chunk of page_to_node array in a page,
1227 	 * but keep the last one as a marker
1228 	 */
1229 	chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
1230 
1231 	for (chunk_start = 0;
1232 	     chunk_start < nr_pages;
1233 	     chunk_start += chunk_nr_pages) {
1234 		int j;
1235 
1236 		if (chunk_start + chunk_nr_pages > nr_pages)
1237 			chunk_nr_pages = nr_pages - chunk_start;
1238 
1239 		/* fill the chunk pm with addrs and nodes from user-space */
1240 		for (j = 0; j < chunk_nr_pages; j++) {
1241 			const void __user *p;
1242 			int node;
1243 
1244 			err = -EFAULT;
1245 			if (get_user(p, pages + j + chunk_start))
1246 				goto out_pm;
1247 			pm[j].addr = (unsigned long) p;
1248 
1249 			if (get_user(node, nodes + j + chunk_start))
1250 				goto out_pm;
1251 
1252 			err = -ENODEV;
1253 			if (node < 0 || node >= MAX_NUMNODES)
1254 				goto out_pm;
1255 
1256 			if (!node_state(node, N_MEMORY))
1257 				goto out_pm;
1258 
1259 			err = -EACCES;
1260 			if (!node_isset(node, task_nodes))
1261 				goto out_pm;
1262 
1263 			pm[j].node = node;
1264 		}
1265 
1266 		/* End marker for this chunk */
1267 		pm[chunk_nr_pages].node = MAX_NUMNODES;
1268 
1269 		/* Migrate this chunk */
1270 		err = do_move_page_to_node_array(mm, pm,
1271 						 flags & MPOL_MF_MOVE_ALL);
1272 		if (err < 0)
1273 			goto out_pm;
1274 
1275 		/* Return status information */
1276 		for (j = 0; j < chunk_nr_pages; j++)
1277 			if (put_user(pm[j].status, status + j + chunk_start)) {
1278 				err = -EFAULT;
1279 				goto out_pm;
1280 			}
1281 	}
1282 	err = 0;
1283 
1284 out_pm:
1285 	free_page((unsigned long)pm);
1286 out:
1287 	return err;
1288 }
1289 
1290 /*
1291  * Determine the nodes of an array of pages and store it in an array of status.
1292  */
1293 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1294 				const void __user **pages, int *status)
1295 {
1296 	unsigned long i;
1297 
1298 	down_read(&mm->mmap_sem);
1299 
1300 	for (i = 0; i < nr_pages; i++) {
1301 		unsigned long addr = (unsigned long)(*pages);
1302 		struct vm_area_struct *vma;
1303 		struct page *page;
1304 		int err = -EFAULT;
1305 
1306 		vma = find_vma(mm, addr);
1307 		if (!vma || addr < vma->vm_start)
1308 			goto set_status;
1309 
1310 		page = follow_page(vma, addr, 0);
1311 
1312 		err = PTR_ERR(page);
1313 		if (IS_ERR(page))
1314 			goto set_status;
1315 
1316 		err = -ENOENT;
1317 		/* Use PageReserved to check for zero page */
1318 		if (!page || PageReserved(page))
1319 			goto set_status;
1320 
1321 		err = page_to_nid(page);
1322 set_status:
1323 		*status = err;
1324 
1325 		pages++;
1326 		status++;
1327 	}
1328 
1329 	up_read(&mm->mmap_sem);
1330 }
1331 
1332 /*
1333  * Determine the nodes of a user array of pages and store it in
1334  * a user array of status.
1335  */
1336 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1337 			 const void __user * __user *pages,
1338 			 int __user *status)
1339 {
1340 #define DO_PAGES_STAT_CHUNK_NR 16
1341 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1342 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1343 
1344 	while (nr_pages) {
1345 		unsigned long chunk_nr;
1346 
1347 		chunk_nr = nr_pages;
1348 		if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1349 			chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1350 
1351 		if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1352 			break;
1353 
1354 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1355 
1356 		if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1357 			break;
1358 
1359 		pages += chunk_nr;
1360 		status += chunk_nr;
1361 		nr_pages -= chunk_nr;
1362 	}
1363 	return nr_pages ? -EFAULT : 0;
1364 }
1365 
1366 /*
1367  * Move a list of pages in the address space of the currently executing
1368  * process.
1369  */
1370 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1371 		const void __user * __user *, pages,
1372 		const int __user *, nodes,
1373 		int __user *, status, int, flags)
1374 {
1375 	const struct cred *cred = current_cred(), *tcred;
1376 	struct task_struct *task;
1377 	struct mm_struct *mm;
1378 	int err;
1379 	nodemask_t task_nodes;
1380 
1381 	/* Check flags */
1382 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1383 		return -EINVAL;
1384 
1385 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1386 		return -EPERM;
1387 
1388 	/* Find the mm_struct */
1389 	rcu_read_lock();
1390 	task = pid ? find_task_by_vpid(pid) : current;
1391 	if (!task) {
1392 		rcu_read_unlock();
1393 		return -ESRCH;
1394 	}
1395 	get_task_struct(task);
1396 
1397 	/*
1398 	 * Check if this process has the right to modify the specified
1399 	 * process. The right exists if the process has administrative
1400 	 * capabilities, superuser privileges or the same
1401 	 * userid as the target process.
1402 	 */
1403 	tcred = __task_cred(task);
1404 	if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
1405 	    !uid_eq(cred->uid,  tcred->suid) && !uid_eq(cred->uid,  tcred->uid) &&
1406 	    !capable(CAP_SYS_NICE)) {
1407 		rcu_read_unlock();
1408 		err = -EPERM;
1409 		goto out;
1410 	}
1411 	rcu_read_unlock();
1412 
1413  	err = security_task_movememory(task);
1414  	if (err)
1415 		goto out;
1416 
1417 	task_nodes = cpuset_mems_allowed(task);
1418 	mm = get_task_mm(task);
1419 	put_task_struct(task);
1420 
1421 	if (!mm)
1422 		return -EINVAL;
1423 
1424 	if (nodes)
1425 		err = do_pages_move(mm, task_nodes, nr_pages, pages,
1426 				    nodes, status, flags);
1427 	else
1428 		err = do_pages_stat(mm, nr_pages, pages, status);
1429 
1430 	mmput(mm);
1431 	return err;
1432 
1433 out:
1434 	put_task_struct(task);
1435 	return err;
1436 }
1437 
1438 /*
1439  * Call migration functions in the vma_ops that may prepare
1440  * memory in a vm for migration. migration functions may perform
1441  * the migration for vmas that do not have an underlying page struct.
1442  */
1443 int migrate_vmas(struct mm_struct *mm, const nodemask_t *to,
1444 	const nodemask_t *from, unsigned long flags)
1445 {
1446  	struct vm_area_struct *vma;
1447  	int err = 0;
1448 
1449 	for (vma = mm->mmap; vma && !err; vma = vma->vm_next) {
1450  		if (vma->vm_ops && vma->vm_ops->migrate) {
1451  			err = vma->vm_ops->migrate(vma, to, from, flags);
1452  			if (err)
1453  				break;
1454  		}
1455  	}
1456  	return err;
1457 }
1458 
1459 #ifdef CONFIG_NUMA_BALANCING
1460 /*
1461  * Returns true if this is a safe migration target node for misplaced NUMA
1462  * pages. Currently it only checks the watermarks which crude
1463  */
1464 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1465 				   unsigned long nr_migrate_pages)
1466 {
1467 	int z;
1468 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1469 		struct zone *zone = pgdat->node_zones + z;
1470 
1471 		if (!populated_zone(zone))
1472 			continue;
1473 
1474 		if (!zone_reclaimable(zone))
1475 			continue;
1476 
1477 		/* Avoid waking kswapd by allocating pages_to_migrate pages. */
1478 		if (!zone_watermark_ok(zone, 0,
1479 				       high_wmark_pages(zone) +
1480 				       nr_migrate_pages,
1481 				       0, 0))
1482 			continue;
1483 		return true;
1484 	}
1485 	return false;
1486 }
1487 
1488 static struct page *alloc_misplaced_dst_page(struct page *page,
1489 					   unsigned long data,
1490 					   int **result)
1491 {
1492 	int nid = (int) data;
1493 	struct page *newpage;
1494 
1495 	newpage = alloc_pages_exact_node(nid,
1496 					 (GFP_HIGHUSER_MOVABLE | GFP_THISNODE |
1497 					  __GFP_NOMEMALLOC | __GFP_NORETRY |
1498 					  __GFP_NOWARN) &
1499 					 ~GFP_IOFS, 0);
1500 	if (newpage)
1501 		page_nid_xchg_last(newpage, page_nid_last(page));
1502 
1503 	return newpage;
1504 }
1505 
1506 /*
1507  * page migration rate limiting control.
1508  * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs
1509  * window of time. Default here says do not migrate more than 1280M per second.
1510  * If a node is rate-limited then PTE NUMA updates are also rate-limited. However
1511  * as it is faults that reset the window, pte updates will happen unconditionally
1512  * if there has not been a fault since @pteupdate_interval_millisecs after the
1513  * throttle window closed.
1514  */
1515 static unsigned int migrate_interval_millisecs __read_mostly = 100;
1516 static unsigned int pteupdate_interval_millisecs __read_mostly = 1000;
1517 static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT);
1518 
1519 /* Returns true if NUMA migration is currently rate limited */
1520 bool migrate_ratelimited(int node)
1521 {
1522 	pg_data_t *pgdat = NODE_DATA(node);
1523 
1524 	if (time_after(jiffies, pgdat->numabalancing_migrate_next_window +
1525 				msecs_to_jiffies(pteupdate_interval_millisecs)))
1526 		return false;
1527 
1528 	if (pgdat->numabalancing_migrate_nr_pages < ratelimit_pages)
1529 		return false;
1530 
1531 	return true;
1532 }
1533 
1534 /* Returns true if the node is migrate rate-limited after the update */
1535 bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages)
1536 {
1537 	bool rate_limited = false;
1538 
1539 	/*
1540 	 * Rate-limit the amount of data that is being migrated to a node.
1541 	 * Optimal placement is no good if the memory bus is saturated and
1542 	 * all the time is being spent migrating!
1543 	 */
1544 	spin_lock(&pgdat->numabalancing_migrate_lock);
1545 	if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) {
1546 		pgdat->numabalancing_migrate_nr_pages = 0;
1547 		pgdat->numabalancing_migrate_next_window = jiffies +
1548 			msecs_to_jiffies(migrate_interval_millisecs);
1549 	}
1550 	if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages)
1551 		rate_limited = true;
1552 	else
1553 		pgdat->numabalancing_migrate_nr_pages += nr_pages;
1554 	spin_unlock(&pgdat->numabalancing_migrate_lock);
1555 
1556 	return rate_limited;
1557 }
1558 
1559 int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
1560 {
1561 	int page_lru;
1562 
1563 	VM_BUG_ON(compound_order(page) && !PageTransHuge(page));
1564 
1565 	/* Avoid migrating to a node that is nearly full */
1566 	if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
1567 		return 0;
1568 
1569 	if (isolate_lru_page(page))
1570 		return 0;
1571 
1572 	/*
1573 	 * migrate_misplaced_transhuge_page() skips page migration's usual
1574 	 * check on page_count(), so we must do it here, now that the page
1575 	 * has been isolated: a GUP pin, or any other pin, prevents migration.
1576 	 * The expected page count is 3: 1 for page's mapcount and 1 for the
1577 	 * caller's pin and 1 for the reference taken by isolate_lru_page().
1578 	 */
1579 	if (PageTransHuge(page) && page_count(page) != 3) {
1580 		putback_lru_page(page);
1581 		return 0;
1582 	}
1583 
1584 	page_lru = page_is_file_cache(page);
1585 	mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru,
1586 				hpage_nr_pages(page));
1587 
1588 	/*
1589 	 * Isolating the page has taken another reference, so the
1590 	 * caller's reference can be safely dropped without the page
1591 	 * disappearing underneath us during migration.
1592 	 */
1593 	put_page(page);
1594 	return 1;
1595 }
1596 
1597 /*
1598  * Attempt to migrate a misplaced page to the specified destination
1599  * node. Caller is expected to have an elevated reference count on
1600  * the page that will be dropped by this function before returning.
1601  */
1602 int migrate_misplaced_page(struct page *page, int node)
1603 {
1604 	pg_data_t *pgdat = NODE_DATA(node);
1605 	int isolated;
1606 	int nr_remaining;
1607 	LIST_HEAD(migratepages);
1608 
1609 	/*
1610 	 * Don't migrate pages that are mapped in multiple processes.
1611 	 * TODO: Handle false sharing detection instead of this hammer
1612 	 */
1613 	if (page_mapcount(page) != 1)
1614 		goto out;
1615 
1616 	/*
1617 	 * Rate-limit the amount of data that is being migrated to a node.
1618 	 * Optimal placement is no good if the memory bus is saturated and
1619 	 * all the time is being spent migrating!
1620 	 */
1621 	if (numamigrate_update_ratelimit(pgdat, 1))
1622 		goto out;
1623 
1624 	isolated = numamigrate_isolate_page(pgdat, page);
1625 	if (!isolated)
1626 		goto out;
1627 
1628 	list_add(&page->lru, &migratepages);
1629 	nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
1630 				     node, MIGRATE_ASYNC, MR_NUMA_MISPLACED);
1631 	if (nr_remaining) {
1632 		putback_lru_pages(&migratepages);
1633 		isolated = 0;
1634 	} else
1635 		count_vm_numa_event(NUMA_PAGE_MIGRATE);
1636 	BUG_ON(!list_empty(&migratepages));
1637 	return isolated;
1638 
1639 out:
1640 	put_page(page);
1641 	return 0;
1642 }
1643 #endif /* CONFIG_NUMA_BALANCING */
1644 
1645 #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1646 /*
1647  * Migrates a THP to a given target node. page must be locked and is unlocked
1648  * before returning.
1649  */
1650 int migrate_misplaced_transhuge_page(struct mm_struct *mm,
1651 				struct vm_area_struct *vma,
1652 				pmd_t *pmd, pmd_t entry,
1653 				unsigned long address,
1654 				struct page *page, int node)
1655 {
1656 	unsigned long haddr = address & HPAGE_PMD_MASK;
1657 	pg_data_t *pgdat = NODE_DATA(node);
1658 	int isolated = 0;
1659 	struct page *new_page = NULL;
1660 	struct mem_cgroup *memcg = NULL;
1661 	int page_lru = page_is_file_cache(page);
1662 
1663 	/*
1664 	 * Don't migrate pages that are mapped in multiple processes.
1665 	 * TODO: Handle false sharing detection instead of this hammer
1666 	 */
1667 	if (page_mapcount(page) != 1)
1668 		goto out_dropref;
1669 
1670 	/*
1671 	 * Rate-limit the amount of data that is being migrated to a node.
1672 	 * Optimal placement is no good if the memory bus is saturated and
1673 	 * all the time is being spent migrating!
1674 	 */
1675 	if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))
1676 		goto out_dropref;
1677 
1678 	new_page = alloc_pages_node(node,
1679 		(GFP_TRANSHUGE | GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER);
1680 	if (!new_page)
1681 		goto out_fail;
1682 
1683 	page_nid_xchg_last(new_page, page_nid_last(page));
1684 
1685 	isolated = numamigrate_isolate_page(pgdat, page);
1686 	if (!isolated) {
1687 		put_page(new_page);
1688 		goto out_fail;
1689 	}
1690 
1691 	/* Prepare a page as a migration target */
1692 	__set_page_locked(new_page);
1693 	SetPageSwapBacked(new_page);
1694 
1695 	/* anon mapping, we can simply copy page->mapping to the new page: */
1696 	new_page->mapping = page->mapping;
1697 	new_page->index = page->index;
1698 	migrate_page_copy(new_page, page);
1699 	WARN_ON(PageLRU(new_page));
1700 
1701 	/* Recheck the target PMD */
1702 	spin_lock(&mm->page_table_lock);
1703 	if (unlikely(!pmd_same(*pmd, entry))) {
1704 		spin_unlock(&mm->page_table_lock);
1705 
1706 		/* Reverse changes made by migrate_page_copy() */
1707 		if (TestClearPageActive(new_page))
1708 			SetPageActive(page);
1709 		if (TestClearPageUnevictable(new_page))
1710 			SetPageUnevictable(page);
1711 		mlock_migrate_page(page, new_page);
1712 
1713 		unlock_page(new_page);
1714 		put_page(new_page);		/* Free it */
1715 
1716 		unlock_page(page);
1717 		putback_lru_page(page);
1718 
1719 		count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
1720 		isolated = 0;
1721 		goto out;
1722 	}
1723 
1724 	/*
1725 	 * Traditional migration needs to prepare the memcg charge
1726 	 * transaction early to prevent the old page from being
1727 	 * uncharged when installing migration entries.  Here we can
1728 	 * save the potential rollback and start the charge transfer
1729 	 * only when migration is already known to end successfully.
1730 	 */
1731 	mem_cgroup_prepare_migration(page, new_page, &memcg);
1732 
1733 	entry = mk_pmd(new_page, vma->vm_page_prot);
1734 	entry = pmd_mknonnuma(entry);
1735 	entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1736 	entry = pmd_mkhuge(entry);
1737 
1738 	page_add_new_anon_rmap(new_page, vma, haddr);
1739 
1740 	set_pmd_at(mm, haddr, pmd, entry);
1741 	update_mmu_cache_pmd(vma, address, &entry);
1742 	page_remove_rmap(page);
1743 	/*
1744 	 * Finish the charge transaction under the page table lock to
1745 	 * prevent split_huge_page() from dividing up the charge
1746 	 * before it's fully transferred to the new page.
1747 	 */
1748 	mem_cgroup_end_migration(memcg, page, new_page, true);
1749 	spin_unlock(&mm->page_table_lock);
1750 
1751 	unlock_page(new_page);
1752 	unlock_page(page);
1753 	put_page(page);			/* Drop the rmap reference */
1754 	put_page(page);			/* Drop the LRU isolation reference */
1755 
1756 	count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
1757 	count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
1758 
1759 out:
1760 	mod_zone_page_state(page_zone(page),
1761 			NR_ISOLATED_ANON + page_lru,
1762 			-HPAGE_PMD_NR);
1763 	return isolated;
1764 
1765 out_fail:
1766 	count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
1767 out_dropref:
1768 	unlock_page(page);
1769 	put_page(page);
1770 	return 0;
1771 }
1772 #endif /* CONFIG_NUMA_BALANCING */
1773 
1774 #endif /* CONFIG_NUMA */
1775