x86: add tizen_qemu_x86_defconfig & tizen_qemu_x86_64_defconfig
[platform/kernel/linux-rpi.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                         int i, nr = compound_nr(newpage);
953
954                         for (i = 0; i < nr; i++)
955                                 flush_dcache_page(newpage + i);
956                 }
957         }
958 out:
959         return rc;
960 }
961
962 static int __unmap_and_move(struct page *page, struct page *newpage,
963                                 int force, enum migrate_mode mode)
964 {
965         int rc = -EAGAIN;
966         bool page_was_mapped = false;
967         struct anon_vma *anon_vma = NULL;
968         bool is_lru = !__PageMovable(page);
969
970         if (!trylock_page(page)) {
971                 if (!force || mode == MIGRATE_ASYNC)
972                         goto out;
973
974                 /*
975                  * It's not safe for direct compaction to call lock_page.
976                  * For example, during page readahead pages are added locked
977                  * to the LRU. Later, when the IO completes the pages are
978                  * marked uptodate and unlocked. However, the queueing
979                  * could be merging multiple pages for one bio (e.g.
980                  * mpage_readahead). If an allocation happens for the
981                  * second or third page, the process can end up locking
982                  * the same page twice and deadlocking. Rather than
983                  * trying to be clever about what pages can be locked,
984                  * avoid the use of lock_page for direct compaction
985                  * altogether.
986                  */
987                 if (current->flags & PF_MEMALLOC)
988                         goto out;
989
990                 lock_page(page);
991         }
992
993         if (PageWriteback(page)) {
994                 /*
995                  * Only in the case of a full synchronous migration is it
996                  * necessary to wait for PageWriteback. In the async case,
997                  * the retry loop is too short and in the sync-light case,
998                  * the overhead of stalling is too much
999                  */
1000                 switch (mode) {
1001                 case MIGRATE_SYNC:
1002                 case MIGRATE_SYNC_NO_COPY:
1003                         break;
1004                 default:
1005                         rc = -EBUSY;
1006                         goto out_unlock;
1007                 }
1008                 if (!force)
1009                         goto out_unlock;
1010                 wait_on_page_writeback(page);
1011         }
1012
1013         /*
1014          * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
1015          * we cannot notice that anon_vma is freed while we migrates a page.
1016          * This get_anon_vma() delays freeing anon_vma pointer until the end
1017          * of migration. File cache pages are no problem because of page_lock()
1018          * File Caches may use write_page() or lock_page() in migration, then,
1019          * just care Anon page here.
1020          *
1021          * Only page_get_anon_vma() understands the subtleties of
1022          * getting a hold on an anon_vma from outside one of its mms.
1023          * But if we cannot get anon_vma, then we won't need it anyway,
1024          * because that implies that the anon page is no longer mapped
1025          * (and cannot be remapped so long as we hold the page lock).
1026          */
1027         if (PageAnon(page) && !PageKsm(page))
1028                 anon_vma = page_get_anon_vma(page);
1029
1030         /*
1031          * Block others from accessing the new page when we get around to
1032          * establishing additional references. We are usually the only one
1033          * holding a reference to newpage at this point. We used to have a BUG
1034          * here if trylock_page(newpage) fails, but would like to allow for
1035          * cases where there might be a race with the previous use of newpage.
1036          * This is much like races on refcount of oldpage: just don't BUG().
1037          */
1038         if (unlikely(!trylock_page(newpage)))
1039                 goto out_unlock;
1040
1041         if (unlikely(!is_lru)) {
1042                 rc = move_to_new_page(newpage, page, mode);
1043                 goto out_unlock_both;
1044         }
1045
1046         /*
1047          * Corner case handling:
1048          * 1. When a new swap-cache page is read into, it is added to the LRU
1049          * and treated as swapcache but it has no rmap yet.
1050          * Calling try_to_unmap() against a page->mapping==NULL page will
1051          * trigger a BUG.  So handle it here.
1052          * 2. An orphaned page (see truncate_cleanup_page) might have
1053          * fs-private metadata. The page can be picked up due to memory
1054          * offlining.  Everywhere else except page reclaim, the page is
1055          * invisible to the vm, so the page can not be migrated.  So try to
1056          * free the metadata, so the page can be freed.
1057          */
1058         if (!page->mapping) {
1059                 VM_BUG_ON_PAGE(PageAnon(page), page);
1060                 if (page_has_private(page)) {
1061                         try_to_free_buffers(page);
1062                         goto out_unlock_both;
1063                 }
1064         } else if (page_mapped(page)) {
1065                 /* Establish migration ptes */
1066                 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1067                                 page);
1068                 try_to_migrate(page, 0);
1069                 page_was_mapped = true;
1070         }
1071
1072         if (!page_mapped(page))
1073                 rc = move_to_new_page(newpage, page, mode);
1074
1075         if (page_was_mapped)
1076                 remove_migration_ptes(page,
1077                         rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1078
1079 out_unlock_both:
1080         unlock_page(newpage);
1081 out_unlock:
1082         /* Drop an anon_vma reference if we took one */
1083         if (anon_vma)
1084                 put_anon_vma(anon_vma);
1085         unlock_page(page);
1086 out:
1087         /*
1088          * If migration is successful, decrease refcount of the newpage
1089          * which will not free the page because new page owner increased
1090          * refcounter. As well, if it is LRU page, add the page to LRU
1091          * list in here. Use the old state of the isolated source page to
1092          * determine if we migrated a LRU page. newpage was already unlocked
1093          * and possibly modified by its owner - don't rely on the page
1094          * state.
1095          */
1096         if (rc == MIGRATEPAGE_SUCCESS) {
1097                 if (unlikely(!is_lru))
1098                         put_page(newpage);
1099                 else
1100                         putback_lru_page(newpage);
1101         }
1102
1103         return rc;
1104 }
1105
1106
1107 /*
1108  * node_demotion[] example:
1109  *
1110  * Consider a system with two sockets.  Each socket has
1111  * three classes of memory attached: fast, medium and slow.
1112  * Each memory class is placed in its own NUMA node.  The
1113  * CPUs are placed in the node with the "fast" memory.  The
1114  * 6 NUMA nodes (0-5) might be split among the sockets like
1115  * this:
1116  *
1117  *      Socket A: 0, 1, 2
1118  *      Socket B: 3, 4, 5
1119  *
1120  * When Node 0 fills up, its memory should be migrated to
1121  * Node 1.  When Node 1 fills up, it should be migrated to
1122  * Node 2.  The migration path start on the nodes with the
1123  * processors (since allocations default to this node) and
1124  * fast memory, progress through medium and end with the
1125  * slow memory:
1126  *
1127  *      0 -> 1 -> 2 -> stop
1128  *      3 -> 4 -> 5 -> stop
1129  *
1130  * This is represented in the node_demotion[] like this:
1131  *
1132  *      {  1, // Node 0 migrates to 1
1133  *         2, // Node 1 migrates to 2
1134  *        -1, // Node 2 does not migrate
1135  *         4, // Node 3 migrates to 4
1136  *         5, // Node 4 migrates to 5
1137  *        -1} // Node 5 does not migrate
1138  */
1139
1140 /*
1141  * Writes to this array occur without locking.  Cycles are
1142  * not allowed: Node X demotes to Y which demotes to X...
1143  *
1144  * If multiple reads are performed, a single rcu_read_lock()
1145  * must be held over all reads to ensure that no cycles are
1146  * observed.
1147  */
1148 static int node_demotion[MAX_NUMNODES] __read_mostly =
1149         {[0 ...  MAX_NUMNODES - 1] = NUMA_NO_NODE};
1150
1151 /**
1152  * next_demotion_node() - Get the next node in the demotion path
1153  * @node: The starting node to lookup the next node
1154  *
1155  * Return: node id for next memory node in the demotion path hierarchy
1156  * from @node; NUMA_NO_NODE if @node is terminal.  This does not keep
1157  * @node online or guarantee that it *continues* to be the next demotion
1158  * target.
1159  */
1160 int next_demotion_node(int node)
1161 {
1162         int target;
1163
1164         /*
1165          * node_demotion[] is updated without excluding this
1166          * function from running.  RCU doesn't provide any
1167          * compiler barriers, so the READ_ONCE() is required
1168          * to avoid compiler reordering or read merging.
1169          *
1170          * Make sure to use RCU over entire code blocks if
1171          * node_demotion[] reads need to be consistent.
1172          */
1173         rcu_read_lock();
1174         target = READ_ONCE(node_demotion[node]);
1175         rcu_read_unlock();
1176
1177         return target;
1178 }
1179
1180 /*
1181  * Obtain the lock on page, remove all ptes and migrate the page
1182  * to the newly allocated page in newpage.
1183  */
1184 static int unmap_and_move(new_page_t get_new_page,
1185                                    free_page_t put_new_page,
1186                                    unsigned long private, struct page *page,
1187                                    int force, enum migrate_mode mode,
1188                                    enum migrate_reason reason,
1189                                    struct list_head *ret)
1190 {
1191         int rc = MIGRATEPAGE_SUCCESS;
1192         struct page *newpage = NULL;
1193
1194         if (!thp_migration_supported() && PageTransHuge(page))
1195                 return -ENOSYS;
1196
1197         if (page_count(page) == 1) {
1198                 /* page was freed from under us. So we are done. */
1199                 ClearPageActive(page);
1200                 ClearPageUnevictable(page);
1201                 if (unlikely(__PageMovable(page))) {
1202                         lock_page(page);
1203                         if (!PageMovable(page))
1204                                 __ClearPageIsolated(page);
1205                         unlock_page(page);
1206                 }
1207                 goto out;
1208         }
1209
1210         newpage = get_new_page(page, private);
1211         if (!newpage)
1212                 return -ENOMEM;
1213
1214         rc = __unmap_and_move(page, newpage, force, mode);
1215         if (rc == MIGRATEPAGE_SUCCESS)
1216                 set_page_owner_migrate_reason(newpage, reason);
1217
1218 out:
1219         if (rc != -EAGAIN) {
1220                 /*
1221                  * A page that has been migrated has all references
1222                  * removed and will be freed. A page that has not been
1223                  * migrated will have kept its references and be restored.
1224                  */
1225                 list_del(&page->lru);
1226         }
1227
1228         /*
1229          * If migration is successful, releases reference grabbed during
1230          * isolation. Otherwise, restore the page to right list unless
1231          * we want to retry.
1232          */
1233         if (rc == MIGRATEPAGE_SUCCESS) {
1234                 /*
1235                  * Compaction can migrate also non-LRU pages which are
1236                  * not accounted to NR_ISOLATED_*. They can be recognized
1237                  * as __PageMovable
1238                  */
1239                 if (likely(!__PageMovable(page)))
1240                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1241                                         page_is_file_lru(page), -thp_nr_pages(page));
1242
1243                 if (reason != MR_MEMORY_FAILURE)
1244                         /*
1245                          * We release the page in page_handle_poison.
1246                          */
1247                         put_page(page);
1248         } else {
1249                 if (rc != -EAGAIN)
1250                         list_add_tail(&page->lru, ret);
1251
1252                 if (put_new_page)
1253                         put_new_page(newpage, private);
1254                 else
1255                         put_page(newpage);
1256         }
1257
1258         return rc;
1259 }
1260
1261 /*
1262  * Counterpart of unmap_and_move_page() for hugepage migration.
1263  *
1264  * This function doesn't wait the completion of hugepage I/O
1265  * because there is no race between I/O and migration for hugepage.
1266  * Note that currently hugepage I/O occurs only in direct I/O
1267  * where no lock is held and PG_writeback is irrelevant,
1268  * and writeback status of all subpages are counted in the reference
1269  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1270  * under direct I/O, the reference of the head page is 512 and a bit more.)
1271  * This means that when we try to migrate hugepage whose subpages are
1272  * doing direct I/O, some references remain after try_to_unmap() and
1273  * hugepage migration fails without data corruption.
1274  *
1275  * There is also no race when direct I/O is issued on the page under migration,
1276  * because then pte is replaced with migration swap entry and direct I/O code
1277  * will wait in the page fault for migration to complete.
1278  */
1279 static int unmap_and_move_huge_page(new_page_t get_new_page,
1280                                 free_page_t put_new_page, unsigned long private,
1281                                 struct page *hpage, int force,
1282                                 enum migrate_mode mode, int reason,
1283                                 struct list_head *ret)
1284 {
1285         int rc = -EAGAIN;
1286         int page_was_mapped = 0;
1287         struct page *new_hpage;
1288         struct anon_vma *anon_vma = NULL;
1289         struct address_space *mapping = NULL;
1290
1291         /*
1292          * Migratability of hugepages depends on architectures and their size.
1293          * This check is necessary because some callers of hugepage migration
1294          * like soft offline and memory hotremove don't walk through page
1295          * tables or check whether the hugepage is pmd-based or not before
1296          * kicking migration.
1297          */
1298         if (!hugepage_migration_supported(page_hstate(hpage))) {
1299                 list_move_tail(&hpage->lru, ret);
1300                 return -ENOSYS;
1301         }
1302
1303         if (page_count(hpage) == 1) {
1304                 /* page was freed from under us. So we are done. */
1305                 putback_active_hugepage(hpage);
1306                 return MIGRATEPAGE_SUCCESS;
1307         }
1308
1309         new_hpage = get_new_page(hpage, private);
1310         if (!new_hpage)
1311                 return -ENOMEM;
1312
1313         if (!trylock_page(hpage)) {
1314                 if (!force)
1315                         goto out;
1316                 switch (mode) {
1317                 case MIGRATE_SYNC:
1318                 case MIGRATE_SYNC_NO_COPY:
1319                         break;
1320                 default:
1321                         goto out;
1322                 }
1323                 lock_page(hpage);
1324         }
1325
1326         /*
1327          * Check for pages which are in the process of being freed.  Without
1328          * page_mapping() set, hugetlbfs specific move page routine will not
1329          * be called and we could leak usage counts for subpools.
1330          */
1331         if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1332                 rc = -EBUSY;
1333                 goto out_unlock;
1334         }
1335
1336         if (PageAnon(hpage))
1337                 anon_vma = page_get_anon_vma(hpage);
1338
1339         if (unlikely(!trylock_page(new_hpage)))
1340                 goto put_anon;
1341
1342         if (page_mapped(hpage)) {
1343                 bool mapping_locked = false;
1344                 enum ttu_flags ttu = 0;
1345
1346                 if (!PageAnon(hpage)) {
1347                         /*
1348                          * In shared mappings, try_to_unmap could potentially
1349                          * call huge_pmd_unshare.  Because of this, take
1350                          * semaphore in write mode here and set TTU_RMAP_LOCKED
1351                          * to let lower levels know we have taken the lock.
1352                          */
1353                         mapping = hugetlb_page_mapping_lock_write(hpage);
1354                         if (unlikely(!mapping))
1355                                 goto unlock_put_anon;
1356
1357                         mapping_locked = true;
1358                         ttu |= TTU_RMAP_LOCKED;
1359                 }
1360
1361                 try_to_migrate(hpage, ttu);
1362                 page_was_mapped = 1;
1363
1364                 if (mapping_locked)
1365                         i_mmap_unlock_write(mapping);
1366         }
1367
1368         if (!page_mapped(hpage))
1369                 rc = move_to_new_page(new_hpage, hpage, mode);
1370
1371         if (page_was_mapped)
1372                 remove_migration_ptes(hpage,
1373                         rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1374
1375 unlock_put_anon:
1376         unlock_page(new_hpage);
1377
1378 put_anon:
1379         if (anon_vma)
1380                 put_anon_vma(anon_vma);
1381
1382         if (rc == MIGRATEPAGE_SUCCESS) {
1383                 move_hugetlb_state(hpage, new_hpage, reason);
1384                 put_new_page = NULL;
1385         }
1386
1387 out_unlock:
1388         unlock_page(hpage);
1389 out:
1390         if (rc == MIGRATEPAGE_SUCCESS)
1391                 putback_active_hugepage(hpage);
1392         else if (rc != -EAGAIN)
1393                 list_move_tail(&hpage->lru, ret);
1394
1395         /*
1396          * If migration was not successful and there's a freeing callback, use
1397          * it.  Otherwise, put_page() will drop the reference grabbed during
1398          * isolation.
1399          */
1400         if (put_new_page)
1401                 put_new_page(new_hpage, private);
1402         else
1403                 putback_active_hugepage(new_hpage);
1404
1405         return rc;
1406 }
1407
1408 static inline int try_split_thp(struct page *page, struct page **page2,
1409                                 struct list_head *from)
1410 {
1411         int rc = 0;
1412
1413         lock_page(page);
1414         rc = split_huge_page_to_list(page, from);
1415         unlock_page(page);
1416         if (!rc)
1417                 list_safe_reset_next(page, *page2, lru);
1418
1419         return rc;
1420 }
1421
1422 /*
1423  * migrate_pages - migrate the pages specified in a list, to the free pages
1424  *                 supplied as the target for the page migration
1425  *
1426  * @from:               The list of pages to be migrated.
1427  * @get_new_page:       The function used to allocate free pages to be used
1428  *                      as the target of the page migration.
1429  * @put_new_page:       The function used to free target pages if migration
1430  *                      fails, or NULL if no special handling is necessary.
1431  * @private:            Private data to be passed on to get_new_page()
1432  * @mode:               The migration mode that specifies the constraints for
1433  *                      page migration, if any.
1434  * @reason:             The reason for page migration.
1435  * @ret_succeeded:      Set to the number of pages migrated successfully if
1436  *                      the caller passes a non-NULL pointer.
1437  *
1438  * The function returns after 10 attempts or if no pages are movable any more
1439  * because the list has become empty or no retryable pages exist any more.
1440  * It is caller's responsibility to call putback_movable_pages() to return pages
1441  * to the LRU or free list only if ret != 0.
1442  *
1443  * Returns the number of pages that were not migrated, or an error code.
1444  */
1445 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1446                 free_page_t put_new_page, unsigned long private,
1447                 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1448 {
1449         int retry = 1;
1450         int thp_retry = 1;
1451         int nr_failed = 0;
1452         int nr_succeeded = 0;
1453         int nr_thp_succeeded = 0;
1454         int nr_thp_failed = 0;
1455         int nr_thp_split = 0;
1456         int pass = 0;
1457         bool is_thp = false;
1458         struct page *page;
1459         struct page *page2;
1460         int swapwrite = current->flags & PF_SWAPWRITE;
1461         int rc, nr_subpages;
1462         LIST_HEAD(ret_pages);
1463         bool nosplit = (reason == MR_NUMA_MISPLACED);
1464
1465         trace_mm_migrate_pages_start(mode, reason);
1466
1467         if (!swapwrite)
1468                 current->flags |= PF_SWAPWRITE;
1469
1470         for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1471                 retry = 0;
1472                 thp_retry = 0;
1473
1474                 list_for_each_entry_safe(page, page2, from, lru) {
1475 retry:
1476                         /*
1477                          * THP statistics is based on the source huge page.
1478                          * Capture required information that might get lost
1479                          * during migration.
1480                          */
1481                         is_thp = PageTransHuge(page) && !PageHuge(page);
1482                         nr_subpages = thp_nr_pages(page);
1483                         cond_resched();
1484
1485                         if (PageHuge(page))
1486                                 rc = unmap_and_move_huge_page(get_new_page,
1487                                                 put_new_page, private, page,
1488                                                 pass > 2, mode, reason,
1489                                                 &ret_pages);
1490                         else
1491                                 rc = unmap_and_move(get_new_page, put_new_page,
1492                                                 private, page, pass > 2, mode,
1493                                                 reason, &ret_pages);
1494                         /*
1495                          * The rules are:
1496                          *      Success: non hugetlb page will be freed, hugetlb
1497                          *               page will be put back
1498                          *      -EAGAIN: stay on the from list
1499                          *      -ENOMEM: stay on the from list
1500                          *      Other errno: put on ret_pages list then splice to
1501                          *                   from list
1502                          */
1503                         switch(rc) {
1504                         /*
1505                          * THP migration might be unsupported or the
1506                          * allocation could've failed so we should
1507                          * retry on the same page with the THP split
1508                          * to base pages.
1509                          *
1510                          * Head page is retried immediately and tail
1511                          * pages are added to the tail of the list so
1512                          * we encounter them after the rest of the list
1513                          * is processed.
1514                          */
1515                         case -ENOSYS:
1516                                 /* THP migration is unsupported */
1517                                 if (is_thp) {
1518                                         if (!try_split_thp(page, &page2, from)) {
1519                                                 nr_thp_split++;
1520                                                 goto retry;
1521                                         }
1522
1523                                         nr_thp_failed++;
1524                                         nr_failed += nr_subpages;
1525                                         break;
1526                                 }
1527
1528                                 /* Hugetlb migration is unsupported */
1529                                 nr_failed++;
1530                                 break;
1531                         case -ENOMEM:
1532                                 /*
1533                                  * When memory is low, don't bother to try to migrate
1534                                  * other pages, just exit.
1535                                  * THP NUMA faulting doesn't split THP to retry.
1536                                  */
1537                                 if (is_thp && !nosplit) {
1538                                         if (!try_split_thp(page, &page2, from)) {
1539                                                 nr_thp_split++;
1540                                                 goto retry;
1541                                         }
1542
1543                                         nr_thp_failed++;
1544                                         nr_failed += nr_subpages;
1545                                         goto out;
1546                                 }
1547                                 nr_failed++;
1548                                 goto out;
1549                         case -EAGAIN:
1550                                 if (is_thp) {
1551                                         thp_retry++;
1552                                         break;
1553                                 }
1554                                 retry++;
1555                                 break;
1556                         case MIGRATEPAGE_SUCCESS:
1557                                 if (is_thp) {
1558                                         nr_thp_succeeded++;
1559                                         nr_succeeded += nr_subpages;
1560                                         break;
1561                                 }
1562                                 nr_succeeded++;
1563                                 break;
1564                         default:
1565                                 /*
1566                                  * Permanent failure (-EBUSY, etc.):
1567                                  * unlike -EAGAIN case, the failed page is
1568                                  * removed from migration page list and not
1569                                  * retried in the next outer loop.
1570                                  */
1571                                 if (is_thp) {
1572                                         nr_thp_failed++;
1573                                         nr_failed += nr_subpages;
1574                                         break;
1575                                 }
1576                                 nr_failed++;
1577                                 break;
1578                         }
1579                 }
1580         }
1581         nr_failed += retry + thp_retry;
1582         nr_thp_failed += thp_retry;
1583         rc = nr_failed;
1584 out:
1585         /*
1586          * Put the permanent failure page back to migration list, they
1587          * will be put back to the right list by the caller.
1588          */
1589         list_splice(&ret_pages, from);
1590
1591         count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1592         count_vm_events(PGMIGRATE_FAIL, nr_failed);
1593         count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1594         count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1595         count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1596         trace_mm_migrate_pages(nr_succeeded, nr_failed, nr_thp_succeeded,
1597                                nr_thp_failed, nr_thp_split, mode, reason);
1598
1599         if (!swapwrite)
1600                 current->flags &= ~PF_SWAPWRITE;
1601
1602         if (ret_succeeded)
1603                 *ret_succeeded = nr_succeeded;
1604
1605         return rc;
1606 }
1607
1608 struct page *alloc_migration_target(struct page *page, unsigned long private)
1609 {
1610         struct migration_target_control *mtc;
1611         gfp_t gfp_mask;
1612         unsigned int order = 0;
1613         struct page *new_page = NULL;
1614         int nid;
1615         int zidx;
1616
1617         mtc = (struct migration_target_control *)private;
1618         gfp_mask = mtc->gfp_mask;
1619         nid = mtc->nid;
1620         if (nid == NUMA_NO_NODE)
1621                 nid = page_to_nid(page);
1622
1623         if (PageHuge(page)) {
1624                 struct hstate *h = page_hstate(compound_head(page));
1625
1626                 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1627                 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1628         }
1629
1630         if (PageTransHuge(page)) {
1631                 /*
1632                  * clear __GFP_RECLAIM to make the migration callback
1633                  * consistent with regular THP allocations.
1634                  */
1635                 gfp_mask &= ~__GFP_RECLAIM;
1636                 gfp_mask |= GFP_TRANSHUGE;
1637                 order = HPAGE_PMD_ORDER;
1638         }
1639         zidx = zone_idx(page_zone(page));
1640         if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1641                 gfp_mask |= __GFP_HIGHMEM;
1642
1643         new_page = __alloc_pages(gfp_mask, order, nid, mtc->nmask);
1644
1645         if (new_page && PageTransHuge(new_page))
1646                 prep_transhuge_page(new_page);
1647
1648         return new_page;
1649 }
1650
1651 #ifdef CONFIG_NUMA
1652
1653 static int store_status(int __user *status, int start, int value, int nr)
1654 {
1655         while (nr-- > 0) {
1656                 if (put_user(value, status + start))
1657                         return -EFAULT;
1658                 start++;
1659         }
1660
1661         return 0;
1662 }
1663
1664 static int do_move_pages_to_node(struct mm_struct *mm,
1665                 struct list_head *pagelist, int node)
1666 {
1667         int err;
1668         struct migration_target_control mtc = {
1669                 .nid = node,
1670                 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1671         };
1672
1673         err = migrate_pages(pagelist, alloc_migration_target, NULL,
1674                 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1675         if (err)
1676                 putback_movable_pages(pagelist);
1677         return err;
1678 }
1679
1680 /*
1681  * Resolves the given address to a struct page, isolates it from the LRU and
1682  * puts it to the given pagelist.
1683  * Returns:
1684  *     errno - if the page cannot be found/isolated
1685  *     0 - when it doesn't have to be migrated because it is already on the
1686  *         target node
1687  *     1 - when it has been queued
1688  */
1689 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1690                 int node, struct list_head *pagelist, bool migrate_all)
1691 {
1692         struct vm_area_struct *vma;
1693         struct page *page;
1694         unsigned int follflags;
1695         int err;
1696
1697         mmap_read_lock(mm);
1698         err = -EFAULT;
1699         vma = find_vma(mm, addr);
1700         if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1701                 goto out;
1702
1703         /* FOLL_DUMP to ignore special (like zero) pages */
1704         follflags = FOLL_GET | FOLL_DUMP;
1705         page = follow_page(vma, addr, follflags);
1706
1707         err = PTR_ERR(page);
1708         if (IS_ERR(page))
1709                 goto out;
1710
1711         err = -ENOENT;
1712         if (!page)
1713                 goto out;
1714
1715         err = 0;
1716         if (page_to_nid(page) == node)
1717                 goto out_putpage;
1718
1719         err = -EACCES;
1720         if (page_mapcount(page) > 1 && !migrate_all)
1721                 goto out_putpage;
1722
1723         if (PageHuge(page)) {
1724                 if (PageHead(page)) {
1725                         isolate_huge_page(page, pagelist);
1726                         err = 1;
1727                 }
1728         } else {
1729                 struct page *head;
1730
1731                 head = compound_head(page);
1732                 err = isolate_lru_page(head);
1733                 if (err)
1734                         goto out_putpage;
1735
1736                 err = 1;
1737                 list_add_tail(&head->lru, pagelist);
1738                 mod_node_page_state(page_pgdat(head),
1739                         NR_ISOLATED_ANON + page_is_file_lru(head),
1740                         thp_nr_pages(head));
1741         }
1742 out_putpage:
1743         /*
1744          * Either remove the duplicate refcount from
1745          * isolate_lru_page() or drop the page ref if it was
1746          * not isolated.
1747          */
1748         put_page(page);
1749 out:
1750         mmap_read_unlock(mm);
1751         return err;
1752 }
1753
1754 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1755                 struct list_head *pagelist, int __user *status,
1756                 int start, int i, unsigned long nr_pages)
1757 {
1758         int err;
1759
1760         if (list_empty(pagelist))
1761                 return 0;
1762
1763         err = do_move_pages_to_node(mm, pagelist, node);
1764         if (err) {
1765                 /*
1766                  * Positive err means the number of failed
1767                  * pages to migrate.  Since we are going to
1768                  * abort and return the number of non-migrated
1769                  * pages, so need to include the rest of the
1770                  * nr_pages that have not been attempted as
1771                  * well.
1772                  */
1773                 if (err > 0)
1774                         err += nr_pages - i - 1;
1775                 return err;
1776         }
1777         return store_status(status, start, node, i - start);
1778 }
1779
1780 /*
1781  * Migrate an array of page address onto an array of nodes and fill
1782  * the corresponding array of status.
1783  */
1784 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1785                          unsigned long nr_pages,
1786                          const void __user * __user *pages,
1787                          const int __user *nodes,
1788                          int __user *status, int flags)
1789 {
1790         int current_node = NUMA_NO_NODE;
1791         LIST_HEAD(pagelist);
1792         int start, i;
1793         int err = 0, err1;
1794
1795         lru_cache_disable();
1796
1797         for (i = start = 0; i < nr_pages; i++) {
1798                 const void __user *p;
1799                 unsigned long addr;
1800                 int node;
1801
1802                 err = -EFAULT;
1803                 if (get_user(p, pages + i))
1804                         goto out_flush;
1805                 if (get_user(node, nodes + i))
1806                         goto out_flush;
1807                 addr = (unsigned long)untagged_addr(p);
1808
1809                 err = -ENODEV;
1810                 if (node < 0 || node >= MAX_NUMNODES)
1811                         goto out_flush;
1812                 if (!node_state(node, N_MEMORY))
1813                         goto out_flush;
1814
1815                 err = -EACCES;
1816                 if (!node_isset(node, task_nodes))
1817                         goto out_flush;
1818
1819                 if (current_node == NUMA_NO_NODE) {
1820                         current_node = node;
1821                         start = i;
1822                 } else if (node != current_node) {
1823                         err = move_pages_and_store_status(mm, current_node,
1824                                         &pagelist, status, start, i, nr_pages);
1825                         if (err)
1826                                 goto out;
1827                         start = i;
1828                         current_node = node;
1829                 }
1830
1831                 /*
1832                  * Errors in the page lookup or isolation are not fatal and we simply
1833                  * report them via status
1834                  */
1835                 err = add_page_for_migration(mm, addr, current_node,
1836                                 &pagelist, flags & MPOL_MF_MOVE_ALL);
1837
1838                 if (err > 0) {
1839                         /* The page is successfully queued for migration */
1840                         continue;
1841                 }
1842
1843                 /*
1844                  * If the page is already on the target node (!err), store the
1845                  * node, otherwise, store the err.
1846                  */
1847                 err = store_status(status, i, err ? : current_node, 1);
1848                 if (err)
1849                         goto out_flush;
1850
1851                 err = move_pages_and_store_status(mm, current_node, &pagelist,
1852                                 status, start, i, nr_pages);
1853                 if (err)
1854                         goto out;
1855                 current_node = NUMA_NO_NODE;
1856         }
1857 out_flush:
1858         /* Make sure we do not overwrite the existing error */
1859         err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1860                                 status, start, i, nr_pages);
1861         if (err >= 0)
1862                 err = err1;
1863 out:
1864         lru_cache_enable();
1865         return err;
1866 }
1867
1868 /*
1869  * Determine the nodes of an array of pages and store it in an array of status.
1870  */
1871 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1872                                 const void __user **pages, int *status)
1873 {
1874         unsigned long i;
1875
1876         mmap_read_lock(mm);
1877
1878         for (i = 0; i < nr_pages; i++) {
1879                 unsigned long addr = (unsigned long)(*pages);
1880                 struct vm_area_struct *vma;
1881                 struct page *page;
1882                 int err = -EFAULT;
1883
1884                 vma = vma_lookup(mm, addr);
1885                 if (!vma)
1886                         goto set_status;
1887
1888                 /* FOLL_DUMP to ignore special (like zero) pages */
1889                 page = follow_page(vma, addr, FOLL_DUMP);
1890
1891                 err = PTR_ERR(page);
1892                 if (IS_ERR(page))
1893                         goto set_status;
1894
1895                 err = page ? page_to_nid(page) : -ENOENT;
1896 set_status:
1897                 *status = err;
1898
1899                 pages++;
1900                 status++;
1901         }
1902
1903         mmap_read_unlock(mm);
1904 }
1905
1906 static int get_compat_pages_array(const void __user *chunk_pages[],
1907                                   const void __user * __user *pages,
1908                                   unsigned long chunk_nr)
1909 {
1910         compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1911         compat_uptr_t p;
1912         int i;
1913
1914         for (i = 0; i < chunk_nr; i++) {
1915                 if (get_user(p, pages32 + i))
1916                         return -EFAULT;
1917                 chunk_pages[i] = compat_ptr(p);
1918         }
1919
1920         return 0;
1921 }
1922
1923 /*
1924  * Determine the nodes of a user array of pages and store it in
1925  * a user array of status.
1926  */
1927 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1928                          const void __user * __user *pages,
1929                          int __user *status)
1930 {
1931 #define DO_PAGES_STAT_CHUNK_NR 16
1932         const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1933         int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1934
1935         while (nr_pages) {
1936                 unsigned long chunk_nr;
1937
1938                 chunk_nr = nr_pages;
1939                 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1940                         chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1941
1942                 if (in_compat_syscall()) {
1943                         if (get_compat_pages_array(chunk_pages, pages,
1944                                                    chunk_nr))
1945                                 break;
1946                 } else {
1947                         if (copy_from_user(chunk_pages, pages,
1948                                       chunk_nr * sizeof(*chunk_pages)))
1949                                 break;
1950                 }
1951
1952                 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1953
1954                 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1955                         break;
1956
1957                 pages += chunk_nr;
1958                 status += chunk_nr;
1959                 nr_pages -= chunk_nr;
1960         }
1961         return nr_pages ? -EFAULT : 0;
1962 }
1963
1964 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1965 {
1966         struct task_struct *task;
1967         struct mm_struct *mm;
1968
1969         /*
1970          * There is no need to check if current process has the right to modify
1971          * the specified process when they are same.
1972          */
1973         if (!pid) {
1974                 mmget(current->mm);
1975                 *mem_nodes = cpuset_mems_allowed(current);
1976                 return current->mm;
1977         }
1978
1979         /* Find the mm_struct */
1980         rcu_read_lock();
1981         task = find_task_by_vpid(pid);
1982         if (!task) {
1983                 rcu_read_unlock();
1984                 return ERR_PTR(-ESRCH);
1985         }
1986         get_task_struct(task);
1987
1988         /*
1989          * Check if this process has the right to modify the specified
1990          * process. Use the regular "ptrace_may_access()" checks.
1991          */
1992         if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1993                 rcu_read_unlock();
1994                 mm = ERR_PTR(-EPERM);
1995                 goto out;
1996         }
1997         rcu_read_unlock();
1998
1999         mm = ERR_PTR(security_task_movememory(task));
2000         if (IS_ERR(mm))
2001                 goto out;
2002         *mem_nodes = cpuset_mems_allowed(task);
2003         mm = get_task_mm(task);
2004 out:
2005         put_task_struct(task);
2006         if (!mm)
2007                 mm = ERR_PTR(-EINVAL);
2008         return mm;
2009 }
2010
2011 /*
2012  * Move a list of pages in the address space of the currently executing
2013  * process.
2014  */
2015 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
2016                              const void __user * __user *pages,
2017                              const int __user *nodes,
2018                              int __user *status, int flags)
2019 {
2020         struct mm_struct *mm;
2021         int err;
2022         nodemask_t task_nodes;
2023
2024         /* Check flags */
2025         if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
2026                 return -EINVAL;
2027
2028         if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
2029                 return -EPERM;
2030
2031         mm = find_mm_struct(pid, &task_nodes);
2032         if (IS_ERR(mm))
2033                 return PTR_ERR(mm);
2034
2035         if (nodes)
2036                 err = do_pages_move(mm, task_nodes, nr_pages, pages,
2037                                     nodes, status, flags);
2038         else
2039                 err = do_pages_stat(mm, nr_pages, pages, status);
2040
2041         mmput(mm);
2042         return err;
2043 }
2044
2045 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
2046                 const void __user * __user *, pages,
2047                 const int __user *, nodes,
2048                 int __user *, status, int, flags)
2049 {
2050         return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
2051 }
2052
2053 #ifdef CONFIG_NUMA_BALANCING
2054 /*
2055  * Returns true if this is a safe migration target node for misplaced NUMA
2056  * pages. Currently it only checks the watermarks which crude
2057  */
2058 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
2059                                    unsigned long nr_migrate_pages)
2060 {
2061         int z;
2062
2063         for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2064                 struct zone *zone = pgdat->node_zones + z;
2065
2066                 if (!populated_zone(zone))
2067                         continue;
2068
2069                 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
2070                 if (!zone_watermark_ok(zone, 0,
2071                                        high_wmark_pages(zone) +
2072                                        nr_migrate_pages,
2073                                        ZONE_MOVABLE, 0))
2074                         continue;
2075                 return true;
2076         }
2077         return false;
2078 }
2079
2080 static struct page *alloc_misplaced_dst_page(struct page *page,
2081                                            unsigned long data)
2082 {
2083         int nid = (int) data;
2084         struct page *newpage;
2085
2086         newpage = __alloc_pages_node(nid,
2087                                          (GFP_HIGHUSER_MOVABLE |
2088                                           __GFP_THISNODE | __GFP_NOMEMALLOC |
2089                                           __GFP_NORETRY | __GFP_NOWARN) &
2090                                          ~__GFP_RECLAIM, 0);
2091
2092         return newpage;
2093 }
2094
2095 static struct page *alloc_misplaced_dst_page_thp(struct page *page,
2096                                                  unsigned long data)
2097 {
2098         int nid = (int) data;
2099         struct page *newpage;
2100
2101         newpage = alloc_pages_node(nid, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2102                                    HPAGE_PMD_ORDER);
2103         if (!newpage)
2104                 goto out;
2105
2106         prep_transhuge_page(newpage);
2107
2108 out:
2109         return newpage;
2110 }
2111
2112 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2113 {
2114         int page_lru;
2115         int nr_pages = thp_nr_pages(page);
2116
2117         VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
2118
2119         /* Do not migrate THP mapped by multiple processes */
2120         if (PageTransHuge(page) && total_mapcount(page) > 1)
2121                 return 0;
2122
2123         /* Avoid migrating to a node that is nearly full */
2124         if (!migrate_balanced_pgdat(pgdat, nr_pages))
2125                 return 0;
2126
2127         if (isolate_lru_page(page))
2128                 return 0;
2129
2130         page_lru = page_is_file_lru(page);
2131         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
2132                             nr_pages);
2133
2134         /*
2135          * Isolating the page has taken another reference, so the
2136          * caller's reference can be safely dropped without the page
2137          * disappearing underneath us during migration.
2138          */
2139         put_page(page);
2140         return 1;
2141 }
2142
2143 /*
2144  * Attempt to migrate a misplaced page to the specified destination
2145  * node. Caller is expected to have an elevated reference count on
2146  * the page that will be dropped by this function before returning.
2147  */
2148 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2149                            int node)
2150 {
2151         pg_data_t *pgdat = NODE_DATA(node);
2152         int isolated;
2153         int nr_remaining;
2154         LIST_HEAD(migratepages);
2155         new_page_t *new;
2156         bool compound;
2157         int nr_pages = thp_nr_pages(page);
2158
2159         /*
2160          * PTE mapped THP or HugeTLB page can't reach here so the page could
2161          * be either base page or THP.  And it must be head page if it is
2162          * THP.
2163          */
2164         compound = PageTransHuge(page);
2165
2166         if (compound)
2167                 new = alloc_misplaced_dst_page_thp;
2168         else
2169                 new = alloc_misplaced_dst_page;
2170
2171         /*
2172          * Don't migrate file pages that are mapped in multiple processes
2173          * with execute permissions as they are probably shared libraries.
2174          */
2175         if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2176             (vma->vm_flags & VM_EXEC))
2177                 goto out;
2178
2179         /*
2180          * Also do not migrate dirty pages as not all filesystems can move
2181          * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2182          */
2183         if (page_is_file_lru(page) && PageDirty(page))
2184                 goto out;
2185
2186         isolated = numamigrate_isolate_page(pgdat, page);
2187         if (!isolated)
2188                 goto out;
2189
2190         list_add(&page->lru, &migratepages);
2191         nr_remaining = migrate_pages(&migratepages, *new, NULL, node,
2192                                      MIGRATE_ASYNC, MR_NUMA_MISPLACED, NULL);
2193         if (nr_remaining) {
2194                 if (!list_empty(&migratepages)) {
2195                         list_del(&page->lru);
2196                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2197                                         page_is_file_lru(page), -nr_pages);
2198                         putback_lru_page(page);
2199                 }
2200                 isolated = 0;
2201         } else
2202                 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_pages);
2203         BUG_ON(!list_empty(&migratepages));
2204         return isolated;
2205
2206 out:
2207         put_page(page);
2208         return 0;
2209 }
2210 #endif /* CONFIG_NUMA_BALANCING */
2211 #endif /* CONFIG_NUMA */
2212
2213 #ifdef CONFIG_DEVICE_PRIVATE
2214 static int migrate_vma_collect_skip(unsigned long start,
2215                                     unsigned long end,
2216                                     struct mm_walk *walk)
2217 {
2218         struct migrate_vma *migrate = walk->private;
2219         unsigned long addr;
2220
2221         for (addr = start; addr < end; addr += PAGE_SIZE) {
2222                 migrate->dst[migrate->npages] = 0;
2223                 migrate->src[migrate->npages++] = 0;
2224         }
2225
2226         return 0;
2227 }
2228
2229 static int migrate_vma_collect_hole(unsigned long start,
2230                                     unsigned long end,
2231                                     __always_unused int depth,
2232                                     struct mm_walk *walk)
2233 {
2234         struct migrate_vma *migrate = walk->private;
2235         unsigned long addr;
2236
2237         /* Only allow populating anonymous memory. */
2238         if (!vma_is_anonymous(walk->vma))
2239                 return migrate_vma_collect_skip(start, end, walk);
2240
2241         for (addr = start; addr < end; addr += PAGE_SIZE) {
2242                 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2243                 migrate->dst[migrate->npages] = 0;
2244                 migrate->npages++;
2245                 migrate->cpages++;
2246         }
2247
2248         return 0;
2249 }
2250
2251 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2252                                    unsigned long start,
2253                                    unsigned long end,
2254                                    struct mm_walk *walk)
2255 {
2256         struct migrate_vma *migrate = walk->private;
2257         struct vm_area_struct *vma = walk->vma;
2258         struct mm_struct *mm = vma->vm_mm;
2259         unsigned long addr = start, unmapped = 0;
2260         spinlock_t *ptl;
2261         pte_t *ptep;
2262
2263 again:
2264         if (pmd_none(*pmdp))
2265                 return migrate_vma_collect_hole(start, end, -1, walk);
2266
2267         if (pmd_trans_huge(*pmdp)) {
2268                 struct page *page;
2269
2270                 ptl = pmd_lock(mm, pmdp);
2271                 if (unlikely(!pmd_trans_huge(*pmdp))) {
2272                         spin_unlock(ptl);
2273                         goto again;
2274                 }
2275
2276                 page = pmd_page(*pmdp);
2277                 if (is_huge_zero_page(page)) {
2278                         spin_unlock(ptl);
2279                         split_huge_pmd(vma, pmdp, addr);
2280                         if (pmd_trans_unstable(pmdp))
2281                                 return migrate_vma_collect_skip(start, end,
2282                                                                 walk);
2283                 } else {
2284                         int ret;
2285
2286                         get_page(page);
2287                         spin_unlock(ptl);
2288                         if (unlikely(!trylock_page(page)))
2289                                 return migrate_vma_collect_skip(start, end,
2290                                                                 walk);
2291                         ret = split_huge_page(page);
2292                         unlock_page(page);
2293                         put_page(page);
2294                         if (ret)
2295                                 return migrate_vma_collect_skip(start, end,
2296                                                                 walk);
2297                         if (pmd_none(*pmdp))
2298                                 return migrate_vma_collect_hole(start, end, -1,
2299                                                                 walk);
2300                 }
2301         }
2302
2303         if (unlikely(pmd_bad(*pmdp)))
2304                 return migrate_vma_collect_skip(start, end, walk);
2305
2306         ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2307         arch_enter_lazy_mmu_mode();
2308
2309         for (; addr < end; addr += PAGE_SIZE, ptep++) {
2310                 unsigned long mpfn = 0, pfn;
2311                 struct page *page;
2312                 swp_entry_t entry;
2313                 pte_t pte;
2314
2315                 pte = *ptep;
2316
2317                 if (pte_none(pte)) {
2318                         if (vma_is_anonymous(vma)) {
2319                                 mpfn = MIGRATE_PFN_MIGRATE;
2320                                 migrate->cpages++;
2321                         }
2322                         goto next;
2323                 }
2324
2325                 if (!pte_present(pte)) {
2326                         /*
2327                          * Only care about unaddressable device page special
2328                          * page table entry. Other special swap entries are not
2329                          * migratable, and we ignore regular swapped page.
2330                          */
2331                         entry = pte_to_swp_entry(pte);
2332                         if (!is_device_private_entry(entry))
2333                                 goto next;
2334
2335                         page = pfn_swap_entry_to_page(entry);
2336                         if (!(migrate->flags &
2337                                 MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
2338                             page->pgmap->owner != migrate->pgmap_owner)
2339                                 goto next;
2340
2341                         mpfn = migrate_pfn(page_to_pfn(page)) |
2342                                         MIGRATE_PFN_MIGRATE;
2343                         if (is_writable_device_private_entry(entry))
2344                                 mpfn |= MIGRATE_PFN_WRITE;
2345                 } else {
2346                         if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
2347                                 goto next;
2348                         pfn = pte_pfn(pte);
2349                         if (is_zero_pfn(pfn)) {
2350                                 mpfn = MIGRATE_PFN_MIGRATE;
2351                                 migrate->cpages++;
2352                                 goto next;
2353                         }
2354                         page = vm_normal_page(migrate->vma, addr, pte);
2355                         mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2356                         mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2357                 }
2358
2359                 /* FIXME support THP */
2360                 if (!page || !page->mapping || PageTransCompound(page)) {
2361                         mpfn = 0;
2362                         goto next;
2363                 }
2364
2365                 /*
2366                  * By getting a reference on the page we pin it and that blocks
2367                  * any kind of migration. Side effect is that it "freezes" the
2368                  * pte.
2369                  *
2370                  * We drop this reference after isolating the page from the lru
2371                  * for non device page (device page are not on the lru and thus
2372                  * can't be dropped from it).
2373                  */
2374                 get_page(page);
2375                 migrate->cpages++;
2376
2377                 /*
2378                  * Optimize for the common case where page is only mapped once
2379                  * in one process. If we can lock the page, then we can safely
2380                  * set up a special migration page table entry now.
2381                  */
2382                 if (trylock_page(page)) {
2383                         pte_t swp_pte;
2384
2385                         mpfn |= MIGRATE_PFN_LOCKED;
2386                         ptep_get_and_clear(mm, addr, ptep);
2387
2388                         /* Setup special migration page table entry */
2389                         if (mpfn & MIGRATE_PFN_WRITE)
2390                                 entry = make_writable_migration_entry(
2391                                                         page_to_pfn(page));
2392                         else
2393                                 entry = make_readable_migration_entry(
2394                                                         page_to_pfn(page));
2395                         swp_pte = swp_entry_to_pte(entry);
2396                         if (pte_present(pte)) {
2397                                 if (pte_soft_dirty(pte))
2398                                         swp_pte = pte_swp_mksoft_dirty(swp_pte);
2399                                 if (pte_uffd_wp(pte))
2400                                         swp_pte = pte_swp_mkuffd_wp(swp_pte);
2401                         } else {
2402                                 if (pte_swp_soft_dirty(pte))
2403                                         swp_pte = pte_swp_mksoft_dirty(swp_pte);
2404                                 if (pte_swp_uffd_wp(pte))
2405                                         swp_pte = pte_swp_mkuffd_wp(swp_pte);
2406                         }
2407                         set_pte_at(mm, addr, ptep, swp_pte);
2408
2409                         /*
2410                          * This is like regular unmap: we remove the rmap and
2411                          * drop page refcount. Page won't be freed, as we took
2412                          * a reference just above.
2413                          */
2414                         page_remove_rmap(page, false);
2415                         put_page(page);
2416
2417                         if (pte_present(pte))
2418                                 unmapped++;
2419                 }
2420
2421 next:
2422                 migrate->dst[migrate->npages] = 0;
2423                 migrate->src[migrate->npages++] = mpfn;
2424         }
2425
2426         /* Only flush the TLB if we actually modified any entries */
2427         if (unmapped)
2428                 flush_tlb_range(walk->vma, start, end);
2429
2430         arch_leave_lazy_mmu_mode();
2431         pte_unmap_unlock(ptep - 1, ptl);
2432
2433         return 0;
2434 }
2435
2436 static const struct mm_walk_ops migrate_vma_walk_ops = {
2437         .pmd_entry              = migrate_vma_collect_pmd,
2438         .pte_hole               = migrate_vma_collect_hole,
2439 };
2440
2441 /*
2442  * migrate_vma_collect() - collect pages over a range of virtual addresses
2443  * @migrate: migrate struct containing all migration information
2444  *
2445  * This will walk the CPU page table. For each virtual address backed by a
2446  * valid page, it updates the src array and takes a reference on the page, in
2447  * order to pin the page until we lock it and unmap it.
2448  */
2449 static void migrate_vma_collect(struct migrate_vma *migrate)
2450 {
2451         struct mmu_notifier_range range;
2452
2453         /*
2454          * Note that the pgmap_owner is passed to the mmu notifier callback so
2455          * that the registered device driver can skip invalidating device
2456          * private page mappings that won't be migrated.
2457          */
2458         mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
2459                 migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
2460                 migrate->pgmap_owner);
2461         mmu_notifier_invalidate_range_start(&range);
2462
2463         walk_page_range(migrate->vma->vm_mm, migrate->start, migrate->end,
2464                         &migrate_vma_walk_ops, migrate);
2465
2466         mmu_notifier_invalidate_range_end(&range);
2467         migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2468 }
2469
2470 /*
2471  * migrate_vma_check_page() - check if page is pinned or not
2472  * @page: struct page to check
2473  *
2474  * Pinned pages cannot be migrated. This is the same test as in
2475  * migrate_page_move_mapping(), except that here we allow migration of a
2476  * ZONE_DEVICE page.
2477  */
2478 static bool migrate_vma_check_page(struct page *page)
2479 {
2480         /*
2481          * One extra ref because caller holds an extra reference, either from
2482          * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2483          * a device page.
2484          */
2485         int extra = 1;
2486
2487         /*
2488          * FIXME support THP (transparent huge page), it is bit more complex to
2489          * check them than regular pages, because they can be mapped with a pmd
2490          * or with a pte (split pte mapping).
2491          */
2492         if (PageCompound(page))
2493                 return false;
2494
2495         /* Page from ZONE_DEVICE have one extra reference */
2496         if (is_zone_device_page(page)) {
2497                 /*
2498                  * Private page can never be pin as they have no valid pte and
2499                  * GUP will fail for those. Yet if there is a pending migration
2500                  * a thread might try to wait on the pte migration entry and
2501                  * will bump the page reference count. Sadly there is no way to
2502                  * differentiate a regular pin from migration wait. Hence to
2503                  * avoid 2 racing thread trying to migrate back to CPU to enter
2504                  * infinite loop (one stopping migration because the other is
2505                  * waiting on pte migration entry). We always return true here.
2506                  *
2507                  * FIXME proper solution is to rework migration_entry_wait() so
2508                  * it does not need to take a reference on page.
2509                  */
2510                 return is_device_private_page(page);
2511         }
2512
2513         /* For file back page */
2514         if (page_mapping(page))
2515                 extra += 1 + page_has_private(page);
2516
2517         if ((page_count(page) - extra) > page_mapcount(page))
2518                 return false;
2519
2520         return true;
2521 }
2522
2523 /*
2524  * migrate_vma_prepare() - lock pages and isolate them from the lru
2525  * @migrate: migrate struct containing all migration information
2526  *
2527  * This locks pages that have been collected by migrate_vma_collect(). Once each
2528  * page is locked it is isolated from the lru (for non-device pages). Finally,
2529  * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2530  * migrated by concurrent kernel threads.
2531  */
2532 static void migrate_vma_prepare(struct migrate_vma *migrate)
2533 {
2534         const unsigned long npages = migrate->npages;
2535         const unsigned long start = migrate->start;
2536         unsigned long addr, i, restore = 0;
2537         bool allow_drain = true;
2538
2539         lru_add_drain();
2540
2541         for (i = 0; (i < npages) && migrate->cpages; i++) {
2542                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2543                 bool remap = true;
2544
2545                 if (!page)
2546                         continue;
2547
2548                 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2549                         /*
2550                          * Because we are migrating several pages there can be
2551                          * a deadlock between 2 concurrent migration where each
2552                          * are waiting on each other page lock.
2553                          *
2554                          * Make migrate_vma() a best effort thing and backoff
2555                          * for any page we can not lock right away.
2556                          */
2557                         if (!trylock_page(page)) {
2558                                 migrate->src[i] = 0;
2559                                 migrate->cpages--;
2560                                 put_page(page);
2561                                 continue;
2562                         }
2563                         remap = false;
2564                         migrate->src[i] |= MIGRATE_PFN_LOCKED;
2565                 }
2566
2567                 /* ZONE_DEVICE pages are not on LRU */
2568                 if (!is_zone_device_page(page)) {
2569                         if (!PageLRU(page) && allow_drain) {
2570                                 /* Drain CPU's pagevec */
2571                                 lru_add_drain_all();
2572                                 allow_drain = false;
2573                         }
2574
2575                         if (isolate_lru_page(page)) {
2576                                 if (remap) {
2577                                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2578                                         migrate->cpages--;
2579                                         restore++;
2580                                 } else {
2581                                         migrate->src[i] = 0;
2582                                         unlock_page(page);
2583                                         migrate->cpages--;
2584                                         put_page(page);
2585                                 }
2586                                 continue;
2587                         }
2588
2589                         /* Drop the reference we took in collect */
2590                         put_page(page);
2591                 }
2592
2593                 if (!migrate_vma_check_page(page)) {
2594                         if (remap) {
2595                                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2596                                 migrate->cpages--;
2597                                 restore++;
2598
2599                                 if (!is_zone_device_page(page)) {
2600                                         get_page(page);
2601                                         putback_lru_page(page);
2602                                 }
2603                         } else {
2604                                 migrate->src[i] = 0;
2605                                 unlock_page(page);
2606                                 migrate->cpages--;
2607
2608                                 if (!is_zone_device_page(page))
2609                                         putback_lru_page(page);
2610                                 else
2611                                         put_page(page);
2612                         }
2613                 }
2614         }
2615
2616         for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2617                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2618
2619                 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2620                         continue;
2621
2622                 remove_migration_pte(page, migrate->vma, addr, page);
2623
2624                 migrate->src[i] = 0;
2625                 unlock_page(page);
2626                 put_page(page);
2627                 restore--;
2628         }
2629 }
2630
2631 /*
2632  * migrate_vma_unmap() - replace page mapping with special migration pte entry
2633  * @migrate: migrate struct containing all migration information
2634  *
2635  * Replace page mapping (CPU page table pte) with a special migration pte entry
2636  * and check again if it has been pinned. Pinned pages are restored because we
2637  * cannot migrate them.
2638  *
2639  * This is the last step before we call the device driver callback to allocate
2640  * destination memory and copy contents of original page over to new page.
2641  */
2642 static void migrate_vma_unmap(struct migrate_vma *migrate)
2643 {
2644         const unsigned long npages = migrate->npages;
2645         const unsigned long start = migrate->start;
2646         unsigned long addr, i, restore = 0;
2647
2648         for (i = 0; i < npages; i++) {
2649                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2650
2651                 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2652                         continue;
2653
2654                 if (page_mapped(page)) {
2655                         try_to_migrate(page, 0);
2656                         if (page_mapped(page))
2657                                 goto restore;
2658                 }
2659
2660                 if (migrate_vma_check_page(page))
2661                         continue;
2662
2663 restore:
2664                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2665                 migrate->cpages--;
2666                 restore++;
2667         }
2668
2669         for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2670                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2671
2672                 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2673                         continue;
2674
2675                 remove_migration_ptes(page, page, false);
2676
2677                 migrate->src[i] = 0;
2678                 unlock_page(page);
2679                 restore--;
2680
2681                 if (is_zone_device_page(page))
2682                         put_page(page);
2683                 else
2684                         putback_lru_page(page);
2685         }
2686 }
2687
2688 /**
2689  * migrate_vma_setup() - prepare to migrate a range of memory
2690  * @args: contains the vma, start, and pfns arrays for the migration
2691  *
2692  * Returns: negative errno on failures, 0 when 0 or more pages were migrated
2693  * without an error.
2694  *
2695  * Prepare to migrate a range of memory virtual address range by collecting all
2696  * the pages backing each virtual address in the range, saving them inside the
2697  * src array.  Then lock those pages and unmap them. Once the pages are locked
2698  * and unmapped, check whether each page is pinned or not.  Pages that aren't
2699  * pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
2700  * corresponding src array entry.  Then restores any pages that are pinned, by
2701  * remapping and unlocking those pages.
2702  *
2703  * The caller should then allocate destination memory and copy source memory to
2704  * it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
2705  * flag set).  Once these are allocated and copied, the caller must update each
2706  * corresponding entry in the dst array with the pfn value of the destination
2707  * page and with the MIGRATE_PFN_VALID and MIGRATE_PFN_LOCKED flags set
2708  * (destination pages must have their struct pages locked, via lock_page()).
2709  *
2710  * Note that the caller does not have to migrate all the pages that are marked
2711  * with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
2712  * device memory to system memory.  If the caller cannot migrate a device page
2713  * back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
2714  * consequences for the userspace process, so it must be avoided if at all
2715  * possible.
2716  *
2717  * For empty entries inside CPU page table (pte_none() or pmd_none() is true) we
2718  * do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
2719  * allowing the caller to allocate device memory for those unbacked virtual
2720  * addresses.  For this the caller simply has to allocate device memory and
2721  * properly set the destination entry like for regular migration.  Note that
2722  * this can still fail, and thus inside the device driver you must check if the
2723  * migration was successful for those entries after calling migrate_vma_pages(),
2724  * just like for regular migration.
2725  *
2726  * After that, the callers must call migrate_vma_pages() to go over each entry
2727  * in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2728  * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2729  * then migrate_vma_pages() to migrate struct page information from the source
2730  * struct page to the destination struct page.  If it fails to migrate the
2731  * struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
2732  * src array.
2733  *
2734  * At this point all successfully migrated pages have an entry in the src
2735  * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2736  * array entry with MIGRATE_PFN_VALID flag set.
2737  *
2738  * Once migrate_vma_pages() returns the caller may inspect which pages were
2739  * successfully migrated, and which were not.  Successfully migrated pages will
2740  * have the MIGRATE_PFN_MIGRATE flag set for their src array entry.
2741  *
2742  * It is safe to update device page table after migrate_vma_pages() because
2743  * both destination and source page are still locked, and the mmap_lock is held
2744  * in read mode (hence no one can unmap the range being migrated).
2745  *
2746  * Once the caller is done cleaning up things and updating its page table (if it
2747  * chose to do so, this is not an obligation) it finally calls
2748  * migrate_vma_finalize() to update the CPU page table to point to new pages
2749  * for successfully migrated pages or otherwise restore the CPU page table to
2750  * point to the original source pages.
2751  */
2752 int migrate_vma_setup(struct migrate_vma *args)
2753 {
2754         long nr_pages = (args->end - args->start) >> PAGE_SHIFT;
2755
2756         args->start &= PAGE_MASK;
2757         args->end &= PAGE_MASK;
2758         if (!args->vma || is_vm_hugetlb_page(args->vma) ||
2759             (args->vma->vm_flags & VM_SPECIAL) || vma_is_dax(args->vma))
2760                 return -EINVAL;
2761         if (nr_pages <= 0)
2762                 return -EINVAL;
2763         if (args->start < args->vma->vm_start ||
2764             args->start >= args->vma->vm_end)
2765                 return -EINVAL;
2766         if (args->end <= args->vma->vm_start || args->end > args->vma->vm_end)
2767                 return -EINVAL;
2768         if (!args->src || !args->dst)
2769                 return -EINVAL;
2770
2771         memset(args->src, 0, sizeof(*args->src) * nr_pages);
2772         args->cpages = 0;
2773         args->npages = 0;
2774
2775         migrate_vma_collect(args);
2776
2777         if (args->cpages)
2778                 migrate_vma_prepare(args);
2779         if (args->cpages)
2780                 migrate_vma_unmap(args);
2781
2782         /*
2783          * At this point pages are locked and unmapped, and thus they have
2784          * stable content and can safely be copied to destination memory that
2785          * is allocated by the drivers.
2786          */
2787         return 0;
2788
2789 }
2790 EXPORT_SYMBOL(migrate_vma_setup);
2791
2792 /*
2793  * This code closely matches the code in:
2794  *   __handle_mm_fault()
2795  *     handle_pte_fault()
2796  *       do_anonymous_page()
2797  * to map in an anonymous zero page but the struct page will be a ZONE_DEVICE
2798  * private page.
2799  */
2800 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2801                                     unsigned long addr,
2802                                     struct page *page,
2803                                     unsigned long *src)
2804 {
2805         struct vm_area_struct *vma = migrate->vma;
2806         struct mm_struct *mm = vma->vm_mm;
2807         bool flush = false;
2808         spinlock_t *ptl;
2809         pte_t entry;
2810         pgd_t *pgdp;
2811         p4d_t *p4dp;
2812         pud_t *pudp;
2813         pmd_t *pmdp;
2814         pte_t *ptep;
2815
2816         /* Only allow populating anonymous memory */
2817         if (!vma_is_anonymous(vma))
2818                 goto abort;
2819
2820         pgdp = pgd_offset(mm, addr);
2821         p4dp = p4d_alloc(mm, pgdp, addr);
2822         if (!p4dp)
2823                 goto abort;
2824         pudp = pud_alloc(mm, p4dp, addr);
2825         if (!pudp)
2826                 goto abort;
2827         pmdp = pmd_alloc(mm, pudp, addr);
2828         if (!pmdp)
2829                 goto abort;
2830
2831         if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2832                 goto abort;
2833
2834         /*
2835          * Use pte_alloc() instead of pte_alloc_map().  We can't run
2836          * pte_offset_map() on pmds where a huge pmd might be created
2837          * from a different thread.
2838          *
2839          * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
2840          * parallel threads are excluded by other means.
2841          *
2842          * Here we only have mmap_read_lock(mm).
2843          */
2844         if (pte_alloc(mm, pmdp))
2845                 goto abort;
2846
2847         /* See the comment in pte_alloc_one_map() */
2848         if (unlikely(pmd_trans_unstable(pmdp)))
2849                 goto abort;
2850
2851         if (unlikely(anon_vma_prepare(vma)))
2852                 goto abort;
2853         if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
2854                 goto abort;
2855
2856         /*
2857          * The memory barrier inside __SetPageUptodate makes sure that
2858          * preceding stores to the page contents become visible before
2859          * the set_pte_at() write.
2860          */
2861         __SetPageUptodate(page);
2862
2863         if (is_zone_device_page(page)) {
2864                 if (is_device_private_page(page)) {
2865                         swp_entry_t swp_entry;
2866
2867                         if (vma->vm_flags & VM_WRITE)
2868                                 swp_entry = make_writable_device_private_entry(
2869                                                         page_to_pfn(page));
2870                         else
2871                                 swp_entry = make_readable_device_private_entry(
2872                                                         page_to_pfn(page));
2873                         entry = swp_entry_to_pte(swp_entry);
2874                 } else {
2875                         /*
2876                          * For now we only support migrating to un-addressable
2877                          * device memory.
2878                          */
2879                         pr_warn_once("Unsupported ZONE_DEVICE page type.\n");
2880                         goto abort;
2881                 }
2882         } else {
2883                 entry = mk_pte(page, vma->vm_page_prot);
2884                 if (vma->vm_flags & VM_WRITE)
2885                         entry = pte_mkwrite(pte_mkdirty(entry));
2886         }
2887
2888         ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2889
2890         if (check_stable_address_space(mm))
2891                 goto unlock_abort;
2892
2893         if (pte_present(*ptep)) {
2894                 unsigned long pfn = pte_pfn(*ptep);
2895
2896                 if (!is_zero_pfn(pfn))
2897                         goto unlock_abort;
2898                 flush = true;
2899         } else if (!pte_none(*ptep))
2900                 goto unlock_abort;
2901
2902         /*
2903          * Check for userfaultfd but do not deliver the fault. Instead,
2904          * just back off.
2905          */
2906         if (userfaultfd_missing(vma))
2907                 goto unlock_abort;
2908
2909         inc_mm_counter(mm, MM_ANONPAGES);
2910         page_add_new_anon_rmap(page, vma, addr, false);
2911         if (!is_zone_device_page(page))
2912                 lru_cache_add_inactive_or_unevictable(page, vma);
2913         get_page(page);
2914
2915         if (flush) {
2916                 flush_cache_page(vma, addr, pte_pfn(*ptep));
2917                 ptep_clear_flush_notify(vma, addr, ptep);
2918                 set_pte_at_notify(mm, addr, ptep, entry);
2919                 update_mmu_cache(vma, addr, ptep);
2920         } else {
2921                 /* No need to invalidate - it was non-present before */
2922                 set_pte_at(mm, addr, ptep, entry);
2923                 update_mmu_cache(vma, addr, ptep);
2924         }
2925
2926         pte_unmap_unlock(ptep, ptl);
2927         *src = MIGRATE_PFN_MIGRATE;
2928         return;
2929
2930 unlock_abort:
2931         pte_unmap_unlock(ptep, ptl);
2932 abort:
2933         *src &= ~MIGRATE_PFN_MIGRATE;
2934 }
2935
2936 /**
2937  * migrate_vma_pages() - migrate meta-data from src page to dst page
2938  * @migrate: migrate struct containing all migration information
2939  *
2940  * This migrates struct page meta-data from source struct page to destination
2941  * struct page. This effectively finishes the migration from source page to the
2942  * destination page.
2943  */
2944 void migrate_vma_pages(struct migrate_vma *migrate)
2945 {
2946         const unsigned long npages = migrate->npages;
2947         const unsigned long start = migrate->start;
2948         struct mmu_notifier_range range;
2949         unsigned long addr, i;
2950         bool notified = false;
2951
2952         for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2953                 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2954                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2955                 struct address_space *mapping;
2956                 int r;
2957
2958                 if (!newpage) {
2959                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2960                         continue;
2961                 }
2962
2963                 if (!page) {
2964                         if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2965                                 continue;
2966                         if (!notified) {
2967                                 notified = true;
2968
2969                                 mmu_notifier_range_init_owner(&range,
2970                                         MMU_NOTIFY_MIGRATE, 0, migrate->vma,
2971                                         migrate->vma->vm_mm, addr, migrate->end,
2972                                         migrate->pgmap_owner);
2973                                 mmu_notifier_invalidate_range_start(&range);
2974                         }
2975                         migrate_vma_insert_page(migrate, addr, newpage,
2976                                                 &migrate->src[i]);
2977                         continue;
2978                 }
2979
2980                 mapping = page_mapping(page);
2981
2982                 if (is_zone_device_page(newpage)) {
2983                         if (is_device_private_page(newpage)) {
2984                                 /*
2985                                  * For now only support private anonymous when
2986                                  * migrating to un-addressable device memory.
2987                                  */
2988                                 if (mapping) {
2989                                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2990                                         continue;
2991                                 }
2992                         } else {
2993                                 /*
2994                                  * Other types of ZONE_DEVICE page are not
2995                                  * supported.
2996                                  */
2997                                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2998                                 continue;
2999                         }
3000                 }
3001
3002                 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
3003                 if (r != MIGRATEPAGE_SUCCESS)
3004                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
3005         }
3006
3007         /*
3008          * No need to double call mmu_notifier->invalidate_range() callback as
3009          * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
3010          * did already call it.
3011          */
3012         if (notified)
3013                 mmu_notifier_invalidate_range_only_end(&range);
3014 }
3015 EXPORT_SYMBOL(migrate_vma_pages);
3016
3017 /**
3018  * migrate_vma_finalize() - restore CPU page table entry
3019  * @migrate: migrate struct containing all migration information
3020  *
3021  * This replaces the special migration pte entry with either a mapping to the
3022  * new page if migration was successful for that page, or to the original page
3023  * otherwise.
3024  *
3025  * This also unlocks the pages and puts them back on the lru, or drops the extra
3026  * refcount, for device pages.
3027  */
3028 void migrate_vma_finalize(struct migrate_vma *migrate)
3029 {
3030         const unsigned long npages = migrate->npages;
3031         unsigned long i;
3032
3033         for (i = 0; i < npages; i++) {
3034                 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
3035                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
3036
3037                 if (!page) {
3038                         if (newpage) {
3039                                 unlock_page(newpage);
3040                                 put_page(newpage);
3041                         }
3042                         continue;
3043                 }
3044
3045                 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
3046                         if (newpage) {
3047                                 unlock_page(newpage);
3048                                 put_page(newpage);
3049                         }
3050                         newpage = page;
3051                 }
3052
3053                 remove_migration_ptes(page, newpage, false);
3054                 unlock_page(page);
3055
3056                 if (is_zone_device_page(page))
3057                         put_page(page);
3058                 else
3059                         putback_lru_page(page);
3060
3061                 if (newpage != page) {
3062                         unlock_page(newpage);
3063                         if (is_zone_device_page(newpage))
3064                                 put_page(newpage);
3065                         else
3066                                 putback_lru_page(newpage);
3067                 }
3068         }
3069 }
3070 EXPORT_SYMBOL(migrate_vma_finalize);
3071 #endif /* CONFIG_DEVICE_PRIVATE */
3072
3073 #if defined(CONFIG_HOTPLUG_CPU)
3074 /* Disable reclaim-based migration. */
3075 static void __disable_all_migrate_targets(void)
3076 {
3077         int node;
3078
3079         for_each_online_node(node)
3080                 node_demotion[node] = NUMA_NO_NODE;
3081 }
3082
3083 static void disable_all_migrate_targets(void)
3084 {
3085         __disable_all_migrate_targets();
3086
3087         /*
3088          * Ensure that the "disable" is visible across the system.
3089          * Readers will see either a combination of before+disable
3090          * state or disable+after.  They will never see before and
3091          * after state together.
3092          *
3093          * The before+after state together might have cycles and
3094          * could cause readers to do things like loop until this
3095          * function finishes.  This ensures they can only see a
3096          * single "bad" read and would, for instance, only loop
3097          * once.
3098          */
3099         synchronize_rcu();
3100 }
3101
3102 /*
3103  * Find an automatic demotion target for 'node'.
3104  * Failing here is OK.  It might just indicate
3105  * being at the end of a chain.
3106  */
3107 static int establish_migrate_target(int node, nodemask_t *used)
3108 {
3109         int migration_target;
3110
3111         /*
3112          * Can not set a migration target on a
3113          * node with it already set.
3114          *
3115          * No need for READ_ONCE() here since this
3116          * in the write path for node_demotion[].
3117          * This should be the only thread writing.
3118          */
3119         if (node_demotion[node] != NUMA_NO_NODE)
3120                 return NUMA_NO_NODE;
3121
3122         migration_target = find_next_best_node(node, used);
3123         if (migration_target == NUMA_NO_NODE)
3124                 return NUMA_NO_NODE;
3125
3126         node_demotion[node] = migration_target;
3127
3128         return migration_target;
3129 }
3130
3131 /*
3132  * When memory fills up on a node, memory contents can be
3133  * automatically migrated to another node instead of
3134  * discarded at reclaim.
3135  *
3136  * Establish a "migration path" which will start at nodes
3137  * with CPUs and will follow the priorities used to build the
3138  * page allocator zonelists.
3139  *
3140  * The difference here is that cycles must be avoided.  If
3141  * node0 migrates to node1, then neither node1, nor anything
3142  * node1 migrates to can migrate to node0.
3143  *
3144  * This function can run simultaneously with readers of
3145  * node_demotion[].  However, it can not run simultaneously
3146  * with itself.  Exclusion is provided by memory hotplug events
3147  * being single-threaded.
3148  */
3149 static void __set_migration_target_nodes(void)
3150 {
3151         nodemask_t next_pass    = NODE_MASK_NONE;
3152         nodemask_t this_pass    = NODE_MASK_NONE;
3153         nodemask_t used_targets = NODE_MASK_NONE;
3154         int node;
3155
3156         /*
3157          * Avoid any oddities like cycles that could occur
3158          * from changes in the topology.  This will leave
3159          * a momentary gap when migration is disabled.
3160          */
3161         disable_all_migrate_targets();
3162
3163         /*
3164          * Allocations go close to CPUs, first.  Assume that
3165          * the migration path starts at the nodes with CPUs.
3166          */
3167         next_pass = node_states[N_CPU];
3168 again:
3169         this_pass = next_pass;
3170         next_pass = NODE_MASK_NONE;
3171         /*
3172          * To avoid cycles in the migration "graph", ensure
3173          * that migration sources are not future targets by
3174          * setting them in 'used_targets'.  Do this only
3175          * once per pass so that multiple source nodes can
3176          * share a target node.
3177          *
3178          * 'used_targets' will become unavailable in future
3179          * passes.  This limits some opportunities for
3180          * multiple source nodes to share a destination.
3181          */
3182         nodes_or(used_targets, used_targets, this_pass);
3183         for_each_node_mask(node, this_pass) {
3184                 int target_node = establish_migrate_target(node, &used_targets);
3185
3186                 if (target_node == NUMA_NO_NODE)
3187                         continue;
3188
3189                 /*
3190                  * Visit targets from this pass in the next pass.
3191                  * Eventually, every node will have been part of
3192                  * a pass, and will become set in 'used_targets'.
3193                  */
3194                 node_set(target_node, next_pass);
3195         }
3196         /*
3197          * 'next_pass' contains nodes which became migration
3198          * targets in this pass.  Make additional passes until
3199          * no more migrations targets are available.
3200          */
3201         if (!nodes_empty(next_pass))
3202                 goto again;
3203 }
3204
3205 /*
3206  * For callers that do not hold get_online_mems() already.
3207  */
3208 static void set_migration_target_nodes(void)
3209 {
3210         get_online_mems();
3211         __set_migration_target_nodes();
3212         put_online_mems();
3213 }
3214
3215 /*
3216  * This leaves migrate-on-reclaim transiently disabled between
3217  * the MEM_GOING_OFFLINE and MEM_OFFLINE events.  This runs
3218  * whether reclaim-based migration is enabled or not, which
3219  * ensures that the user can turn reclaim-based migration at
3220  * any time without needing to recalculate migration targets.
3221  *
3222  * These callbacks already hold get_online_mems().  That is why
3223  * __set_migration_target_nodes() can be used as opposed to
3224  * set_migration_target_nodes().
3225  */
3226 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
3227                                                  unsigned long action, void *_arg)
3228 {
3229         struct memory_notify *arg = _arg;
3230
3231         /*
3232          * Only update the node migration order when a node is
3233          * changing status, like online->offline.  This avoids
3234          * the overhead of synchronize_rcu() in most cases.
3235          */
3236         if (arg->status_change_nid < 0)
3237                 return notifier_from_errno(0);
3238
3239         switch (action) {
3240         case MEM_GOING_OFFLINE:
3241                 /*
3242                  * Make sure there are not transient states where
3243                  * an offline node is a migration target.  This
3244                  * will leave migration disabled until the offline
3245                  * completes and the MEM_OFFLINE case below runs.
3246                  */
3247                 disable_all_migrate_targets();
3248                 break;
3249         case MEM_OFFLINE:
3250         case MEM_ONLINE:
3251                 /*
3252                  * Recalculate the target nodes once the node
3253                  * reaches its final state (online or offline).
3254                  */
3255                 __set_migration_target_nodes();
3256                 break;
3257         case MEM_CANCEL_OFFLINE:
3258                 /*
3259                  * MEM_GOING_OFFLINE disabled all the migration
3260                  * targets.  Reenable them.
3261                  */
3262                 __set_migration_target_nodes();
3263                 break;
3264         case MEM_GOING_ONLINE:
3265         case MEM_CANCEL_ONLINE:
3266                 break;
3267         }
3268
3269         return notifier_from_errno(0);
3270 }
3271
3272 /*
3273  * React to hotplug events that might affect the migration targets
3274  * like events that online or offline NUMA nodes.
3275  *
3276  * The ordering is also currently dependent on which nodes have
3277  * CPUs.  That means we need CPU on/offline notification too.
3278  */
3279 static int migration_online_cpu(unsigned int cpu)
3280 {
3281         set_migration_target_nodes();
3282         return 0;
3283 }
3284
3285 static int migration_offline_cpu(unsigned int cpu)
3286 {
3287         set_migration_target_nodes();
3288         return 0;
3289 }
3290
3291 static int __init migrate_on_reclaim_init(void)
3292 {
3293         int ret;
3294
3295         ret = cpuhp_setup_state_nocalls(CPUHP_MM_DEMOTION_DEAD, "mm/demotion:offline",
3296                                         NULL, migration_offline_cpu);
3297         /*
3298          * In the unlikely case that this fails, the automatic
3299          * migration targets may become suboptimal for nodes
3300          * where N_CPU changes.  With such a small impact in a
3301          * rare case, do not bother trying to do anything special.
3302          */
3303         WARN_ON(ret < 0);
3304         ret = cpuhp_setup_state(CPUHP_AP_MM_DEMOTION_ONLINE, "mm/demotion:online",
3305                                 migration_online_cpu, NULL);
3306         WARN_ON(ret < 0);
3307
3308         hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
3309         return 0;
3310 }
3311 late_initcall(migrate_on_reclaim_init);
3312 #endif /* CONFIG_HOTPLUG_CPU */