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