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