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