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