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