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