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