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