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