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