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