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