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