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