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_hugetlb().
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 err = isolate_hugetlb(page, pagelist);
1646 if (!err)
1647 err = 1;
1648 }
1649 } else {
1650 struct page *head;
1651
1652 head = compound_head(page);
1653 err = isolate_lru_page(head);
1654 if (err)
1655 goto out_putpage;
1656
1657 err = 1;
1658 list_add_tail(&head->lru, pagelist);
1659 mod_node_page_state(page_pgdat(head),
1660 NR_ISOLATED_ANON + page_is_file_lru(head),
1661 thp_nr_pages(head));
1662 }
1663 out_putpage:
1664 /*
1665 * Either remove the duplicate refcount from
1666 * isolate_lru_page() or drop the page ref if it was
1667 * not isolated.
1668 */
1669 put_user_page(page);
1670 out:
1671 mmap_read_unlock(mm);
1672 return err;
1673 }
1674
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)1675 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1676 struct list_head *pagelist, int __user *status,
1677 int start, int i, unsigned long nr_pages)
1678 {
1679 int err;
1680
1681 if (list_empty(pagelist))
1682 return 0;
1683
1684 err = do_move_pages_to_node(mm, pagelist, node);
1685 if (err) {
1686 /*
1687 * Positive err means the number of failed
1688 * pages to migrate. Since we are going to
1689 * abort and return the number of non-migrated
1690 * pages, so need to incude the rest of the
1691 * nr_pages that have not been attempted as
1692 * well.
1693 */
1694 if (err > 0)
1695 err += nr_pages - i - 1;
1696 return err;
1697 }
1698 return store_status(status, start, node, i - start);
1699 }
1700
1701 /*
1702 * Migrate an array of page address onto an array of nodes and fill
1703 * the corresponding array of status.
1704 */
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)1705 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1706 unsigned long nr_pages,
1707 const void __user * __user *pages,
1708 const int __user *nodes,
1709 int __user *status, int flags)
1710 {
1711 int current_node = NUMA_NO_NODE;
1712 LIST_HEAD(pagelist);
1713 int start, i;
1714 int err = 0, err1;
1715
1716 lru_cache_disable();
1717
1718 for (i = start = 0; i < nr_pages; i++) {
1719 const void __user *p;
1720 unsigned long addr;
1721 int node;
1722
1723 err = -EFAULT;
1724 if (get_user(p, pages + i))
1725 goto out_flush;
1726 if (get_user(node, nodes + i))
1727 goto out_flush;
1728 addr = (unsigned long)untagged_addr(p);
1729
1730 err = -ENODEV;
1731 if (node < 0 || node >= MAX_NUMNODES)
1732 goto out_flush;
1733 if (!node_state(node, N_MEMORY))
1734 goto out_flush;
1735
1736 err = -EACCES;
1737 if (!node_isset(node, task_nodes))
1738 goto out_flush;
1739
1740 if (current_node == NUMA_NO_NODE) {
1741 current_node = node;
1742 start = i;
1743 } else if (node != current_node) {
1744 err = move_pages_and_store_status(mm, current_node,
1745 &pagelist, status, start, i, nr_pages);
1746 if (err)
1747 goto out;
1748 start = i;
1749 current_node = node;
1750 }
1751
1752 /*
1753 * Errors in the page lookup or isolation are not fatal and we simply
1754 * report them via status
1755 */
1756 err = add_page_for_migration(mm, addr, current_node,
1757 &pagelist, flags & MPOL_MF_MOVE_ALL);
1758
1759 if (err > 0) {
1760 /* The page is successfully queued for migration */
1761 continue;
1762 }
1763
1764 /*
1765 * If the page is already on the target node (!err), store the
1766 * node, otherwise, store the err.
1767 */
1768 err = store_status(status, i, err ? : current_node, 1);
1769 if (err)
1770 goto out_flush;
1771
1772 err = move_pages_and_store_status(mm, current_node, &pagelist,
1773 status, start, i, nr_pages);
1774 if (err)
1775 goto out;
1776 current_node = NUMA_NO_NODE;
1777 }
1778 out_flush:
1779 /* Make sure we do not overwrite the existing error */
1780 err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1781 status, start, i, nr_pages);
1782 if (err >= 0)
1783 err = err1;
1784 out:
1785 lru_cache_enable();
1786 return err;
1787 }
1788
1789 /*
1790 * Determine the nodes of an array of pages and store it in an array of status.
1791 */
do_pages_stat_array(struct mm_struct * mm,unsigned long nr_pages,const void __user ** pages,int * status)1792 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1793 const void __user **pages, int *status)
1794 {
1795 unsigned long i;
1796
1797 mmap_read_lock(mm);
1798
1799 for (i = 0; i < nr_pages; i++) {
1800 unsigned long addr = (unsigned long)(*pages);
1801 struct vm_area_struct *vma;
1802 struct page *page;
1803 int err = -EFAULT;
1804
1805 vma = find_vma(mm, addr);
1806 if (!vma || addr < vma->vm_start)
1807 goto set_status;
1808
1809 /* FOLL_DUMP to ignore special (like zero) pages */
1810 page = follow_page(vma, addr, FOLL_DUMP);
1811
1812 err = PTR_ERR(page);
1813 if (IS_ERR(page))
1814 goto set_status;
1815
1816 err = page ? page_to_nid(page) : -ENOENT;
1817 set_status:
1818 *status = err;
1819
1820 pages++;
1821 status++;
1822 }
1823
1824 mmap_read_unlock(mm);
1825 }
1826
1827 /*
1828 * Determine the nodes of a user array of pages and store it in
1829 * a user array of status.
1830 */
do_pages_stat(struct mm_struct * mm,unsigned long nr_pages,const void __user * __user * pages,int __user * status)1831 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1832 const void __user * __user *pages,
1833 int __user *status)
1834 {
1835 #define DO_PAGES_STAT_CHUNK_NR 16
1836 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1837 int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1838
1839 while (nr_pages) {
1840 unsigned long chunk_nr;
1841
1842 chunk_nr = nr_pages;
1843 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1844 chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1845
1846 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1847 break;
1848
1849 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1850
1851 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1852 break;
1853
1854 pages += chunk_nr;
1855 status += chunk_nr;
1856 nr_pages -= chunk_nr;
1857 }
1858 return nr_pages ? -EFAULT : 0;
1859 }
1860
find_mm_struct(pid_t pid,nodemask_t * mem_nodes)1861 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1862 {
1863 struct task_struct *task;
1864 struct mm_struct *mm;
1865
1866 /*
1867 * There is no need to check if current process has the right to modify
1868 * the specified process when they are same.
1869 */
1870 if (!pid) {
1871 mmget(current->mm);
1872 *mem_nodes = cpuset_mems_allowed(current);
1873 return current->mm;
1874 }
1875
1876 /* Find the mm_struct */
1877 rcu_read_lock();
1878 task = find_task_by_vpid(pid);
1879 if (!task) {
1880 rcu_read_unlock();
1881 return ERR_PTR(-ESRCH);
1882 }
1883 get_task_struct(task);
1884
1885 /*
1886 * Check if this process has the right to modify the specified
1887 * process. Use the regular "ptrace_may_access()" checks.
1888 */
1889 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1890 rcu_read_unlock();
1891 mm = ERR_PTR(-EPERM);
1892 goto out;
1893 }
1894 rcu_read_unlock();
1895
1896 mm = ERR_PTR(security_task_movememory(task));
1897 if (IS_ERR(mm))
1898 goto out;
1899 *mem_nodes = cpuset_mems_allowed(task);
1900 mm = get_task_mm(task);
1901 out:
1902 put_task_struct(task);
1903 if (!mm)
1904 mm = ERR_PTR(-EINVAL);
1905 return mm;
1906 }
1907
1908 /*
1909 * Move a list of pages in the address space of the currently executing
1910 * process.
1911 */
kernel_move_pages(pid_t pid,unsigned long nr_pages,const void __user * __user * pages,const int __user * nodes,int __user * status,int flags)1912 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
1913 const void __user * __user *pages,
1914 const int __user *nodes,
1915 int __user *status, int flags)
1916 {
1917 struct mm_struct *mm;
1918 int err;
1919 nodemask_t task_nodes;
1920
1921 /* Check flags */
1922 if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1923 return -EINVAL;
1924
1925 if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1926 return -EPERM;
1927
1928 mm = find_mm_struct(pid, &task_nodes);
1929 if (IS_ERR(mm))
1930 return PTR_ERR(mm);
1931
1932 if (nodes)
1933 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1934 nodes, status, flags);
1935 else
1936 err = do_pages_stat(mm, nr_pages, pages, status);
1937
1938 mmput(mm);
1939 return err;
1940 }
1941
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)1942 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1943 const void __user * __user *, pages,
1944 const int __user *, nodes,
1945 int __user *, status, int, flags)
1946 {
1947 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1948 }
1949
1950 #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)1951 COMPAT_SYSCALL_DEFINE6(move_pages, pid_t, pid, compat_ulong_t, nr_pages,
1952 compat_uptr_t __user *, pages32,
1953 const int __user *, nodes,
1954 int __user *, status,
1955 int, flags)
1956 {
1957 const void __user * __user *pages;
1958 int i;
1959
1960 pages = compat_alloc_user_space(nr_pages * sizeof(void *));
1961 for (i = 0; i < nr_pages; i++) {
1962 compat_uptr_t p;
1963
1964 if (get_user(p, pages32 + i) ||
1965 put_user(compat_ptr(p), pages + i))
1966 return -EFAULT;
1967 }
1968 return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1969 }
1970 #endif /* CONFIG_COMPAT */
1971
1972 #ifdef CONFIG_NUMA_BALANCING
1973 /*
1974 * Returns true if this is a safe migration target node for misplaced NUMA
1975 * pages. Currently it only checks the watermarks which crude
1976 */
migrate_balanced_pgdat(struct pglist_data * pgdat,unsigned long nr_migrate_pages)1977 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1978 unsigned long nr_migrate_pages)
1979 {
1980 int z;
1981
1982 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1983 struct zone *zone = pgdat->node_zones + z;
1984
1985 if (!populated_zone(zone))
1986 continue;
1987
1988 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1989 if (!zone_watermark_ok(zone, 0,
1990 high_wmark_pages(zone) +
1991 nr_migrate_pages,
1992 ZONE_MOVABLE, 0))
1993 continue;
1994 return true;
1995 }
1996 return false;
1997 }
1998
alloc_misplaced_dst_page(struct page * page,unsigned long data)1999 static struct page *alloc_misplaced_dst_page(struct page *page,
2000 unsigned long data)
2001 {
2002 int nid = (int) data;
2003 struct page *newpage;
2004
2005 newpage = __alloc_pages_node(nid,
2006 (GFP_HIGHUSER_MOVABLE |
2007 __GFP_THISNODE | __GFP_NOMEMALLOC |
2008 __GFP_NORETRY | __GFP_NOWARN) &
2009 ~__GFP_RECLAIM, 0);
2010
2011 return newpage;
2012 }
2013
numamigrate_isolate_page(pg_data_t * pgdat,struct page * page)2014 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2015 {
2016 int page_lru;
2017
2018 VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2019
2020 /* Avoid migrating to a node that is nearly full */
2021 if (!migrate_balanced_pgdat(pgdat, compound_nr(page)))
2022 return 0;
2023
2024 if (isolate_lru_page(page))
2025 return 0;
2026
2027 /*
2028 * migrate_misplaced_transhuge_page() skips page migration's usual
2029 * check on page_count(), so we must do it here, now that the page
2030 * has been isolated: a GUP pin, or any other pin, prevents migration.
2031 * The expected page count is 3: 1 for page's mapcount and 1 for the
2032 * caller's pin and 1 for the reference taken by isolate_lru_page().
2033 */
2034 if (PageTransHuge(page) && page_count(page) != 3) {
2035 putback_lru_page(page);
2036 return 0;
2037 }
2038
2039 page_lru = page_is_file_lru(page);
2040 mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2041 thp_nr_pages(page));
2042
2043 /*
2044 * Isolating the page has taken another reference, so the
2045 * caller's reference can be safely dropped without the page
2046 * disappearing underneath us during migration.
2047 */
2048 put_page(page);
2049 return 1;
2050 }
2051
pmd_trans_migrating(pmd_t pmd)2052 bool pmd_trans_migrating(pmd_t pmd)
2053 {
2054 struct page *page = pmd_page(pmd);
2055 return PageLocked(page);
2056 }
2057
2058 /*
2059 * Attempt to migrate a misplaced page to the specified destination
2060 * node. Caller is expected to have an elevated reference count on
2061 * the page that will be dropped by this function before returning.
2062 */
migrate_misplaced_page(struct page * page,struct vm_fault * vmf,int node)2063 int migrate_misplaced_page(struct page *page, struct vm_fault *vmf,
2064 int node)
2065 {
2066 pg_data_t *pgdat = NODE_DATA(node);
2067 int isolated;
2068 int nr_remaining;
2069 LIST_HEAD(migratepages);
2070
2071 /*
2072 * Don't migrate file pages that are mapped in multiple processes
2073 * with execute permissions as they are probably shared libraries.
2074 */
2075 if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2076 (vmf->vma_flags & VM_EXEC))
2077 goto out;
2078
2079 /*
2080 * Also do not migrate dirty pages as not all filesystems can move
2081 * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2082 */
2083 if (page_is_file_lru(page) && PageDirty(page))
2084 goto out;
2085
2086 isolated = numamigrate_isolate_page(pgdat, page);
2087 if (!isolated)
2088 goto out;
2089
2090 list_add(&page->lru, &migratepages);
2091 nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2092 NULL, node, MIGRATE_ASYNC,
2093 MR_NUMA_MISPLACED);
2094 if (nr_remaining) {
2095 if (!list_empty(&migratepages)) {
2096 list_del(&page->lru);
2097 dec_node_page_state(page, NR_ISOLATED_ANON +
2098 page_is_file_lru(page));
2099 putback_lru_page(page);
2100 }
2101 isolated = 0;
2102 } else
2103 count_vm_numa_event(NUMA_PAGE_MIGRATE);
2104 BUG_ON(!list_empty(&migratepages));
2105 return isolated;
2106
2107 out:
2108 put_page(page);
2109 return 0;
2110 }
2111 #endif /* CONFIG_NUMA_BALANCING */
2112
2113 #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2114 /*
2115 * Migrates a THP to a given target node. page must be locked and is unlocked
2116 * before returning.
2117 */
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)2118 int migrate_misplaced_transhuge_page(struct mm_struct *mm,
2119 struct vm_area_struct *vma,
2120 pmd_t *pmd, pmd_t entry,
2121 unsigned long address,
2122 struct page *page, int node)
2123 {
2124 spinlock_t *ptl;
2125 pg_data_t *pgdat = NODE_DATA(node);
2126 int isolated = 0;
2127 struct page *new_page = NULL;
2128 int page_lru = page_is_file_lru(page);
2129 unsigned long start = address & HPAGE_PMD_MASK;
2130
2131 new_page = alloc_pages_node(node,
2132 (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2133 HPAGE_PMD_ORDER);
2134 if (!new_page)
2135 goto out_fail;
2136 prep_transhuge_page(new_page);
2137
2138 isolated = numamigrate_isolate_page(pgdat, page);
2139 if (!isolated) {
2140 put_page(new_page);
2141 goto out_fail;
2142 }
2143
2144 /* Prepare a page as a migration target */
2145 __SetPageLocked(new_page);
2146 if (PageSwapBacked(page))
2147 __SetPageSwapBacked(new_page);
2148
2149 /* anon mapping, we can simply copy page->mapping to the new page: */
2150 new_page->mapping = page->mapping;
2151 new_page->index = page->index;
2152 /* flush the cache before copying using the kernel virtual address */
2153 flush_cache_range(vma, start, start + HPAGE_PMD_SIZE);
2154 migrate_page_copy(new_page, page);
2155 WARN_ON(PageLRU(new_page));
2156
2157 /* Recheck the target PMD */
2158 ptl = pmd_lock(mm, pmd);
2159 if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) {
2160 spin_unlock(ptl);
2161
2162 /* Reverse changes made by migrate_page_copy() */
2163 if (TestClearPageActive(new_page))
2164 SetPageActive(page);
2165 if (TestClearPageUnevictable(new_page))
2166 SetPageUnevictable(page);
2167
2168 unlock_page(new_page);
2169 put_page(new_page); /* Free it */
2170
2171 /* Retake the callers reference and putback on LRU */
2172 get_page(page);
2173 putback_lru_page(page);
2174 mod_node_page_state(page_pgdat(page),
2175 NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
2176
2177 goto out_unlock;
2178 }
2179
2180 entry = mk_huge_pmd(new_page, vma->vm_page_prot);
2181 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
2182
2183 /*
2184 * Overwrite the old entry under pagetable lock and establish
2185 * the new PTE. Any parallel GUP will either observe the old
2186 * page blocking on the page lock, block on the page table
2187 * lock or observe the new page. The SetPageUptodate on the
2188 * new page and page_add_new_anon_rmap guarantee the copy is
2189 * visible before the pagetable update.
2190 */
2191 page_add_anon_rmap(new_page, vma, start, true);
2192 /*
2193 * At this point the pmd is numa/protnone (i.e. non present) and the TLB
2194 * has already been flushed globally. So no TLB can be currently
2195 * caching this non present pmd mapping. There's no need to clear the
2196 * pmd before doing set_pmd_at(), nor to flush the TLB after
2197 * set_pmd_at(). Clearing the pmd here would introduce a race
2198 * condition against MADV_DONTNEED, because MADV_DONTNEED only holds the
2199 * mmap_lock for reading. If the pmd is set to NULL at any given time,
2200 * MADV_DONTNEED won't wait on the pmd lock and it'll skip clearing this
2201 * pmd.
2202 */
2203 set_pmd_at(mm, start, pmd, entry);
2204 update_mmu_cache_pmd(vma, address, &entry);
2205
2206 page_ref_unfreeze(page, 2);
2207 mlock_migrate_page(new_page, page);
2208 page_remove_rmap(page, true);
2209 set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED);
2210
2211 spin_unlock(ptl);
2212
2213 /* Take an "isolate" reference and put new page on the LRU. */
2214 get_page(new_page);
2215 putback_lru_page(new_page);
2216
2217 unlock_page(new_page);
2218 unlock_page(page);
2219 put_page(page); /* Drop the rmap reference */
2220 put_page(page); /* Drop the LRU isolation reference */
2221
2222 count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
2223 count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
2224
2225 mod_node_page_state(page_pgdat(page),
2226 NR_ISOLATED_ANON + page_lru,
2227 -HPAGE_PMD_NR);
2228 return isolated;
2229
2230 out_fail:
2231 count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
2232 ptl = pmd_lock(mm, pmd);
2233 if (pmd_same(*pmd, entry)) {
2234 entry = pmd_modify(entry, vma->vm_page_prot);
2235 set_pmd_at(mm, start, pmd, entry);
2236 update_mmu_cache_pmd(vma, address, &entry);
2237 }
2238 spin_unlock(ptl);
2239
2240 out_unlock:
2241 unlock_page(page);
2242 put_page(page);
2243 return 0;
2244 }
2245 #endif /* CONFIG_NUMA_BALANCING */
2246
2247 #endif /* CONFIG_NUMA */
2248
2249 #ifdef CONFIG_DEVICE_PRIVATE
migrate_vma_collect_hole(unsigned long start,unsigned long end,__always_unused int depth,struct mm_walk * walk)2250 static int migrate_vma_collect_hole(unsigned long start,
2251 unsigned long end,
2252 __always_unused int depth,
2253 struct mm_walk *walk)
2254 {
2255 struct migrate_vma *migrate = walk->private;
2256 unsigned long addr;
2257
2258 /* Only allow populating anonymous memory. */
2259 if (!vma_is_anonymous(walk->vma)) {
2260 for (addr = start; addr < end; addr += PAGE_SIZE) {
2261 migrate->src[migrate->npages] = 0;
2262 migrate->dst[migrate->npages] = 0;
2263 migrate->npages++;
2264 }
2265 return 0;
2266 }
2267
2268 for (addr = start; addr < end; addr += PAGE_SIZE) {
2269 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2270 migrate->dst[migrate->npages] = 0;
2271 migrate->npages++;
2272 migrate->cpages++;
2273 }
2274
2275 return 0;
2276 }
2277
migrate_vma_collect_skip(unsigned long start,unsigned long end,struct mm_walk * walk)2278 static int migrate_vma_collect_skip(unsigned long start,
2279 unsigned long end,
2280 struct mm_walk *walk)
2281 {
2282 struct migrate_vma *migrate = walk->private;
2283 unsigned long addr;
2284
2285 for (addr = start; addr < end; addr += PAGE_SIZE) {
2286 migrate->dst[migrate->npages] = 0;
2287 migrate->src[migrate->npages++] = 0;
2288 }
2289
2290 return 0;
2291 }
2292
migrate_vma_collect_pmd(pmd_t * pmdp,unsigned long start,unsigned long end,struct mm_walk * walk)2293 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2294 unsigned long start,
2295 unsigned long end,
2296 struct mm_walk *walk)
2297 {
2298 struct migrate_vma *migrate = walk->private;
2299 struct vm_area_struct *vma = walk->vma;
2300 struct mm_struct *mm = vma->vm_mm;
2301 unsigned long addr = start, unmapped = 0;
2302 spinlock_t *ptl;
2303 pte_t *ptep;
2304
2305 again:
2306 if (pmd_none(*pmdp))
2307 return migrate_vma_collect_hole(start, end, -1, walk);
2308
2309 if (pmd_trans_huge(*pmdp)) {
2310 struct page *page;
2311
2312 ptl = pmd_lock(mm, pmdp);
2313 if (unlikely(!pmd_trans_huge(*pmdp))) {
2314 spin_unlock(ptl);
2315 goto again;
2316 }
2317
2318 page = pmd_page(*pmdp);
2319 if (is_huge_zero_page(page)) {
2320 spin_unlock(ptl);
2321 split_huge_pmd(vma, pmdp, addr);
2322 if (pmd_trans_unstable(pmdp))
2323 return migrate_vma_collect_skip(start, end,
2324 walk);
2325 } else {
2326 int ret;
2327
2328 get_page(page);
2329 spin_unlock(ptl);
2330 if (unlikely(!trylock_page(page)))
2331 return migrate_vma_collect_skip(start, end,
2332 walk);
2333 ret = split_huge_page(page);
2334 unlock_page(page);
2335 put_page(page);
2336 if (ret)
2337 return migrate_vma_collect_skip(start, end,
2338 walk);
2339 if (pmd_none(*pmdp))
2340 return migrate_vma_collect_hole(start, end, -1,
2341 walk);
2342 }
2343 }
2344
2345 if (unlikely(pmd_bad(*pmdp)))
2346 return migrate_vma_collect_skip(start, end, walk);
2347
2348 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2349 arch_enter_lazy_mmu_mode();
2350
2351 for (; addr < end; addr += PAGE_SIZE, ptep++) {
2352 unsigned long mpfn = 0, pfn;
2353 struct page *page;
2354 swp_entry_t entry;
2355 pte_t pte;
2356
2357 pte = *ptep;
2358
2359 if (pte_none(pte)) {
2360 if (vma_is_anonymous(vma)) {
2361 mpfn = MIGRATE_PFN_MIGRATE;
2362 migrate->cpages++;
2363 }
2364 goto next;
2365 }
2366
2367 if (!pte_present(pte)) {
2368 /*
2369 * Only care about unaddressable device page special
2370 * page table entry. Other special swap entries are not
2371 * migratable, and we ignore regular swapped page.
2372 */
2373 entry = pte_to_swp_entry(pte);
2374 if (!is_device_private_entry(entry))
2375 goto next;
2376
2377 page = device_private_entry_to_page(entry);
2378 if (!(migrate->flags &
2379 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2380 page->pgmap->owner != migrate->pgmap_owner)
2381 goto next;
2382
2383 mpfn = migrate_pfn(page_to_pfn(page)) |
2384 MIGRATE_PFN_MIGRATE;
2385 if (is_write_device_private_entry(entry))
2386 mpfn |= MIGRATE_PFN_WRITE;
2387 } else {
2388 if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2389 goto next;
2390 pfn = pte_pfn(pte);
2391 if (is_zero_pfn(pfn)) {
2392 mpfn = MIGRATE_PFN_MIGRATE;
2393 migrate->cpages++;
2394 goto next;
2395 }
2396 page = vm_normal_page(migrate->vma, addr, pte);
2397 mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2398 mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2399 }
2400
2401 /* FIXME support THP */
2402 if (!page || !page->mapping || PageTransCompound(page)) {
2403 mpfn = 0;
2404 goto next;
2405 }
2406
2407 /*
2408 * By getting a reference on the page we pin it and that blocks
2409 * any kind of migration. Side effect is that it "freezes" the
2410 * pte.
2411 *
2412 * We drop this reference after isolating the page from the lru
2413 * for non device page (device page are not on the lru and thus
2414 * can't be dropped from it).
2415 */
2416 get_page(page);
2417 migrate->cpages++;
2418
2419 /*
2420 * Optimize for the common case where page is only mapped once
2421 * in one process. If we can lock the page, then we can safely
2422 * set up a special migration page table entry now.
2423 */
2424 if (trylock_page(page)) {
2425 pte_t swp_pte;
2426
2427 mpfn |= MIGRATE_PFN_LOCKED;
2428 ptep_get_and_clear(mm, addr, ptep);
2429
2430 /* Setup special migration page table entry */
2431 entry = make_migration_entry(page, mpfn &
2432 MIGRATE_PFN_WRITE);
2433 swp_pte = swp_entry_to_pte(entry);
2434 if (pte_present(pte)) {
2435 if (pte_soft_dirty(pte))
2436 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2437 if (pte_uffd_wp(pte))
2438 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2439 } else {
2440 if (pte_swp_soft_dirty(pte))
2441 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2442 if (pte_swp_uffd_wp(pte))
2443 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2444 }
2445 set_pte_at(mm, addr, ptep, swp_pte);
2446
2447 /*
2448 * This is like regular unmap: we remove the rmap and
2449 * drop page refcount. Page won't be freed, as we took
2450 * a reference just above.
2451 */
2452 page_remove_rmap(page, false);
2453 put_page(page);
2454
2455 if (pte_present(pte))
2456 unmapped++;
2457 }
2458
2459 next:
2460 migrate->dst[migrate->npages] = 0;
2461 migrate->src[migrate->npages++] = mpfn;
2462 }
2463
2464 /* Only flush the TLB if we actually modified any entries */
2465 if (unmapped)
2466 flush_tlb_range(walk->vma, start, end);
2467
2468 arch_leave_lazy_mmu_mode();
2469 pte_unmap_unlock(ptep - 1, ptl);
2470
2471 return 0;
2472 }
2473
2474 static const struct mm_walk_ops migrate_vma_walk_ops = {
2475 .pmd_entry = migrate_vma_collect_pmd,
2476 .pte_hole = migrate_vma_collect_hole,
2477 };
2478
2479 /*
2480 * migrate_vma_collect() - collect pages over a range of virtual addresses
2481 * @migrate: migrate struct containing all migration information
2482 *
2483 * This will walk the CPU page table. For each virtual address backed by a
2484 * valid page, it updates the src array and takes a reference on the page, in
2485 * order to pin the page until we lock it and unmap it.
2486 */
migrate_vma_collect(struct migrate_vma * migrate)2487 static void migrate_vma_collect(struct migrate_vma *migrate)
2488 {
2489 struct mmu_notifier_range range;
2490
2491 /*
2492 * Note that the pgmap_owner is passed to the mmu notifier callback so
2493 * that the registered device driver can skip invalidating device
2494 * private page mappings that won't be migrated.
2495 */
2496 mmu_notifier_range_init_migrate(&range, 0, migrate->vma,
2497 migrate->vma->vm_mm, migrate->start, migrate->end,
2498 migrate->pgmap_owner);
2499 mmu_notifier_invalidate_range_start(&range);
2500
2501 walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2502 &migrate_vma_walk_ops, migrate);
2503
2504 mmu_notifier_invalidate_range_end(&range);
2505 migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2506 }
2507
2508 /*
2509 * migrate_vma_check_page() - check if page is pinned or not
2510 * @page: struct page to check
2511 *
2512 * Pinned pages cannot be migrated. This is the same test as in
2513 * migrate_page_move_mapping(), except that here we allow migration of a
2514 * ZONE_DEVICE page.
2515 */
migrate_vma_check_page(struct page * page)2516 static bool migrate_vma_check_page(struct page *page)
2517 {
2518 /*
2519 * One extra ref because caller holds an extra reference, either from
2520 * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2521 * a device page.
2522 */
2523 int extra = 1;
2524
2525 /*
2526 * FIXME support THP (transparent huge page), it is bit more complex to
2527 * check them than regular pages, because they can be mapped with a pmd
2528 * or with a pte (split pte mapping).
2529 */
2530 if (PageCompound(page))
2531 return false;
2532
2533 /* Page from ZONE_DEVICE have one extra reference */
2534 if (is_zone_device_page(page)) {
2535 /*
2536 * Private page can never be pin as they have no valid pte and
2537 * GUP will fail for those. Yet if there is a pending migration
2538 * a thread might try to wait on the pte migration entry and
2539 * will bump the page reference count. Sadly there is no way to
2540 * differentiate a regular pin from migration wait. Hence to
2541 * avoid 2 racing thread trying to migrate back to CPU to enter
2542 * infinite loop (one stoping migration because the other is
2543 * waiting on pte migration entry). We always return true here.
2544 *
2545 * FIXME proper solution is to rework migration_entry_wait() so
2546 * it does not need to take a reference on page.
2547 */
2548 return is_device_private_page(page);
2549 }
2550
2551 /* For file back page */
2552 if (page_mapping(page))
2553 extra += 1 + page_has_private(page);
2554
2555 if ((page_count(page) - extra) > page_mapcount(page))
2556 return false;
2557
2558 return true;
2559 }
2560
2561 /*
2562 * migrate_vma_prepare() - lock pages and isolate them from the lru
2563 * @migrate: migrate struct containing all migration information
2564 *
2565 * This locks pages that have been collected by migrate_vma_collect(). Once each
2566 * page is locked it is isolated from the lru (for non-device pages). Finally,
2567 * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2568 * migrated by concurrent kernel threads.
2569 */
migrate_vma_prepare(struct migrate_vma * migrate)2570 static void migrate_vma_prepare(struct migrate_vma *migrate)
2571 {
2572 const unsigned long npages = migrate->npages;
2573 const unsigned long start = migrate->start;
2574 unsigned long addr, i, restore = 0;
2575 bool allow_drain = true;
2576
2577 lru_add_drain();
2578
2579 for (i = 0; (i < npages) && migrate->cpages; i++) {
2580 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2581 bool remap = true;
2582
2583 if (!page)
2584 continue;
2585
2586 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2587 /*
2588 * Because we are migrating several pages there can be
2589 * a deadlock between 2 concurrent migration where each
2590 * are waiting on each other page lock.
2591 *
2592 * Make migrate_vma() a best effort thing and backoff
2593 * for any page we can not lock right away.
2594 */
2595 if (!trylock_page(page)) {
2596 migrate->src[i] = 0;
2597 migrate->cpages--;
2598 put_page(page);
2599 continue;
2600 }
2601 remap = false;
2602 migrate->src[i] |= MIGRATE_PFN_LOCKED;
2603 }
2604
2605 /* ZONE_DEVICE pages are not on LRU */
2606 if (!is_zone_device_page(page)) {
2607 if (!PageLRU(page) && allow_drain) {
2608 /* Drain CPU's pagevec */
2609 lru_add_drain_all();
2610 allow_drain = false;
2611 }
2612
2613 if (isolate_lru_page(page)) {
2614 if (remap) {
2615 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2616 migrate->cpages--;
2617 restore++;
2618 } else {
2619 migrate->src[i] = 0;
2620 unlock_page(page);
2621 migrate->cpages--;
2622 put_page(page);
2623 }
2624 continue;
2625 }
2626
2627 /* Drop the reference we took in collect */
2628 put_page(page);
2629 }
2630
2631 if (!migrate_vma_check_page(page)) {
2632 if (remap) {
2633 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2634 migrate->cpages--;
2635 restore++;
2636
2637 if (!is_zone_device_page(page)) {
2638 get_page(page);
2639 putback_lru_page(page);
2640 }
2641 } else {
2642 migrate->src[i] = 0;
2643 unlock_page(page);
2644 migrate->cpages--;
2645
2646 if (!is_zone_device_page(page))
2647 putback_lru_page(page);
2648 else
2649 put_page(page);
2650 }
2651 }
2652 }
2653
2654 for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2655 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2656
2657 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2658 continue;
2659
2660 remove_migration_pte(page, migrate->vma, addr, page);
2661
2662 migrate->src[i] = 0;
2663 unlock_page(page);
2664 put_page(page);
2665 restore--;
2666 }
2667 }
2668
2669 /*
2670 * migrate_vma_unmap() - replace page mapping with special migration pte entry
2671 * @migrate: migrate struct containing all migration information
2672 *
2673 * Replace page mapping (CPU page table pte) with a special migration pte entry
2674 * and check again if it has been pinned. Pinned pages are restored because we
2675 * cannot migrate them.
2676 *
2677 * This is the last step before we call the device driver callback to allocate
2678 * destination memory and copy contents of original page over to new page.
2679 */
migrate_vma_unmap(struct migrate_vma * migrate)2680 static void migrate_vma_unmap(struct migrate_vma *migrate)
2681 {
2682 int flags = TTU_MIGRATION | TTU_IGNORE_MLOCK;
2683 const unsigned long npages = migrate->npages;
2684 const unsigned long start = migrate->start;
2685 unsigned long addr, i, restore = 0;
2686
2687 for (i = 0; i < npages; i++) {
2688 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2689
2690 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2691 continue;
2692
2693 if (page_mapped(page)) {
2694 try_to_unmap(page, flags);
2695 if (page_mapped(page))
2696 goto restore;
2697 }
2698
2699 if (migrate_vma_check_page(page))
2700 continue;
2701
2702 restore:
2703 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2704 migrate->cpages--;
2705 restore++;
2706 }
2707
2708 for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2709 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2710
2711 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2712 continue;
2713
2714 remove_migration_ptes(page, page, false);
2715
2716 migrate->src[i] = 0;
2717 unlock_page(page);
2718 restore--;
2719
2720 if (is_zone_device_page(page))
2721 put_page(page);
2722 else
2723 putback_lru_page(page);
2724 }
2725 }
2726
2727 /**
2728 * migrate_vma_setup() - prepare to migrate a range of memory
2729 * @args: contains the vma, start, and pfns arrays for the migration
2730 *
2731 * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2732 * without an error.
2733 *
2734 * Prepare to migrate a range of memory virtual address range by collecting all
2735 * the pages backing each virtual address in the range, saving them inside the
2736 * src array. Then lock those pages and unmap them. Once the pages are locked
2737 * and unmapped, check whether each page is pinned or not. Pages that aren't
2738 * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2739 * corresponding src array entry. Then restores any pages that are pinned, by
2740 * remapping and unlocking those pages.
2741 *
2742 * The caller should then allocate destination memory and copy source memory to
2743 * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2744 * flag set). Once these are allocated and copied, the caller must update each
2745 * corresponding entry in the dst array with the pfn value of the destination
2746 * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2747 * (destination pages must have their struct pages locked, via lock_page()).
2748 *
2749 * Note that the caller does not have to migrate all the pages that are marked
2750 * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2751 * device memory to system memory. If the caller cannot migrate a device page
2752 * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2753 * consequences for the userspace process, so it must be avoided if at all
2754 * possible.
2755 *
2756 * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2757 * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2758 * allowing the caller to allocate device memory for those unback virtual
2759 * address. For this the caller simply has to allocate device memory and
2760 * properly set the destination entry like for regular migration. Note that
2761 * this can still fails and thus inside the device driver must check if the
2762 * migration was successful for those entries after calling migrate_vma_pages()
2763 * just like for regular migration.
2764 *
2765 * After that, the callers must call migrate_vma_pages() to go over each entry
2766 * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2767 * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2768 * then migrate_vma_pages() to migrate struct page information from the source
2769 * struct page to the destination struct page. If it fails to migrate the
2770 * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2771 * src array.
2772 *
2773 * At this point all successfully migrated pages have an entry in the src
2774 * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2775 * array entry with MIGRATE_PFN_VALID flag set.
2776 *
2777 * Once migrate_vma_pages() returns the caller may inspect which pages were
2778 * successfully migrated, and which were not. Successfully migrated pages will
2779 * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2780 *
2781 * It is safe to update device page table after migrate_vma_pages() because
2782 * both destination and source page are still locked, and the mmap_lock is held
2783 * in read mode (hence no one can unmap the range being migrated).
2784 *
2785 * Once the caller is done cleaning up things and updating its page table (if it
2786 * chose to do so, this is not an obligation) it finally calls
2787 * migrate_vma_finalize() to update the CPU page table to point to new pages
2788 * for successfully migrated pages or otherwise restore the CPU page table to
2789 * point to the original source pages.
2790 */
migrate_vma_setup(struct migrate_vma * args)2791 int migrate_vma_setup(struct migrate_vma *args)
2792 {
2793 long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2794
2795 args->start &= PAGE_MASK;
2796 args->end &= PAGE_MASK;
2797 if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2798 (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2799 return -EINVAL;
2800 if (nr_pages <= 0)
2801 return -EINVAL;
2802 if (args->start < args->vma->vm_start ||
2803 args->start >= args->vma->vm_end)
2804 return -EINVAL;
2805 if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2806 return -EINVAL;
2807 if (!args->src || !args->dst)
2808 return -EINVAL;
2809
2810 memset(args->src, 0, sizeof(*args->src) * nr_pages);
2811 args->cpages = 0;
2812 args->npages = 0;
2813
2814 migrate_vma_collect(args);
2815
2816 if (args->cpages)
2817 migrate_vma_prepare(args);
2818 if (args->cpages)
2819 migrate_vma_unmap(args);
2820
2821 /*
2822 * At this point pages are locked and unmapped, and thus they have
2823 * stable content and can safely be copied to destination memory that
2824 * is allocated by the drivers.
2825 */
2826 return 0;
2827
2828 }
2829 EXPORT_SYMBOL(migrate_vma_setup);
2830
2831 /*
2832 * This code closely matches the code in:
2833 * __handle_mm_fault()
2834 * handle_pte_fault()
2835 * do_anonymous_page()
2836 * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2837 * private page.
2838 */
migrate_vma_insert_page(struct migrate_vma * migrate,unsigned long addr,struct page * page,unsigned long * src,unsigned long * dst)2839 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2840 unsigned long addr,
2841 struct page *page,
2842 unsigned long *src,
2843 unsigned long *dst)
2844 {
2845 struct vm_area_struct *vma = migrate->vma;
2846 struct mm_struct *mm = vma->vm_mm;
2847 bool flush = false;
2848 spinlock_t *ptl;
2849 pte_t entry;
2850 pgd_t *pgdp;
2851 p4d_t *p4dp;
2852 pud_t *pudp;
2853 pmd_t *pmdp;
2854 pte_t *ptep;
2855
2856 /* Only allow populating anonymous memory */
2857 if (!vma_is_anonymous(vma))
2858 goto abort;
2859
2860 pgdp = pgd_offset(mm, addr);
2861 p4dp = p4d_alloc(mm, pgdp, addr);
2862 if (!p4dp)
2863 goto abort;
2864 pudp = pud_alloc(mm, p4dp, addr);
2865 if (!pudp)
2866 goto abort;
2867 pmdp = pmd_alloc(mm, pudp, addr);
2868 if (!pmdp)
2869 goto abort;
2870
2871 if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2872 goto abort;
2873
2874 /*
2875 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2876 * pte_offset_map() on pmds where a huge pmd might be created
2877 * from a different thread.
2878 *
2879 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2880 * parallel threads are excluded by other means.
2881 *
2882 * Here we only have mmap_read_lock(mm).
2883 */
2884 if (pte_alloc(mm, pmdp))
2885 goto abort;
2886
2887 /* See the comment in pte_alloc_one_map() */
2888 if (unlikely(pmd_trans_unstable(pmdp)))
2889 goto abort;
2890
2891 if (unlikely(anon_vma_prepare(vma)))
2892 goto abort;
2893 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
2894 goto abort;
2895
2896 /*
2897 * The memory barrier inside __SetPageUptodate makes sure that
2898 * preceding stores to the page contents become visible before
2899 * the set_pte_at() write.
2900 */
2901 __SetPageUptodate(page);
2902
2903 if (is_zone_device_page(page)) {
2904 if (is_device_private_page(page)) {
2905 swp_entry_t swp_entry;
2906
2907 swp_entry = make_device_private_entry(page, vma->vm_flags & VM_WRITE);
2908 entry = swp_entry_to_pte(swp_entry);
2909 } else {
2910 /*
2911 * For now we only support migrating to un-addressable
2912 * device memory.
2913 */
2914 pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2915 goto abort;
2916 }
2917 } else {
2918 entry = mk_pte(page, vma->vm_page_prot);
2919 if (vma->vm_flags & VM_WRITE)
2920 entry = pte_mkwrite(pte_mkdirty(entry));
2921 }
2922
2923 ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2924
2925 if (check_stable_address_space(mm))
2926 goto unlock_abort;
2927
2928 if (pte_present(*ptep)) {
2929 unsigned long pfn = pte_pfn(*ptep);
2930
2931 if (!is_zero_pfn(pfn))
2932 goto unlock_abort;
2933 flush = true;
2934 } else if (!pte_none(*ptep))
2935 goto unlock_abort;
2936
2937 /*
2938 * Check for userfaultfd but do not deliver the fault. Instead,
2939 * just back off.
2940 */
2941 if (userfaultfd_missing(vma))
2942 goto unlock_abort;
2943
2944 inc_mm_counter(mm, MM_ANONPAGES);
2945 page_add_new_anon_rmap(page, vma, addr, false);
2946 if (!is_zone_device_page(page))
2947 lru_cache_add_inactive_or_unevictable(page, vma);
2948 get_page(page);
2949
2950 if (flush) {
2951 flush_cache_page(vma, addr, pte_pfn(*ptep));
2952 ptep_clear_flush_notify(vma, addr, ptep);
2953 set_pte_at_notify(mm, addr, ptep, entry);
2954 update_mmu_cache(vma, addr, ptep);
2955 } else {
2956 /* No need to invalidate - it was non-present before */
2957 set_pte_at(mm, addr, ptep, entry);
2958 update_mmu_cache(vma, addr, ptep);
2959 }
2960
2961 pte_unmap_unlock(ptep, ptl);
2962 *src = MIGRATE_PFN_MIGRATE;
2963 return;
2964
2965 unlock_abort:
2966 pte_unmap_unlock(ptep, ptl);
2967 abort:
2968 *src &= ~MIGRATE_PFN_MIGRATE;
2969 }
2970
2971 /**
2972 * migrate_vma_pages() - migrate meta-data from src page to dst page
2973 * @migrate: migrate struct containing all migration information
2974 *
2975 * This migrates struct page meta-data from source struct page to destination
2976 * struct page. This effectively finishes the migration from source page to the
2977 * destination page.
2978 */
migrate_vma_pages(struct migrate_vma * migrate)2979 void migrate_vma_pages(struct migrate_vma *migrate)
2980 {
2981 const unsigned long npages = migrate->npages;
2982 const unsigned long start = migrate->start;
2983 struct mmu_notifier_range range;
2984 unsigned long addr, i;
2985 bool notified = false;
2986
2987 for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2988 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2989 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2990 struct address_space *mapping;
2991 int r;
2992
2993 if (!newpage) {
2994 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2995 continue;
2996 }
2997
2998 if (!page) {
2999 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
3000 continue;
3001 if (!notified) {
3002 notified = true;
3003
3004 mmu_notifier_range_init(&range,
3005 MMU_NOTIFY_CLEAR, 0,
3006 NULL,
3007 migrate->vma->vm_mm,
3008 addr, migrate->end);
3009 mmu_notifier_invalidate_range_start(&range);
3010 }
3011 migrate_vma_insert_page(migrate, addr, newpage,
3012 &migrate->src[i],
3013 &migrate->dst[i]);
3014 continue;
3015 }
3016
3017 mapping = page_mapping(page);
3018
3019 if (is_zone_device_page(newpage)) {
3020 if (is_device_private_page(newpage)) {
3021 /*
3022 * For now only support private anonymous when
3023 * migrating to un-addressable device memory.
3024 */
3025 if (mapping) {
3026 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3027 continue;
3028 }
3029 } else {
3030 /*
3031 * Other types of ZONE_DEVICE page are not
3032 * supported.
3033 */
3034 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3035 continue;
3036 }
3037 }
3038
3039 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
3040 if (r != MIGRATEPAGE_SUCCESS)
3041 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3042 }
3043
3044 /*
3045 * No need to double call mmu_notifier->invalidate_range() callback as
3046 * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3047 * did already call it.
3048 */
3049 if (notified)
3050 mmu_notifier_invalidate_range_only_end(&range);
3051 }
3052 EXPORT_SYMBOL(migrate_vma_pages);
3053
3054 /**
3055 * migrate_vma_finalize() - restore CPU page table entry
3056 * @migrate: migrate struct containing all migration information
3057 *
3058 * This replaces the special migration pte entry with either a mapping to the
3059 * new page if migration was successful for that page, or to the original page
3060 * otherwise.
3061 *
3062 * This also unlocks the pages and puts them back on the lru, or drops the extra
3063 * refcount, for device pages.
3064 */
migrate_vma_finalize(struct migrate_vma * migrate)3065 void migrate_vma_finalize(struct migrate_vma *migrate)
3066 {
3067 const unsigned long npages = migrate->npages;
3068 unsigned long i;
3069
3070 for (i = 0; i < npages; i++) {
3071 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3072 struct page *page = migrate_pfn_to_page(migrate->src[i]);
3073
3074 if (!page) {
3075 if (newpage) {
3076 unlock_page(newpage);
3077 put_page(newpage);
3078 }
3079 continue;
3080 }
3081
3082 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3083 if (newpage) {
3084 unlock_page(newpage);
3085 put_page(newpage);
3086 }
3087 newpage = page;
3088 }
3089
3090 remove_migration_ptes(page, newpage, false);
3091 unlock_page(page);
3092
3093 if (is_zone_device_page(page))
3094 put_page(page);
3095 else
3096 putback_lru_page(page);
3097
3098 if (newpage != page) {
3099 unlock_page(newpage);
3100 if (is_zone_device_page(newpage))
3101 put_page(newpage);
3102 else
3103 putback_lru_page(newpage);
3104 }
3105 }
3106 }
3107 EXPORT_SYMBOL(migrate_vma_finalize);
3108 #endif /* CONFIG_DEVICE_PRIVATE */
3109