Merge tag 'amd-drm-fixes-5.19-2022-06-08' of https://gitlab.freedesktop.org/agd5f...
[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/pfn_t.h>
42 #include <linux/memremap.h>
43 #include <linux/userfaultfd_k.h>
44 #include <linux/balloon_compaction.h>
45 #include <linux/page_idle.h>
46 #include <linux/page_owner.h>
47 #include <linux/sched/mm.h>
48 #include <linux/ptrace.h>
49 #include <linux/oom.h>
50 #include <linux/memory.h>
51 #include <linux/random.h>
52 #include <linux/sched/sysctl.h>
53
54 #include <asm/tlbflush.h>
55
56 #include <trace/events/migrate.h>
57
58 #include "internal.h"
59
60 int isolate_movable_page(struct page *page, isolate_mode_t mode)
61 {
62         struct address_space *mapping;
63
64         /*
65          * Avoid burning cycles with pages that are yet under __free_pages(),
66          * or just got freed under us.
67          *
68          * In case we 'win' a race for a movable page being freed under us and
69          * raise its refcount preventing __free_pages() from doing its job
70          * the put_page() at the end of this block will take care of
71          * release this page, thus avoiding a nasty leakage.
72          */
73         if (unlikely(!get_page_unless_zero(page)))
74                 goto out;
75
76         /*
77          * Check PageMovable before holding a PG_lock because page's owner
78          * assumes anybody doesn't touch PG_lock of newly allocated page
79          * so unconditionally grabbing the lock ruins page's owner side.
80          */
81         if (unlikely(!__PageMovable(page)))
82                 goto out_putpage;
83         /*
84          * As movable pages are not isolated from LRU lists, concurrent
85          * compaction threads can race against page migration functions
86          * as well as race against the releasing a page.
87          *
88          * In order to avoid having an already isolated movable page
89          * being (wrongly) re-isolated while it is under migration,
90          * or to avoid attempting to isolate pages being released,
91          * lets be sure we have the page lock
92          * before proceeding with the movable page isolation steps.
93          */
94         if (unlikely(!trylock_page(page)))
95                 goto out_putpage;
96
97         if (!PageMovable(page) || PageIsolated(page))
98                 goto out_no_isolated;
99
100         mapping = page_mapping(page);
101         VM_BUG_ON_PAGE(!mapping, page);
102
103         if (!mapping->a_ops->isolate_page(page, mode))
104                 goto out_no_isolated;
105
106         /* Driver shouldn't use PG_isolated bit of page->flags */
107         WARN_ON_ONCE(PageIsolated(page));
108         SetPageIsolated(page);
109         unlock_page(page);
110
111         return 0;
112
113 out_no_isolated:
114         unlock_page(page);
115 out_putpage:
116         put_page(page);
117 out:
118         return -EBUSY;
119 }
120
121 static void putback_movable_page(struct page *page)
122 {
123         struct address_space *mapping;
124
125         mapping = page_mapping(page);
126         mapping->a_ops->putback_page(page);
127         ClearPageIsolated(page);
128 }
129
130 /*
131  * Put previously isolated pages back onto the appropriate lists
132  * from where they were once taken off for compaction/migration.
133  *
134  * This function shall be used whenever the isolated pageset has been
135  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
136  * and isolate_huge_page().
137  */
138 void putback_movable_pages(struct list_head *l)
139 {
140         struct page *page;
141         struct page *page2;
142
143         list_for_each_entry_safe(page, page2, l, lru) {
144                 if (unlikely(PageHuge(page))) {
145                         putback_active_hugepage(page);
146                         continue;
147                 }
148                 list_del(&page->lru);
149                 /*
150                  * We isolated non-lru movable page so here we can use
151                  * __PageMovable because LRU page's mapping cannot have
152                  * PAGE_MAPPING_MOVABLE.
153                  */
154                 if (unlikely(__PageMovable(page))) {
155                         VM_BUG_ON_PAGE(!PageIsolated(page), page);
156                         lock_page(page);
157                         if (PageMovable(page))
158                                 putback_movable_page(page);
159                         else
160                                 ClearPageIsolated(page);
161                         unlock_page(page);
162                         put_page(page);
163                 } else {
164                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
165                                         page_is_file_lru(page), -thp_nr_pages(page));
166                         putback_lru_page(page);
167                 }
168         }
169 }
170
171 /*
172  * Restore a potential migration pte to a working pte entry
173  */
174 static bool remove_migration_pte(struct folio *folio,
175                 struct vm_area_struct *vma, unsigned long addr, void *old)
176 {
177         DEFINE_FOLIO_VMA_WALK(pvmw, old, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
178
179         while (page_vma_mapped_walk(&pvmw)) {
180                 rmap_t rmap_flags = RMAP_NONE;
181                 pte_t pte;
182                 swp_entry_t entry;
183                 struct page *new;
184                 unsigned long idx = 0;
185
186                 /* pgoff is invalid for ksm pages, but they are never large */
187                 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
188                         idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
189                 new = folio_page(folio, idx);
190
191 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
192                 /* PMD-mapped THP migration entry */
193                 if (!pvmw.pte) {
194                         VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
195                                         !folio_test_pmd_mappable(folio), folio);
196                         remove_migration_pmd(&pvmw, new);
197                         continue;
198                 }
199 #endif
200
201                 folio_get(folio);
202                 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
203                 if (pte_swp_soft_dirty(*pvmw.pte))
204                         pte = pte_mksoft_dirty(pte);
205
206                 /*
207                  * Recheck VMA as permissions can change since migration started
208                  */
209                 entry = pte_to_swp_entry(*pvmw.pte);
210                 if (is_writable_migration_entry(entry))
211                         pte = maybe_mkwrite(pte, vma);
212                 else if (pte_swp_uffd_wp(*pvmw.pte))
213                         pte = pte_mkuffd_wp(pte);
214
215                 if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
216                         rmap_flags |= RMAP_EXCLUSIVE;
217
218                 if (unlikely(is_device_private_page(new))) {
219                         if (pte_write(pte))
220                                 entry = make_writable_device_private_entry(
221                                                         page_to_pfn(new));
222                         else
223                                 entry = make_readable_device_private_entry(
224                                                         page_to_pfn(new));
225                         pte = swp_entry_to_pte(entry);
226                         if (pte_swp_soft_dirty(*pvmw.pte))
227                                 pte = pte_swp_mksoft_dirty(pte);
228                         if (pte_swp_uffd_wp(*pvmw.pte))
229                                 pte = pte_swp_mkuffd_wp(pte);
230                 }
231
232 #ifdef CONFIG_HUGETLB_PAGE
233                 if (folio_test_hugetlb(folio)) {
234                         unsigned int shift = huge_page_shift(hstate_vma(vma));
235
236                         pte = pte_mkhuge(pte);
237                         pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
238                         if (folio_test_anon(folio))
239                                 hugepage_add_anon_rmap(new, vma, pvmw.address,
240                                                        rmap_flags);
241                         else
242                                 page_dup_file_rmap(new, true);
243                         set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
244                 } else
245 #endif
246                 {
247                         if (folio_test_anon(folio))
248                                 page_add_anon_rmap(new, vma, pvmw.address,
249                                                    rmap_flags);
250                         else
251                                 page_add_file_rmap(new, vma, false);
252                         set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
253                 }
254                 if (vma->vm_flags & VM_LOCKED)
255                         mlock_page_drain_local();
256
257                 trace_remove_migration_pte(pvmw.address, pte_val(pte),
258                                            compound_order(new));
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 folio *src, struct folio *dst, bool locked)
272 {
273         struct rmap_walk_control rwc = {
274                 .rmap_one = remove_migration_pte,
275                 .arg = src,
276         };
277
278         if (locked)
279                 rmap_walk_locked(dst, &rwc);
280         else
281                 rmap_walk(dst, &rwc);
282 }
283
284 /*
285  * Something used the pte of a page under migration. We need to
286  * get to the page and wait until migration is finished.
287  * When we return from this function the fault will be retried.
288  */
289 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
290                                 spinlock_t *ptl)
291 {
292         pte_t pte;
293         swp_entry_t entry;
294
295         spin_lock(ptl);
296         pte = *ptep;
297         if (!is_swap_pte(pte))
298                 goto out;
299
300         entry = pte_to_swp_entry(pte);
301         if (!is_migration_entry(entry))
302                 goto out;
303
304         migration_entry_wait_on_locked(entry, ptep, ptl);
305         return;
306 out:
307         pte_unmap_unlock(ptep, ptl);
308 }
309
310 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
311                                 unsigned long address)
312 {
313         spinlock_t *ptl = pte_lockptr(mm, pmd);
314         pte_t *ptep = pte_offset_map(pmd, address);
315         __migration_entry_wait(mm, ptep, ptl);
316 }
317
318 void migration_entry_wait_huge(struct vm_area_struct *vma,
319                 struct mm_struct *mm, pte_t *pte)
320 {
321         spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
322         __migration_entry_wait(mm, pte, ptl);
323 }
324
325 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
326 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
327 {
328         spinlock_t *ptl;
329
330         ptl = pmd_lock(mm, pmd);
331         if (!is_pmd_migration_entry(*pmd))
332                 goto unlock;
333         migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), NULL, ptl);
334         return;
335 unlock:
336         spin_unlock(ptl);
337 }
338 #endif
339
340 static int expected_page_refs(struct address_space *mapping, struct page *page)
341 {
342         int expected_count = 1;
343
344         if (mapping)
345                 expected_count += compound_nr(page) + page_has_private(page);
346         return expected_count;
347 }
348
349 /*
350  * Replace the page in the mapping.
351  *
352  * The number of remaining references must be:
353  * 1 for anonymous pages without a mapping
354  * 2 for pages with a mapping
355  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
356  */
357 int folio_migrate_mapping(struct address_space *mapping,
358                 struct folio *newfolio, struct folio *folio, int extra_count)
359 {
360         XA_STATE(xas, &mapping->i_pages, folio_index(folio));
361         struct zone *oldzone, *newzone;
362         int dirty;
363         int expected_count = expected_page_refs(mapping, &folio->page) + extra_count;
364         long nr = folio_nr_pages(folio);
365
366         if (!mapping) {
367                 /* Anonymous page without mapping */
368                 if (folio_ref_count(folio) != expected_count)
369                         return -EAGAIN;
370
371                 /* No turning back from here */
372                 newfolio->index = folio->index;
373                 newfolio->mapping = folio->mapping;
374                 if (folio_test_swapbacked(folio))
375                         __folio_set_swapbacked(newfolio);
376
377                 return MIGRATEPAGE_SUCCESS;
378         }
379
380         oldzone = folio_zone(folio);
381         newzone = folio_zone(newfolio);
382
383         xas_lock_irq(&xas);
384         if (!folio_ref_freeze(folio, expected_count)) {
385                 xas_unlock_irq(&xas);
386                 return -EAGAIN;
387         }
388
389         /*
390          * Now we know that no one else is looking at the folio:
391          * no turning back from here.
392          */
393         newfolio->index = folio->index;
394         newfolio->mapping = folio->mapping;
395         folio_ref_add(newfolio, nr); /* add cache reference */
396         if (folio_test_swapbacked(folio)) {
397                 __folio_set_swapbacked(newfolio);
398                 if (folio_test_swapcache(folio)) {
399                         folio_set_swapcache(newfolio);
400                         newfolio->private = folio_get_private(folio);
401                 }
402         } else {
403                 VM_BUG_ON_FOLIO(folio_test_swapcache(folio), folio);
404         }
405
406         /* Move dirty while page refs frozen and newpage not yet exposed */
407         dirty = folio_test_dirty(folio);
408         if (dirty) {
409                 folio_clear_dirty(folio);
410                 folio_set_dirty(newfolio);
411         }
412
413         xas_store(&xas, newfolio);
414
415         /*
416          * Drop cache reference from old page by unfreezing
417          * to one less reference.
418          * We know this isn't the last reference.
419          */
420         folio_ref_unfreeze(folio, expected_count - nr);
421
422         xas_unlock(&xas);
423         /* Leave irq disabled to prevent preemption while updating stats */
424
425         /*
426          * If moved to a different zone then also account
427          * the page for that zone. Other VM counters will be
428          * taken care of when we establish references to the
429          * new page and drop references to the old page.
430          *
431          * Note that anonymous pages are accounted for
432          * via NR_FILE_PAGES and NR_ANON_MAPPED if they
433          * are mapped to swap space.
434          */
435         if (newzone != oldzone) {
436                 struct lruvec *old_lruvec, *new_lruvec;
437                 struct mem_cgroup *memcg;
438
439                 memcg = folio_memcg(folio);
440                 old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
441                 new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
442
443                 __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
444                 __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
445                 if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
446                         __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
447                         __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
448                 }
449 #ifdef CONFIG_SWAP
450                 if (folio_test_swapcache(folio)) {
451                         __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
452                         __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
453                 }
454 #endif
455                 if (dirty && mapping_can_writeback(mapping)) {
456                         __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
457                         __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
458                         __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
459                         __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
460                 }
461         }
462         local_irq_enable();
463
464         return MIGRATEPAGE_SUCCESS;
465 }
466 EXPORT_SYMBOL(folio_migrate_mapping);
467
468 /*
469  * The expected number of remaining references is the same as that
470  * of folio_migrate_mapping().
471  */
472 int migrate_huge_page_move_mapping(struct address_space *mapping,
473                                    struct page *newpage, struct page *page)
474 {
475         XA_STATE(xas, &mapping->i_pages, page_index(page));
476         int expected_count;
477
478         xas_lock_irq(&xas);
479         expected_count = 2 + page_has_private(page);
480         if (!page_ref_freeze(page, expected_count)) {
481                 xas_unlock_irq(&xas);
482                 return -EAGAIN;
483         }
484
485         newpage->index = page->index;
486         newpage->mapping = page->mapping;
487
488         get_page(newpage);
489
490         xas_store(&xas, newpage);
491
492         page_ref_unfreeze(page, expected_count - 1);
493
494         xas_unlock_irq(&xas);
495
496         return MIGRATEPAGE_SUCCESS;
497 }
498
499 /*
500  * Copy the flags and some other ancillary information
501  */
502 void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
503 {
504         int cpupid;
505
506         if (folio_test_error(folio))
507                 folio_set_error(newfolio);
508         if (folio_test_referenced(folio))
509                 folio_set_referenced(newfolio);
510         if (folio_test_uptodate(folio))
511                 folio_mark_uptodate(newfolio);
512         if (folio_test_clear_active(folio)) {
513                 VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
514                 folio_set_active(newfolio);
515         } else if (folio_test_clear_unevictable(folio))
516                 folio_set_unevictable(newfolio);
517         if (folio_test_workingset(folio))
518                 folio_set_workingset(newfolio);
519         if (folio_test_checked(folio))
520                 folio_set_checked(newfolio);
521         /*
522          * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
523          * migration entries. We can still have PG_anon_exclusive set on an
524          * effectively unmapped and unreferenced first sub-pages of an
525          * anonymous THP: we can simply copy it here via PG_mappedtodisk.
526          */
527         if (folio_test_mappedtodisk(folio))
528                 folio_set_mappedtodisk(newfolio);
529
530         /* Move dirty on pages not done by folio_migrate_mapping() */
531         if (folio_test_dirty(folio))
532                 folio_set_dirty(newfolio);
533
534         if (folio_test_young(folio))
535                 folio_set_young(newfolio);
536         if (folio_test_idle(folio))
537                 folio_set_idle(newfolio);
538
539         /*
540          * Copy NUMA information to the new page, to prevent over-eager
541          * future migrations of this same page.
542          */
543         cpupid = page_cpupid_xchg_last(&folio->page, -1);
544         page_cpupid_xchg_last(&newfolio->page, cpupid);
545
546         folio_migrate_ksm(newfolio, folio);
547         /*
548          * Please do not reorder this without considering how mm/ksm.c's
549          * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
550          */
551         if (folio_test_swapcache(folio))
552                 folio_clear_swapcache(folio);
553         folio_clear_private(folio);
554
555         /* page->private contains hugetlb specific flags */
556         if (!folio_test_hugetlb(folio))
557                 folio->private = NULL;
558
559         /*
560          * If any waiters have accumulated on the new page then
561          * wake them up.
562          */
563         if (folio_test_writeback(newfolio))
564                 folio_end_writeback(newfolio);
565
566         /*
567          * PG_readahead shares the same bit with PG_reclaim.  The above
568          * end_page_writeback() may clear PG_readahead mistakenly, so set the
569          * bit after that.
570          */
571         if (folio_test_readahead(folio))
572                 folio_set_readahead(newfolio);
573
574         folio_copy_owner(newfolio, folio);
575
576         if (!folio_test_hugetlb(folio))
577                 mem_cgroup_migrate(folio, newfolio);
578 }
579 EXPORT_SYMBOL(folio_migrate_flags);
580
581 void folio_migrate_copy(struct folio *newfolio, struct folio *folio)
582 {
583         folio_copy(newfolio, folio);
584         folio_migrate_flags(newfolio, folio);
585 }
586 EXPORT_SYMBOL(folio_migrate_copy);
587
588 /************************************************************
589  *                    Migration functions
590  ***********************************************************/
591
592 /*
593  * Common logic to directly migrate a single LRU page suitable for
594  * pages that do not use PagePrivate/PagePrivate2.
595  *
596  * Pages are locked upon entry and exit.
597  */
598 int migrate_page(struct address_space *mapping,
599                 struct page *newpage, struct page *page,
600                 enum migrate_mode mode)
601 {
602         struct folio *newfolio = page_folio(newpage);
603         struct folio *folio = page_folio(page);
604         int rc;
605
606         BUG_ON(folio_test_writeback(folio));    /* Writeback must be complete */
607
608         rc = folio_migrate_mapping(mapping, newfolio, folio, 0);
609
610         if (rc != MIGRATEPAGE_SUCCESS)
611                 return rc;
612
613         if (mode != MIGRATE_SYNC_NO_COPY)
614                 folio_migrate_copy(newfolio, folio);
615         else
616                 folio_migrate_flags(newfolio, folio);
617         return MIGRATEPAGE_SUCCESS;
618 }
619 EXPORT_SYMBOL(migrate_page);
620
621 #ifdef CONFIG_BLOCK
622 /* Returns true if all buffers are successfully locked */
623 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
624                                                         enum migrate_mode mode)
625 {
626         struct buffer_head *bh = head;
627
628         /* Simple case, sync compaction */
629         if (mode != MIGRATE_ASYNC) {
630                 do {
631                         lock_buffer(bh);
632                         bh = bh->b_this_page;
633
634                 } while (bh != head);
635
636                 return true;
637         }
638
639         /* async case, we cannot block on lock_buffer so use trylock_buffer */
640         do {
641                 if (!trylock_buffer(bh)) {
642                         /*
643                          * We failed to lock the buffer and cannot stall in
644                          * async migration. Release the taken locks
645                          */
646                         struct buffer_head *failed_bh = bh;
647                         bh = head;
648                         while (bh != failed_bh) {
649                                 unlock_buffer(bh);
650                                 bh = bh->b_this_page;
651                         }
652                         return false;
653                 }
654
655                 bh = bh->b_this_page;
656         } while (bh != head);
657         return true;
658 }
659
660 static int __buffer_migrate_page(struct address_space *mapping,
661                 struct page *newpage, struct page *page, enum migrate_mode mode,
662                 bool check_refs)
663 {
664         struct buffer_head *bh, *head;
665         int rc;
666         int expected_count;
667
668         if (!page_has_buffers(page))
669                 return migrate_page(mapping, newpage, page, mode);
670
671         /* Check whether page does not have extra refs before we do more work */
672         expected_count = expected_page_refs(mapping, page);
673         if (page_count(page) != expected_count)
674                 return -EAGAIN;
675
676         head = page_buffers(page);
677         if (!buffer_migrate_lock_buffers(head, mode))
678                 return -EAGAIN;
679
680         if (check_refs) {
681                 bool busy;
682                 bool invalidated = false;
683
684 recheck_buffers:
685                 busy = false;
686                 spin_lock(&mapping->private_lock);
687                 bh = head;
688                 do {
689                         if (atomic_read(&bh->b_count)) {
690                                 busy = true;
691                                 break;
692                         }
693                         bh = bh->b_this_page;
694                 } while (bh != head);
695                 if (busy) {
696                         if (invalidated) {
697                                 rc = -EAGAIN;
698                                 goto unlock_buffers;
699                         }
700                         spin_unlock(&mapping->private_lock);
701                         invalidate_bh_lrus();
702                         invalidated = true;
703                         goto recheck_buffers;
704                 }
705         }
706
707         rc = migrate_page_move_mapping(mapping, newpage, page, 0);
708         if (rc != MIGRATEPAGE_SUCCESS)
709                 goto unlock_buffers;
710
711         attach_page_private(newpage, detach_page_private(page));
712
713         bh = head;
714         do {
715                 set_bh_page(bh, newpage, bh_offset(bh));
716                 bh = bh->b_this_page;
717
718         } while (bh != head);
719
720         if (mode != MIGRATE_SYNC_NO_COPY)
721                 migrate_page_copy(newpage, page);
722         else
723                 migrate_page_states(newpage, page);
724
725         rc = MIGRATEPAGE_SUCCESS;
726 unlock_buffers:
727         if (check_refs)
728                 spin_unlock(&mapping->private_lock);
729         bh = head;
730         do {
731                 unlock_buffer(bh);
732                 bh = bh->b_this_page;
733
734         } while (bh != head);
735
736         return rc;
737 }
738
739 /*
740  * Migration function for pages with buffers. This function can only be used
741  * if the underlying filesystem guarantees that no other references to "page"
742  * exist. For example attached buffer heads are accessed only under page lock.
743  */
744 int buffer_migrate_page(struct address_space *mapping,
745                 struct page *newpage, struct page *page, enum migrate_mode mode)
746 {
747         return __buffer_migrate_page(mapping, newpage, page, mode, false);
748 }
749 EXPORT_SYMBOL(buffer_migrate_page);
750
751 /*
752  * Same as above except that this variant is more careful and checks that there
753  * are also no buffer head references. This function is the right one for
754  * mappings where buffer heads are directly looked up and referenced (such as
755  * block device mappings).
756  */
757 int buffer_migrate_page_norefs(struct address_space *mapping,
758                 struct page *newpage, struct page *page, enum migrate_mode mode)
759 {
760         return __buffer_migrate_page(mapping, newpage, page, mode, true);
761 }
762 #endif
763
764 /*
765  * Writeback a page to clean the dirty state
766  */
767 static int writeout(struct address_space *mapping, struct page *page)
768 {
769         struct folio *folio = page_folio(page);
770         struct writeback_control wbc = {
771                 .sync_mode = WB_SYNC_NONE,
772                 .nr_to_write = 1,
773                 .range_start = 0,
774                 .range_end = LLONG_MAX,
775                 .for_reclaim = 1
776         };
777         int rc;
778
779         if (!mapping->a_ops->writepage)
780                 /* No write method for the address space */
781                 return -EINVAL;
782
783         if (!clear_page_dirty_for_io(page))
784                 /* Someone else already triggered a write */
785                 return -EAGAIN;
786
787         /*
788          * A dirty page may imply that the underlying filesystem has
789          * the page on some queue. So the page must be clean for
790          * migration. Writeout may mean we loose the lock and the
791          * page state is no longer what we checked for earlier.
792          * At this point we know that the migration attempt cannot
793          * be successful.
794          */
795         remove_migration_ptes(folio, folio, false);
796
797         rc = mapping->a_ops->writepage(page, &wbc);
798
799         if (rc != AOP_WRITEPAGE_ACTIVATE)
800                 /* unlocked. Relock */
801                 lock_page(page);
802
803         return (rc < 0) ? -EIO : -EAGAIN;
804 }
805
806 /*
807  * Default handling if a filesystem does not provide a migration function.
808  */
809 static int fallback_migrate_page(struct address_space *mapping,
810         struct page *newpage, struct page *page, enum migrate_mode mode)
811 {
812         if (PageDirty(page)) {
813                 /* Only writeback pages in full synchronous migration */
814                 switch (mode) {
815                 case MIGRATE_SYNC:
816                 case MIGRATE_SYNC_NO_COPY:
817                         break;
818                 default:
819                         return -EBUSY;
820                 }
821                 return writeout(mapping, page);
822         }
823
824         /*
825          * Buffers may be managed in a filesystem specific way.
826          * We must have no buffers or drop them.
827          */
828         if (page_has_private(page) &&
829             !try_to_release_page(page, GFP_KERNEL))
830                 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
831
832         return migrate_page(mapping, newpage, page, mode);
833 }
834
835 /*
836  * Move a page to a newly allocated page
837  * The page is locked and all ptes have been successfully removed.
838  *
839  * The new page will have replaced the old page if this function
840  * is successful.
841  *
842  * Return value:
843  *   < 0 - error code
844  *  MIGRATEPAGE_SUCCESS - success
845  */
846 static int move_to_new_folio(struct folio *dst, struct folio *src,
847                                 enum migrate_mode mode)
848 {
849         struct address_space *mapping;
850         int rc = -EAGAIN;
851         bool is_lru = !__PageMovable(&src->page);
852
853         VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
854         VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
855
856         mapping = folio_mapping(src);
857
858         if (likely(is_lru)) {
859                 if (!mapping)
860                         rc = migrate_page(mapping, &dst->page, &src->page, mode);
861                 else if (mapping->a_ops->migratepage)
862                         /*
863                          * Most pages have a mapping and most filesystems
864                          * provide a migratepage callback. Anonymous pages
865                          * are part of swap space which also has its own
866                          * migratepage callback. This is the most common path
867                          * for page migration.
868                          */
869                         rc = mapping->a_ops->migratepage(mapping, &dst->page,
870                                                         &src->page, mode);
871                 else
872                         rc = fallback_migrate_page(mapping, &dst->page,
873                                                         &src->page, mode);
874         } else {
875                 /*
876                  * In case of non-lru page, it could be released after
877                  * isolation step. In that case, we shouldn't try migration.
878                  */
879                 VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
880                 if (!folio_test_movable(src)) {
881                         rc = MIGRATEPAGE_SUCCESS;
882                         folio_clear_isolated(src);
883                         goto out;
884                 }
885
886                 rc = mapping->a_ops->migratepage(mapping, &dst->page,
887                                                 &src->page, mode);
888                 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
889                                 !folio_test_isolated(src));
890         }
891
892         /*
893          * When successful, old pagecache src->mapping must be cleared before
894          * src is freed; but stats require that PageAnon be left as PageAnon.
895          */
896         if (rc == MIGRATEPAGE_SUCCESS) {
897                 if (__PageMovable(&src->page)) {
898                         VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
899
900                         /*
901                          * We clear PG_movable under page_lock so any compactor
902                          * cannot try to migrate this page.
903                          */
904                         folio_clear_isolated(src);
905                 }
906
907                 /*
908                  * Anonymous and movable src->mapping will be cleared by
909                  * free_pages_prepare so don't reset it here for keeping
910                  * the type to work PageAnon, for example.
911                  */
912                 if (!folio_mapping_flags(src))
913                         src->mapping = NULL;
914
915                 if (likely(!folio_is_zone_device(dst)))
916                         flush_dcache_folio(dst);
917         }
918 out:
919         return rc;
920 }
921
922 static int __unmap_and_move(struct page *page, struct page *newpage,
923                                 int force, enum migrate_mode mode)
924 {
925         struct folio *folio = page_folio(page);
926         struct folio *dst = page_folio(newpage);
927         int rc = -EAGAIN;
928         bool page_was_mapped = false;
929         struct anon_vma *anon_vma = NULL;
930         bool is_lru = !__PageMovable(page);
931
932         if (!trylock_page(page)) {
933                 if (!force || mode == MIGRATE_ASYNC)
934                         goto out;
935
936                 /*
937                  * It's not safe for direct compaction to call lock_page.
938                  * For example, during page readahead pages are added locked
939                  * to the LRU. Later, when the IO completes the pages are
940                  * marked uptodate and unlocked. However, the queueing
941                  * could be merging multiple pages for one bio (e.g.
942                  * mpage_readahead). If an allocation happens for the
943                  * second or third page, the process can end up locking
944                  * the same page twice and deadlocking. Rather than
945                  * trying to be clever about what pages can be locked,
946                  * avoid the use of lock_page for direct compaction
947                  * altogether.
948                  */
949                 if (current->flags & PF_MEMALLOC)
950                         goto out;
951
952                 lock_page(page);
953         }
954
955         if (PageWriteback(page)) {
956                 /*
957                  * Only in the case of a full synchronous migration is it
958                  * necessary to wait for PageWriteback. In the async case,
959                  * the retry loop is too short and in the sync-light case,
960                  * the overhead of stalling is too much
961                  */
962                 switch (mode) {
963                 case MIGRATE_SYNC:
964                 case MIGRATE_SYNC_NO_COPY:
965                         break;
966                 default:
967                         rc = -EBUSY;
968                         goto out_unlock;
969                 }
970                 if (!force)
971                         goto out_unlock;
972                 wait_on_page_writeback(page);
973         }
974
975         /*
976          * By try_to_migrate(), page->mapcount goes down to 0 here. In this case,
977          * we cannot notice that anon_vma is freed while we migrates a page.
978          * This get_anon_vma() delays freeing anon_vma pointer until the end
979          * of migration. File cache pages are no problem because of page_lock()
980          * File Caches may use write_page() or lock_page() in migration, then,
981          * just care Anon page here.
982          *
983          * Only page_get_anon_vma() understands the subtleties of
984          * getting a hold on an anon_vma from outside one of its mms.
985          * But if we cannot get anon_vma, then we won't need it anyway,
986          * because that implies that the anon page is no longer mapped
987          * (and cannot be remapped so long as we hold the page lock).
988          */
989         if (PageAnon(page) && !PageKsm(page))
990                 anon_vma = page_get_anon_vma(page);
991
992         /*
993          * Block others from accessing the new page when we get around to
994          * establishing additional references. We are usually the only one
995          * holding a reference to newpage at this point. We used to have a BUG
996          * here if trylock_page(newpage) fails, but would like to allow for
997          * cases where there might be a race with the previous use of newpage.
998          * This is much like races on refcount of oldpage: just don't BUG().
999          */
1000         if (unlikely(!trylock_page(newpage)))
1001                 goto out_unlock;
1002
1003         if (unlikely(!is_lru)) {
1004                 rc = move_to_new_folio(dst, folio, mode);
1005                 goto out_unlock_both;
1006         }
1007
1008         /*
1009          * Corner case handling:
1010          * 1. When a new swap-cache page is read into, it is added to the LRU
1011          * and treated as swapcache but it has no rmap yet.
1012          * Calling try_to_unmap() against a page->mapping==NULL page will
1013          * trigger a BUG.  So handle it here.
1014          * 2. An orphaned page (see truncate_cleanup_page) might have
1015          * fs-private metadata. The page can be picked up due to memory
1016          * offlining.  Everywhere else except page reclaim, the page is
1017          * invisible to the vm, so the page can not be migrated.  So try to
1018          * free the metadata, so the page can be freed.
1019          */
1020         if (!page->mapping) {
1021                 VM_BUG_ON_PAGE(PageAnon(page), page);
1022                 if (page_has_private(page)) {
1023                         try_to_free_buffers(folio);
1024                         goto out_unlock_both;
1025                 }
1026         } else if (page_mapped(page)) {
1027                 /* Establish migration ptes */
1028                 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1029                                 page);
1030                 try_to_migrate(folio, 0);
1031                 page_was_mapped = true;
1032         }
1033
1034         if (!page_mapped(page))
1035                 rc = move_to_new_folio(dst, folio, mode);
1036
1037         /*
1038          * When successful, push newpage to LRU immediately: so that if it
1039          * turns out to be an mlocked page, remove_migration_ptes() will
1040          * automatically build up the correct newpage->mlock_count for it.
1041          *
1042          * We would like to do something similar for the old page, when
1043          * unsuccessful, and other cases when a page has been temporarily
1044          * isolated from the unevictable LRU: but this case is the easiest.
1045          */
1046         if (rc == MIGRATEPAGE_SUCCESS) {
1047                 lru_cache_add(newpage);
1048                 if (page_was_mapped)
1049                         lru_add_drain();
1050         }
1051
1052         if (page_was_mapped)
1053                 remove_migration_ptes(folio,
1054                         rc == MIGRATEPAGE_SUCCESS ? dst : folio, false);
1055
1056 out_unlock_both:
1057         unlock_page(newpage);
1058 out_unlock:
1059         /* Drop an anon_vma reference if we took one */
1060         if (anon_vma)
1061                 put_anon_vma(anon_vma);
1062         unlock_page(page);
1063 out:
1064         /*
1065          * If migration is successful, decrease refcount of the newpage,
1066          * which will not free the page because new page owner increased
1067          * refcounter.
1068          */
1069         if (rc == MIGRATEPAGE_SUCCESS)
1070                 put_page(newpage);
1071
1072         return rc;
1073 }
1074
1075 /*
1076  * Obtain the lock on page, remove all ptes and migrate the page
1077  * to the newly allocated page in newpage.
1078  */
1079 static int unmap_and_move(new_page_t get_new_page,
1080                                    free_page_t put_new_page,
1081                                    unsigned long private, struct page *page,
1082                                    int force, enum migrate_mode mode,
1083                                    enum migrate_reason reason,
1084                                    struct list_head *ret)
1085 {
1086         int rc = MIGRATEPAGE_SUCCESS;
1087         struct page *newpage = NULL;
1088
1089         if (!thp_migration_supported() && PageTransHuge(page))
1090                 return -ENOSYS;
1091
1092         if (page_count(page) == 1) {
1093                 /* page was freed from under us. So we are done. */
1094                 ClearPageActive(page);
1095                 ClearPageUnevictable(page);
1096                 if (unlikely(__PageMovable(page))) {
1097                         lock_page(page);
1098                         if (!PageMovable(page))
1099                                 ClearPageIsolated(page);
1100                         unlock_page(page);
1101                 }
1102                 goto out;
1103         }
1104
1105         newpage = get_new_page(page, private);
1106         if (!newpage)
1107                 return -ENOMEM;
1108
1109         rc = __unmap_and_move(page, newpage, force, mode);
1110         if (rc == MIGRATEPAGE_SUCCESS)
1111                 set_page_owner_migrate_reason(newpage, reason);
1112
1113 out:
1114         if (rc != -EAGAIN) {
1115                 /*
1116                  * A page that has been migrated has all references
1117                  * removed and will be freed. A page that has not been
1118                  * migrated will have kept its references and be restored.
1119                  */
1120                 list_del(&page->lru);
1121         }
1122
1123         /*
1124          * If migration is successful, releases reference grabbed during
1125          * isolation. Otherwise, restore the page to right list unless
1126          * we want to retry.
1127          */
1128         if (rc == MIGRATEPAGE_SUCCESS) {
1129                 /*
1130                  * Compaction can migrate also non-LRU pages which are
1131                  * not accounted to NR_ISOLATED_*. They can be recognized
1132                  * as __PageMovable
1133                  */
1134                 if (likely(!__PageMovable(page)))
1135                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1136                                         page_is_file_lru(page), -thp_nr_pages(page));
1137
1138                 if (reason != MR_MEMORY_FAILURE)
1139                         /*
1140                          * We release the page in page_handle_poison.
1141                          */
1142                         put_page(page);
1143         } else {
1144                 if (rc != -EAGAIN)
1145                         list_add_tail(&page->lru, ret);
1146
1147                 if (put_new_page)
1148                         put_new_page(newpage, private);
1149                 else
1150                         put_page(newpage);
1151         }
1152
1153         return rc;
1154 }
1155
1156 /*
1157  * Counterpart of unmap_and_move_page() for hugepage migration.
1158  *
1159  * This function doesn't wait the completion of hugepage I/O
1160  * because there is no race between I/O and migration for hugepage.
1161  * Note that currently hugepage I/O occurs only in direct I/O
1162  * where no lock is held and PG_writeback is irrelevant,
1163  * and writeback status of all subpages are counted in the reference
1164  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1165  * under direct I/O, the reference of the head page is 512 and a bit more.)
1166  * This means that when we try to migrate hugepage whose subpages are
1167  * doing direct I/O, some references remain after try_to_unmap() and
1168  * hugepage migration fails without data corruption.
1169  *
1170  * There is also no race when direct I/O is issued on the page under migration,
1171  * because then pte is replaced with migration swap entry and direct I/O code
1172  * will wait in the page fault for migration to complete.
1173  */
1174 static int unmap_and_move_huge_page(new_page_t get_new_page,
1175                                 free_page_t put_new_page, unsigned long private,
1176                                 struct page *hpage, int force,
1177                                 enum migrate_mode mode, int reason,
1178                                 struct list_head *ret)
1179 {
1180         struct folio *dst, *src = page_folio(hpage);
1181         int rc = -EAGAIN;
1182         int page_was_mapped = 0;
1183         struct page *new_hpage;
1184         struct anon_vma *anon_vma = NULL;
1185         struct address_space *mapping = NULL;
1186
1187         /*
1188          * Migratability of hugepages depends on architectures and their size.
1189          * This check is necessary because some callers of hugepage migration
1190          * like soft offline and memory hotremove don't walk through page
1191          * tables or check whether the hugepage is pmd-based or not before
1192          * kicking migration.
1193          */
1194         if (!hugepage_migration_supported(page_hstate(hpage))) {
1195                 list_move_tail(&hpage->lru, ret);
1196                 return -ENOSYS;
1197         }
1198
1199         if (page_count(hpage) == 1) {
1200                 /* page was freed from under us. So we are done. */
1201                 putback_active_hugepage(hpage);
1202                 return MIGRATEPAGE_SUCCESS;
1203         }
1204
1205         new_hpage = get_new_page(hpage, private);
1206         if (!new_hpage)
1207                 return -ENOMEM;
1208         dst = page_folio(new_hpage);
1209
1210         if (!trylock_page(hpage)) {
1211                 if (!force)
1212                         goto out;
1213                 switch (mode) {
1214                 case MIGRATE_SYNC:
1215                 case MIGRATE_SYNC_NO_COPY:
1216                         break;
1217                 default:
1218                         goto out;
1219                 }
1220                 lock_page(hpage);
1221         }
1222
1223         /*
1224          * Check for pages which are in the process of being freed.  Without
1225          * page_mapping() set, hugetlbfs specific move page routine will not
1226          * be called and we could leak usage counts for subpools.
1227          */
1228         if (hugetlb_page_subpool(hpage) && !page_mapping(hpage)) {
1229                 rc = -EBUSY;
1230                 goto out_unlock;
1231         }
1232
1233         if (PageAnon(hpage))
1234                 anon_vma = page_get_anon_vma(hpage);
1235
1236         if (unlikely(!trylock_page(new_hpage)))
1237                 goto put_anon;
1238
1239         if (page_mapped(hpage)) {
1240                 enum ttu_flags ttu = 0;
1241
1242                 if (!PageAnon(hpage)) {
1243                         /*
1244                          * In shared mappings, try_to_unmap could potentially
1245                          * call huge_pmd_unshare.  Because of this, take
1246                          * semaphore in write mode here and set TTU_RMAP_LOCKED
1247                          * to let lower levels know we have taken the lock.
1248                          */
1249                         mapping = hugetlb_page_mapping_lock_write(hpage);
1250                         if (unlikely(!mapping))
1251                                 goto unlock_put_anon;
1252
1253                         ttu = TTU_RMAP_LOCKED;
1254                 }
1255
1256                 try_to_migrate(src, ttu);
1257                 page_was_mapped = 1;
1258
1259                 if (ttu & TTU_RMAP_LOCKED)
1260                         i_mmap_unlock_write(mapping);
1261         }
1262
1263         if (!page_mapped(hpage))
1264                 rc = move_to_new_folio(dst, src, mode);
1265
1266         if (page_was_mapped)
1267                 remove_migration_ptes(src,
1268                         rc == MIGRATEPAGE_SUCCESS ? dst : src, false);
1269
1270 unlock_put_anon:
1271         unlock_page(new_hpage);
1272
1273 put_anon:
1274         if (anon_vma)
1275                 put_anon_vma(anon_vma);
1276
1277         if (rc == MIGRATEPAGE_SUCCESS) {
1278                 move_hugetlb_state(hpage, new_hpage, reason);
1279                 put_new_page = NULL;
1280         }
1281
1282 out_unlock:
1283         unlock_page(hpage);
1284 out:
1285         if (rc == MIGRATEPAGE_SUCCESS)
1286                 putback_active_hugepage(hpage);
1287         else if (rc != -EAGAIN)
1288                 list_move_tail(&hpage->lru, ret);
1289
1290         /*
1291          * If migration was not successful and there's a freeing callback, use
1292          * it.  Otherwise, put_page() will drop the reference grabbed during
1293          * isolation.
1294          */
1295         if (put_new_page)
1296                 put_new_page(new_hpage, private);
1297         else
1298                 putback_active_hugepage(new_hpage);
1299
1300         return rc;
1301 }
1302
1303 static inline int try_split_thp(struct page *page, struct page **page2,
1304                                 struct list_head *from)
1305 {
1306         int rc = 0;
1307
1308         lock_page(page);
1309         rc = split_huge_page_to_list(page, from);
1310         unlock_page(page);
1311         if (!rc)
1312                 list_safe_reset_next(page, *page2, lru);
1313
1314         return rc;
1315 }
1316
1317 /*
1318  * migrate_pages - migrate the pages specified in a list, to the free pages
1319  *                 supplied as the target for the page migration
1320  *
1321  * @from:               The list of pages to be migrated.
1322  * @get_new_page:       The function used to allocate free pages to be used
1323  *                      as the target of the page migration.
1324  * @put_new_page:       The function used to free target pages if migration
1325  *                      fails, or NULL if no special handling is necessary.
1326  * @private:            Private data to be passed on to get_new_page()
1327  * @mode:               The migration mode that specifies the constraints for
1328  *                      page migration, if any.
1329  * @reason:             The reason for page migration.
1330  * @ret_succeeded:      Set to the number of normal pages migrated successfully if
1331  *                      the caller passes a non-NULL pointer.
1332  *
1333  * The function returns after 10 attempts or if no pages are movable any more
1334  * because the list has become empty or no retryable pages exist any more.
1335  * It is caller's responsibility to call putback_movable_pages() to return pages
1336  * to the LRU or free list only if ret != 0.
1337  *
1338  * Returns the number of {normal page, THP, hugetlb} that were not migrated, or
1339  * an error code. The number of THP splits will be considered as the number of
1340  * non-migrated THP, no matter how many subpages of the THP are migrated successfully.
1341  */
1342 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1343                 free_page_t put_new_page, unsigned long private,
1344                 enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
1345 {
1346         int retry = 1;
1347         int thp_retry = 1;
1348         int nr_failed = 0;
1349         int nr_failed_pages = 0;
1350         int nr_succeeded = 0;
1351         int nr_thp_succeeded = 0;
1352         int nr_thp_failed = 0;
1353         int nr_thp_split = 0;
1354         int pass = 0;
1355         bool is_thp = false;
1356         struct page *page;
1357         struct page *page2;
1358         int rc, nr_subpages;
1359         LIST_HEAD(ret_pages);
1360         LIST_HEAD(thp_split_pages);
1361         bool nosplit = (reason == MR_NUMA_MISPLACED);
1362         bool no_subpage_counting = false;
1363
1364         trace_mm_migrate_pages_start(mode, reason);
1365
1366 thp_subpage_migration:
1367         for (pass = 0; pass < 10 && (retry || thp_retry); pass++) {
1368                 retry = 0;
1369                 thp_retry = 0;
1370
1371                 list_for_each_entry_safe(page, page2, from, lru) {
1372 retry:
1373                         /*
1374                          * THP statistics is based on the source huge page.
1375                          * Capture required information that might get lost
1376                          * during migration.
1377                          */
1378                         is_thp = PageTransHuge(page) && !PageHuge(page);
1379                         nr_subpages = compound_nr(page);
1380                         cond_resched();
1381
1382                         if (PageHuge(page))
1383                                 rc = unmap_and_move_huge_page(get_new_page,
1384                                                 put_new_page, private, page,
1385                                                 pass > 2, mode, reason,
1386                                                 &ret_pages);
1387                         else
1388                                 rc = unmap_and_move(get_new_page, put_new_page,
1389                                                 private, page, pass > 2, mode,
1390                                                 reason, &ret_pages);
1391                         /*
1392                          * The rules are:
1393                          *      Success: non hugetlb page will be freed, hugetlb
1394                          *               page will be put back
1395                          *      -EAGAIN: stay on the from list
1396                          *      -ENOMEM: stay on the from list
1397                          *      Other errno: put on ret_pages list then splice to
1398                          *                   from list
1399                          */
1400                         switch(rc) {
1401                         /*
1402                          * THP migration might be unsupported or the
1403                          * allocation could've failed so we should
1404                          * retry on the same page with the THP split
1405                          * to base pages.
1406                          *
1407                          * Head page is retried immediately and tail
1408                          * pages are added to the tail of the list so
1409                          * we encounter them after the rest of the list
1410                          * is processed.
1411                          */
1412                         case -ENOSYS:
1413                                 /* THP migration is unsupported */
1414                                 if (is_thp) {
1415                                         nr_thp_failed++;
1416                                         if (!try_split_thp(page, &page2, &thp_split_pages)) {
1417                                                 nr_thp_split++;
1418                                                 goto retry;
1419                                         }
1420                                 /* Hugetlb migration is unsupported */
1421                                 } else if (!no_subpage_counting) {
1422                                         nr_failed++;
1423                                 }
1424
1425                                 nr_failed_pages += nr_subpages;
1426                                 break;
1427                         case -ENOMEM:
1428                                 /*
1429                                  * When memory is low, don't bother to try to migrate
1430                                  * other pages, just exit.
1431                                  * THP NUMA faulting doesn't split THP to retry.
1432                                  */
1433                                 if (is_thp && !nosplit) {
1434                                         nr_thp_failed++;
1435                                         if (!try_split_thp(page, &page2, &thp_split_pages)) {
1436                                                 nr_thp_split++;
1437                                                 goto retry;
1438                                         }
1439                                 } else if (!no_subpage_counting) {
1440                                         nr_failed++;
1441                                 }
1442
1443                                 nr_failed_pages += nr_subpages;
1444                                 /*
1445                                  * There might be some subpages of fail-to-migrate THPs
1446                                  * left in thp_split_pages list. Move them back to migration
1447                                  * list so that they could be put back to the right list by
1448                                  * the caller otherwise the page refcnt will be leaked.
1449                                  */
1450                                 list_splice_init(&thp_split_pages, from);
1451                                 nr_thp_failed += thp_retry;
1452                                 goto out;
1453                         case -EAGAIN:
1454                                 if (is_thp)
1455                                         thp_retry++;
1456                                 else
1457                                         retry++;
1458                                 break;
1459                         case MIGRATEPAGE_SUCCESS:
1460                                 nr_succeeded += nr_subpages;
1461                                 if (is_thp)
1462                                         nr_thp_succeeded++;
1463                                 break;
1464                         default:
1465                                 /*
1466                                  * Permanent failure (-EBUSY, etc.):
1467                                  * unlike -EAGAIN case, the failed page is
1468                                  * removed from migration page list and not
1469                                  * retried in the next outer loop.
1470                                  */
1471                                 if (is_thp)
1472                                         nr_thp_failed++;
1473                                 else if (!no_subpage_counting)
1474                                         nr_failed++;
1475
1476                                 nr_failed_pages += nr_subpages;
1477                                 break;
1478                         }
1479                 }
1480         }
1481         nr_failed += retry;
1482         nr_thp_failed += thp_retry;
1483         /*
1484          * Try to migrate subpages of fail-to-migrate THPs, no nr_failed
1485          * counting in this round, since all subpages of a THP is counted
1486          * as 1 failure in the first round.
1487          */
1488         if (!list_empty(&thp_split_pages)) {
1489                 /*
1490                  * Move non-migrated pages (after 10 retries) to ret_pages
1491                  * to avoid migrating them again.
1492                  */
1493                 list_splice_init(from, &ret_pages);
1494                 list_splice_init(&thp_split_pages, from);
1495                 no_subpage_counting = true;
1496                 retry = 1;
1497                 goto thp_subpage_migration;
1498         }
1499
1500         rc = nr_failed + nr_thp_failed;
1501 out:
1502         /*
1503          * Put the permanent failure page back to migration list, they
1504          * will be put back to the right list by the caller.
1505          */
1506         list_splice(&ret_pages, from);
1507
1508         count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1509         count_vm_events(PGMIGRATE_FAIL, nr_failed_pages);
1510         count_vm_events(THP_MIGRATION_SUCCESS, nr_thp_succeeded);
1511         count_vm_events(THP_MIGRATION_FAIL, nr_thp_failed);
1512         count_vm_events(THP_MIGRATION_SPLIT, nr_thp_split);
1513         trace_mm_migrate_pages(nr_succeeded, nr_failed_pages, nr_thp_succeeded,
1514                                nr_thp_failed, nr_thp_split, mode, reason);
1515
1516         if (ret_succeeded)
1517                 *ret_succeeded = nr_succeeded;
1518
1519         return rc;
1520 }
1521
1522 struct page *alloc_migration_target(struct page *page, unsigned long private)
1523 {
1524         struct folio *folio = page_folio(page);
1525         struct migration_target_control *mtc;
1526         gfp_t gfp_mask;
1527         unsigned int order = 0;
1528         struct folio *new_folio = NULL;
1529         int nid;
1530         int zidx;
1531
1532         mtc = (struct migration_target_control *)private;
1533         gfp_mask = mtc->gfp_mask;
1534         nid = mtc->nid;
1535         if (nid == NUMA_NO_NODE)
1536                 nid = folio_nid(folio);
1537
1538         if (folio_test_hugetlb(folio)) {
1539                 struct hstate *h = page_hstate(&folio->page);
1540
1541                 gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
1542                 return alloc_huge_page_nodemask(h, nid, mtc->nmask, gfp_mask);
1543         }
1544
1545         if (folio_test_large(folio)) {
1546                 /*
1547                  * clear __GFP_RECLAIM to make the migration callback
1548                  * consistent with regular THP allocations.
1549                  */
1550                 gfp_mask &= ~__GFP_RECLAIM;
1551                 gfp_mask |= GFP_TRANSHUGE;
1552                 order = folio_order(folio);
1553         }
1554         zidx = zone_idx(folio_zone(folio));
1555         if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
1556                 gfp_mask |= __GFP_HIGHMEM;
1557
1558         new_folio = __folio_alloc(gfp_mask, order, nid, mtc->nmask);
1559
1560         return &new_folio->page;
1561 }
1562
1563 #ifdef CONFIG_NUMA
1564
1565 static int store_status(int __user *status, int start, int value, int nr)
1566 {
1567         while (nr-- > 0) {
1568                 if (put_user(value, status + start))
1569                         return -EFAULT;
1570                 start++;
1571         }
1572
1573         return 0;
1574 }
1575
1576 static int do_move_pages_to_node(struct mm_struct *mm,
1577                 struct list_head *pagelist, int node)
1578 {
1579         int err;
1580         struct migration_target_control mtc = {
1581                 .nid = node,
1582                 .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1583         };
1584
1585         err = migrate_pages(pagelist, alloc_migration_target, NULL,
1586                 (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1587         if (err)
1588                 putback_movable_pages(pagelist);
1589         return err;
1590 }
1591
1592 /*
1593  * Resolves the given address to a struct page, isolates it from the LRU and
1594  * puts it to the given pagelist.
1595  * Returns:
1596  *     errno - if the page cannot be found/isolated
1597  *     0 - when it doesn't have to be migrated because it is already on the
1598  *         target node
1599  *     1 - when it has been queued
1600  */
1601 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1602                 int node, struct list_head *pagelist, bool migrate_all)
1603 {
1604         struct vm_area_struct *vma;
1605         struct page *page;
1606         int err;
1607
1608         mmap_read_lock(mm);
1609         err = -EFAULT;
1610         vma = vma_lookup(mm, addr);
1611         if (!vma || !vma_migratable(vma))
1612                 goto out;
1613
1614         /* FOLL_DUMP to ignore special (like zero) pages */
1615         page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1616
1617         err = PTR_ERR(page);
1618         if (IS_ERR(page))
1619                 goto out;
1620
1621         err = -ENOENT;
1622         if (!page)
1623                 goto out;
1624
1625         err = 0;
1626         if (page_to_nid(page) == node)
1627                 goto out_putpage;
1628
1629         err = -EACCES;
1630         if (page_mapcount(page) > 1 && !migrate_all)
1631                 goto out_putpage;
1632
1633         if (PageHuge(page)) {
1634                 if (PageHead(page)) {
1635                         isolate_huge_page(page, pagelist);
1636                         err = 1;
1637                 }
1638         } else {
1639                 struct page *head;
1640
1641                 head = compound_head(page);
1642                 err = isolate_lru_page(head);
1643                 if (err)
1644                         goto out_putpage;
1645
1646                 err = 1;
1647                 list_add_tail(&head->lru, pagelist);
1648                 mod_node_page_state(page_pgdat(head),
1649                         NR_ISOLATED_ANON + page_is_file_lru(head),
1650                         thp_nr_pages(head));
1651         }
1652 out_putpage:
1653         /*
1654          * Either remove the duplicate refcount from
1655          * isolate_lru_page() or drop the page ref if it was
1656          * not isolated.
1657          */
1658         put_page(page);
1659 out:
1660         mmap_read_unlock(mm);
1661         return err;
1662 }
1663
1664 static int move_pages_and_store_status(struct mm_struct *mm, int node,
1665                 struct list_head *pagelist, int __user *status,
1666                 int start, int i, unsigned long nr_pages)
1667 {
1668         int err;
1669
1670         if (list_empty(pagelist))
1671                 return 0;
1672
1673         err = do_move_pages_to_node(mm, pagelist, node);
1674         if (err) {
1675                 /*
1676                  * Positive err means the number of failed
1677                  * pages to migrate.  Since we are going to
1678                  * abort and return the number of non-migrated
1679                  * pages, so need to include the rest of the
1680                  * nr_pages that have not been attempted as
1681                  * well.
1682                  */
1683                 if (err > 0)
1684                         err += nr_pages - i - 1;
1685                 return err;
1686         }
1687         return store_status(status, start, node, i - start);
1688 }
1689
1690 /*
1691  * Migrate an array of page address onto an array of nodes and fill
1692  * the corresponding array of status.
1693  */
1694 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1695                          unsigned long nr_pages,
1696                          const void __user * __user *pages,
1697                          const int __user *nodes,
1698                          int __user *status, int flags)
1699 {
1700         int current_node = NUMA_NO_NODE;
1701         LIST_HEAD(pagelist);
1702         int start, i;
1703         int err = 0, err1;
1704
1705         lru_cache_disable();
1706
1707         for (i = start = 0; i < nr_pages; i++) {
1708                 const void __user *p;
1709                 unsigned long addr;
1710                 int node;
1711
1712                 err = -EFAULT;
1713                 if (get_user(p, pages + i))
1714                         goto out_flush;
1715                 if (get_user(node, nodes + i))
1716                         goto out_flush;
1717                 addr = (unsigned long)untagged_addr(p);
1718
1719                 err = -ENODEV;
1720                 if (node < 0 || node >= MAX_NUMNODES)
1721                         goto out_flush;
1722                 if (!node_state(node, N_MEMORY))
1723                         goto out_flush;
1724
1725                 err = -EACCES;
1726                 if (!node_isset(node, task_nodes))
1727                         goto out_flush;
1728
1729                 if (current_node == NUMA_NO_NODE) {
1730                         current_node = node;
1731                         start = i;
1732                 } else if (node != current_node) {
1733                         err = move_pages_and_store_status(mm, current_node,
1734                                         &pagelist, status, start, i, nr_pages);
1735                         if (err)
1736                                 goto out;
1737                         start = i;
1738                         current_node = node;
1739                 }
1740
1741                 /*
1742                  * Errors in the page lookup or isolation are not fatal and we simply
1743                  * report them via status
1744                  */
1745                 err = add_page_for_migration(mm, addr, current_node,
1746                                 &pagelist, flags & MPOL_MF_MOVE_ALL);
1747
1748                 if (err > 0) {
1749                         /* The page is successfully queued for migration */
1750                         continue;
1751                 }
1752
1753                 /*
1754                  * The move_pages() man page does not have an -EEXIST choice, so
1755                  * use -EFAULT instead.
1756                  */
1757                 if (err == -EEXIST)
1758                         err = -EFAULT;
1759
1760                 /*
1761                  * If the page is already on the target node (!err), store the
1762                  * node, otherwise, store the err.
1763                  */
1764                 err = store_status(status, i, err ? : current_node, 1);
1765                 if (err)
1766                         goto out_flush;
1767
1768                 err = move_pages_and_store_status(mm, current_node, &pagelist,
1769                                 status, start, i, nr_pages);
1770                 if (err)
1771                         goto out;
1772                 current_node = NUMA_NO_NODE;
1773         }
1774 out_flush:
1775         /* Make sure we do not overwrite the existing error */
1776         err1 = move_pages_and_store_status(mm, current_node, &pagelist,
1777                                 status, start, i, nr_pages);
1778         if (err >= 0)
1779                 err = err1;
1780 out:
1781         lru_cache_enable();
1782         return err;
1783 }
1784
1785 /*
1786  * Determine the nodes of an array of pages and store it in an array of status.
1787  */
1788 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1789                                 const void __user **pages, int *status)
1790 {
1791         unsigned long i;
1792
1793         mmap_read_lock(mm);
1794
1795         for (i = 0; i < nr_pages; i++) {
1796                 unsigned long addr = (unsigned long)(*pages);
1797                 struct vm_area_struct *vma;
1798                 struct page *page;
1799                 int err = -EFAULT;
1800
1801                 vma = vma_lookup(mm, addr);
1802                 if (!vma)
1803                         goto set_status;
1804
1805                 /* FOLL_DUMP to ignore special (like zero) pages */
1806                 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
1807
1808                 err = PTR_ERR(page);
1809                 if (IS_ERR(page))
1810                         goto set_status;
1811
1812                 if (page) {
1813                         err = page_to_nid(page);
1814                         put_page(page);
1815                 } else {
1816                         err = -ENOENT;
1817                 }
1818 set_status:
1819                 *status = err;
1820
1821                 pages++;
1822                 status++;
1823         }
1824
1825         mmap_read_unlock(mm);
1826 }
1827
1828 static int get_compat_pages_array(const void __user *chunk_pages[],
1829                                   const void __user * __user *pages,
1830                                   unsigned long chunk_nr)
1831 {
1832         compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
1833         compat_uptr_t p;
1834         int i;
1835
1836         for (i = 0; i < chunk_nr; i++) {
1837                 if (get_user(p, pages32 + i))
1838                         return -EFAULT;
1839                 chunk_pages[i] = compat_ptr(p);
1840         }
1841
1842         return 0;
1843 }
1844
1845 /*
1846  * Determine the nodes of a user array of pages and store it in
1847  * a user array of status.
1848  */
1849 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1850                          const void __user * __user *pages,
1851                          int __user *status)
1852 {
1853 #define DO_PAGES_STAT_CHUNK_NR 16UL
1854         const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1855         int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1856
1857         while (nr_pages) {
1858                 unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
1859
1860                 if (in_compat_syscall()) {
1861                         if (get_compat_pages_array(chunk_pages, pages,
1862                                                    chunk_nr))
1863                                 break;
1864                 } else {
1865                         if (copy_from_user(chunk_pages, pages,
1866                                       chunk_nr * sizeof(*chunk_pages)))
1867                                 break;
1868                 }
1869
1870                 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1871
1872                 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1873                         break;
1874
1875                 pages += chunk_nr;
1876                 status += chunk_nr;
1877                 nr_pages -= chunk_nr;
1878         }
1879         return nr_pages ? -EFAULT : 0;
1880 }
1881
1882 static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
1883 {
1884         struct task_struct *task;
1885         struct mm_struct *mm;
1886
1887         /*
1888          * There is no need to check if current process has the right to modify
1889          * the specified process when they are same.
1890          */
1891         if (!pid) {
1892                 mmget(current->mm);
1893                 *mem_nodes = cpuset_mems_allowed(current);
1894                 return current->mm;
1895         }
1896
1897         /* Find the mm_struct */
1898         rcu_read_lock();
1899         task = find_task_by_vpid(pid);
1900         if (!task) {
1901                 rcu_read_unlock();
1902                 return ERR_PTR(-ESRCH);
1903         }
1904         get_task_struct(task);
1905
1906         /*
1907          * Check if this process has the right to modify the specified
1908          * process. Use the regular "ptrace_may_access()" checks.
1909          */
1910         if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1911                 rcu_read_unlock();
1912                 mm = ERR_PTR(-EPERM);
1913                 goto out;
1914         }
1915         rcu_read_unlock();
1916
1917         mm = ERR_PTR(security_task_movememory(task));
1918         if (IS_ERR(mm))
1919                 goto out;
1920         *mem_nodes = cpuset_mems_allowed(task);
1921         mm = get_task_mm(task);
1922 out:
1923         put_task_struct(task);
1924         if (!mm)
1925                 mm = ERR_PTR(-EINVAL);
1926         return mm;
1927 }
1928
1929 /*
1930  * Move a list of pages in the address space of the currently executing
1931  * process.
1932  */
1933 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
1934                              const void __user * __user *pages,
1935                              const int __user *nodes,
1936                              int __user *status, int flags)
1937 {
1938         struct mm_struct *mm;
1939         int err;
1940         nodemask_t task_nodes;
1941
1942         /* Check flags */
1943         if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1944                 return -EINVAL;
1945
1946         if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1947                 return -EPERM;
1948
1949         mm = find_mm_struct(pid, &task_nodes);
1950         if (IS_ERR(mm))
1951                 return PTR_ERR(mm);
1952
1953         if (nodes)
1954                 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1955                                     nodes, status, flags);
1956         else
1957                 err = do_pages_stat(mm, nr_pages, pages, status);
1958
1959         mmput(mm);
1960         return err;
1961 }
1962
1963 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1964                 const void __user * __user *, pages,
1965                 const int __user *, nodes,
1966                 int __user *, status, int, flags)
1967 {
1968         return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1969 }
1970
1971 #ifdef CONFIG_NUMA_BALANCING
1972 /*
1973  * Returns true if this is a safe migration target node for misplaced NUMA
1974  * pages. Currently it only checks the watermarks which is crude.
1975  */
1976 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1977                                    unsigned long nr_migrate_pages)
1978 {
1979         int z;
1980
1981         for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1982                 struct zone *zone = pgdat->node_zones + z;
1983
1984                 if (!managed_zone(zone))
1985                         continue;
1986
1987                 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1988                 if (!zone_watermark_ok(zone, 0,
1989                                        high_wmark_pages(zone) +
1990                                        nr_migrate_pages,
1991                                        ZONE_MOVABLE, 0))
1992                         continue;
1993                 return true;
1994         }
1995         return false;
1996 }
1997
1998 static struct page *alloc_misplaced_dst_page(struct page *page,
1999                                            unsigned long data)
2000 {
2001         int nid = (int) data;
2002         int order = compound_order(page);
2003         gfp_t gfp = __GFP_THISNODE;
2004         struct folio *new;
2005
2006         if (order > 0)
2007                 gfp |= GFP_TRANSHUGE_LIGHT;
2008         else {
2009                 gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
2010                         __GFP_NOWARN;
2011                 gfp &= ~__GFP_RECLAIM;
2012         }
2013         new = __folio_alloc_node(gfp, order, nid);
2014
2015         return &new->page;
2016 }
2017
2018 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
2019 {
2020         int nr_pages = thp_nr_pages(page);
2021         int order = compound_order(page);
2022
2023         VM_BUG_ON_PAGE(order && !PageTransHuge(page), page);
2024
2025         /* Do not migrate THP mapped by multiple processes */
2026         if (PageTransHuge(page) && total_mapcount(page) > 1)
2027                 return 0;
2028
2029         /* Avoid migrating to a node that is nearly full */
2030         if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
2031                 int z;
2032
2033                 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
2034                         return 0;
2035                 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2036                         if (managed_zone(pgdat->node_zones + z))
2037                                 break;
2038                 }
2039                 wakeup_kswapd(pgdat->node_zones + z, 0, order, ZONE_MOVABLE);
2040                 return 0;
2041         }
2042
2043         if (isolate_lru_page(page))
2044                 return 0;
2045
2046         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_is_file_lru(page),
2047                             nr_pages);
2048
2049         /*
2050          * Isolating the page has taken another reference, so the
2051          * caller's reference can be safely dropped without the page
2052          * disappearing underneath us during migration.
2053          */
2054         put_page(page);
2055         return 1;
2056 }
2057
2058 /*
2059  * Attempt to migrate a misplaced page to the specified destination
2060  * node. Caller is expected to have an elevated reference count on
2061  * the page that will be dropped by this function before returning.
2062  */
2063 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
2064                            int node)
2065 {
2066         pg_data_t *pgdat = NODE_DATA(node);
2067         int isolated;
2068         int nr_remaining;
2069         unsigned int nr_succeeded;
2070         LIST_HEAD(migratepages);
2071         int nr_pages = thp_nr_pages(page);
2072
2073         /*
2074          * Don't migrate file pages that are mapped in multiple processes
2075          * with execute permissions as they are probably shared libraries.
2076          */
2077         if (page_mapcount(page) != 1 && page_is_file_lru(page) &&
2078             (vma->vm_flags & VM_EXEC))
2079                 goto out;
2080
2081         /*
2082          * Also do not migrate dirty pages as not all filesystems can move
2083          * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
2084          */
2085         if (page_is_file_lru(page) && PageDirty(page))
2086                 goto out;
2087
2088         isolated = numamigrate_isolate_page(pgdat, page);
2089         if (!isolated)
2090                 goto out;
2091
2092         list_add(&page->lru, &migratepages);
2093         nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
2094                                      NULL, node, MIGRATE_ASYNC,
2095                                      MR_NUMA_MISPLACED, &nr_succeeded);
2096         if (nr_remaining) {
2097                 if (!list_empty(&migratepages)) {
2098                         list_del(&page->lru);
2099                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
2100                                         page_is_file_lru(page), -nr_pages);
2101                         putback_lru_page(page);
2102                 }
2103                 isolated = 0;
2104         }
2105         if (nr_succeeded) {
2106                 count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
2107                 if (!node_is_toptier(page_to_nid(page)) && node_is_toptier(node))
2108                         mod_node_page_state(pgdat, PGPROMOTE_SUCCESS,
2109                                             nr_succeeded);
2110         }
2111         BUG_ON(!list_empty(&migratepages));
2112         return isolated;
2113
2114 out:
2115         put_page(page);
2116         return 0;
2117 }
2118 #endif /* CONFIG_NUMA_BALANCING */
2119
2120 /*
2121  * node_demotion[] example:
2122  *
2123  * Consider a system with two sockets.  Each socket has
2124  * three classes of memory attached: fast, medium and slow.
2125  * Each memory class is placed in its own NUMA node.  The
2126  * CPUs are placed in the node with the "fast" memory.  The
2127  * 6 NUMA nodes (0-5) might be split among the sockets like
2128  * this:
2129  *
2130  *      Socket A: 0, 1, 2
2131  *      Socket B: 3, 4, 5
2132  *
2133  * When Node 0 fills up, its memory should be migrated to
2134  * Node 1.  When Node 1 fills up, it should be migrated to
2135  * Node 2.  The migration path start on the nodes with the
2136  * processors (since allocations default to this node) and
2137  * fast memory, progress through medium and end with the
2138  * slow memory:
2139  *
2140  *      0 -> 1 -> 2 -> stop
2141  *      3 -> 4 -> 5 -> stop
2142  *
2143  * This is represented in the node_demotion[] like this:
2144  *
2145  *      {  nr=1, nodes[0]=1 }, // Node 0 migrates to 1
2146  *      {  nr=1, nodes[0]=2 }, // Node 1 migrates to 2
2147  *      {  nr=0, nodes[0]=-1 }, // Node 2 does not migrate
2148  *      {  nr=1, nodes[0]=4 }, // Node 3 migrates to 4
2149  *      {  nr=1, nodes[0]=5 }, // Node 4 migrates to 5
2150  *      {  nr=0, nodes[0]=-1 }, // Node 5 does not migrate
2151  *
2152  * Moreover some systems may have multiple slow memory nodes.
2153  * Suppose a system has one socket with 3 memory nodes, node 0
2154  * is fast memory type, and node 1/2 both are slow memory
2155  * type, and the distance between fast memory node and slow
2156  * memory node is same. So the migration path should be:
2157  *
2158  *      0 -> 1/2 -> stop
2159  *
2160  * This is represented in the node_demotion[] like this:
2161  *      { nr=2, {nodes[0]=1, nodes[1]=2} }, // Node 0 migrates to node 1 and node 2
2162  *      { nr=0, nodes[0]=-1, }, // Node 1 dose not migrate
2163  *      { nr=0, nodes[0]=-1, }, // Node 2 does not migrate
2164  */
2165
2166 /*
2167  * Writes to this array occur without locking.  Cycles are
2168  * not allowed: Node X demotes to Y which demotes to X...
2169  *
2170  * If multiple reads are performed, a single rcu_read_lock()
2171  * must be held over all reads to ensure that no cycles are
2172  * observed.
2173  */
2174 #define DEFAULT_DEMOTION_TARGET_NODES 15
2175
2176 #if MAX_NUMNODES < DEFAULT_DEMOTION_TARGET_NODES
2177 #define DEMOTION_TARGET_NODES   (MAX_NUMNODES - 1)
2178 #else
2179 #define DEMOTION_TARGET_NODES   DEFAULT_DEMOTION_TARGET_NODES
2180 #endif
2181
2182 struct demotion_nodes {
2183         unsigned short nr;
2184         short nodes[DEMOTION_TARGET_NODES];
2185 };
2186
2187 static struct demotion_nodes *node_demotion __read_mostly;
2188
2189 /**
2190  * next_demotion_node() - Get the next node in the demotion path
2191  * @node: The starting node to lookup the next node
2192  *
2193  * Return: node id for next memory node in the demotion path hierarchy
2194  * from @node; NUMA_NO_NODE if @node is terminal.  This does not keep
2195  * @node online or guarantee that it *continues* to be the next demotion
2196  * target.
2197  */
2198 int next_demotion_node(int node)
2199 {
2200         struct demotion_nodes *nd;
2201         unsigned short target_nr, index;
2202         int target;
2203
2204         if (!node_demotion)
2205                 return NUMA_NO_NODE;
2206
2207         nd = &node_demotion[node];
2208
2209         /*
2210          * node_demotion[] is updated without excluding this
2211          * function from running.  RCU doesn't provide any
2212          * compiler barriers, so the READ_ONCE() is required
2213          * to avoid compiler reordering or read merging.
2214          *
2215          * Make sure to use RCU over entire code blocks if
2216          * node_demotion[] reads need to be consistent.
2217          */
2218         rcu_read_lock();
2219         target_nr = READ_ONCE(nd->nr);
2220
2221         switch (target_nr) {
2222         case 0:
2223                 target = NUMA_NO_NODE;
2224                 goto out;
2225         case 1:
2226                 index = 0;
2227                 break;
2228         default:
2229                 /*
2230                  * If there are multiple target nodes, just select one
2231                  * target node randomly.
2232                  *
2233                  * In addition, we can also use round-robin to select
2234                  * target node, but we should introduce another variable
2235                  * for node_demotion[] to record last selected target node,
2236                  * that may cause cache ping-pong due to the changing of
2237                  * last target node. Or introducing per-cpu data to avoid
2238                  * caching issue, which seems more complicated. So selecting
2239                  * target node randomly seems better until now.
2240                  */
2241                 index = get_random_int() % target_nr;
2242                 break;
2243         }
2244
2245         target = READ_ONCE(nd->nodes[index]);
2246
2247 out:
2248         rcu_read_unlock();
2249         return target;
2250 }
2251
2252 /* Disable reclaim-based migration. */
2253 static void __disable_all_migrate_targets(void)
2254 {
2255         int node, i;
2256
2257         if (!node_demotion)
2258                 return;
2259
2260         for_each_online_node(node) {
2261                 node_demotion[node].nr = 0;
2262                 for (i = 0; i < DEMOTION_TARGET_NODES; i++)
2263                         node_demotion[node].nodes[i] = NUMA_NO_NODE;
2264         }
2265 }
2266
2267 static void disable_all_migrate_targets(void)
2268 {
2269         __disable_all_migrate_targets();
2270
2271         /*
2272          * Ensure that the "disable" is visible across the system.
2273          * Readers will see either a combination of before+disable
2274          * state or disable+after.  They will never see before and
2275          * after state together.
2276          *
2277          * The before+after state together might have cycles and
2278          * could cause readers to do things like loop until this
2279          * function finishes.  This ensures they can only see a
2280          * single "bad" read and would, for instance, only loop
2281          * once.
2282          */
2283         synchronize_rcu();
2284 }
2285
2286 /*
2287  * Find an automatic demotion target for 'node'.
2288  * Failing here is OK.  It might just indicate
2289  * being at the end of a chain.
2290  */
2291 static int establish_migrate_target(int node, nodemask_t *used,
2292                                     int best_distance)
2293 {
2294         int migration_target, index, val;
2295         struct demotion_nodes *nd;
2296
2297         if (!node_demotion)
2298                 return NUMA_NO_NODE;
2299
2300         nd = &node_demotion[node];
2301
2302         migration_target = find_next_best_node(node, used);
2303         if (migration_target == NUMA_NO_NODE)
2304                 return NUMA_NO_NODE;
2305
2306         /*
2307          * If the node has been set a migration target node before,
2308          * which means it's the best distance between them. Still
2309          * check if this node can be demoted to other target nodes
2310          * if they have a same best distance.
2311          */
2312         if (best_distance != -1) {
2313                 val = node_distance(node, migration_target);
2314                 if (val > best_distance)
2315                         goto out_clear;
2316         }
2317
2318         index = nd->nr;
2319         if (WARN_ONCE(index >= DEMOTION_TARGET_NODES,
2320                       "Exceeds maximum demotion target nodes\n"))
2321                 goto out_clear;
2322
2323         nd->nodes[index] = migration_target;
2324         nd->nr++;
2325
2326         return migration_target;
2327 out_clear:
2328         node_clear(migration_target, *used);
2329         return NUMA_NO_NODE;
2330 }
2331
2332 /*
2333  * When memory fills up on a node, memory contents can be
2334  * automatically migrated to another node instead of
2335  * discarded at reclaim.
2336  *
2337  * Establish a "migration path" which will start at nodes
2338  * with CPUs and will follow the priorities used to build the
2339  * page allocator zonelists.
2340  *
2341  * The difference here is that cycles must be avoided.  If
2342  * node0 migrates to node1, then neither node1, nor anything
2343  * node1 migrates to can migrate to node0. Also one node can
2344  * be migrated to multiple nodes if the target nodes all have
2345  * a same best-distance against the source node.
2346  *
2347  * This function can run simultaneously with readers of
2348  * node_demotion[].  However, it can not run simultaneously
2349  * with itself.  Exclusion is provided by memory hotplug events
2350  * being single-threaded.
2351  */
2352 static void __set_migration_target_nodes(void)
2353 {
2354         nodemask_t next_pass;
2355         nodemask_t this_pass;
2356         nodemask_t used_targets = NODE_MASK_NONE;
2357         int node, best_distance;
2358
2359         /*
2360          * Avoid any oddities like cycles that could occur
2361          * from changes in the topology.  This will leave
2362          * a momentary gap when migration is disabled.
2363          */
2364         disable_all_migrate_targets();
2365
2366         /*
2367          * Allocations go close to CPUs, first.  Assume that
2368          * the migration path starts at the nodes with CPUs.
2369          */
2370         next_pass = node_states[N_CPU];
2371 again:
2372         this_pass = next_pass;
2373         next_pass = NODE_MASK_NONE;
2374         /*
2375          * To avoid cycles in the migration "graph", ensure
2376          * that migration sources are not future targets by
2377          * setting them in 'used_targets'.  Do this only
2378          * once per pass so that multiple source nodes can
2379          * share a target node.
2380          *
2381          * 'used_targets' will become unavailable in future
2382          * passes.  This limits some opportunities for
2383          * multiple source nodes to share a destination.
2384          */
2385         nodes_or(used_targets, used_targets, this_pass);
2386
2387         for_each_node_mask(node, this_pass) {
2388                 best_distance = -1;
2389
2390                 /*
2391                  * Try to set up the migration path for the node, and the target
2392                  * migration nodes can be multiple, so doing a loop to find all
2393                  * the target nodes if they all have a best node distance.
2394                  */
2395                 do {
2396                         int target_node =
2397                                 establish_migrate_target(node, &used_targets,
2398                                                          best_distance);
2399
2400                         if (target_node == NUMA_NO_NODE)
2401                                 break;
2402
2403                         if (best_distance == -1)
2404                                 best_distance = node_distance(node, target_node);
2405
2406                         /*
2407                          * Visit targets from this pass in the next pass.
2408                          * Eventually, every node will have been part of
2409                          * a pass, and will become set in 'used_targets'.
2410                          */
2411                         node_set(target_node, next_pass);
2412                 } while (1);
2413         }
2414         /*
2415          * 'next_pass' contains nodes which became migration
2416          * targets in this pass.  Make additional passes until
2417          * no more migrations targets are available.
2418          */
2419         if (!nodes_empty(next_pass))
2420                 goto again;
2421 }
2422
2423 /*
2424  * For callers that do not hold get_online_mems() already.
2425  */
2426 void set_migration_target_nodes(void)
2427 {
2428         get_online_mems();
2429         __set_migration_target_nodes();
2430         put_online_mems();
2431 }
2432
2433 /*
2434  * This leaves migrate-on-reclaim transiently disabled between
2435  * the MEM_GOING_OFFLINE and MEM_OFFLINE events.  This runs
2436  * whether reclaim-based migration is enabled or not, which
2437  * ensures that the user can turn reclaim-based migration at
2438  * any time without needing to recalculate migration targets.
2439  *
2440  * These callbacks already hold get_online_mems().  That is why
2441  * __set_migration_target_nodes() can be used as opposed to
2442  * set_migration_target_nodes().
2443  */
2444 #ifdef CONFIG_MEMORY_HOTPLUG
2445 static int __meminit migrate_on_reclaim_callback(struct notifier_block *self,
2446                                                  unsigned long action, void *_arg)
2447 {
2448         struct memory_notify *arg = _arg;
2449
2450         /*
2451          * Only update the node migration order when a node is
2452          * changing status, like online->offline.  This avoids
2453          * the overhead of synchronize_rcu() in most cases.
2454          */
2455         if (arg->status_change_nid < 0)
2456                 return notifier_from_errno(0);
2457
2458         switch (action) {
2459         case MEM_GOING_OFFLINE:
2460                 /*
2461                  * Make sure there are not transient states where
2462                  * an offline node is a migration target.  This
2463                  * will leave migration disabled until the offline
2464                  * completes and the MEM_OFFLINE case below runs.
2465                  */
2466                 disable_all_migrate_targets();
2467                 break;
2468         case MEM_OFFLINE:
2469         case MEM_ONLINE:
2470                 /*
2471                  * Recalculate the target nodes once the node
2472                  * reaches its final state (online or offline).
2473                  */
2474                 __set_migration_target_nodes();
2475                 break;
2476         case MEM_CANCEL_OFFLINE:
2477                 /*
2478                  * MEM_GOING_OFFLINE disabled all the migration
2479                  * targets.  Reenable them.
2480                  */
2481                 __set_migration_target_nodes();
2482                 break;
2483         case MEM_GOING_ONLINE:
2484         case MEM_CANCEL_ONLINE:
2485                 break;
2486         }
2487
2488         return notifier_from_errno(0);
2489 }
2490 #endif
2491
2492 void __init migrate_on_reclaim_init(void)
2493 {
2494         node_demotion = kcalloc(nr_node_ids,
2495                                 sizeof(struct demotion_nodes),
2496                                 GFP_KERNEL);
2497         WARN_ON(!node_demotion);
2498 #ifdef CONFIG_MEMORY_HOTPLUG
2499         hotplug_memory_notifier(migrate_on_reclaim_callback, 100);
2500 #endif
2501         /*
2502          * At this point, all numa nodes with memory/CPus have their state
2503          * properly set, so we can build the demotion order now.
2504          * Let us hold the cpu_hotplug lock just, as we could possibily have
2505          * CPU hotplug events during boot.
2506          */
2507         cpus_read_lock();
2508         set_migration_target_nodes();
2509         cpus_read_unlock();
2510 }
2511
2512 bool numa_demotion_enabled = false;
2513
2514 #ifdef CONFIG_SYSFS
2515 static ssize_t numa_demotion_enabled_show(struct kobject *kobj,
2516                                           struct kobj_attribute *attr, char *buf)
2517 {
2518         return sysfs_emit(buf, "%s\n",
2519                           numa_demotion_enabled ? "true" : "false");
2520 }
2521
2522 static ssize_t numa_demotion_enabled_store(struct kobject *kobj,
2523                                            struct kobj_attribute *attr,
2524                                            const char *buf, size_t count)
2525 {
2526         ssize_t ret;
2527
2528         ret = kstrtobool(buf, &numa_demotion_enabled);
2529         if (ret)
2530                 return ret;
2531
2532         return count;
2533 }
2534
2535 static struct kobj_attribute numa_demotion_enabled_attr =
2536         __ATTR(demotion_enabled, 0644, numa_demotion_enabled_show,
2537                numa_demotion_enabled_store);
2538
2539 static struct attribute *numa_attrs[] = {
2540         &numa_demotion_enabled_attr.attr,
2541         NULL,
2542 };
2543
2544 static const struct attribute_group numa_attr_group = {
2545         .attrs = numa_attrs,
2546 };
2547
2548 static int __init numa_init_sysfs(void)
2549 {
2550         int err;
2551         struct kobject *numa_kobj;
2552
2553         numa_kobj = kobject_create_and_add("numa", mm_kobj);
2554         if (!numa_kobj) {
2555                 pr_err("failed to create numa kobject\n");
2556                 return -ENOMEM;
2557         }
2558         err = sysfs_create_group(numa_kobj, &numa_attr_group);
2559         if (err) {
2560                 pr_err("failed to register numa group\n");
2561                 goto delete_obj;
2562         }
2563         return 0;
2564
2565 delete_obj:
2566         kobject_put(numa_kobj);
2567         return err;
2568 }
2569 subsys_initcall(numa_init_sysfs);
2570 #endif /* CONFIG_SYSFS */
2571 #endif /* CONFIG_NUMA */