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