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