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