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