]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - mm/migrate.c
mm/migrate: support un-addressable ZONE_DEVICE page in migration
[mirror_ubuntu-hirsute-kernel.git] / mm / migrate.c
1 /*
2 * Memory Migration functionality - linux/mm/migrate.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/backing-dev.h>
34 #include <linux/compaction.h>
35 #include <linux/syscalls.h>
36 #include <linux/hugetlb.h>
37 #include <linux/hugetlb_cgroup.h>
38 #include <linux/gfp.h>
39 #include <linux/memremap.h>
40 #include <linux/balloon_compaction.h>
41 #include <linux/mmu_notifier.h>
42 #include <linux/page_idle.h>
43 #include <linux/page_owner.h>
44 #include <linux/sched/mm.h>
45 #include <linux/ptrace.h>
46
47 #include <asm/tlbflush.h>
48
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/migrate.h>
51
52 #include "internal.h"
53
54 /*
55 * migrate_prep() needs to be called before we start compiling a list of pages
56 * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
57 * undesirable, use migrate_prep_local()
58 */
59 int migrate_prep(void)
60 {
61 /*
62 * Clear the LRU lists so pages can be isolated.
63 * Note that pages may be moved off the LRU after we have
64 * drained them. Those pages will fail to migrate like other
65 * pages that may be busy.
66 */
67 lru_add_drain_all();
68
69 return 0;
70 }
71
72 /* Do the necessary work of migrate_prep but not if it involves other CPUs */
73 int migrate_prep_local(void)
74 {
75 lru_add_drain();
76
77 return 0;
78 }
79
80 int isolate_movable_page(struct page *page, isolate_mode_t mode)
81 {
82 struct address_space *mapping;
83
84 /*
85 * Avoid burning cycles with pages that are yet under __free_pages(),
86 * or just got freed under us.
87 *
88 * In case we 'win' a race for a movable page being freed under us and
89 * raise its refcount preventing __free_pages() from doing its job
90 * the put_page() at the end of this block will take care of
91 * release this page, thus avoiding a nasty leakage.
92 */
93 if (unlikely(!get_page_unless_zero(page)))
94 goto out;
95
96 /*
97 * Check PageMovable before holding a PG_lock because page's owner
98 * assumes anybody doesn't touch PG_lock of newly allocated page
99 * so unconditionally grapping the lock ruins page's owner side.
100 */
101 if (unlikely(!__PageMovable(page)))
102 goto out_putpage;
103 /*
104 * As movable pages are not isolated from LRU lists, concurrent
105 * compaction threads can race against page migration functions
106 * as well as race against the releasing a page.
107 *
108 * In order to avoid having an already isolated movable page
109 * being (wrongly) re-isolated while it is under migration,
110 * or to avoid attempting to isolate pages being released,
111 * lets be sure we have the page lock
112 * before proceeding with the movable page isolation steps.
113 */
114 if (unlikely(!trylock_page(page)))
115 goto out_putpage;
116
117 if (!PageMovable(page) || PageIsolated(page))
118 goto out_no_isolated;
119
120 mapping = page_mapping(page);
121 VM_BUG_ON_PAGE(!mapping, page);
122
123 if (!mapping->a_ops->isolate_page(page, mode))
124 goto out_no_isolated;
125
126 /* Driver shouldn't use PG_isolated bit of page->flags */
127 WARN_ON_ONCE(PageIsolated(page));
128 __SetPageIsolated(page);
129 unlock_page(page);
130
131 return 0;
132
133 out_no_isolated:
134 unlock_page(page);
135 out_putpage:
136 put_page(page);
137 out:
138 return -EBUSY;
139 }
140
141 /* It should be called on page which is PG_movable */
142 void putback_movable_page(struct page *page)
143 {
144 struct address_space *mapping;
145
146 VM_BUG_ON_PAGE(!PageLocked(page), page);
147 VM_BUG_ON_PAGE(!PageMovable(page), page);
148 VM_BUG_ON_PAGE(!PageIsolated(page), page);
149
150 mapping = page_mapping(page);
151 mapping->a_ops->putback_page(page);
152 __ClearPageIsolated(page);
153 }
154
155 /*
156 * Put previously isolated pages back onto the appropriate lists
157 * from where they were once taken off for compaction/migration.
158 *
159 * This function shall be used whenever the isolated pageset has been
160 * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
161 * and isolate_huge_page().
162 */
163 void putback_movable_pages(struct list_head *l)
164 {
165 struct page *page;
166 struct page *page2;
167
168 list_for_each_entry_safe(page, page2, l, lru) {
169 if (unlikely(PageHuge(page))) {
170 putback_active_hugepage(page);
171 continue;
172 }
173 list_del(&page->lru);
174 /*
175 * We isolated non-lru movable page so here we can use
176 * __PageMovable because LRU page's mapping cannot have
177 * PAGE_MAPPING_MOVABLE.
178 */
179 if (unlikely(__PageMovable(page))) {
180 VM_BUG_ON_PAGE(!PageIsolated(page), page);
181 lock_page(page);
182 if (PageMovable(page))
183 putback_movable_page(page);
184 else
185 __ClearPageIsolated(page);
186 unlock_page(page);
187 put_page(page);
188 } else {
189 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
190 page_is_file_cache(page), -hpage_nr_pages(page));
191 putback_lru_page(page);
192 }
193 }
194 }
195
196 /*
197 * Restore a potential migration pte to a working pte entry
198 */
199 static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
200 unsigned long addr, void *old)
201 {
202 struct page_vma_mapped_walk pvmw = {
203 .page = old,
204 .vma = vma,
205 .address = addr,
206 .flags = PVMW_SYNC | PVMW_MIGRATION,
207 };
208 struct page *new;
209 pte_t pte;
210 swp_entry_t entry;
211
212 VM_BUG_ON_PAGE(PageTail(page), page);
213 while (page_vma_mapped_walk(&pvmw)) {
214 if (PageKsm(page))
215 new = page;
216 else
217 new = page - pvmw.page->index +
218 linear_page_index(vma, pvmw.address);
219
220 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
221 /* PMD-mapped THP migration entry */
222 if (!pvmw.pte) {
223 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
224 remove_migration_pmd(&pvmw, new);
225 continue;
226 }
227 #endif
228
229 get_page(new);
230 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
231 if (pte_swp_soft_dirty(*pvmw.pte))
232 pte = pte_mksoft_dirty(pte);
233
234 /*
235 * Recheck VMA as permissions can change since migration started
236 */
237 entry = pte_to_swp_entry(*pvmw.pte);
238 if (is_write_migration_entry(entry))
239 pte = maybe_mkwrite(pte, vma);
240
241 if (unlikely(is_zone_device_page(new)) &&
242 is_device_private_page(new)) {
243 entry = make_device_private_entry(new, pte_write(pte));
244 pte = swp_entry_to_pte(entry);
245 } else
246 flush_dcache_page(new);
247
248 #ifdef CONFIG_HUGETLB_PAGE
249 if (PageHuge(new)) {
250 pte = pte_mkhuge(pte);
251 pte = arch_make_huge_pte(pte, vma, new, 0);
252 set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
253 if (PageAnon(new))
254 hugepage_add_anon_rmap(new, vma, pvmw.address);
255 else
256 page_dup_rmap(new, true);
257 } else
258 #endif
259 {
260 set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
261
262 if (PageAnon(new))
263 page_add_anon_rmap(new, vma, pvmw.address, false);
264 else
265 page_add_file_rmap(new, false);
266 }
267 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
268 mlock_vma_page(new);
269
270 /* No need to invalidate - it was non-present before */
271 update_mmu_cache(vma, pvmw.address, pvmw.pte);
272 }
273
274 return true;
275 }
276
277 /*
278 * Get rid of all migration entries and replace them by
279 * references to the indicated page.
280 */
281 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
282 {
283 struct rmap_walk_control rwc = {
284 .rmap_one = remove_migration_pte,
285 .arg = old,
286 };
287
288 if (locked)
289 rmap_walk_locked(new, &rwc);
290 else
291 rmap_walk(new, &rwc);
292 }
293
294 /*
295 * Something used the pte of a page under migration. We need to
296 * get to the page and wait until migration is finished.
297 * When we return from this function the fault will be retried.
298 */
299 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
300 spinlock_t *ptl)
301 {
302 pte_t pte;
303 swp_entry_t entry;
304 struct page *page;
305
306 spin_lock(ptl);
307 pte = *ptep;
308 if (!is_swap_pte(pte))
309 goto out;
310
311 entry = pte_to_swp_entry(pte);
312 if (!is_migration_entry(entry))
313 goto out;
314
315 page = migration_entry_to_page(entry);
316
317 /*
318 * Once radix-tree replacement of page migration started, page_count
319 * *must* be zero. And, we don't want to call wait_on_page_locked()
320 * against a page without get_page().
321 * So, we use get_page_unless_zero(), here. Even failed, page fault
322 * will occur again.
323 */
324 if (!get_page_unless_zero(page))
325 goto out;
326 pte_unmap_unlock(ptep, ptl);
327 wait_on_page_locked(page);
328 put_page(page);
329 return;
330 out:
331 pte_unmap_unlock(ptep, ptl);
332 }
333
334 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
335 unsigned long address)
336 {
337 spinlock_t *ptl = pte_lockptr(mm, pmd);
338 pte_t *ptep = pte_offset_map(pmd, address);
339 __migration_entry_wait(mm, ptep, ptl);
340 }
341
342 void migration_entry_wait_huge(struct vm_area_struct *vma,
343 struct mm_struct *mm, pte_t *pte)
344 {
345 spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
346 __migration_entry_wait(mm, pte, ptl);
347 }
348
349 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
350 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
351 {
352 spinlock_t *ptl;
353 struct page *page;
354
355 ptl = pmd_lock(mm, pmd);
356 if (!is_pmd_migration_entry(*pmd))
357 goto unlock;
358 page = migration_entry_to_page(pmd_to_swp_entry(*pmd));
359 if (!get_page_unless_zero(page))
360 goto unlock;
361 spin_unlock(ptl);
362 wait_on_page_locked(page);
363 put_page(page);
364 return;
365 unlock:
366 spin_unlock(ptl);
367 }
368 #endif
369
370 #ifdef CONFIG_BLOCK
371 /* Returns true if all buffers are successfully locked */
372 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
373 enum migrate_mode mode)
374 {
375 struct buffer_head *bh = head;
376
377 /* Simple case, sync compaction */
378 if (mode != MIGRATE_ASYNC) {
379 do {
380 get_bh(bh);
381 lock_buffer(bh);
382 bh = bh->b_this_page;
383
384 } while (bh != head);
385
386 return true;
387 }
388
389 /* async case, we cannot block on lock_buffer so use trylock_buffer */
390 do {
391 get_bh(bh);
392 if (!trylock_buffer(bh)) {
393 /*
394 * We failed to lock the buffer and cannot stall in
395 * async migration. Release the taken locks
396 */
397 struct buffer_head *failed_bh = bh;
398 put_bh(failed_bh);
399 bh = head;
400 while (bh != failed_bh) {
401 unlock_buffer(bh);
402 put_bh(bh);
403 bh = bh->b_this_page;
404 }
405 return false;
406 }
407
408 bh = bh->b_this_page;
409 } while (bh != head);
410 return true;
411 }
412 #else
413 static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
414 enum migrate_mode mode)
415 {
416 return true;
417 }
418 #endif /* CONFIG_BLOCK */
419
420 /*
421 * Replace the page in the mapping.
422 *
423 * The number of remaining references must be:
424 * 1 for anonymous pages without a mapping
425 * 2 for pages with a mapping
426 * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
427 */
428 int migrate_page_move_mapping(struct address_space *mapping,
429 struct page *newpage, struct page *page,
430 struct buffer_head *head, enum migrate_mode mode,
431 int extra_count)
432 {
433 struct zone *oldzone, *newzone;
434 int dirty;
435 int expected_count = 1 + extra_count;
436 void **pslot;
437
438 /*
439 * ZONE_DEVICE pages have 1 refcount always held by their device
440 *
441 * Note that DAX memory will never reach that point as it does not have
442 * the MEMORY_DEVICE_ALLOW_MIGRATE flag set (see memory_hotplug.h).
443 */
444 expected_count += is_zone_device_page(page);
445
446 if (!mapping) {
447 /* Anonymous page without mapping */
448 if (page_count(page) != expected_count)
449 return -EAGAIN;
450
451 /* No turning back from here */
452 newpage->index = page->index;
453 newpage->mapping = page->mapping;
454 if (PageSwapBacked(page))
455 __SetPageSwapBacked(newpage);
456
457 return MIGRATEPAGE_SUCCESS;
458 }
459
460 oldzone = page_zone(page);
461 newzone = page_zone(newpage);
462
463 spin_lock_irq(&mapping->tree_lock);
464
465 pslot = radix_tree_lookup_slot(&mapping->page_tree,
466 page_index(page));
467
468 expected_count += 1 + page_has_private(page);
469 if (page_count(page) != expected_count ||
470 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
471 spin_unlock_irq(&mapping->tree_lock);
472 return -EAGAIN;
473 }
474
475 if (!page_ref_freeze(page, expected_count)) {
476 spin_unlock_irq(&mapping->tree_lock);
477 return -EAGAIN;
478 }
479
480 /*
481 * In the async migration case of moving a page with buffers, lock the
482 * buffers using trylock before the mapping is moved. If the mapping
483 * was moved, we later failed to lock the buffers and could not move
484 * the mapping back due to an elevated page count, we would have to
485 * block waiting on other references to be dropped.
486 */
487 if (mode == MIGRATE_ASYNC && head &&
488 !buffer_migrate_lock_buffers(head, mode)) {
489 page_ref_unfreeze(page, expected_count);
490 spin_unlock_irq(&mapping->tree_lock);
491 return -EAGAIN;
492 }
493
494 /*
495 * Now we know that no one else is looking at the page:
496 * no turning back from here.
497 */
498 newpage->index = page->index;
499 newpage->mapping = page->mapping;
500 get_page(newpage); /* add cache reference */
501 if (PageSwapBacked(page)) {
502 __SetPageSwapBacked(newpage);
503 if (PageSwapCache(page)) {
504 SetPageSwapCache(newpage);
505 set_page_private(newpage, page_private(page));
506 }
507 } else {
508 VM_BUG_ON_PAGE(PageSwapCache(page), page);
509 }
510
511 /* Move dirty while page refs frozen and newpage not yet exposed */
512 dirty = PageDirty(page);
513 if (dirty) {
514 ClearPageDirty(page);
515 SetPageDirty(newpage);
516 }
517
518 radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
519
520 /*
521 * Drop cache reference from old page by unfreezing
522 * to one less reference.
523 * We know this isn't the last reference.
524 */
525 page_ref_unfreeze(page, expected_count - 1);
526
527 spin_unlock(&mapping->tree_lock);
528 /* Leave irq disabled to prevent preemption while updating stats */
529
530 /*
531 * If moved to a different zone then also account
532 * the page for that zone. Other VM counters will be
533 * taken care of when we establish references to the
534 * new page and drop references to the old page.
535 *
536 * Note that anonymous pages are accounted for
537 * via NR_FILE_PAGES and NR_ANON_MAPPED if they
538 * are mapped to swap space.
539 */
540 if (newzone != oldzone) {
541 __dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES);
542 __inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES);
543 if (PageSwapBacked(page) && !PageSwapCache(page)) {
544 __dec_node_state(oldzone->zone_pgdat, NR_SHMEM);
545 __inc_node_state(newzone->zone_pgdat, NR_SHMEM);
546 }
547 if (dirty && mapping_cap_account_dirty(mapping)) {
548 __dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY);
549 __dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING);
550 __inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY);
551 __inc_zone_state(newzone, NR_ZONE_WRITE_PENDING);
552 }
553 }
554 local_irq_enable();
555
556 return MIGRATEPAGE_SUCCESS;
557 }
558 EXPORT_SYMBOL(migrate_page_move_mapping);
559
560 /*
561 * The expected number of remaining references is the same as that
562 * of migrate_page_move_mapping().
563 */
564 int migrate_huge_page_move_mapping(struct address_space *mapping,
565 struct page *newpage, struct page *page)
566 {
567 int expected_count;
568 void **pslot;
569
570 spin_lock_irq(&mapping->tree_lock);
571
572 pslot = radix_tree_lookup_slot(&mapping->page_tree,
573 page_index(page));
574
575 expected_count = 2 + page_has_private(page);
576 if (page_count(page) != expected_count ||
577 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
578 spin_unlock_irq(&mapping->tree_lock);
579 return -EAGAIN;
580 }
581
582 if (!page_ref_freeze(page, expected_count)) {
583 spin_unlock_irq(&mapping->tree_lock);
584 return -EAGAIN;
585 }
586
587 newpage->index = page->index;
588 newpage->mapping = page->mapping;
589
590 get_page(newpage);
591
592 radix_tree_replace_slot(&mapping->page_tree, pslot, newpage);
593
594 page_ref_unfreeze(page, expected_count - 1);
595
596 spin_unlock_irq(&mapping->tree_lock);
597
598 return MIGRATEPAGE_SUCCESS;
599 }
600
601 /*
602 * Gigantic pages are so large that we do not guarantee that page++ pointer
603 * arithmetic will work across the entire page. We need something more
604 * specialized.
605 */
606 static void __copy_gigantic_page(struct page *dst, struct page *src,
607 int nr_pages)
608 {
609 int i;
610 struct page *dst_base = dst;
611 struct page *src_base = src;
612
613 for (i = 0; i < nr_pages; ) {
614 cond_resched();
615 copy_highpage(dst, src);
616
617 i++;
618 dst = mem_map_next(dst, dst_base, i);
619 src = mem_map_next(src, src_base, i);
620 }
621 }
622
623 static void copy_huge_page(struct page *dst, struct page *src)
624 {
625 int i;
626 int nr_pages;
627
628 if (PageHuge(src)) {
629 /* hugetlbfs page */
630 struct hstate *h = page_hstate(src);
631 nr_pages = pages_per_huge_page(h);
632
633 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) {
634 __copy_gigantic_page(dst, src, nr_pages);
635 return;
636 }
637 } else {
638 /* thp page */
639 BUG_ON(!PageTransHuge(src));
640 nr_pages = hpage_nr_pages(src);
641 }
642
643 for (i = 0; i < nr_pages; i++) {
644 cond_resched();
645 copy_highpage(dst + i, src + i);
646 }
647 }
648
649 /*
650 * Copy the page to its new location
651 */
652 void migrate_page_states(struct page *newpage, struct page *page)
653 {
654 int cpupid;
655
656 if (PageError(page))
657 SetPageError(newpage);
658 if (PageReferenced(page))
659 SetPageReferenced(newpage);
660 if (PageUptodate(page))
661 SetPageUptodate(newpage);
662 if (TestClearPageActive(page)) {
663 VM_BUG_ON_PAGE(PageUnevictable(page), page);
664 SetPageActive(newpage);
665 } else if (TestClearPageUnevictable(page))
666 SetPageUnevictable(newpage);
667 if (PageChecked(page))
668 SetPageChecked(newpage);
669 if (PageMappedToDisk(page))
670 SetPageMappedToDisk(newpage);
671
672 /* Move dirty on pages not done by migrate_page_move_mapping() */
673 if (PageDirty(page))
674 SetPageDirty(newpage);
675
676 if (page_is_young(page))
677 set_page_young(newpage);
678 if (page_is_idle(page))
679 set_page_idle(newpage);
680
681 /*
682 * Copy NUMA information to the new page, to prevent over-eager
683 * future migrations of this same page.
684 */
685 cpupid = page_cpupid_xchg_last(page, -1);
686 page_cpupid_xchg_last(newpage, cpupid);
687
688 ksm_migrate_page(newpage, page);
689 /*
690 * Please do not reorder this without considering how mm/ksm.c's
691 * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
692 */
693 if (PageSwapCache(page))
694 ClearPageSwapCache(page);
695 ClearPagePrivate(page);
696 set_page_private(page, 0);
697
698 /*
699 * If any waiters have accumulated on the new page then
700 * wake them up.
701 */
702 if (PageWriteback(newpage))
703 end_page_writeback(newpage);
704
705 copy_page_owner(page, newpage);
706
707 mem_cgroup_migrate(page, newpage);
708 }
709 EXPORT_SYMBOL(migrate_page_states);
710
711 void migrate_page_copy(struct page *newpage, struct page *page)
712 {
713 if (PageHuge(page) || PageTransHuge(page))
714 copy_huge_page(newpage, page);
715 else
716 copy_highpage(newpage, page);
717
718 migrate_page_states(newpage, page);
719 }
720 EXPORT_SYMBOL(migrate_page_copy);
721
722 /************************************************************
723 * Migration functions
724 ***********************************************************/
725
726 /*
727 * Common logic to directly migrate a single LRU page suitable for
728 * pages that do not use PagePrivate/PagePrivate2.
729 *
730 * Pages are locked upon entry and exit.
731 */
732 int migrate_page(struct address_space *mapping,
733 struct page *newpage, struct page *page,
734 enum migrate_mode mode)
735 {
736 int rc;
737
738 BUG_ON(PageWriteback(page)); /* Writeback must be complete */
739
740 rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
741
742 if (rc != MIGRATEPAGE_SUCCESS)
743 return rc;
744
745 if (mode != MIGRATE_SYNC_NO_COPY)
746 migrate_page_copy(newpage, page);
747 else
748 migrate_page_states(newpage, page);
749 return MIGRATEPAGE_SUCCESS;
750 }
751 EXPORT_SYMBOL(migrate_page);
752
753 #ifdef CONFIG_BLOCK
754 /*
755 * Migration function for pages with buffers. This function can only be used
756 * if the underlying filesystem guarantees that no other references to "page"
757 * exist.
758 */
759 int buffer_migrate_page(struct address_space *mapping,
760 struct page *newpage, struct page *page, enum migrate_mode mode)
761 {
762 struct buffer_head *bh, *head;
763 int rc;
764
765 if (!page_has_buffers(page))
766 return migrate_page(mapping, newpage, page, mode);
767
768 head = page_buffers(page);
769
770 rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0);
771
772 if (rc != MIGRATEPAGE_SUCCESS)
773 return rc;
774
775 /*
776 * In the async case, migrate_page_move_mapping locked the buffers
777 * with an IRQ-safe spinlock held. In the sync case, the buffers
778 * need to be locked now
779 */
780 if (mode != MIGRATE_ASYNC)
781 BUG_ON(!buffer_migrate_lock_buffers(head, mode));
782
783 ClearPagePrivate(page);
784 set_page_private(newpage, page_private(page));
785 set_page_private(page, 0);
786 put_page(page);
787 get_page(newpage);
788
789 bh = head;
790 do {
791 set_bh_page(bh, newpage, bh_offset(bh));
792 bh = bh->b_this_page;
793
794 } while (bh != head);
795
796 SetPagePrivate(newpage);
797
798 if (mode != MIGRATE_SYNC_NO_COPY)
799 migrate_page_copy(newpage, page);
800 else
801 migrate_page_states(newpage, page);
802
803 bh = head;
804 do {
805 unlock_buffer(bh);
806 put_bh(bh);
807 bh = bh->b_this_page;
808
809 } while (bh != head);
810
811 return MIGRATEPAGE_SUCCESS;
812 }
813 EXPORT_SYMBOL(buffer_migrate_page);
814 #endif
815
816 /*
817 * Writeback a page to clean the dirty state
818 */
819 static int writeout(struct address_space *mapping, struct page *page)
820 {
821 struct writeback_control wbc = {
822 .sync_mode = WB_SYNC_NONE,
823 .nr_to_write = 1,
824 .range_start = 0,
825 .range_end = LLONG_MAX,
826 .for_reclaim = 1
827 };
828 int rc;
829
830 if (!mapping->a_ops->writepage)
831 /* No write method for the address space */
832 return -EINVAL;
833
834 if (!clear_page_dirty_for_io(page))
835 /* Someone else already triggered a write */
836 return -EAGAIN;
837
838 /*
839 * A dirty page may imply that the underlying filesystem has
840 * the page on some queue. So the page must be clean for
841 * migration. Writeout may mean we loose the lock and the
842 * page state is no longer what we checked for earlier.
843 * At this point we know that the migration attempt cannot
844 * be successful.
845 */
846 remove_migration_ptes(page, page, false);
847
848 rc = mapping->a_ops->writepage(page, &wbc);
849
850 if (rc != AOP_WRITEPAGE_ACTIVATE)
851 /* unlocked. Relock */
852 lock_page(page);
853
854 return (rc < 0) ? -EIO : -EAGAIN;
855 }
856
857 /*
858 * Default handling if a filesystem does not provide a migration function.
859 */
860 static int fallback_migrate_page(struct address_space *mapping,
861 struct page *newpage, struct page *page, enum migrate_mode mode)
862 {
863 if (PageDirty(page)) {
864 /* Only writeback pages in full synchronous migration */
865 switch (mode) {
866 case MIGRATE_SYNC:
867 case MIGRATE_SYNC_NO_COPY:
868 break;
869 default:
870 return -EBUSY;
871 }
872 return writeout(mapping, page);
873 }
874
875 /*
876 * Buffers may be managed in a filesystem specific way.
877 * We must have no buffers or drop them.
878 */
879 if (page_has_private(page) &&
880 !try_to_release_page(page, GFP_KERNEL))
881 return -EAGAIN;
882
883 return migrate_page(mapping, newpage, page, mode);
884 }
885
886 /*
887 * Move a page to a newly allocated page
888 * The page is locked and all ptes have been successfully removed.
889 *
890 * The new page will have replaced the old page if this function
891 * is successful.
892 *
893 * Return value:
894 * < 0 - error code
895 * MIGRATEPAGE_SUCCESS - success
896 */
897 static int move_to_new_page(struct page *newpage, struct page *page,
898 enum migrate_mode mode)
899 {
900 struct address_space *mapping;
901 int rc = -EAGAIN;
902 bool is_lru = !__PageMovable(page);
903
904 VM_BUG_ON_PAGE(!PageLocked(page), page);
905 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
906
907 mapping = page_mapping(page);
908
909 if (likely(is_lru)) {
910 if (!mapping)
911 rc = migrate_page(mapping, newpage, page, mode);
912 else if (mapping->a_ops->migratepage)
913 /*
914 * Most pages have a mapping and most filesystems
915 * provide a migratepage callback. Anonymous pages
916 * are part of swap space which also has its own
917 * migratepage callback. This is the most common path
918 * for page migration.
919 */
920 rc = mapping->a_ops->migratepage(mapping, newpage,
921 page, mode);
922 else
923 rc = fallback_migrate_page(mapping, newpage,
924 page, mode);
925 } else {
926 /*
927 * In case of non-lru page, it could be released after
928 * isolation step. In that case, we shouldn't try migration.
929 */
930 VM_BUG_ON_PAGE(!PageIsolated(page), page);
931 if (!PageMovable(page)) {
932 rc = MIGRATEPAGE_SUCCESS;
933 __ClearPageIsolated(page);
934 goto out;
935 }
936
937 rc = mapping->a_ops->migratepage(mapping, newpage,
938 page, mode);
939 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
940 !PageIsolated(page));
941 }
942
943 /*
944 * When successful, old pagecache page->mapping must be cleared before
945 * page is freed; but stats require that PageAnon be left as PageAnon.
946 */
947 if (rc == MIGRATEPAGE_SUCCESS) {
948 if (__PageMovable(page)) {
949 VM_BUG_ON_PAGE(!PageIsolated(page), page);
950
951 /*
952 * We clear PG_movable under page_lock so any compactor
953 * cannot try to migrate this page.
954 */
955 __ClearPageIsolated(page);
956 }
957
958 /*
959 * Anonymous and movable page->mapping will be cleard by
960 * free_pages_prepare so don't reset it here for keeping
961 * the type to work PageAnon, for example.
962 */
963 if (!PageMappingFlags(page))
964 page->mapping = NULL;
965 }
966 out:
967 return rc;
968 }
969
970 static int __unmap_and_move(struct page *page, struct page *newpage,
971 int force, enum migrate_mode mode)
972 {
973 int rc = -EAGAIN;
974 int page_was_mapped = 0;
975 struct anon_vma *anon_vma = NULL;
976 bool is_lru = !__PageMovable(page);
977
978 if (!trylock_page(page)) {
979 if (!force || mode == MIGRATE_ASYNC)
980 goto out;
981
982 /*
983 * It's not safe for direct compaction to call lock_page.
984 * For example, during page readahead pages are added locked
985 * to the LRU. Later, when the IO completes the pages are
986 * marked uptodate and unlocked. However, the queueing
987 * could be merging multiple pages for one bio (e.g.
988 * mpage_readpages). If an allocation happens for the
989 * second or third page, the process can end up locking
990 * the same page twice and deadlocking. Rather than
991 * trying to be clever about what pages can be locked,
992 * avoid the use of lock_page for direct compaction
993 * altogether.
994 */
995 if (current->flags & PF_MEMALLOC)
996 goto out;
997
998 lock_page(page);
999 }
1000
1001 if (PageWriteback(page)) {
1002 /*
1003 * Only in the case of a full synchronous migration is it
1004 * necessary to wait for PageWriteback. In the async case,
1005 * the retry loop is too short and in the sync-light case,
1006 * the overhead of stalling is too much
1007 */
1008 switch (mode) {
1009 case MIGRATE_SYNC:
1010 case MIGRATE_SYNC_NO_COPY:
1011 break;
1012 default:
1013 rc = -EBUSY;
1014 goto out_unlock;
1015 }
1016 if (!force)
1017 goto out_unlock;
1018 wait_on_page_writeback(page);
1019 }
1020
1021 /*
1022 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
1023 * we cannot notice that anon_vma is freed while we migrates a page.
1024 * This get_anon_vma() delays freeing anon_vma pointer until the end
1025 * of migration. File cache pages are no problem because of page_lock()
1026 * File Caches may use write_page() or lock_page() in migration, then,
1027 * just care Anon page here.
1028 *
1029 * Only page_get_anon_vma() understands the subtleties of
1030 * getting a hold on an anon_vma from outside one of its mms.
1031 * But if we cannot get anon_vma, then we won't need it anyway,
1032 * because that implies that the anon page is no longer mapped
1033 * (and cannot be remapped so long as we hold the page lock).
1034 */
1035 if (PageAnon(page) && !PageKsm(page))
1036 anon_vma = page_get_anon_vma(page);
1037
1038 /*
1039 * Block others from accessing the new page when we get around to
1040 * establishing additional references. We are usually the only one
1041 * holding a reference to newpage at this point. We used to have a BUG
1042 * here if trylock_page(newpage) fails, but would like to allow for
1043 * cases where there might be a race with the previous use of newpage.
1044 * This is much like races on refcount of oldpage: just don't BUG().
1045 */
1046 if (unlikely(!trylock_page(newpage)))
1047 goto out_unlock;
1048
1049 if (unlikely(!is_lru)) {
1050 rc = move_to_new_page(newpage, page, mode);
1051 goto out_unlock_both;
1052 }
1053
1054 /*
1055 * Corner case handling:
1056 * 1. When a new swap-cache page is read into, it is added to the LRU
1057 * and treated as swapcache but it has no rmap yet.
1058 * Calling try_to_unmap() against a page->mapping==NULL page will
1059 * trigger a BUG. So handle it here.
1060 * 2. An orphaned page (see truncate_complete_page) might have
1061 * fs-private metadata. The page can be picked up due to memory
1062 * offlining. Everywhere else except page reclaim, the page is
1063 * invisible to the vm, so the page can not be migrated. So try to
1064 * free the metadata, so the page can be freed.
1065 */
1066 if (!page->mapping) {
1067 VM_BUG_ON_PAGE(PageAnon(page), page);
1068 if (page_has_private(page)) {
1069 try_to_free_buffers(page);
1070 goto out_unlock_both;
1071 }
1072 } else if (page_mapped(page)) {
1073 /* Establish migration ptes */
1074 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1075 page);
1076 try_to_unmap(page,
1077 TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1078 page_was_mapped = 1;
1079 }
1080
1081 if (!page_mapped(page))
1082 rc = move_to_new_page(newpage, page, mode);
1083
1084 if (page_was_mapped)
1085 remove_migration_ptes(page,
1086 rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1087
1088 out_unlock_both:
1089 unlock_page(newpage);
1090 out_unlock:
1091 /* Drop an anon_vma reference if we took one */
1092 if (anon_vma)
1093 put_anon_vma(anon_vma);
1094 unlock_page(page);
1095 out:
1096 /*
1097 * If migration is successful, decrease refcount of the newpage
1098 * which will not free the page because new page owner increased
1099 * refcounter. As well, if it is LRU page, add the page to LRU
1100 * list in here.
1101 */
1102 if (rc == MIGRATEPAGE_SUCCESS) {
1103 if (unlikely(__PageMovable(newpage)))
1104 put_page(newpage);
1105 else
1106 putback_lru_page(newpage);
1107 }
1108
1109 return rc;
1110 }
1111
1112 /*
1113 * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work
1114 * around it.
1115 */
1116 #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM)
1117 #define ICE_noinline noinline
1118 #else
1119 #define ICE_noinline
1120 #endif
1121
1122 /*
1123 * Obtain the lock on page, remove all ptes and migrate the page
1124 * to the newly allocated page in newpage.
1125 */
1126 static ICE_noinline int unmap_and_move(new_page_t get_new_page,
1127 free_page_t put_new_page,
1128 unsigned long private, struct page *page,
1129 int force, enum migrate_mode mode,
1130 enum migrate_reason reason)
1131 {
1132 int rc = MIGRATEPAGE_SUCCESS;
1133 int *result = NULL;
1134 struct page *newpage;
1135
1136 newpage = get_new_page(page, private, &result);
1137 if (!newpage)
1138 return -ENOMEM;
1139
1140 if (page_count(page) == 1) {
1141 /* page was freed from under us. So we are done. */
1142 ClearPageActive(page);
1143 ClearPageUnevictable(page);
1144 if (unlikely(__PageMovable(page))) {
1145 lock_page(page);
1146 if (!PageMovable(page))
1147 __ClearPageIsolated(page);
1148 unlock_page(page);
1149 }
1150 if (put_new_page)
1151 put_new_page(newpage, private);
1152 else
1153 put_page(newpage);
1154 goto out;
1155 }
1156
1157 if (unlikely(PageTransHuge(page) && !PageTransHuge(newpage))) {
1158 lock_page(page);
1159 rc = split_huge_page(page);
1160 unlock_page(page);
1161 if (rc)
1162 goto out;
1163 }
1164
1165 rc = __unmap_and_move(page, newpage, force, mode);
1166 if (rc == MIGRATEPAGE_SUCCESS)
1167 set_page_owner_migrate_reason(newpage, reason);
1168
1169 out:
1170 if (rc != -EAGAIN) {
1171 /*
1172 * A page that has been migrated has all references
1173 * removed and will be freed. A page that has not been
1174 * migrated will have kepts its references and be
1175 * restored.
1176 */
1177 list_del(&page->lru);
1178
1179 /*
1180 * Compaction can migrate also non-LRU pages which are
1181 * not accounted to NR_ISOLATED_*. They can be recognized
1182 * as __PageMovable
1183 */
1184 if (likely(!__PageMovable(page)))
1185 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1186 page_is_file_cache(page), -hpage_nr_pages(page));
1187 }
1188
1189 /*
1190 * If migration is successful, releases reference grabbed during
1191 * isolation. Otherwise, restore the page to right list unless
1192 * we want to retry.
1193 */
1194 if (rc == MIGRATEPAGE_SUCCESS) {
1195 put_page(page);
1196 if (reason == MR_MEMORY_FAILURE) {
1197 /*
1198 * Set PG_HWPoison on just freed page
1199 * intentionally. Although it's rather weird,
1200 * it's how HWPoison flag works at the moment.
1201 */
1202 if (!test_set_page_hwpoison(page))
1203 num_poisoned_pages_inc();
1204 }
1205 } else {
1206 if (rc != -EAGAIN) {
1207 if (likely(!__PageMovable(page))) {
1208 putback_lru_page(page);
1209 goto put_new;
1210 }
1211
1212 lock_page(page);
1213 if (PageMovable(page))
1214 putback_movable_page(page);
1215 else
1216 __ClearPageIsolated(page);
1217 unlock_page(page);
1218 put_page(page);
1219 }
1220 put_new:
1221 if (put_new_page)
1222 put_new_page(newpage, private);
1223 else
1224 put_page(newpage);
1225 }
1226
1227 if (result) {
1228 if (rc)
1229 *result = rc;
1230 else
1231 *result = page_to_nid(newpage);
1232 }
1233 return rc;
1234 }
1235
1236 /*
1237 * Counterpart of unmap_and_move_page() for hugepage migration.
1238 *
1239 * This function doesn't wait the completion of hugepage I/O
1240 * because there is no race between I/O and migration for hugepage.
1241 * Note that currently hugepage I/O occurs only in direct I/O
1242 * where no lock is held and PG_writeback is irrelevant,
1243 * and writeback status of all subpages are counted in the reference
1244 * count of the head page (i.e. if all subpages of a 2MB hugepage are
1245 * under direct I/O, the reference of the head page is 512 and a bit more.)
1246 * This means that when we try to migrate hugepage whose subpages are
1247 * doing direct I/O, some references remain after try_to_unmap() and
1248 * hugepage migration fails without data corruption.
1249 *
1250 * There is also no race when direct I/O is issued on the page under migration,
1251 * because then pte is replaced with migration swap entry and direct I/O code
1252 * will wait in the page fault for migration to complete.
1253 */
1254 static int unmap_and_move_huge_page(new_page_t get_new_page,
1255 free_page_t put_new_page, unsigned long private,
1256 struct page *hpage, int force,
1257 enum migrate_mode mode, int reason)
1258 {
1259 int rc = -EAGAIN;
1260 int *result = NULL;
1261 int page_was_mapped = 0;
1262 struct page *new_hpage;
1263 struct anon_vma *anon_vma = NULL;
1264
1265 /*
1266 * Movability of hugepages depends on architectures and hugepage size.
1267 * This check is necessary because some callers of hugepage migration
1268 * like soft offline and memory hotremove don't walk through page
1269 * tables or check whether the hugepage is pmd-based or not before
1270 * kicking migration.
1271 */
1272 if (!hugepage_migration_supported(page_hstate(hpage))) {
1273 putback_active_hugepage(hpage);
1274 return -ENOSYS;
1275 }
1276
1277 new_hpage = get_new_page(hpage, private, &result);
1278 if (!new_hpage)
1279 return -ENOMEM;
1280
1281 if (!trylock_page(hpage)) {
1282 if (!force)
1283 goto out;
1284 switch (mode) {
1285 case MIGRATE_SYNC:
1286 case MIGRATE_SYNC_NO_COPY:
1287 break;
1288 default:
1289 goto out;
1290 }
1291 lock_page(hpage);
1292 }
1293
1294 if (PageAnon(hpage))
1295 anon_vma = page_get_anon_vma(hpage);
1296
1297 if (unlikely(!trylock_page(new_hpage)))
1298 goto put_anon;
1299
1300 if (page_mapped(hpage)) {
1301 try_to_unmap(hpage,
1302 TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1303 page_was_mapped = 1;
1304 }
1305
1306 if (!page_mapped(hpage))
1307 rc = move_to_new_page(new_hpage, hpage, mode);
1308
1309 if (page_was_mapped)
1310 remove_migration_ptes(hpage,
1311 rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1312
1313 unlock_page(new_hpage);
1314
1315 put_anon:
1316 if (anon_vma)
1317 put_anon_vma(anon_vma);
1318
1319 if (rc == MIGRATEPAGE_SUCCESS) {
1320 hugetlb_cgroup_migrate(hpage, new_hpage);
1321 put_new_page = NULL;
1322 set_page_owner_migrate_reason(new_hpage, reason);
1323 }
1324
1325 unlock_page(hpage);
1326 out:
1327 if (rc != -EAGAIN)
1328 putback_active_hugepage(hpage);
1329 if (reason == MR_MEMORY_FAILURE && !test_set_page_hwpoison(hpage))
1330 num_poisoned_pages_inc();
1331
1332 /*
1333 * If migration was not successful and there's a freeing callback, use
1334 * it. Otherwise, put_page() will drop the reference grabbed during
1335 * isolation.
1336 */
1337 if (put_new_page)
1338 put_new_page(new_hpage, private);
1339 else
1340 putback_active_hugepage(new_hpage);
1341
1342 if (result) {
1343 if (rc)
1344 *result = rc;
1345 else
1346 *result = page_to_nid(new_hpage);
1347 }
1348 return rc;
1349 }
1350
1351 /*
1352 * migrate_pages - migrate the pages specified in a list, to the free pages
1353 * supplied as the target for the page migration
1354 *
1355 * @from: The list of pages to be migrated.
1356 * @get_new_page: The function used to allocate free pages to be used
1357 * as the target of the page migration.
1358 * @put_new_page: The function used to free target pages if migration
1359 * fails, or NULL if no special handling is necessary.
1360 * @private: Private data to be passed on to get_new_page()
1361 * @mode: The migration mode that specifies the constraints for
1362 * page migration, if any.
1363 * @reason: The reason for page migration.
1364 *
1365 * The function returns after 10 attempts or if no pages are movable any more
1366 * because the list has become empty or no retryable pages exist any more.
1367 * The caller should call putback_movable_pages() to return pages to the LRU
1368 * or free list only if ret != 0.
1369 *
1370 * Returns the number of pages that were not migrated, or an error code.
1371 */
1372 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1373 free_page_t put_new_page, unsigned long private,
1374 enum migrate_mode mode, int reason)
1375 {
1376 int retry = 1;
1377 int nr_failed = 0;
1378 int nr_succeeded = 0;
1379 int pass = 0;
1380 struct page *page;
1381 struct page *page2;
1382 int swapwrite = current->flags & PF_SWAPWRITE;
1383 int rc;
1384
1385 if (!swapwrite)
1386 current->flags |= PF_SWAPWRITE;
1387
1388 for(pass = 0; pass < 10 && retry; pass++) {
1389 retry = 0;
1390
1391 list_for_each_entry_safe(page, page2, from, lru) {
1392 cond_resched();
1393
1394 if (PageHuge(page))
1395 rc = unmap_and_move_huge_page(get_new_page,
1396 put_new_page, private, page,
1397 pass > 2, mode, reason);
1398 else
1399 rc = unmap_and_move(get_new_page, put_new_page,
1400 private, page, pass > 2, mode,
1401 reason);
1402
1403 switch(rc) {
1404 case -ENOMEM:
1405 nr_failed++;
1406 goto out;
1407 case -EAGAIN:
1408 retry++;
1409 break;
1410 case MIGRATEPAGE_SUCCESS:
1411 nr_succeeded++;
1412 break;
1413 default:
1414 /*
1415 * Permanent failure (-EBUSY, -ENOSYS, etc.):
1416 * unlike -EAGAIN case, the failed page is
1417 * removed from migration page list and not
1418 * retried in the next outer loop.
1419 */
1420 nr_failed++;
1421 break;
1422 }
1423 }
1424 }
1425 nr_failed += retry;
1426 rc = nr_failed;
1427 out:
1428 if (nr_succeeded)
1429 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1430 if (nr_failed)
1431 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1432 trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
1433
1434 if (!swapwrite)
1435 current->flags &= ~PF_SWAPWRITE;
1436
1437 return rc;
1438 }
1439
1440 #ifdef CONFIG_NUMA
1441 /*
1442 * Move a list of individual pages
1443 */
1444 struct page_to_node {
1445 unsigned long addr;
1446 struct page *page;
1447 int node;
1448 int status;
1449 };
1450
1451 static struct page *new_page_node(struct page *p, unsigned long private,
1452 int **result)
1453 {
1454 struct page_to_node *pm = (struct page_to_node *)private;
1455
1456 while (pm->node != MAX_NUMNODES && pm->page != p)
1457 pm++;
1458
1459 if (pm->node == MAX_NUMNODES)
1460 return NULL;
1461
1462 *result = &pm->status;
1463
1464 if (PageHuge(p))
1465 return alloc_huge_page_node(page_hstate(compound_head(p)),
1466 pm->node);
1467 else if (thp_migration_supported() && PageTransHuge(p)) {
1468 struct page *thp;
1469
1470 thp = alloc_pages_node(pm->node,
1471 (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_RECLAIM,
1472 HPAGE_PMD_ORDER);
1473 if (!thp)
1474 return NULL;
1475 prep_transhuge_page(thp);
1476 return thp;
1477 } else
1478 return __alloc_pages_node(pm->node,
1479 GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0);
1480 }
1481
1482 /*
1483 * Move a set of pages as indicated in the pm array. The addr
1484 * field must be set to the virtual address of the page to be moved
1485 * and the node number must contain a valid target node.
1486 * The pm array ends with node = MAX_NUMNODES.
1487 */
1488 static int do_move_page_to_node_array(struct mm_struct *mm,
1489 struct page_to_node *pm,
1490 int migrate_all)
1491 {
1492 int err;
1493 struct page_to_node *pp;
1494 LIST_HEAD(pagelist);
1495
1496 down_read(&mm->mmap_sem);
1497
1498 /*
1499 * Build a list of pages to migrate
1500 */
1501 for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
1502 struct vm_area_struct *vma;
1503 struct page *page;
1504 struct page *head;
1505 unsigned int follflags;
1506
1507 err = -EFAULT;
1508 vma = find_vma(mm, pp->addr);
1509 if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
1510 goto set_status;
1511
1512 /* FOLL_DUMP to ignore special (like zero) pages */
1513 follflags = FOLL_GET | FOLL_DUMP;
1514 if (!thp_migration_supported())
1515 follflags |= FOLL_SPLIT;
1516 page = follow_page(vma, pp->addr, follflags);
1517
1518 err = PTR_ERR(page);
1519 if (IS_ERR(page))
1520 goto set_status;
1521
1522 err = -ENOENT;
1523 if (!page)
1524 goto set_status;
1525
1526 err = page_to_nid(page);
1527
1528 if (err == pp->node)
1529 /*
1530 * Node already in the right place
1531 */
1532 goto put_and_set;
1533
1534 err = -EACCES;
1535 if (page_mapcount(page) > 1 &&
1536 !migrate_all)
1537 goto put_and_set;
1538
1539 if (PageHuge(page)) {
1540 if (PageHead(page)) {
1541 isolate_huge_page(page, &pagelist);
1542 err = 0;
1543 pp->page = page;
1544 }
1545 goto put_and_set;
1546 }
1547
1548 pp->page = compound_head(page);
1549 head = compound_head(page);
1550 err = isolate_lru_page(head);
1551 if (!err) {
1552 list_add_tail(&head->lru, &pagelist);
1553 mod_node_page_state(page_pgdat(head),
1554 NR_ISOLATED_ANON + page_is_file_cache(head),
1555 hpage_nr_pages(head));
1556 }
1557 put_and_set:
1558 /*
1559 * Either remove the duplicate refcount from
1560 * isolate_lru_page() or drop the page ref if it was
1561 * not isolated.
1562 */
1563 put_page(page);
1564 set_status:
1565 pp->status = err;
1566 }
1567
1568 err = 0;
1569 if (!list_empty(&pagelist)) {
1570 err = migrate_pages(&pagelist, new_page_node, NULL,
1571 (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL);
1572 if (err)
1573 putback_movable_pages(&pagelist);
1574 }
1575
1576 up_read(&mm->mmap_sem);
1577 return err;
1578 }
1579
1580 /*
1581 * Migrate an array of page address onto an array of nodes and fill
1582 * the corresponding array of status.
1583 */
1584 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1585 unsigned long nr_pages,
1586 const void __user * __user *pages,
1587 const int __user *nodes,
1588 int __user *status, int flags)
1589 {
1590 struct page_to_node *pm;
1591 unsigned long chunk_nr_pages;
1592 unsigned long chunk_start;
1593 int err;
1594
1595 err = -ENOMEM;
1596 pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
1597 if (!pm)
1598 goto out;
1599
1600 migrate_prep();
1601
1602 /*
1603 * Store a chunk of page_to_node array in a page,
1604 * but keep the last one as a marker
1605 */
1606 chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
1607
1608 for (chunk_start = 0;
1609 chunk_start < nr_pages;
1610 chunk_start += chunk_nr_pages) {
1611 int j;
1612
1613 if (chunk_start + chunk_nr_pages > nr_pages)
1614 chunk_nr_pages = nr_pages - chunk_start;
1615
1616 /* fill the chunk pm with addrs and nodes from user-space */
1617 for (j = 0; j < chunk_nr_pages; j++) {
1618 const void __user *p;
1619 int node;
1620
1621 err = -EFAULT;
1622 if (get_user(p, pages + j + chunk_start))
1623 goto out_pm;
1624 pm[j].addr = (unsigned long) p;
1625
1626 if (get_user(node, nodes + j + chunk_start))
1627 goto out_pm;
1628
1629 err = -ENODEV;
1630 if (node < 0 || node >= MAX_NUMNODES)
1631 goto out_pm;
1632
1633 if (!node_state(node, N_MEMORY))
1634 goto out_pm;
1635
1636 err = -EACCES;
1637 if (!node_isset(node, task_nodes))
1638 goto out_pm;
1639
1640 pm[j].node = node;
1641 }
1642
1643 /* End marker for this chunk */
1644 pm[chunk_nr_pages].node = MAX_NUMNODES;
1645
1646 /* Migrate this chunk */
1647 err = do_move_page_to_node_array(mm, pm,
1648 flags & MPOL_MF_MOVE_ALL);
1649 if (err < 0)
1650 goto out_pm;
1651
1652 /* Return status information */
1653 for (j = 0; j < chunk_nr_pages; j++)
1654 if (put_user(pm[j].status, status + j + chunk_start)) {
1655 err = -EFAULT;
1656 goto out_pm;
1657 }
1658 }
1659 err = 0;
1660
1661 out_pm:
1662 free_page((unsigned long)pm);
1663 out:
1664 return err;
1665 }
1666
1667 /*
1668 * Determine the nodes of an array of pages and store it in an array of status.
1669 */
1670 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1671 const void __user **pages, int *status)
1672 {
1673 unsigned long i;
1674
1675 down_read(&mm->mmap_sem);
1676
1677 for (i = 0; i < nr_pages; i++) {
1678 unsigned long addr = (unsigned long)(*pages);
1679 struct vm_area_struct *vma;
1680 struct page *page;
1681 int err = -EFAULT;
1682
1683 vma = find_vma(mm, addr);
1684 if (!vma || addr < vma->vm_start)
1685 goto set_status;
1686
1687 /* FOLL_DUMP to ignore special (like zero) pages */
1688 page = follow_page(vma, addr, FOLL_DUMP);
1689
1690 err = PTR_ERR(page);
1691 if (IS_ERR(page))
1692 goto set_status;
1693
1694 err = page ? page_to_nid(page) : -ENOENT;
1695 set_status:
1696 *status = err;
1697
1698 pages++;
1699 status++;
1700 }
1701
1702 up_read(&mm->mmap_sem);
1703 }
1704
1705 /*
1706 * Determine the nodes of a user array of pages and store it in
1707 * a user array of status.
1708 */
1709 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1710 const void __user * __user *pages,
1711 int __user *status)
1712 {
1713 #define DO_PAGES_STAT_CHUNK_NR 16
1714 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1715 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1716
1717 while (nr_pages) {
1718 unsigned long chunk_nr;
1719
1720 chunk_nr = nr_pages;
1721 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1722 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1723
1724 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1725 break;
1726
1727 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1728
1729 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1730 break;
1731
1732 pages += chunk_nr;
1733 status += chunk_nr;
1734 nr_pages -= chunk_nr;
1735 }
1736 return nr_pages ? -EFAULT : 0;
1737 }
1738
1739 /*
1740 * Move a list of pages in the address space of the currently executing
1741 * process.
1742 */
1743 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1744 const void __user * __user *, pages,
1745 const int __user *, nodes,
1746 int __user *, status, int, flags)
1747 {
1748 struct task_struct *task;
1749 struct mm_struct *mm;
1750 int err;
1751 nodemask_t task_nodes;
1752
1753 /* Check flags */
1754 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1755 return -EINVAL;
1756
1757 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1758 return -EPERM;
1759
1760 /* Find the mm_struct */
1761 rcu_read_lock();
1762 task = pid ? find_task_by_vpid(pid) : current;
1763 if (!task) {
1764 rcu_read_unlock();
1765 return -ESRCH;
1766 }
1767 get_task_struct(task);
1768
1769 /*
1770 * Check if this process has the right to modify the specified
1771 * process. Use the regular "ptrace_may_access()" checks.
1772 */
1773 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1774 rcu_read_unlock();
1775 err = -EPERM;
1776 goto out;
1777 }
1778 rcu_read_unlock();
1779
1780 err = security_task_movememory(task);
1781 if (err)
1782 goto out;
1783
1784 task_nodes = cpuset_mems_allowed(task);
1785 mm = get_task_mm(task);
1786 put_task_struct(task);
1787
1788 if (!mm)
1789 return -EINVAL;
1790
1791 if (nodes)
1792 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1793 nodes, status, flags);
1794 else
1795 err = do_pages_stat(mm, nr_pages, pages, status);
1796
1797 mmput(mm);
1798 return err;
1799
1800 out:
1801 put_task_struct(task);
1802 return err;
1803 }
1804
1805 #ifdef CONFIG_NUMA_BALANCING
1806 /*
1807 * Returns true if this is a safe migration target node for misplaced NUMA
1808 * pages. Currently it only checks the watermarks which crude
1809 */
1810 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1811 unsigned long nr_migrate_pages)
1812 {
1813 int z;
1814
1815 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1816 struct zone *zone = pgdat->node_zones + z;
1817
1818 if (!populated_zone(zone))
1819 continue;
1820
1821 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1822 if (!zone_watermark_ok(zone, 0,
1823 high_wmark_pages(zone) +
1824 nr_migrate_pages,
1825 0, 0))
1826 continue;
1827 return true;
1828 }
1829 return false;
1830 }
1831
1832 static struct page *alloc_misplaced_dst_page(struct page *page,
1833 unsigned long data,
1834 int **result)
1835 {
1836 int nid = (int) data;
1837 struct page *newpage;
1838
1839 newpage = __alloc_pages_node(nid,
1840 (GFP_HIGHUSER_MOVABLE |
1841 __GFP_THISNODE | __GFP_NOMEMALLOC |
1842 __GFP_NORETRY | __GFP_NOWARN) &
1843 ~__GFP_RECLAIM, 0);
1844
1845 return newpage;
1846 }
1847
1848 /*
1849 * page migration rate limiting control.
1850 * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs
1851 * window of time. Default here says do not migrate more than 1280M per second.
1852 */
1853 static unsigned int migrate_interval_millisecs __read_mostly = 100;
1854 static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT);
1855
1856 /* Returns true if the node is migrate rate-limited after the update */
1857 static bool numamigrate_update_ratelimit(pg_data_t *pgdat,
1858 unsigned long nr_pages)
1859 {
1860 /*
1861 * Rate-limit the amount of data that is being migrated to a node.
1862 * Optimal placement is no good if the memory bus is saturated and
1863 * all the time is being spent migrating!
1864 */
1865 if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) {
1866 spin_lock(&pgdat->numabalancing_migrate_lock);
1867 pgdat->numabalancing_migrate_nr_pages = 0;
1868 pgdat->numabalancing_migrate_next_window = jiffies +
1869 msecs_to_jiffies(migrate_interval_millisecs);
1870 spin_unlock(&pgdat->numabalancing_migrate_lock);
1871 }
1872 if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) {
1873 trace_mm_numa_migrate_ratelimit(current, pgdat->node_id,
1874 nr_pages);
1875 return true;
1876 }
1877
1878 /*
1879 * This is an unlocked non-atomic update so errors are possible.
1880 * The consequences are failing to migrate when we potentiall should
1881 * have which is not severe enough to warrant locking. If it is ever
1882 * a problem, it can be converted to a per-cpu counter.
1883 */
1884 pgdat->numabalancing_migrate_nr_pages += nr_pages;
1885 return false;
1886 }
1887
1888 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
1889 {
1890 int page_lru;
1891
1892 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
1893
1894 /* Avoid migrating to a node that is nearly full */
1895 if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
1896 return 0;
1897
1898 if (isolate_lru_page(page))
1899 return 0;
1900
1901 /*
1902 * migrate_misplaced_transhuge_page() skips page migration's usual
1903 * check on page_count(), so we must do it here, now that the page
1904 * has been isolated: a GUP pin, or any other pin, prevents migration.
1905 * The expected page count is 3: 1 for page's mapcount and 1 for the
1906 * caller's pin and 1 for the reference taken by isolate_lru_page().
1907 */
1908 if (PageTransHuge(page) && page_count(page) != 3) {
1909 putback_lru_page(page);
1910 return 0;
1911 }
1912
1913 page_lru = page_is_file_cache(page);
1914 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
1915 hpage_nr_pages(page));
1916
1917 /*
1918 * Isolating the page has taken another reference, so the
1919 * caller's reference can be safely dropped without the page
1920 * disappearing underneath us during migration.
1921 */
1922 put_page(page);
1923 return 1;
1924 }
1925
1926 bool pmd_trans_migrating(pmd_t pmd)
1927 {
1928 struct page *page = pmd_page(pmd);
1929 return PageLocked(page);
1930 }
1931
1932 /*
1933 * Attempt to migrate a misplaced page to the specified destination
1934 * node. Caller is expected to have an elevated reference count on
1935 * the page that will be dropped by this function before returning.
1936 */
1937 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
1938 int node)
1939 {
1940 pg_data_t *pgdat = NODE_DATA(node);
1941 int isolated;
1942 int nr_remaining;
1943 LIST_HEAD(migratepages);
1944
1945 /*
1946 * Don't migrate file pages that are mapped in multiple processes
1947 * with execute permissions as they are probably shared libraries.
1948 */
1949 if (page_mapcount(page) != 1 && page_is_file_cache(page) &&
1950 (vma->vm_flags & VM_EXEC))
1951 goto out;
1952
1953 /*
1954 * Rate-limit the amount of data that is being migrated to a node.
1955 * Optimal placement is no good if the memory bus is saturated and
1956 * all the time is being spent migrating!
1957 */
1958 if (numamigrate_update_ratelimit(pgdat, 1))
1959 goto out;
1960
1961 isolated = numamigrate_isolate_page(pgdat, page);
1962 if (!isolated)
1963 goto out;
1964
1965 list_add(&page->lru, &migratepages);
1966 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
1967 NULL, node, MIGRATE_ASYNC,
1968 MR_NUMA_MISPLACED);
1969 if (nr_remaining) {
1970 if (!list_empty(&migratepages)) {
1971 list_del(&page->lru);
1972 dec_node_page_state(page, NR_ISOLATED_ANON +
1973 page_is_file_cache(page));
1974 putback_lru_page(page);
1975 }
1976 isolated = 0;
1977 } else
1978 count_vm_numa_event(NUMA_PAGE_MIGRATE);
1979 BUG_ON(!list_empty(&migratepages));
1980 return isolated;
1981
1982 out:
1983 put_page(page);
1984 return 0;
1985 }
1986 #endif /* CONFIG_NUMA_BALANCING */
1987
1988 #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1989 /*
1990 * Migrates a THP to a given target node. page must be locked and is unlocked
1991 * before returning.
1992 */
1993 int migrate_misplaced_transhuge_page(struct mm_struct *mm,
1994 struct vm_area_struct *vma,
1995 pmd_t *pmd, pmd_t entry,
1996 unsigned long address,
1997 struct page *page, int node)
1998 {
1999 spinlock_t *ptl;
2000 pg_data_t *pgdat = NODE_DATA(node);
2001 int isolated = 0;
2002 struct page *new_page = NULL;
2003 int page_lru = page_is_file_cache(page);
2004 unsigned long mmun_start = address & HPAGE_PMD_MASK;
2005 unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE;
2006
2007 /*
2008 * Rate-limit the amount of data that is being migrated to a node.
2009 * Optimal placement is no good if the memory bus is saturated and
2010 * all the time is being spent migrating!
2011 */
2012 if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))
2013 goto out_dropref;
2014
2015 new_page = alloc_pages_node(node,
2016 (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2017 HPAGE_PMD_ORDER);
2018 if (!new_page)
2019 goto out_fail;
2020 prep_transhuge_page(new_page);
2021
2022 isolated = numamigrate_isolate_page(pgdat, page);
2023 if (!isolated) {
2024 put_page(new_page);
2025 goto out_fail;
2026 }
2027
2028 /* Prepare a page as a migration target */
2029 __SetPageLocked(new_page);
2030 if (PageSwapBacked(page))
2031 __SetPageSwapBacked(new_page);
2032
2033 /* anon mapping, we can simply copy page->mapping to the new page: */
2034 new_page->mapping = page->mapping;
2035 new_page->index = page->index;
2036 migrate_page_copy(new_page, page);
2037 WARN_ON(PageLRU(new_page));
2038
2039 /* Recheck the target PMD */
2040 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2041 ptl = pmd_lock(mm, pmd);
2042 if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) {
2043 spin_unlock(ptl);
2044 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2045
2046 /* Reverse changes made by migrate_page_copy() */
2047 if (TestClearPageActive(new_page))
2048 SetPageActive(page);
2049 if (TestClearPageUnevictable(new_page))
2050 SetPageUnevictable(page);
2051
2052 unlock_page(new_page);
2053 put_page(new_page); /* Free it */
2054
2055 /* Retake the callers reference and putback on LRU */
2056 get_page(page);
2057 putback_lru_page(page);
2058 mod_node_page_state(page_pgdat(page),
2059 NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
2060
2061 goto out_unlock;
2062 }
2063
2064 entry = mk_huge_pmd(new_page, vma->vm_page_prot);
2065 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
2066
2067 /*
2068 * Clear the old entry under pagetable lock and establish the new PTE.
2069 * Any parallel GUP will either observe the old page blocking on the
2070 * page lock, block on the page table lock or observe the new page.
2071 * The SetPageUptodate on the new page and page_add_new_anon_rmap
2072 * guarantee the copy is visible before the pagetable update.
2073 */
2074 flush_cache_range(vma, mmun_start, mmun_end);
2075 page_add_anon_rmap(new_page, vma, mmun_start, true);
2076 pmdp_huge_clear_flush_notify(vma, mmun_start, pmd);
2077 set_pmd_at(mm, mmun_start, pmd, entry);
2078 update_mmu_cache_pmd(vma, address, &entry);
2079
2080 page_ref_unfreeze(page, 2);
2081 mlock_migrate_page(new_page, page);
2082 page_remove_rmap(page, true);
2083 set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED);
2084
2085 spin_unlock(ptl);
2086 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2087
2088 /* Take an "isolate" reference and put new page on the LRU. */
2089 get_page(new_page);
2090 putback_lru_page(new_page);
2091
2092 unlock_page(new_page);
2093 unlock_page(page);
2094 put_page(page); /* Drop the rmap reference */
2095 put_page(page); /* Drop the LRU isolation reference */
2096
2097 count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
2098 count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
2099
2100 mod_node_page_state(page_pgdat(page),
2101 NR_ISOLATED_ANON + page_lru,
2102 -HPAGE_PMD_NR);
2103 return isolated;
2104
2105 out_fail:
2106 count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
2107 out_dropref:
2108 ptl = pmd_lock(mm, pmd);
2109 if (pmd_same(*pmd, entry)) {
2110 entry = pmd_modify(entry, vma->vm_page_prot);
2111 set_pmd_at(mm, mmun_start, pmd, entry);
2112 update_mmu_cache_pmd(vma, address, &entry);
2113 }
2114 spin_unlock(ptl);
2115
2116 out_unlock:
2117 unlock_page(page);
2118 put_page(page);
2119 return 0;
2120 }
2121 #endif /* CONFIG_NUMA_BALANCING */
2122
2123 #endif /* CONFIG_NUMA */
2124
2125
2126 struct migrate_vma {
2127 struct vm_area_struct *vma;
2128 unsigned long *dst;
2129 unsigned long *src;
2130 unsigned long cpages;
2131 unsigned long npages;
2132 unsigned long start;
2133 unsigned long end;
2134 };
2135
2136 static int migrate_vma_collect_hole(unsigned long start,
2137 unsigned long end,
2138 struct mm_walk *walk)
2139 {
2140 struct migrate_vma *migrate = walk->private;
2141 unsigned long addr;
2142
2143 for (addr = start & PAGE_MASK; addr < end; addr += PAGE_SIZE) {
2144 migrate->dst[migrate->npages] = 0;
2145 migrate->src[migrate->npages++] = 0;
2146 }
2147
2148 return 0;
2149 }
2150
2151 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2152 unsigned long start,
2153 unsigned long end,
2154 struct mm_walk *walk)
2155 {
2156 struct migrate_vma *migrate = walk->private;
2157 struct vm_area_struct *vma = walk->vma;
2158 struct mm_struct *mm = vma->vm_mm;
2159 unsigned long addr = start, unmapped = 0;
2160 spinlock_t *ptl;
2161 pte_t *ptep;
2162
2163 again:
2164 if (pmd_none(*pmdp))
2165 return migrate_vma_collect_hole(start, end, walk);
2166
2167 if (pmd_trans_huge(*pmdp)) {
2168 struct page *page;
2169
2170 ptl = pmd_lock(mm, pmdp);
2171 if (unlikely(!pmd_trans_huge(*pmdp))) {
2172 spin_unlock(ptl);
2173 goto again;
2174 }
2175
2176 page = pmd_page(*pmdp);
2177 if (is_huge_zero_page(page)) {
2178 spin_unlock(ptl);
2179 split_huge_pmd(vma, pmdp, addr);
2180 if (pmd_trans_unstable(pmdp))
2181 return migrate_vma_collect_hole(start, end,
2182 walk);
2183 } else {
2184 int ret;
2185
2186 get_page(page);
2187 spin_unlock(ptl);
2188 if (unlikely(!trylock_page(page)))
2189 return migrate_vma_collect_hole(start, end,
2190 walk);
2191 ret = split_huge_page(page);
2192 unlock_page(page);
2193 put_page(page);
2194 if (ret || pmd_none(*pmdp))
2195 return migrate_vma_collect_hole(start, end,
2196 walk);
2197 }
2198 }
2199
2200 if (unlikely(pmd_bad(*pmdp)))
2201 return migrate_vma_collect_hole(start, end, walk);
2202
2203 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2204 arch_enter_lazy_mmu_mode();
2205
2206 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2207 unsigned long mpfn, pfn;
2208 struct page *page;
2209 swp_entry_t entry;
2210 pte_t pte;
2211
2212 pte = *ptep;
2213 pfn = pte_pfn(pte);
2214
2215 if (pte_none(pte)) {
2216 mpfn = pfn = 0;
2217 goto next;
2218 }
2219
2220 if (!pte_present(pte)) {
2221 mpfn = pfn = 0;
2222
2223 /*
2224 * Only care about unaddressable device page special
2225 * page table entry. Other special swap entries are not
2226 * migratable, and we ignore regular swapped page.
2227 */
2228 entry = pte_to_swp_entry(pte);
2229 if (!is_device_private_entry(entry))
2230 goto next;
2231
2232 page = device_private_entry_to_page(entry);
2233 mpfn = migrate_pfn(page_to_pfn(page))|
2234 MIGRATE_PFN_DEVICE | MIGRATE_PFN_MIGRATE;
2235 if (is_write_device_private_entry(entry))
2236 mpfn |= MIGRATE_PFN_WRITE;
2237 } else {
2238 page = vm_normal_page(migrate->vma, addr, pte);
2239 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2240 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2241 }
2242
2243 /* FIXME support THP */
2244 if (!page || !page->mapping || PageTransCompound(page)) {
2245 mpfn = pfn = 0;
2246 goto next;
2247 }
2248 pfn = page_to_pfn(page);
2249
2250 /*
2251 * By getting a reference on the page we pin it and that blocks
2252 * any kind of migration. Side effect is that it "freezes" the
2253 * pte.
2254 *
2255 * We drop this reference after isolating the page from the lru
2256 * for non device page (device page are not on the lru and thus
2257 * can't be dropped from it).
2258 */
2259 get_page(page);
2260 migrate->cpages++;
2261
2262 /*
2263 * Optimize for the common case where page is only mapped once
2264 * in one process. If we can lock the page, then we can safely
2265 * set up a special migration page table entry now.
2266 */
2267 if (trylock_page(page)) {
2268 pte_t swp_pte;
2269
2270 mpfn |= MIGRATE_PFN_LOCKED;
2271 ptep_get_and_clear(mm, addr, ptep);
2272
2273 /* Setup special migration page table entry */
2274 entry = make_migration_entry(page, pte_write(pte));
2275 swp_pte = swp_entry_to_pte(entry);
2276 if (pte_soft_dirty(pte))
2277 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2278 set_pte_at(mm, addr, ptep, swp_pte);
2279
2280 /*
2281 * This is like regular unmap: we remove the rmap and
2282 * drop page refcount. Page won't be freed, as we took
2283 * a reference just above.
2284 */
2285 page_remove_rmap(page, false);
2286 put_page(page);
2287
2288 if (pte_present(pte))
2289 unmapped++;
2290 }
2291
2292 next:
2293 migrate->dst[migrate->npages] = 0;
2294 migrate->src[migrate->npages++] = mpfn;
2295 }
2296 arch_leave_lazy_mmu_mode();
2297 pte_unmap_unlock(ptep - 1, ptl);
2298
2299 /* Only flush the TLB if we actually modified any entries */
2300 if (unmapped)
2301 flush_tlb_range(walk->vma, start, end);
2302
2303 return 0;
2304 }
2305
2306 /*
2307 * migrate_vma_collect() - collect pages over a range of virtual addresses
2308 * @migrate: migrate struct containing all migration information
2309 *
2310 * This will walk the CPU page table. For each virtual address backed by a
2311 * valid page, it updates the src array and takes a reference on the page, in
2312 * order to pin the page until we lock it and unmap it.
2313 */
2314 static void migrate_vma_collect(struct migrate_vma *migrate)
2315 {
2316 struct mm_walk mm_walk;
2317
2318 mm_walk.pmd_entry = migrate_vma_collect_pmd;
2319 mm_walk.pte_entry = NULL;
2320 mm_walk.pte_hole = migrate_vma_collect_hole;
2321 mm_walk.hugetlb_entry = NULL;
2322 mm_walk.test_walk = NULL;
2323 mm_walk.vma = migrate->vma;
2324 mm_walk.mm = migrate->vma->vm_mm;
2325 mm_walk.private = migrate;
2326
2327 mmu_notifier_invalidate_range_start(mm_walk.mm,
2328 migrate->start,
2329 migrate->end);
2330 walk_page_range(migrate->start, migrate->end, &mm_walk);
2331 mmu_notifier_invalidate_range_end(mm_walk.mm,
2332 migrate->start,
2333 migrate->end);
2334
2335 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2336 }
2337
2338 /*
2339 * migrate_vma_check_page() - check if page is pinned or not
2340 * @page: struct page to check
2341 *
2342 * Pinned pages cannot be migrated. This is the same test as in
2343 * migrate_page_move_mapping(), except that here we allow migration of a
2344 * ZONE_DEVICE page.
2345 */
2346 static bool migrate_vma_check_page(struct page *page)
2347 {
2348 /*
2349 * One extra ref because caller holds an extra reference, either from
2350 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2351 * a device page.
2352 */
2353 int extra = 1;
2354
2355 /*
2356 * FIXME support THP (transparent huge page), it is bit more complex to
2357 * check them than regular pages, because they can be mapped with a pmd
2358 * or with a pte (split pte mapping).
2359 */
2360 if (PageCompound(page))
2361 return false;
2362
2363 /* Page from ZONE_DEVICE have one extra reference */
2364 if (is_zone_device_page(page)) {
2365 /*
2366 * Private page can never be pin as they have no valid pte and
2367 * GUP will fail for those. Yet if there is a pending migration
2368 * a thread might try to wait on the pte migration entry and
2369 * will bump the page reference count. Sadly there is no way to
2370 * differentiate a regular pin from migration wait. Hence to
2371 * avoid 2 racing thread trying to migrate back to CPU to enter
2372 * infinite loop (one stoping migration because the other is
2373 * waiting on pte migration entry). We always return true here.
2374 *
2375 * FIXME proper solution is to rework migration_entry_wait() so
2376 * it does not need to take a reference on page.
2377 */
2378 if (is_device_private_page(page))
2379 return true;
2380
2381 /* Other ZONE_DEVICE memory type are not supported */
2382 return false;
2383 }
2384
2385 if ((page_count(page) - extra) > page_mapcount(page))
2386 return false;
2387
2388 return true;
2389 }
2390
2391 /*
2392 * migrate_vma_prepare() - lock pages and isolate them from the lru
2393 * @migrate: migrate struct containing all migration information
2394 *
2395 * This locks pages that have been collected by migrate_vma_collect(). Once each
2396 * page is locked it is isolated from the lru (for non-device pages). Finally,
2397 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2398 * migrated by concurrent kernel threads.
2399 */
2400 static void migrate_vma_prepare(struct migrate_vma *migrate)
2401 {
2402 const unsigned long npages = migrate->npages;
2403 const unsigned long start = migrate->start;
2404 unsigned long addr, i, restore = 0;
2405 bool allow_drain = true;
2406
2407 lru_add_drain();
2408
2409 for (i = 0; (i < npages) && migrate->cpages; i++) {
2410 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2411 bool remap = true;
2412
2413 if (!page)
2414 continue;
2415
2416 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2417 /*
2418 * Because we are migrating several pages there can be
2419 * a deadlock between 2 concurrent migration where each
2420 * are waiting on each other page lock.
2421 *
2422 * Make migrate_vma() a best effort thing and backoff
2423 * for any page we can not lock right away.
2424 */
2425 if (!trylock_page(page)) {
2426 migrate->src[i] = 0;
2427 migrate->cpages--;
2428 put_page(page);
2429 continue;
2430 }
2431 remap = false;
2432 migrate->src[i] |= MIGRATE_PFN_LOCKED;
2433 }
2434
2435 /* ZONE_DEVICE pages are not on LRU */
2436 if (!is_zone_device_page(page)) {
2437 if (!PageLRU(page) && allow_drain) {
2438 /* Drain CPU's pagevec */
2439 lru_add_drain_all();
2440 allow_drain = false;
2441 }
2442
2443 if (isolate_lru_page(page)) {
2444 if (remap) {
2445 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2446 migrate->cpages--;
2447 restore++;
2448 } else {
2449 migrate->src[i] = 0;
2450 unlock_page(page);
2451 migrate->cpages--;
2452 put_page(page);
2453 }
2454 continue;
2455 }
2456
2457 /* Drop the reference we took in collect */
2458 put_page(page);
2459 }
2460
2461 if (!migrate_vma_check_page(page)) {
2462 if (remap) {
2463 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2464 migrate->cpages--;
2465 restore++;
2466
2467 if (!is_zone_device_page(page)) {
2468 get_page(page);
2469 putback_lru_page(page);
2470 }
2471 } else {
2472 migrate->src[i] = 0;
2473 unlock_page(page);
2474 migrate->cpages--;
2475
2476 if (!is_zone_device_page(page))
2477 putback_lru_page(page);
2478 else
2479 put_page(page);
2480 }
2481 }
2482 }
2483
2484 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2485 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2486
2487 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2488 continue;
2489
2490 remove_migration_pte(page, migrate->vma, addr, page);
2491
2492 migrate->src[i] = 0;
2493 unlock_page(page);
2494 put_page(page);
2495 restore--;
2496 }
2497 }
2498
2499 /*
2500 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2501 * @migrate: migrate struct containing all migration information
2502 *
2503 * Replace page mapping (CPU page table pte) with a special migration pte entry
2504 * and check again if it has been pinned. Pinned pages are restored because we
2505 * cannot migrate them.
2506 *
2507 * This is the last step before we call the device driver callback to allocate
2508 * destination memory and copy contents of original page over to new page.
2509 */
2510 static void migrate_vma_unmap(struct migrate_vma *migrate)
2511 {
2512 int flags = TTU_MIGRATION | TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS;
2513 const unsigned long npages = migrate->npages;
2514 const unsigned long start = migrate->start;
2515 unsigned long addr, i, restore = 0;
2516
2517 for (i = 0; i < npages; i++) {
2518 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2519
2520 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2521 continue;
2522
2523 if (page_mapped(page)) {
2524 try_to_unmap(page, flags);
2525 if (page_mapped(page))
2526 goto restore;
2527 }
2528
2529 if (migrate_vma_check_page(page))
2530 continue;
2531
2532 restore:
2533 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2534 migrate->cpages--;
2535 restore++;
2536 }
2537
2538 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2539 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2540
2541 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2542 continue;
2543
2544 remove_migration_ptes(page, page, false);
2545
2546 migrate->src[i] = 0;
2547 unlock_page(page);
2548 restore--;
2549
2550 if (is_zone_device_page(page))
2551 put_page(page);
2552 else
2553 putback_lru_page(page);
2554 }
2555 }
2556
2557 /*
2558 * migrate_vma_pages() - migrate meta-data from src page to dst page
2559 * @migrate: migrate struct containing all migration information
2560 *
2561 * This migrates struct page meta-data from source struct page to destination
2562 * struct page. This effectively finishes the migration from source page to the
2563 * destination page.
2564 */
2565 static void migrate_vma_pages(struct migrate_vma *migrate)
2566 {
2567 const unsigned long npages = migrate->npages;
2568 const unsigned long start = migrate->start;
2569 unsigned long addr, i;
2570
2571 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2572 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2573 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2574 struct address_space *mapping;
2575 int r;
2576
2577 if (!page || !newpage)
2578 continue;
2579 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2580 continue;
2581
2582 mapping = page_mapping(page);
2583
2584 if (is_zone_device_page(newpage)) {
2585 if (is_device_private_page(newpage)) {
2586 /*
2587 * For now only support private anonymous when
2588 * migrating to un-addressable device memory.
2589 */
2590 if (mapping) {
2591 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2592 continue;
2593 }
2594 } else {
2595 /*
2596 * Other types of ZONE_DEVICE page are not
2597 * supported.
2598 */
2599 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2600 continue;
2601 }
2602 }
2603
2604 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2605 if (r != MIGRATEPAGE_SUCCESS)
2606 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2607 }
2608 }
2609
2610 /*
2611 * migrate_vma_finalize() - restore CPU page table entry
2612 * @migrate: migrate struct containing all migration information
2613 *
2614 * This replaces the special migration pte entry with either a mapping to the
2615 * new page if migration was successful for that page, or to the original page
2616 * otherwise.
2617 *
2618 * This also unlocks the pages and puts them back on the lru, or drops the extra
2619 * refcount, for device pages.
2620 */
2621 static void migrate_vma_finalize(struct migrate_vma *migrate)
2622 {
2623 const unsigned long npages = migrate->npages;
2624 unsigned long i;
2625
2626 for (i = 0; i < npages; i++) {
2627 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2628 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2629
2630 if (!page)
2631 continue;
2632 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
2633 if (newpage) {
2634 unlock_page(newpage);
2635 put_page(newpage);
2636 }
2637 newpage = page;
2638 }
2639
2640 remove_migration_ptes(page, newpage, false);
2641 unlock_page(page);
2642 migrate->cpages--;
2643
2644 if (is_zone_device_page(page))
2645 put_page(page);
2646 else
2647 putback_lru_page(page);
2648
2649 if (newpage != page) {
2650 unlock_page(newpage);
2651 if (is_zone_device_page(newpage))
2652 put_page(newpage);
2653 else
2654 putback_lru_page(newpage);
2655 }
2656 }
2657 }
2658
2659 /*
2660 * migrate_vma() - migrate a range of memory inside vma
2661 *
2662 * @ops: migration callback for allocating destination memory and copying
2663 * @vma: virtual memory area containing the range to be migrated
2664 * @start: start address of the range to migrate (inclusive)
2665 * @end: end address of the range to migrate (exclusive)
2666 * @src: array of hmm_pfn_t containing source pfns
2667 * @dst: array of hmm_pfn_t containing destination pfns
2668 * @private: pointer passed back to each of the callback
2669 * Returns: 0 on success, error code otherwise
2670 *
2671 * This function tries to migrate a range of memory virtual address range, using
2672 * callbacks to allocate and copy memory from source to destination. First it
2673 * collects all the pages backing each virtual address in the range, saving this
2674 * inside the src array. Then it locks those pages and unmaps them. Once the pages
2675 * are locked and unmapped, it checks whether each page is pinned or not. Pages
2676 * that aren't pinned have the MIGRATE_PFN_MIGRATE flag set (by this function)
2677 * in the corresponding src array entry. It then restores any pages that are
2678 * pinned, by remapping and unlocking those pages.
2679 *
2680 * At this point it calls the alloc_and_copy() callback. For documentation on
2681 * what is expected from that callback, see struct migrate_vma_ops comments in
2682 * include/linux/migrate.h
2683 *
2684 * After the alloc_and_copy() callback, this function goes over each entry in
2685 * the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2686 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2687 * then the function tries to migrate struct page information from the source
2688 * struct page to the destination struct page. If it fails to migrate the struct
2689 * page information, then it clears the MIGRATE_PFN_MIGRATE flag in the src
2690 * array.
2691 *
2692 * At this point all successfully migrated pages have an entry in the src
2693 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2694 * array entry with MIGRATE_PFN_VALID flag set.
2695 *
2696 * It then calls the finalize_and_map() callback. See comments for "struct
2697 * migrate_vma_ops", in include/linux/migrate.h for details about
2698 * finalize_and_map() behavior.
2699 *
2700 * After the finalize_and_map() callback, for successfully migrated pages, this
2701 * function updates the CPU page table to point to new pages, otherwise it
2702 * restores the CPU page table to point to the original source pages.
2703 *
2704 * Function returns 0 after the above steps, even if no pages were migrated
2705 * (The function only returns an error if any of the arguments are invalid.)
2706 *
2707 * Both src and dst array must be big enough for (end - start) >> PAGE_SHIFT
2708 * unsigned long entries.
2709 */
2710 int migrate_vma(const struct migrate_vma_ops *ops,
2711 struct vm_area_struct *vma,
2712 unsigned long start,
2713 unsigned long end,
2714 unsigned long *src,
2715 unsigned long *dst,
2716 void *private)
2717 {
2718 struct migrate_vma migrate;
2719
2720 /* Sanity check the arguments */
2721 start &= PAGE_MASK;
2722 end &= PAGE_MASK;
2723 if (!vma || is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_SPECIAL))
2724 return -EINVAL;
2725 if (start < vma->vm_start || start >= vma->vm_end)
2726 return -EINVAL;
2727 if (end <= vma->vm_start || end > vma->vm_end)
2728 return -EINVAL;
2729 if (!ops || !src || !dst || start >= end)
2730 return -EINVAL;
2731
2732 memset(src, 0, sizeof(*src) * ((end - start) >> PAGE_SHIFT));
2733 migrate.src = src;
2734 migrate.dst = dst;
2735 migrate.start = start;
2736 migrate.npages = 0;
2737 migrate.cpages = 0;
2738 migrate.end = end;
2739 migrate.vma = vma;
2740
2741 /* Collect, and try to unmap source pages */
2742 migrate_vma_collect(&migrate);
2743 if (!migrate.cpages)
2744 return 0;
2745
2746 /* Lock and isolate page */
2747 migrate_vma_prepare(&migrate);
2748 if (!migrate.cpages)
2749 return 0;
2750
2751 /* Unmap pages */
2752 migrate_vma_unmap(&migrate);
2753 if (!migrate.cpages)
2754 return 0;
2755
2756 /*
2757 * At this point pages are locked and unmapped, and thus they have
2758 * stable content and can safely be copied to destination memory that
2759 * is allocated by the callback.
2760 *
2761 * Note that migration can fail in migrate_vma_struct_page() for each
2762 * individual page.
2763 */
2764 ops->alloc_and_copy(vma, src, dst, start, end, private);
2765
2766 /* This does the real migration of struct page */
2767 migrate_vma_pages(&migrate);
2768
2769 ops->finalize_and_map(vma, src, dst, start, end, private);
2770
2771 /* Unlock and remap pages */
2772 migrate_vma_finalize(&migrate);
2773
2774 return 0;
2775 }
2776 EXPORT_SYMBOL(migrate_vma);