xref: /openbmc/linux/mm/memory_hotplug.c (revision 59f876fb9d68a4d8c20305d7a7a0daf4ee9478a8)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
23947be19SDave Hansen /*
33947be19SDave Hansen  *  linux/mm/memory_hotplug.c
43947be19SDave Hansen  *
53947be19SDave Hansen  *  Copyright (C)
63947be19SDave Hansen  */
73947be19SDave Hansen 
83947be19SDave Hansen #include <linux/stddef.h>
93947be19SDave Hansen #include <linux/mm.h>
10174cd4b1SIngo Molnar #include <linux/sched/signal.h>
113947be19SDave Hansen #include <linux/swap.h>
123947be19SDave Hansen #include <linux/interrupt.h>
133947be19SDave Hansen #include <linux/pagemap.h>
143947be19SDave Hansen #include <linux/compiler.h>
15b95f1b31SPaul Gortmaker #include <linux/export.h>
163947be19SDave Hansen #include <linux/pagevec.h>
172d1d43f6SChandra Seetharaman #include <linux/writeback.h>
183947be19SDave Hansen #include <linux/slab.h>
193947be19SDave Hansen #include <linux/sysctl.h>
203947be19SDave Hansen #include <linux/cpu.h>
213947be19SDave Hansen #include <linux/memory.h>
224b94ffdcSDan Williams #include <linux/memremap.h>
233947be19SDave Hansen #include <linux/memory_hotplug.h>
243947be19SDave Hansen #include <linux/vmalloc.h>
250a547039SKAMEZAWA Hiroyuki #include <linux/ioport.h>
260c0e6195SKAMEZAWA Hiroyuki #include <linux/delay.h>
270c0e6195SKAMEZAWA Hiroyuki #include <linux/migrate.h>
280c0e6195SKAMEZAWA Hiroyuki #include <linux/page-isolation.h>
2971088785SBadari Pulavarty #include <linux/pfn.h>
306ad696d2SAndi Kleen #include <linux/suspend.h>
316d9c285aSKOSAKI Motohiro #include <linux/mm_inline.h>
32d96ae530Sakpm@linux-foundation.org #include <linux/firmware-map.h>
3360a5a19eSTang Chen #include <linux/stop_machine.h>
34c8721bbbSNaoya Horiguchi #include <linux/hugetlb.h>
35c5320926STang Chen #include <linux/memblock.h>
36698b1b30SVlastimil Babka #include <linux/compaction.h>
37b15c8726SMichal Hocko #include <linux/rmap.h>
388581fd40SJakub Kicinski #include <linux/module.h>
393947be19SDave Hansen 
403947be19SDave Hansen #include <asm/tlbflush.h>
413947be19SDave Hansen 
421e5ad9a3SAdrian Bunk #include "internal.h"
43e900a918SDan Williams #include "shuffle.h"
441e5ad9a3SAdrian Bunk 
456e02c46bSMuchun Song #ifdef CONFIG_MHP_MEMMAP_ON_MEMORY
46e3a9d9fcSOscar Salvador /*
47e3a9d9fcSOscar Salvador  * memory_hotplug.memmap_on_memory parameter
48e3a9d9fcSOscar Salvador  */
49e3a9d9fcSOscar Salvador static bool memmap_on_memory __ro_after_init;
5066361095SMuchun Song module_param(memmap_on_memory, bool, 0444);
51e3a9d9fcSOscar Salvador MODULE_PARM_DESC(memmap_on_memory, "Enable memmap on memory for memory hotplug");
526e02c46bSMuchun Song 
5366361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
546e02c46bSMuchun Song {
556e02c46bSMuchun Song 	return memmap_on_memory;
566e02c46bSMuchun Song }
5766361095SMuchun Song #else
5866361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
5966361095SMuchun Song {
6066361095SMuchun Song 	return false;
6166361095SMuchun Song }
62e3a9d9fcSOscar Salvador #endif
63a08a2ae3SOscar Salvador 
64e83a437fSDavid Hildenbrand enum {
65e83a437fSDavid Hildenbrand 	ONLINE_POLICY_CONTIG_ZONES = 0,
66e83a437fSDavid Hildenbrand 	ONLINE_POLICY_AUTO_MOVABLE,
67e83a437fSDavid Hildenbrand };
68e83a437fSDavid Hildenbrand 
69ac62554bSTang Yizhou static const char * const online_policy_to_str[] = {
70e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_CONTIG_ZONES] = "contig-zones",
71e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_AUTO_MOVABLE] = "auto-movable",
72e83a437fSDavid Hildenbrand };
73e83a437fSDavid Hildenbrand 
74e83a437fSDavid Hildenbrand static int set_online_policy(const char *val, const struct kernel_param *kp)
75e83a437fSDavid Hildenbrand {
76e83a437fSDavid Hildenbrand 	int ret = sysfs_match_string(online_policy_to_str, val);
77e83a437fSDavid Hildenbrand 
78e83a437fSDavid Hildenbrand 	if (ret < 0)
79e83a437fSDavid Hildenbrand 		return ret;
80e83a437fSDavid Hildenbrand 	*((int *)kp->arg) = ret;
81e83a437fSDavid Hildenbrand 	return 0;
82e83a437fSDavid Hildenbrand }
83e83a437fSDavid Hildenbrand 
84e83a437fSDavid Hildenbrand static int get_online_policy(char *buffer, const struct kernel_param *kp)
85e83a437fSDavid Hildenbrand {
86e83a437fSDavid Hildenbrand 	return sprintf(buffer, "%s\n", online_policy_to_str[*((int *)kp->arg)]);
87e83a437fSDavid Hildenbrand }
88e83a437fSDavid Hildenbrand 
89e83a437fSDavid Hildenbrand /*
90e83a437fSDavid Hildenbrand  * memory_hotplug.online_policy: configure online behavior when onlining without
91e83a437fSDavid Hildenbrand  * specifying a zone (MMOP_ONLINE)
92e83a437fSDavid Hildenbrand  *
93e83a437fSDavid Hildenbrand  * "contig-zones": keep zone contiguous
94e83a437fSDavid Hildenbrand  * "auto-movable": online memory to ZONE_MOVABLE if the configuration
95e83a437fSDavid Hildenbrand  *                 (auto_movable_ratio, auto_movable_numa_aware) allows for it
96e83a437fSDavid Hildenbrand  */
97e83a437fSDavid Hildenbrand static int online_policy __read_mostly = ONLINE_POLICY_CONTIG_ZONES;
98e83a437fSDavid Hildenbrand static const struct kernel_param_ops online_policy_ops = {
99e83a437fSDavid Hildenbrand 	.set = set_online_policy,
100e83a437fSDavid Hildenbrand 	.get = get_online_policy,
101e83a437fSDavid Hildenbrand };
102e83a437fSDavid Hildenbrand module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
103e83a437fSDavid Hildenbrand MODULE_PARM_DESC(online_policy,
104e83a437fSDavid Hildenbrand 		"Set the online policy (\"contig-zones\", \"auto-movable\") "
105e83a437fSDavid Hildenbrand 		"Default: \"contig-zones\"");
106e83a437fSDavid Hildenbrand 
107e83a437fSDavid Hildenbrand /*
108e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio
109e83a437fSDavid Hildenbrand  *
110e83a437fSDavid Hildenbrand  * The ratio represent an upper limit and the kernel might decide to not
111e83a437fSDavid Hildenbrand  * online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory
112e83a437fSDavid Hildenbrand  * doesn't allow for more MOVABLE memory.
113e83a437fSDavid Hildenbrand  */
114e83a437fSDavid Hildenbrand static unsigned int auto_movable_ratio __read_mostly = 301;
115e83a437fSDavid Hildenbrand module_param(auto_movable_ratio, uint, 0644);
116e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_ratio,
117e83a437fSDavid Hildenbrand 		"Set the maximum ratio of MOVABLE:KERNEL memory in the system "
118e83a437fSDavid Hildenbrand 		"in percent for \"auto-movable\" online policy. Default: 301");
119e83a437fSDavid Hildenbrand 
120e83a437fSDavid Hildenbrand /*
121e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_numa_aware: consider numa node stats
122e83a437fSDavid Hildenbrand  */
123e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
124e83a437fSDavid Hildenbrand static bool auto_movable_numa_aware __read_mostly = true;
125e83a437fSDavid Hildenbrand module_param(auto_movable_numa_aware, bool, 0644);
126e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_numa_aware,
127e83a437fSDavid Hildenbrand 		"Consider numa node stats in addition to global stats in "
128e83a437fSDavid Hildenbrand 		"\"auto-movable\" online policy. Default: true");
129e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
130e83a437fSDavid Hildenbrand 
1319d0ad8caSDaniel Kiper /*
1329d0ad8caSDaniel Kiper  * online_page_callback contains pointer to current page onlining function.
1339d0ad8caSDaniel Kiper  * Initially it is generic_online_page(). If it is required it could be
1349d0ad8caSDaniel Kiper  * changed by calling set_online_page_callback() for callback registration
1359d0ad8caSDaniel Kiper  * and restore_online_page_callback() for generic callback restore.
1369d0ad8caSDaniel Kiper  */
1379d0ad8caSDaniel Kiper 
1389d0ad8caSDaniel Kiper static online_page_callback_t online_page_callback = generic_online_page;
139bfc8c901SVladimir Davydov static DEFINE_MUTEX(online_page_callback_lock);
1409d0ad8caSDaniel Kiper 
1413f906ba2SThomas Gleixner DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
14220d6c96bSKOSAKI Motohiro 
1433f906ba2SThomas Gleixner void get_online_mems(void)
1443f906ba2SThomas Gleixner {
1453f906ba2SThomas Gleixner 	percpu_down_read(&mem_hotplug_lock);
1463f906ba2SThomas Gleixner }
147bfc8c901SVladimir Davydov 
1483f906ba2SThomas Gleixner void put_online_mems(void)
1493f906ba2SThomas Gleixner {
1503f906ba2SThomas Gleixner 	percpu_up_read(&mem_hotplug_lock);
1513f906ba2SThomas Gleixner }
152bfc8c901SVladimir Davydov 
1534932381eSMichal Hocko bool movable_node_enabled = false;
1544932381eSMichal Hocko 
1558604d9e5SVitaly Kuznetsov #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
1561adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_OFFLINE;
1578604d9e5SVitaly Kuznetsov #else
1581adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_ONLINE;
1598604d9e5SVitaly Kuznetsov #endif
16031bc3858SVitaly Kuznetsov 
16186dd995dSVitaly Kuznetsov static int __init setup_memhp_default_state(char *str)
16286dd995dSVitaly Kuznetsov {
1631adf8b46SAnshuman Khandual 	const int online_type = mhp_online_type_from_str(str);
1645f47adf7SDavid Hildenbrand 
1655f47adf7SDavid Hildenbrand 	if (online_type >= 0)
1661adf8b46SAnshuman Khandual 		mhp_default_online_type = online_type;
16786dd995dSVitaly Kuznetsov 
16886dd995dSVitaly Kuznetsov 	return 1;
16986dd995dSVitaly Kuznetsov }
17086dd995dSVitaly Kuznetsov __setup("memhp_default_state=", setup_memhp_default_state);
17186dd995dSVitaly Kuznetsov 
17230467e0bSDavid Rientjes void mem_hotplug_begin(void)
173bfc8c901SVladimir Davydov {
1743f906ba2SThomas Gleixner 	cpus_read_lock();
1753f906ba2SThomas Gleixner 	percpu_down_write(&mem_hotplug_lock);
176bfc8c901SVladimir Davydov }
177bfc8c901SVladimir Davydov 
17830467e0bSDavid Rientjes void mem_hotplug_done(void)
179bfc8c901SVladimir Davydov {
1803f906ba2SThomas Gleixner 	percpu_up_write(&mem_hotplug_lock);
1813f906ba2SThomas Gleixner 	cpus_read_unlock();
182bfc8c901SVladimir Davydov }
18320d6c96bSKOSAKI Motohiro 
184357b4da5SJuergen Gross u64 max_mem_size = U64_MAX;
185357b4da5SJuergen Gross 
18645e0b78bSKeith Mannthey /* add this memory to iomem resource */
1877b7b2721SDavid Hildenbrand static struct resource *register_memory_resource(u64 start, u64 size,
1887b7b2721SDavid Hildenbrand 						 const char *resource_name)
18945e0b78bSKeith Mannthey {
1902794129eSDave Hansen 	struct resource *res;
1912794129eSDave Hansen 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
1927b7b2721SDavid Hildenbrand 
1937b7b2721SDavid Hildenbrand 	if (strcmp(resource_name, "System RAM"))
1947cf603d1SDavid Hildenbrand 		flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
195357b4da5SJuergen Gross 
196bca3feaaSAnshuman Khandual 	if (!mhp_range_allowed(start, size, true))
197bca3feaaSAnshuman Khandual 		return ERR_PTR(-E2BIG);
198bca3feaaSAnshuman Khandual 
199f3cd4c86SBaoquan He 	/*
200f3cd4c86SBaoquan He 	 * Make sure value parsed from 'mem=' only restricts memory adding
201f3cd4c86SBaoquan He 	 * while booting, so that memory hotplug won't be impacted. Please
202f3cd4c86SBaoquan He 	 * refer to document of 'mem=' in kernel-parameters.txt for more
203f3cd4c86SBaoquan He 	 * details.
204f3cd4c86SBaoquan He 	 */
205f3cd4c86SBaoquan He 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
206357b4da5SJuergen Gross 		return ERR_PTR(-E2BIG);
207357b4da5SJuergen Gross 
2082794129eSDave Hansen 	/*
2092794129eSDave Hansen 	 * Request ownership of the new memory range.  This might be
2102794129eSDave Hansen 	 * a child of an existing resource that was present but
2112794129eSDave Hansen 	 * not marked as busy.
2122794129eSDave Hansen 	 */
2132794129eSDave Hansen 	res = __request_region(&iomem_resource, start, size,
2142794129eSDave Hansen 			       resource_name, flags);
21545e0b78bSKeith Mannthey 
2162794129eSDave Hansen 	if (!res) {
2172794129eSDave Hansen 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
2182794129eSDave Hansen 				start, start + size);
2196f754ba4SVitaly Kuznetsov 		return ERR_PTR(-EEXIST);
22045e0b78bSKeith Mannthey 	}
22145e0b78bSKeith Mannthey 	return res;
22245e0b78bSKeith Mannthey }
22345e0b78bSKeith Mannthey 
22445e0b78bSKeith Mannthey static void release_memory_resource(struct resource *res)
22545e0b78bSKeith Mannthey {
22645e0b78bSKeith Mannthey 	if (!res)
22745e0b78bSKeith Mannthey 		return;
22845e0b78bSKeith Mannthey 	release_resource(res);
22945e0b78bSKeith Mannthey 	kfree(res);
23045e0b78bSKeith Mannthey }
23145e0b78bSKeith Mannthey 
232943189dbSAnshuman Khandual static int check_pfn_span(unsigned long pfn, unsigned long nr_pages)
2337ea62160SDan Williams {
2347ea62160SDan Williams 	/*
2357ea62160SDan Williams 	 * Disallow all operations smaller than a sub-section and only
2367ea62160SDan Williams 	 * allow operations smaller than a section for
2377ea62160SDan Williams 	 * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
2387ea62160SDan Williams 	 * enforces a larger memory_block_size_bytes() granularity for
2397ea62160SDan Williams 	 * memory that will be marked online, so this check should only
2407ea62160SDan Williams 	 * fire for direct arch_{add,remove}_memory() users outside of
2417ea62160SDan Williams 	 * add_memory_resource().
2427ea62160SDan Williams 	 */
2437ea62160SDan Williams 	unsigned long min_align;
2447ea62160SDan Williams 
2457ea62160SDan Williams 	if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
2467ea62160SDan Williams 		min_align = PAGES_PER_SUBSECTION;
2477ea62160SDan Williams 	else
2487ea62160SDan Williams 		min_align = PAGES_PER_SECTION;
249943189dbSAnshuman Khandual 	if (!IS_ALIGNED(pfn | nr_pages, min_align))
2507ea62160SDan Williams 		return -EINVAL;
2517ea62160SDan Williams 	return 0;
2527ea62160SDan Williams }
2537ea62160SDan Williams 
2544edd7cefSDavid Rientjes /*
2559f605f26SDan Williams  * Return page for the valid pfn only if the page is online. All pfn
2569f605f26SDan Williams  * walkers which rely on the fully initialized page->flags and others
2579f605f26SDan Williams  * should use this rather than pfn_valid && pfn_to_page
2589f605f26SDan Williams  */
2599f605f26SDan Williams struct page *pfn_to_online_page(unsigned long pfn)
2609f605f26SDan Williams {
2619f605f26SDan Williams 	unsigned long nr = pfn_to_section_nr(pfn);
2621f90a347SDan Williams 	struct dev_pagemap *pgmap;
2639f9b02e5SDan Williams 	struct mem_section *ms;
2649f605f26SDan Williams 
2659f9b02e5SDan Williams 	if (nr >= NR_MEM_SECTIONS)
2669f605f26SDan Williams 		return NULL;
2679f9b02e5SDan Williams 
2689f9b02e5SDan Williams 	ms = __nr_to_section(nr);
2699f9b02e5SDan Williams 	if (!online_section(ms))
2709f9b02e5SDan Williams 		return NULL;
2719f9b02e5SDan Williams 
2729f9b02e5SDan Williams 	/*
2739f9b02e5SDan Williams 	 * Save some code text when online_section() +
2749f9b02e5SDan Williams 	 * pfn_section_valid() are sufficient.
2759f9b02e5SDan Williams 	 */
2769f9b02e5SDan Williams 	if (IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID) && !pfn_valid(pfn))
2779f9b02e5SDan Williams 		return NULL;
2789f9b02e5SDan Williams 
2799f9b02e5SDan Williams 	if (!pfn_section_valid(ms, pfn))
2809f9b02e5SDan Williams 		return NULL;
2819f9b02e5SDan Williams 
2821f90a347SDan Williams 	if (!online_device_section(ms))
2831f90a347SDan Williams 		return pfn_to_page(pfn);
2841f90a347SDan Williams 
2851f90a347SDan Williams 	/*
2861f90a347SDan Williams 	 * Slowpath: when ZONE_DEVICE collides with
2871f90a347SDan Williams 	 * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
2881f90a347SDan Williams 	 * the section may be 'offline' but 'valid'. Only
2891f90a347SDan Williams 	 * get_dev_pagemap() can determine sub-section online status.
2901f90a347SDan Williams 	 */
2911f90a347SDan Williams 	pgmap = get_dev_pagemap(pfn, NULL);
2921f90a347SDan Williams 	put_dev_pagemap(pgmap);
2931f90a347SDan Williams 
2941f90a347SDan Williams 	/* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
2951f90a347SDan Williams 	if (pgmap)
2961f90a347SDan Williams 		return NULL;
2971f90a347SDan Williams 
2989f9b02e5SDan Williams 	return pfn_to_page(pfn);
2999f605f26SDan Williams }
3009f605f26SDan Williams EXPORT_SYMBOL_GPL(pfn_to_online_page);
3019f605f26SDan Williams 
3027ea62160SDan Williams int __ref __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
303f5637d3bSLogan Gunthorpe 		struct mhp_params *params)
3044edd7cefSDavid Rientjes {
3056cdd0b30SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
3066cdd0b30SDavid Hildenbrand 	unsigned long cur_nr_pages;
3079a845030SDan Williams 	int err;
308f5637d3bSLogan Gunthorpe 	struct vmem_altmap *altmap = params->altmap;
3094b94ffdcSDan Williams 
3106366238bSliusongtang 	if (WARN_ON_ONCE(!pgprot_val(params->pgprot)))
311bfeb022fSLogan Gunthorpe 		return -EINVAL;
312bfeb022fSLogan Gunthorpe 
313bca3feaaSAnshuman Khandual 	VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
314dca4436dSAlastair D'Silva 
3154b94ffdcSDan Williams 	if (altmap) {
3164b94ffdcSDan Williams 		/*
3174b94ffdcSDan Williams 		 * Validate altmap is within bounds of the total request
3184b94ffdcSDan Williams 		 */
3197ea62160SDan Williams 		if (altmap->base_pfn != pfn
3204b94ffdcSDan Williams 				|| vmem_altmap_offset(altmap) > nr_pages) {
3214b94ffdcSDan Williams 			pr_warn_once("memory add fail, invalid altmap\n");
3227ea62160SDan Williams 			return -EINVAL;
3234b94ffdcSDan Williams 		}
3244b94ffdcSDan Williams 		altmap->alloc = 0;
3254b94ffdcSDan Williams 	}
3264b94ffdcSDan Williams 
327943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
328943189dbSAnshuman Khandual 		WARN(1, "Misaligned %s start: %#lx end: #%lx\n", __func__, pfn, pfn + nr_pages - 1);
329943189dbSAnshuman Khandual 		return -EINVAL;
330943189dbSAnshuman Khandual 	}
3317ea62160SDan Williams 
3326cdd0b30SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
3336cdd0b30SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
3346cdd0b30SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
3356cdd0b30SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
336e3246d8fSJoao Martins 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
337e3246d8fSJoao Martins 					 params->pgmap);
338ba72b4c8SDan Williams 		if (err)
339ba72b4c8SDan Williams 			break;
340f64ac5e6SMichal Hocko 		cond_resched();
3414edd7cefSDavid Rientjes 	}
342c435a390SZhu Guihua 	vmemmap_populate_print_last();
3434edd7cefSDavid Rientjes 	return err;
3444edd7cefSDavid Rientjes }
3454edd7cefSDavid Rientjes 
346815121d2SYasuaki Ishimatsu /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
347d09b0137SYASUAKI ISHIMATSU static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
348815121d2SYasuaki Ishimatsu 				     unsigned long start_pfn,
349815121d2SYasuaki Ishimatsu 				     unsigned long end_pfn)
350815121d2SYasuaki Ishimatsu {
35149ba3c6bSDan Williams 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
3527ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(start_pfn)))
353815121d2SYasuaki Ishimatsu 			continue;
354815121d2SYasuaki Ishimatsu 
355815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(start_pfn) != nid))
356815121d2SYasuaki Ishimatsu 			continue;
357815121d2SYasuaki Ishimatsu 
3589b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(start_pfn)))
359815121d2SYasuaki Ishimatsu 			continue;
360815121d2SYasuaki Ishimatsu 
361815121d2SYasuaki Ishimatsu 		return start_pfn;
362815121d2SYasuaki Ishimatsu 	}
363815121d2SYasuaki Ishimatsu 
364815121d2SYasuaki Ishimatsu 	return 0;
365815121d2SYasuaki Ishimatsu }
366815121d2SYasuaki Ishimatsu 
367815121d2SYasuaki Ishimatsu /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
368d09b0137SYASUAKI ISHIMATSU static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
369815121d2SYasuaki Ishimatsu 				    unsigned long start_pfn,
370815121d2SYasuaki Ishimatsu 				    unsigned long end_pfn)
371815121d2SYasuaki Ishimatsu {
372815121d2SYasuaki Ishimatsu 	unsigned long pfn;
373815121d2SYasuaki Ishimatsu 
374815121d2SYasuaki Ishimatsu 	/* pfn is the end pfn of a memory section. */
375815121d2SYasuaki Ishimatsu 	pfn = end_pfn - 1;
37649ba3c6bSDan Williams 	for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
3777ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(pfn)))
378815121d2SYasuaki Ishimatsu 			continue;
379815121d2SYasuaki Ishimatsu 
380815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(pfn) != nid))
381815121d2SYasuaki Ishimatsu 			continue;
382815121d2SYasuaki Ishimatsu 
3839b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(pfn)))
384815121d2SYasuaki Ishimatsu 			continue;
385815121d2SYasuaki Ishimatsu 
386815121d2SYasuaki Ishimatsu 		return pfn;
387815121d2SYasuaki Ishimatsu 	}
388815121d2SYasuaki Ishimatsu 
389815121d2SYasuaki Ishimatsu 	return 0;
390815121d2SYasuaki Ishimatsu }
391815121d2SYasuaki Ishimatsu 
392815121d2SYasuaki Ishimatsu static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
393815121d2SYasuaki Ishimatsu 			     unsigned long end_pfn)
394815121d2SYasuaki Ishimatsu {
395815121d2SYasuaki Ishimatsu 	unsigned long pfn;
396815121d2SYasuaki Ishimatsu 	int nid = zone_to_nid(zone);
397815121d2SYasuaki Ishimatsu 
3985d12071cSDavid Hildenbrand 	if (zone->zone_start_pfn == start_pfn) {
399815121d2SYasuaki Ishimatsu 		/*
400815121d2SYasuaki Ishimatsu 		 * If the section is smallest section in the zone, it need
401815121d2SYasuaki Ishimatsu 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
402815121d2SYasuaki Ishimatsu 		 * In this case, we find second smallest valid mem_section
403815121d2SYasuaki Ishimatsu 		 * for shrinking zone.
404815121d2SYasuaki Ishimatsu 		 */
405815121d2SYasuaki Ishimatsu 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
4065d12071cSDavid Hildenbrand 						zone_end_pfn(zone));
407815121d2SYasuaki Ishimatsu 		if (pfn) {
4085d12071cSDavid Hildenbrand 			zone->spanned_pages = zone_end_pfn(zone) - pfn;
409815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = pfn;
410950b68d9SDavid Hildenbrand 		} else {
411950b68d9SDavid Hildenbrand 			zone->zone_start_pfn = 0;
412950b68d9SDavid Hildenbrand 			zone->spanned_pages = 0;
413815121d2SYasuaki Ishimatsu 		}
4145d12071cSDavid Hildenbrand 	} else if (zone_end_pfn(zone) == end_pfn) {
415815121d2SYasuaki Ishimatsu 		/*
416815121d2SYasuaki Ishimatsu 		 * If the section is biggest section in the zone, it need
417815121d2SYasuaki Ishimatsu 		 * shrink zone->spanned_pages.
418815121d2SYasuaki Ishimatsu 		 * In this case, we find second biggest valid mem_section for
419815121d2SYasuaki Ishimatsu 		 * shrinking zone.
420815121d2SYasuaki Ishimatsu 		 */
4215d12071cSDavid Hildenbrand 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
422815121d2SYasuaki Ishimatsu 					       start_pfn);
423815121d2SYasuaki Ishimatsu 		if (pfn)
4245d12071cSDavid Hildenbrand 			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
425950b68d9SDavid Hildenbrand 		else {
426815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = 0;
427815121d2SYasuaki Ishimatsu 			zone->spanned_pages = 0;
428950b68d9SDavid Hildenbrand 		}
429950b68d9SDavid Hildenbrand 	}
430815121d2SYasuaki Ishimatsu }
431815121d2SYasuaki Ishimatsu 
43200d6c019SDavid Hildenbrand static void update_pgdat_span(struct pglist_data *pgdat)
433815121d2SYasuaki Ishimatsu {
43400d6c019SDavid Hildenbrand 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
43500d6c019SDavid Hildenbrand 	struct zone *zone;
436815121d2SYasuaki Ishimatsu 
43700d6c019SDavid Hildenbrand 	for (zone = pgdat->node_zones;
43800d6c019SDavid Hildenbrand 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
4396c922cf7SMiaohe Lin 		unsigned long end_pfn = zone_end_pfn(zone);
44000d6c019SDavid Hildenbrand 
44100d6c019SDavid Hildenbrand 		/* No need to lock the zones, they can't change. */
442656d5711SDavid Hildenbrand 		if (!zone->spanned_pages)
443656d5711SDavid Hildenbrand 			continue;
444656d5711SDavid Hildenbrand 		if (!node_end_pfn) {
445656d5711SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
4466c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
447656d5711SDavid Hildenbrand 			continue;
448656d5711SDavid Hildenbrand 		}
449656d5711SDavid Hildenbrand 
4506c922cf7SMiaohe Lin 		if (end_pfn > node_end_pfn)
4516c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
45200d6c019SDavid Hildenbrand 		if (zone->zone_start_pfn < node_start_pfn)
45300d6c019SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
454815121d2SYasuaki Ishimatsu 	}
455815121d2SYasuaki Ishimatsu 
45600d6c019SDavid Hildenbrand 	pgdat->node_start_pfn = node_start_pfn;
45700d6c019SDavid Hildenbrand 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
458815121d2SYasuaki Ishimatsu }
459815121d2SYasuaki Ishimatsu 
460feee6b29SDavid Hildenbrand void __ref remove_pfn_range_from_zone(struct zone *zone,
461feee6b29SDavid Hildenbrand 				      unsigned long start_pfn,
4627ea62160SDan Williams 				      unsigned long nr_pages)
463815121d2SYasuaki Ishimatsu {
464b7e3debdSBen Widawsky 	const unsigned long end_pfn = start_pfn + nr_pages;
465815121d2SYasuaki Ishimatsu 	struct pglist_data *pgdat = zone->zone_pgdat;
46627cacaadSOscar Salvador 	unsigned long pfn, cur_nr_pages;
467815121d2SYasuaki Ishimatsu 
468d33695b1SDavid Hildenbrand 	/* Poison struct pages because they are now uninitialized again. */
469b7e3debdSBen Widawsky 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
470b7e3debdSBen Widawsky 		cond_resched();
471b7e3debdSBen Widawsky 
472b7e3debdSBen Widawsky 		/* Select all remaining pages up to the next section boundary */
473b7e3debdSBen Widawsky 		cur_nr_pages =
474b7e3debdSBen Widawsky 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
475b7e3debdSBen Widawsky 		page_init_poison(pfn_to_page(pfn),
476b7e3debdSBen Widawsky 				 sizeof(struct page) * cur_nr_pages);
477b7e3debdSBen Widawsky 	}
478d33695b1SDavid Hildenbrand 
4797ce700bfSDavid Hildenbrand 	/*
4807ce700bfSDavid Hildenbrand 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
4817ce700bfSDavid Hildenbrand 	 * we will not try to shrink the zones - which is okay as
4827ce700bfSDavid Hildenbrand 	 * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
4837ce700bfSDavid Hildenbrand 	 */
4845ef5f810SMiaohe Lin 	if (zone_is_zone_device(zone))
4857ce700bfSDavid Hildenbrand 		return;
4867ce700bfSDavid Hildenbrand 
487feee6b29SDavid Hildenbrand 	clear_zone_contiguous(zone);
488feee6b29SDavid Hildenbrand 
489815121d2SYasuaki Ishimatsu 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
49000d6c019SDavid Hildenbrand 	update_pgdat_span(pgdat);
491feee6b29SDavid Hildenbrand 
492feee6b29SDavid Hildenbrand 	set_zone_contiguous(zone);
493815121d2SYasuaki Ishimatsu }
494815121d2SYasuaki Ishimatsu 
495feee6b29SDavid Hildenbrand static void __remove_section(unsigned long pfn, unsigned long nr_pages,
496feee6b29SDavid Hildenbrand 			     unsigned long map_offset,
4979d1d887dSDavid Hildenbrand 			     struct vmem_altmap *altmap)
498ea01ea93SBadari Pulavarty {
49910404901Schenqiwu 	struct mem_section *ms = __pfn_to_section(pfn);
500ea01ea93SBadari Pulavarty 
5019d1d887dSDavid Hildenbrand 	if (WARN_ON_ONCE(!valid_section(ms)))
5029d1d887dSDavid Hildenbrand 		return;
503ea01ea93SBadari Pulavarty 
504ba72b4c8SDan Williams 	sparse_remove_section(ms, pfn, nr_pages, map_offset, altmap);
505ea01ea93SBadari Pulavarty }
506ea01ea93SBadari Pulavarty 
507ea01ea93SBadari Pulavarty /**
508feee6b29SDavid Hildenbrand  * __remove_pages() - remove sections of pages
5097ea62160SDan Williams  * @pfn: starting pageframe (must be aligned to start of a section)
510ea01ea93SBadari Pulavarty  * @nr_pages: number of pages to remove (must be multiple of section size)
511e8b098fcSMike Rapoport  * @altmap: alternative device page map or %NULL if default memmap is used
512ea01ea93SBadari Pulavarty  *
513ea01ea93SBadari Pulavarty  * Generic helper function to remove section mappings and sysfs entries
514ea01ea93SBadari Pulavarty  * for the section of the memory we are removing. Caller needs to make
515ea01ea93SBadari Pulavarty  * sure that pages are marked reserved and zones are adjust properly by
516ea01ea93SBadari Pulavarty  * calling offline_pages().
517ea01ea93SBadari Pulavarty  */
518feee6b29SDavid Hildenbrand void __remove_pages(unsigned long pfn, unsigned long nr_pages,
519feee6b29SDavid Hildenbrand 		    struct vmem_altmap *altmap)
520ea01ea93SBadari Pulavarty {
52152fb87c8SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
52252fb87c8SDavid Hildenbrand 	unsigned long cur_nr_pages;
5234b94ffdcSDan Williams 	unsigned long map_offset = 0;
5244b94ffdcSDan Williams 
5254b94ffdcSDan Williams 	map_offset = vmem_altmap_offset(altmap);
526ea01ea93SBadari Pulavarty 
527943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
528943189dbSAnshuman Khandual 		WARN(1, "Misaligned %s start: %#lx end: #%lx\n", __func__, pfn, pfn + nr_pages - 1);
5297ea62160SDan Williams 		return;
530943189dbSAnshuman Khandual 	}
531ea01ea93SBadari Pulavarty 
53252fb87c8SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
533dd33ad7bSMichal Hocko 		cond_resched();
53452fb87c8SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
535a11b9419SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
536a11b9419SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
53752fb87c8SDavid Hildenbrand 		__remove_section(pfn, cur_nr_pages, map_offset, altmap);
5384b94ffdcSDan Williams 		map_offset = 0;
539ea01ea93SBadari Pulavarty 	}
540ea01ea93SBadari Pulavarty }
541ea01ea93SBadari Pulavarty 
5429d0ad8caSDaniel Kiper int set_online_page_callback(online_page_callback_t callback)
5439d0ad8caSDaniel Kiper {
5449d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5459d0ad8caSDaniel Kiper 
546bfc8c901SVladimir Davydov 	get_online_mems();
547bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5489d0ad8caSDaniel Kiper 
5499d0ad8caSDaniel Kiper 	if (online_page_callback == generic_online_page) {
5509d0ad8caSDaniel Kiper 		online_page_callback = callback;
5519d0ad8caSDaniel Kiper 		rc = 0;
5529d0ad8caSDaniel Kiper 	}
5539d0ad8caSDaniel Kiper 
554bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
555bfc8c901SVladimir Davydov 	put_online_mems();
5569d0ad8caSDaniel Kiper 
5579d0ad8caSDaniel Kiper 	return rc;
5589d0ad8caSDaniel Kiper }
5599d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(set_online_page_callback);
5609d0ad8caSDaniel Kiper 
5619d0ad8caSDaniel Kiper int restore_online_page_callback(online_page_callback_t callback)
5629d0ad8caSDaniel Kiper {
5639d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5649d0ad8caSDaniel Kiper 
565bfc8c901SVladimir Davydov 	get_online_mems();
566bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5679d0ad8caSDaniel Kiper 
5689d0ad8caSDaniel Kiper 	if (online_page_callback == callback) {
5699d0ad8caSDaniel Kiper 		online_page_callback = generic_online_page;
5709d0ad8caSDaniel Kiper 		rc = 0;
5719d0ad8caSDaniel Kiper 	}
5729d0ad8caSDaniel Kiper 
573bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
574bfc8c901SVladimir Davydov 	put_online_mems();
5759d0ad8caSDaniel Kiper 
5769d0ad8caSDaniel Kiper 	return rc;
5779d0ad8caSDaniel Kiper }
5789d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(restore_online_page_callback);
5799d0ad8caSDaniel Kiper 
58018db1491SDavid Hildenbrand void generic_online_page(struct page *page, unsigned int order)
5819d0ad8caSDaniel Kiper {
582c87cbc1fSVlastimil Babka 	/*
583c87cbc1fSVlastimil Babka 	 * Freeing the page with debug_pagealloc enabled will try to unmap it,
584c87cbc1fSVlastimil Babka 	 * so we should map it first. This is better than introducing a special
585c87cbc1fSVlastimil Babka 	 * case in page freeing fast path.
586c87cbc1fSVlastimil Babka 	 */
58777bc7fd6SMike Rapoport 	debug_pagealloc_map_pages(page, 1 << order);
588a9cd410aSArun KS 	__free_pages_core(page, order);
589a9cd410aSArun KS 	totalram_pages_add(1UL << order);
590a9cd410aSArun KS }
59118db1491SDavid Hildenbrand EXPORT_SYMBOL_GPL(generic_online_page);
592a9cd410aSArun KS 
593aac65321SDavid Hildenbrand static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
5943947be19SDave Hansen {
595b2c2ab20SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
596b2c2ab20SDavid Hildenbrand 	unsigned long pfn;
5972d070eabSMichal Hocko 
598b2c2ab20SDavid Hildenbrand 	/*
59923baf831SKirill A. Shutemov 	 * Online the pages in MAX_ORDER aligned chunks. The callback might
600aac65321SDavid Hildenbrand 	 * decide to not expose all pages to the buddy (e.g., expose them
601aac65321SDavid Hildenbrand 	 * later). We account all pages as being online and belonging to this
602aac65321SDavid Hildenbrand 	 * zone ("present").
603a08a2ae3SOscar Salvador 	 * When using memmap_on_memory, the range might not be aligned to
604a08a2ae3SOscar Salvador 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
605a08a2ae3SOscar Salvador 	 * this and the first chunk to online will be pageblock_nr_pages.
606b2c2ab20SDavid Hildenbrand 	 */
607a08a2ae3SOscar Salvador 	for (pfn = start_pfn; pfn < end_pfn;) {
608*59f876fbSKirill A. Shutemov 		int order;
609*59f876fbSKirill A. Shutemov 
610*59f876fbSKirill A. Shutemov 		/*
611*59f876fbSKirill A. Shutemov 		 * Free to online pages in the largest chunks alignment allows.
612*59f876fbSKirill A. Shutemov 		 *
613*59f876fbSKirill A. Shutemov 		 * __ffs() behaviour is undefined for 0. start == 0 is
614*59f876fbSKirill A. Shutemov 		 * MAX_ORDER-aligned, Set order to MAX_ORDER for the case.
615*59f876fbSKirill A. Shutemov 		 */
616*59f876fbSKirill A. Shutemov 		if (pfn)
617*59f876fbSKirill A. Shutemov 			order = min_t(int, MAX_ORDER, __ffs(pfn));
618*59f876fbSKirill A. Shutemov 		else
619*59f876fbSKirill A. Shutemov 			order = MAX_ORDER;
620a08a2ae3SOscar Salvador 
621a08a2ae3SOscar Salvador 		(*online_page_callback)(pfn_to_page(pfn), order);
622a08a2ae3SOscar Salvador 		pfn += (1UL << order);
623a08a2ae3SOscar Salvador 	}
6242d070eabSMichal Hocko 
625b2c2ab20SDavid Hildenbrand 	/* mark all involved sections as online */
626b2c2ab20SDavid Hildenbrand 	online_mem_sections(start_pfn, end_pfn);
62775884fb1SKAMEZAWA Hiroyuki }
62875884fb1SKAMEZAWA Hiroyuki 
629d9713679SLai Jiangshan /* check which state of node_states will be changed when online memory */
630d9713679SLai Jiangshan static void node_states_check_changes_online(unsigned long nr_pages,
631d9713679SLai Jiangshan 	struct zone *zone, struct memory_notify *arg)
632d9713679SLai Jiangshan {
633d9713679SLai Jiangshan 	int nid = zone_to_nid(zone);
634d9713679SLai Jiangshan 
63598fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
63698fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
6376715ddf9SLai Jiangshan 
6386715ddf9SLai Jiangshan 	if (!node_state(nid, N_MEMORY))
639d9713679SLai Jiangshan 		arg->status_change_nid = nid;
6408efe33f4SOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
6418efe33f4SOscar Salvador 		arg->status_change_nid_normal = nid;
642d9713679SLai Jiangshan }
643d9713679SLai Jiangshan 
644d9713679SLai Jiangshan static void node_states_set_node(int node, struct memory_notify *arg)
645d9713679SLai Jiangshan {
646d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
647d9713679SLai Jiangshan 		node_set_state(node, N_NORMAL_MEMORY);
648d9713679SLai Jiangshan 
64983d83612SOscar Salvador 	if (arg->status_change_nid >= 0)
6506715ddf9SLai Jiangshan 		node_set_state(node, N_MEMORY);
651d9713679SLai Jiangshan }
652d9713679SLai Jiangshan 
653f1dd2cd1SMichal Hocko static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
654f1dd2cd1SMichal Hocko 		unsigned long nr_pages)
655f1dd2cd1SMichal Hocko {
656f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = zone_end_pfn(zone);
657f1dd2cd1SMichal Hocko 
658f1dd2cd1SMichal Hocko 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
659f1dd2cd1SMichal Hocko 		zone->zone_start_pfn = start_pfn;
660f1dd2cd1SMichal Hocko 
661f1dd2cd1SMichal Hocko 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
662f1dd2cd1SMichal Hocko }
663f1dd2cd1SMichal Hocko 
664f1dd2cd1SMichal Hocko static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
665f1dd2cd1SMichal Hocko                                      unsigned long nr_pages)
666f1dd2cd1SMichal Hocko {
667f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
668f1dd2cd1SMichal Hocko 
669f1dd2cd1SMichal Hocko 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
670f1dd2cd1SMichal Hocko 		pgdat->node_start_pfn = start_pfn;
671f1dd2cd1SMichal Hocko 
672f1dd2cd1SMichal Hocko 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
673f1dd2cd1SMichal Hocko 
6743fccb74cSDavid Hildenbrand }
6751f90a347SDan Williams 
676ed7802ddSMuchun Song #ifdef CONFIG_ZONE_DEVICE
6771f90a347SDan Williams static void section_taint_zone_device(unsigned long pfn)
6781f90a347SDan Williams {
6791f90a347SDan Williams 	struct mem_section *ms = __pfn_to_section(pfn);
6801f90a347SDan Williams 
6811f90a347SDan Williams 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
6821f90a347SDan Williams }
683ed7802ddSMuchun Song #else
684ed7802ddSMuchun Song static inline void section_taint_zone_device(unsigned long pfn)
685ed7802ddSMuchun Song {
686ed7802ddSMuchun Song }
687ed7802ddSMuchun Song #endif
6881f90a347SDan Williams 
6893fccb74cSDavid Hildenbrand /*
6903fccb74cSDavid Hildenbrand  * Associate the pfn range with the given zone, initializing the memmaps
6913fccb74cSDavid Hildenbrand  * and resizing the pgdat/zone data to span the added pages. After this
6923fccb74cSDavid Hildenbrand  * call, all affected pages are PG_reserved.
693d882c006SDavid Hildenbrand  *
694d882c006SDavid Hildenbrand  * All aligned pageblocks are initialized to the specified migratetype
695d882c006SDavid Hildenbrand  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
696d882c006SDavid Hildenbrand  * zone stats (e.g., nr_isolate_pageblock) are touched.
6973fccb74cSDavid Hildenbrand  */
698a99583e7SChristoph Hellwig void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
699d882c006SDavid Hildenbrand 				  unsigned long nr_pages,
700d882c006SDavid Hildenbrand 				  struct vmem_altmap *altmap, int migratetype)
701f1dd2cd1SMichal Hocko {
702f1dd2cd1SMichal Hocko 	struct pglist_data *pgdat = zone->zone_pgdat;
703f1dd2cd1SMichal Hocko 	int nid = pgdat->node_id;
704f1dd2cd1SMichal Hocko 
705f1dd2cd1SMichal Hocko 	clear_zone_contiguous(zone);
706f1dd2cd1SMichal Hocko 
707fa004ab7SWei Yang 	if (zone_is_empty(zone))
708fa004ab7SWei Yang 		init_currently_empty_zone(zone, start_pfn, nr_pages);
709f1dd2cd1SMichal Hocko 	resize_zone_range(zone, start_pfn, nr_pages);
710f1dd2cd1SMichal Hocko 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
711f1dd2cd1SMichal Hocko 
712f1dd2cd1SMichal Hocko 	/*
7131f90a347SDan Williams 	 * Subsection population requires care in pfn_to_online_page().
7141f90a347SDan Williams 	 * Set the taint to enable the slow path detection of
7151f90a347SDan Williams 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
7161f90a347SDan Williams 	 * section.
7171f90a347SDan Williams 	 */
7181f90a347SDan Williams 	if (zone_is_zone_device(zone)) {
7191f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
7201f90a347SDan Williams 			section_taint_zone_device(start_pfn);
7211f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
7221f90a347SDan Williams 			section_taint_zone_device(start_pfn + nr_pages);
7231f90a347SDan Williams 	}
7241f90a347SDan Williams 
7251f90a347SDan Williams 	/*
726f1dd2cd1SMichal Hocko 	 * TODO now we have a visible range of pages which are not associated
727f1dd2cd1SMichal Hocko 	 * with their zone properly. Not nice but set_pfnblock_flags_mask
728f1dd2cd1SMichal Hocko 	 * expects the zone spans the pfn range. All the pages in the range
729f1dd2cd1SMichal Hocko 	 * are reserved so nobody should be touching them so we should be safe
730f1dd2cd1SMichal Hocko 	 */
731ab28cb6eSBaoquan He 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
732d882c006SDavid Hildenbrand 			 MEMINIT_HOTPLUG, altmap, migratetype);
733f1dd2cd1SMichal Hocko 
734f1dd2cd1SMichal Hocko 	set_zone_contiguous(zone);
735f1dd2cd1SMichal Hocko }
736f1dd2cd1SMichal Hocko 
737e83a437fSDavid Hildenbrand struct auto_movable_stats {
738e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages;
739e83a437fSDavid Hildenbrand 	unsigned long movable_pages;
740e83a437fSDavid Hildenbrand };
741e83a437fSDavid Hildenbrand 
742e83a437fSDavid Hildenbrand static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
743e83a437fSDavid Hildenbrand 					    struct zone *zone)
744e83a437fSDavid Hildenbrand {
745e83a437fSDavid Hildenbrand 	if (zone_idx(zone) == ZONE_MOVABLE) {
746e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->present_pages;
747e83a437fSDavid Hildenbrand 	} else {
748e83a437fSDavid Hildenbrand 		stats->kernel_early_pages += zone->present_early_pages;
749e83a437fSDavid Hildenbrand #ifdef CONFIG_CMA
750e83a437fSDavid Hildenbrand 		/*
751e83a437fSDavid Hildenbrand 		 * CMA pages (never on hotplugged memory) behave like
752e83a437fSDavid Hildenbrand 		 * ZONE_MOVABLE.
753e83a437fSDavid Hildenbrand 		 */
754e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->cma_pages;
755e83a437fSDavid Hildenbrand 		stats->kernel_early_pages -= zone->cma_pages;
756e83a437fSDavid Hildenbrand #endif /* CONFIG_CMA */
757e83a437fSDavid Hildenbrand 	}
758e83a437fSDavid Hildenbrand }
7593fcebf90SDavid Hildenbrand struct auto_movable_group_stats {
7603fcebf90SDavid Hildenbrand 	unsigned long movable_pages;
7613fcebf90SDavid Hildenbrand 	unsigned long req_kernel_early_pages;
7623fcebf90SDavid Hildenbrand };
763e83a437fSDavid Hildenbrand 
7643fcebf90SDavid Hildenbrand static int auto_movable_stats_account_group(struct memory_group *group,
7653fcebf90SDavid Hildenbrand 					   void *arg)
766e83a437fSDavid Hildenbrand {
7673fcebf90SDavid Hildenbrand 	const int ratio = READ_ONCE(auto_movable_ratio);
7683fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats *stats = arg;
7693fcebf90SDavid Hildenbrand 	long pages;
7703fcebf90SDavid Hildenbrand 
7713fcebf90SDavid Hildenbrand 	/*
7723fcebf90SDavid Hildenbrand 	 * We don't support modifying the config while the auto-movable online
7733fcebf90SDavid Hildenbrand 	 * policy is already enabled. Just avoid the division by zero below.
7743fcebf90SDavid Hildenbrand 	 */
7753fcebf90SDavid Hildenbrand 	if (!ratio)
7763fcebf90SDavid Hildenbrand 		return 0;
7773fcebf90SDavid Hildenbrand 
7783fcebf90SDavid Hildenbrand 	/*
7793fcebf90SDavid Hildenbrand 	 * Calculate how many early kernel pages this group requires to
7803fcebf90SDavid Hildenbrand 	 * satisfy the configured zone ratio.
7813fcebf90SDavid Hildenbrand 	 */
7823fcebf90SDavid Hildenbrand 	pages = group->present_movable_pages * 100 / ratio;
7833fcebf90SDavid Hildenbrand 	pages -= group->present_kernel_pages;
7843fcebf90SDavid Hildenbrand 
7853fcebf90SDavid Hildenbrand 	if (pages > 0)
7863fcebf90SDavid Hildenbrand 		stats->req_kernel_early_pages += pages;
7873fcebf90SDavid Hildenbrand 	stats->movable_pages += group->present_movable_pages;
7883fcebf90SDavid Hildenbrand 	return 0;
7893fcebf90SDavid Hildenbrand }
7903fcebf90SDavid Hildenbrand 
7913fcebf90SDavid Hildenbrand static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
7923fcebf90SDavid Hildenbrand 					    unsigned long nr_pages)
7933fcebf90SDavid Hildenbrand {
794e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages, movable_pages;
7953fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats group_stats = {};
7963fcebf90SDavid Hildenbrand 	struct auto_movable_stats stats = {};
797e83a437fSDavid Hildenbrand 	pg_data_t *pgdat = NODE_DATA(nid);
798e83a437fSDavid Hildenbrand 	struct zone *zone;
799e83a437fSDavid Hildenbrand 	int i;
800e83a437fSDavid Hildenbrand 
801e83a437fSDavid Hildenbrand 	/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
802e83a437fSDavid Hildenbrand 	if (nid == NUMA_NO_NODE) {
803e83a437fSDavid Hildenbrand 		/* TODO: cache values */
804e83a437fSDavid Hildenbrand 		for_each_populated_zone(zone)
805e83a437fSDavid Hildenbrand 			auto_movable_stats_account_zone(&stats, zone);
806e83a437fSDavid Hildenbrand 	} else {
807e83a437fSDavid Hildenbrand 		for (i = 0; i < MAX_NR_ZONES; i++) {
808e83a437fSDavid Hildenbrand 			zone = pgdat->node_zones + i;
809e83a437fSDavid Hildenbrand 			if (populated_zone(zone))
810e83a437fSDavid Hildenbrand 				auto_movable_stats_account_zone(&stats, zone);
811e83a437fSDavid Hildenbrand 		}
812e83a437fSDavid Hildenbrand 	}
813e83a437fSDavid Hildenbrand 
814e83a437fSDavid Hildenbrand 	kernel_early_pages = stats.kernel_early_pages;
815e83a437fSDavid Hildenbrand 	movable_pages = stats.movable_pages;
816e83a437fSDavid Hildenbrand 
817e83a437fSDavid Hildenbrand 	/*
8183fcebf90SDavid Hildenbrand 	 * Kernel memory inside dynamic memory group allows for more MOVABLE
8193fcebf90SDavid Hildenbrand 	 * memory within the same group. Remove the effect of all but the
8203fcebf90SDavid Hildenbrand 	 * current group from the stats.
8213fcebf90SDavid Hildenbrand 	 */
8223fcebf90SDavid Hildenbrand 	walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
8233fcebf90SDavid Hildenbrand 				   group, &group_stats);
8243fcebf90SDavid Hildenbrand 	if (kernel_early_pages <= group_stats.req_kernel_early_pages)
8253fcebf90SDavid Hildenbrand 		return false;
8263fcebf90SDavid Hildenbrand 	kernel_early_pages -= group_stats.req_kernel_early_pages;
8273fcebf90SDavid Hildenbrand 	movable_pages -= group_stats.movable_pages;
8283fcebf90SDavid Hildenbrand 
8293fcebf90SDavid Hildenbrand 	if (group && group->is_dynamic)
8303fcebf90SDavid Hildenbrand 		kernel_early_pages += group->present_kernel_pages;
8313fcebf90SDavid Hildenbrand 
8323fcebf90SDavid Hildenbrand 	/*
833e83a437fSDavid Hildenbrand 	 * Test if we could online the given number of pages to ZONE_MOVABLE
834e83a437fSDavid Hildenbrand 	 * and still stay in the configured ratio.
835e83a437fSDavid Hildenbrand 	 */
836e83a437fSDavid Hildenbrand 	movable_pages += nr_pages;
837e83a437fSDavid Hildenbrand 	return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
838e83a437fSDavid Hildenbrand }
839e83a437fSDavid Hildenbrand 
840f1dd2cd1SMichal Hocko /*
841c246a213SMichal Hocko  * Returns a default kernel memory zone for the given pfn range.
842c246a213SMichal Hocko  * If no kernel zone covers this pfn range it will automatically go
843c246a213SMichal Hocko  * to the ZONE_NORMAL.
844c246a213SMichal Hocko  */
845c6f03e29SMichal Hocko static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
846c246a213SMichal Hocko 		unsigned long nr_pages)
847c246a213SMichal Hocko {
848c246a213SMichal Hocko 	struct pglist_data *pgdat = NODE_DATA(nid);
849c246a213SMichal Hocko 	int zid;
850c246a213SMichal Hocko 
851d6aad201SMiaohe Lin 	for (zid = 0; zid < ZONE_NORMAL; zid++) {
852c246a213SMichal Hocko 		struct zone *zone = &pgdat->node_zones[zid];
853c246a213SMichal Hocko 
854c246a213SMichal Hocko 		if (zone_intersects(zone, start_pfn, nr_pages))
855c246a213SMichal Hocko 			return zone;
856c246a213SMichal Hocko 	}
857c246a213SMichal Hocko 
858c246a213SMichal Hocko 	return &pgdat->node_zones[ZONE_NORMAL];
859c246a213SMichal Hocko }
860c246a213SMichal Hocko 
861e83a437fSDavid Hildenbrand /*
862e83a437fSDavid Hildenbrand  * Determine to which zone to online memory dynamically based on user
863e83a437fSDavid Hildenbrand  * configuration and system stats. We care about the following ratio:
864e83a437fSDavid Hildenbrand  *
865e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL
866e83a437fSDavid Hildenbrand  *
867e83a437fSDavid Hildenbrand  * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
868e83a437fSDavid Hildenbrand  * one of the kernel zones. CMA pages inside one of the kernel zones really
869e83a437fSDavid Hildenbrand  * behaves like ZONE_MOVABLE, so we treat them accordingly.
870e83a437fSDavid Hildenbrand  *
871e83a437fSDavid Hildenbrand  * We don't allow for hotplugged memory in a KERNEL zone to increase the
872e83a437fSDavid Hildenbrand  * amount of MOVABLE memory we can have, so we end up with:
873e83a437fSDavid Hildenbrand  *
874e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL_EARLY
875e83a437fSDavid Hildenbrand  *
876e83a437fSDavid Hildenbrand  * Whereby KERNEL_EARLY is memory in one of the kernel zones, available sinze
877e83a437fSDavid Hildenbrand  * boot. We base our calculation on KERNEL_EARLY internally, because:
878e83a437fSDavid Hildenbrand  *
879e83a437fSDavid Hildenbrand  * a) Hotplugged memory in one of the kernel zones can sometimes still get
880e83a437fSDavid Hildenbrand  *    hotunplugged, especially when hot(un)plugging individual memory blocks.
881e83a437fSDavid Hildenbrand  *    There is no coordination across memory devices, therefore "automatic"
882e83a437fSDavid Hildenbrand  *    hotunplugging, as implemented in hypervisors, could result in zone
883e83a437fSDavid Hildenbrand  *    imbalances.
884e83a437fSDavid Hildenbrand  * b) Early/boot memory in one of the kernel zones can usually not get
885e83a437fSDavid Hildenbrand  *    hotunplugged again (e.g., no firmware interface to unplug, fragmented
886e83a437fSDavid Hildenbrand  *    with unmovable allocations). While there are corner cases where it might
887e83a437fSDavid Hildenbrand  *    still work, it is barely relevant in practice.
888e83a437fSDavid Hildenbrand  *
8893fcebf90SDavid Hildenbrand  * Exceptions are dynamic memory groups, which allow for more MOVABLE
8903fcebf90SDavid Hildenbrand  * memory within the same memory group -- because in that case, there is
8913fcebf90SDavid Hildenbrand  * coordination within the single memory device managed by a single driver.
8923fcebf90SDavid Hildenbrand  *
893e83a437fSDavid Hildenbrand  * We rely on "present pages" instead of "managed pages", as the latter is
894e83a437fSDavid Hildenbrand  * highly unreliable and dynamic in virtualized environments, and does not
895e83a437fSDavid Hildenbrand  * consider boot time allocations. For example, memory ballooning adjusts the
896e83a437fSDavid Hildenbrand  * managed pages when inflating/deflating the balloon, and balloon compaction
897e83a437fSDavid Hildenbrand  * can even migrate inflated pages between zones.
898e83a437fSDavid Hildenbrand  *
899e83a437fSDavid Hildenbrand  * Using "present pages" is better but some things to keep in mind are:
900e83a437fSDavid Hildenbrand  *
901e83a437fSDavid Hildenbrand  * a) Some memblock allocations, such as for the crashkernel area, are
902e83a437fSDavid Hildenbrand  *    effectively unused by the kernel, yet they account to "present pages".
903e83a437fSDavid Hildenbrand  *    Fortunately, these allocations are comparatively small in relevant setups
904e83a437fSDavid Hildenbrand  *    (e.g., fraction of system memory).
905e83a437fSDavid Hildenbrand  * b) Some hotplugged memory blocks in virtualized environments, esecially
906e83a437fSDavid Hildenbrand  *    hotplugged by virtio-mem, look like they are completely present, however,
907e83a437fSDavid Hildenbrand  *    only parts of the memory block are actually currently usable.
908e83a437fSDavid Hildenbrand  *    "present pages" is an upper limit that can get reached at runtime. As
909e83a437fSDavid Hildenbrand  *    we base our calculations on KERNEL_EARLY, this is not an issue.
910e83a437fSDavid Hildenbrand  */
911445fcf7cSDavid Hildenbrand static struct zone *auto_movable_zone_for_pfn(int nid,
912445fcf7cSDavid Hildenbrand 					      struct memory_group *group,
913445fcf7cSDavid Hildenbrand 					      unsigned long pfn,
914e83a437fSDavid Hildenbrand 					      unsigned long nr_pages)
915e83a437fSDavid Hildenbrand {
916445fcf7cSDavid Hildenbrand 	unsigned long online_pages = 0, max_pages, end_pfn;
917445fcf7cSDavid Hildenbrand 	struct page *page;
918445fcf7cSDavid Hildenbrand 
919e83a437fSDavid Hildenbrand 	if (!auto_movable_ratio)
920e83a437fSDavid Hildenbrand 		goto kernel_zone;
921e83a437fSDavid Hildenbrand 
922445fcf7cSDavid Hildenbrand 	if (group && !group->is_dynamic) {
923445fcf7cSDavid Hildenbrand 		max_pages = group->s.max_pages;
924445fcf7cSDavid Hildenbrand 		online_pages = group->present_movable_pages;
925445fcf7cSDavid Hildenbrand 
926445fcf7cSDavid Hildenbrand 		/* If anything is !MOVABLE online the rest !MOVABLE. */
927445fcf7cSDavid Hildenbrand 		if (group->present_kernel_pages)
928445fcf7cSDavid Hildenbrand 			goto kernel_zone;
929445fcf7cSDavid Hildenbrand 	} else if (!group || group->d.unit_pages == nr_pages) {
930445fcf7cSDavid Hildenbrand 		max_pages = nr_pages;
931445fcf7cSDavid Hildenbrand 	} else {
932445fcf7cSDavid Hildenbrand 		max_pages = group->d.unit_pages;
933445fcf7cSDavid Hildenbrand 		/*
934445fcf7cSDavid Hildenbrand 		 * Take a look at all online sections in the current unit.
935445fcf7cSDavid Hildenbrand 		 * We can safely assume that all pages within a section belong
936445fcf7cSDavid Hildenbrand 		 * to the same zone, because dynamic memory groups only deal
937445fcf7cSDavid Hildenbrand 		 * with hotplugged memory.
938445fcf7cSDavid Hildenbrand 		 */
939445fcf7cSDavid Hildenbrand 		pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
940445fcf7cSDavid Hildenbrand 		end_pfn = pfn + group->d.unit_pages;
941445fcf7cSDavid Hildenbrand 		for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
942445fcf7cSDavid Hildenbrand 			page = pfn_to_online_page(pfn);
943445fcf7cSDavid Hildenbrand 			if (!page)
944445fcf7cSDavid Hildenbrand 				continue;
945445fcf7cSDavid Hildenbrand 			/* If anything is !MOVABLE online the rest !MOVABLE. */
94607252dfeSKefeng Wang 			if (!is_zone_movable_page(page))
947445fcf7cSDavid Hildenbrand 				goto kernel_zone;
948445fcf7cSDavid Hildenbrand 			online_pages += PAGES_PER_SECTION;
949445fcf7cSDavid Hildenbrand 		}
950445fcf7cSDavid Hildenbrand 	}
951445fcf7cSDavid Hildenbrand 
952445fcf7cSDavid Hildenbrand 	/*
953445fcf7cSDavid Hildenbrand 	 * Online MOVABLE if we could *currently* online all remaining parts
954445fcf7cSDavid Hildenbrand 	 * MOVABLE. We expect to (add+) online them immediately next, so if
955445fcf7cSDavid Hildenbrand 	 * nobody interferes, all will be MOVABLE if possible.
956445fcf7cSDavid Hildenbrand 	 */
957445fcf7cSDavid Hildenbrand 	nr_pages = max_pages - online_pages;
9583fcebf90SDavid Hildenbrand 	if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
959e83a437fSDavid Hildenbrand 		goto kernel_zone;
960e83a437fSDavid Hildenbrand 
961e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
962e83a437fSDavid Hildenbrand 	if (auto_movable_numa_aware &&
9633fcebf90SDavid Hildenbrand 	    !auto_movable_can_online_movable(nid, group, nr_pages))
964e83a437fSDavid Hildenbrand 		goto kernel_zone;
965e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
966e83a437fSDavid Hildenbrand 
967e83a437fSDavid Hildenbrand 	return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
968e83a437fSDavid Hildenbrand kernel_zone:
969e83a437fSDavid Hildenbrand 	return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
970e83a437fSDavid Hildenbrand }
971e83a437fSDavid Hildenbrand 
972c6f03e29SMichal Hocko static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
973c6f03e29SMichal Hocko 		unsigned long nr_pages)
974e5e68930SMichal Hocko {
975c6f03e29SMichal Hocko 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
976c6f03e29SMichal Hocko 			nr_pages);
977c6f03e29SMichal Hocko 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
978c6f03e29SMichal Hocko 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
979c6f03e29SMichal Hocko 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
980e5e68930SMichal Hocko 
981e5e68930SMichal Hocko 	/*
982c6f03e29SMichal Hocko 	 * We inherit the existing zone in a simple case where zones do not
983c6f03e29SMichal Hocko 	 * overlap in the given range
984e5e68930SMichal Hocko 	 */
985c6f03e29SMichal Hocko 	if (in_kernel ^ in_movable)
986c6f03e29SMichal Hocko 		return (in_kernel) ? kernel_zone : movable_zone;
987e5e68930SMichal Hocko 
988c6f03e29SMichal Hocko 	/*
989c6f03e29SMichal Hocko 	 * If the range doesn't belong to any zone or two zones overlap in the
990c6f03e29SMichal Hocko 	 * given range then we use movable zone only if movable_node is
991c6f03e29SMichal Hocko 	 * enabled because we always online to a kernel zone by default.
992c6f03e29SMichal Hocko 	 */
993c6f03e29SMichal Hocko 	return movable_node_enabled ? movable_zone : kernel_zone;
9949f123ab5SMichal Hocko }
9959f123ab5SMichal Hocko 
9967cf209baSDavid Hildenbrand struct zone *zone_for_pfn_range(int online_type, int nid,
997445fcf7cSDavid Hildenbrand 		struct memory_group *group, unsigned long start_pfn,
998e5e68930SMichal Hocko 		unsigned long nr_pages)
999f1dd2cd1SMichal Hocko {
1000c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_KERNEL)
1001c6f03e29SMichal Hocko 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
1002f1dd2cd1SMichal Hocko 
1003c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_MOVABLE)
1004c6f03e29SMichal Hocko 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1005f1dd2cd1SMichal Hocko 
1006e83a437fSDavid Hildenbrand 	if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
1007445fcf7cSDavid Hildenbrand 		return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
1008e83a437fSDavid Hildenbrand 
1009c6f03e29SMichal Hocko 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
1010e5e68930SMichal Hocko }
1011e5e68930SMichal Hocko 
1012a08a2ae3SOscar Salvador /*
1013a08a2ae3SOscar Salvador  * This function should only be called by memory_block_{online,offline},
1014a08a2ae3SOscar Salvador  * and {online,offline}_pages.
1015a08a2ae3SOscar Salvador  */
1016836809ecSDavid Hildenbrand void adjust_present_page_count(struct page *page, struct memory_group *group,
1017836809ecSDavid Hildenbrand 			       long nr_pages)
1018f9901144SDavid Hildenbrand {
10194b097002SDavid Hildenbrand 	struct zone *zone = page_zone(page);
1020836809ecSDavid Hildenbrand 	const bool movable = zone_idx(zone) == ZONE_MOVABLE;
10214b097002SDavid Hildenbrand 
10224b097002SDavid Hildenbrand 	/*
10234b097002SDavid Hildenbrand 	 * We only support onlining/offlining/adding/removing of complete
10244b097002SDavid Hildenbrand 	 * memory blocks; therefore, either all is either early or hotplugged.
10254b097002SDavid Hildenbrand 	 */
10264b097002SDavid Hildenbrand 	if (early_section(__pfn_to_section(page_to_pfn(page))))
10274b097002SDavid Hildenbrand 		zone->present_early_pages += nr_pages;
1028f9901144SDavid Hildenbrand 	zone->present_pages += nr_pages;
1029f9901144SDavid Hildenbrand 	zone->zone_pgdat->node_present_pages += nr_pages;
1030836809ecSDavid Hildenbrand 
1031836809ecSDavid Hildenbrand 	if (group && movable)
1032836809ecSDavid Hildenbrand 		group->present_movable_pages += nr_pages;
1033836809ecSDavid Hildenbrand 	else if (group && !movable)
1034836809ecSDavid Hildenbrand 		group->present_kernel_pages += nr_pages;
1035f9901144SDavid Hildenbrand }
1036f9901144SDavid Hildenbrand 
1037a08a2ae3SOscar Salvador int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
1038a08a2ae3SOscar Salvador 			      struct zone *zone)
1039a08a2ae3SOscar Salvador {
1040a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
104166361095SMuchun Song 	int ret, i;
1042a08a2ae3SOscar Salvador 
1043a08a2ae3SOscar Salvador 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1044a08a2ae3SOscar Salvador 	if (ret)
1045a08a2ae3SOscar Salvador 		return ret;
1046a08a2ae3SOscar Salvador 
1047a08a2ae3SOscar Salvador 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE);
1048a08a2ae3SOscar Salvador 
104966361095SMuchun Song 	for (i = 0; i < nr_pages; i++)
105066361095SMuchun Song 		SetPageVmemmapSelfHosted(pfn_to_page(pfn + i));
105166361095SMuchun Song 
1052a08a2ae3SOscar Salvador 	/*
1053a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1054a08a2ae3SOscar Salvador 	 * the case, mark those sections online here as otherwise they will be
1055a08a2ae3SOscar Salvador 	 * left offline.
1056a08a2ae3SOscar Salvador 	 */
1057a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1058a08a2ae3SOscar Salvador 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1059a08a2ae3SOscar Salvador 
1060a08a2ae3SOscar Salvador 	return ret;
1061a08a2ae3SOscar Salvador }
1062a08a2ae3SOscar Salvador 
1063a08a2ae3SOscar Salvador void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
1064a08a2ae3SOscar Salvador {
1065a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
1066a08a2ae3SOscar Salvador 
1067a08a2ae3SOscar Salvador 	/*
1068a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1069a08a2ae3SOscar Salvador 	 * the case, mark those sections offline here as otherwise they will be
1070a08a2ae3SOscar Salvador 	 * left online.
1071a08a2ae3SOscar Salvador 	 */
1072a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1073a08a2ae3SOscar Salvador 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1074a08a2ae3SOscar Salvador 
1075a08a2ae3SOscar Salvador         /*
1076a08a2ae3SOscar Salvador 	 * The pages associated with this vmemmap have been offlined, so
1077a08a2ae3SOscar Salvador 	 * we can reset its state here.
1078a08a2ae3SOscar Salvador 	 */
1079a08a2ae3SOscar Salvador 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
1080a08a2ae3SOscar Salvador 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1081a08a2ae3SOscar Salvador }
1082a08a2ae3SOscar Salvador 
1083836809ecSDavid Hildenbrand int __ref online_pages(unsigned long pfn, unsigned long nr_pages,
1084836809ecSDavid Hildenbrand 		       struct zone *zone, struct memory_group *group)
108575884fb1SKAMEZAWA Hiroyuki {
1086aa47228aSCody P Schafer 	unsigned long flags;
10876811378eSYasunori Goto 	int need_zonelists_rebuild = 0;
1088a08a2ae3SOscar Salvador 	const int nid = zone_to_nid(zone);
10897b78d335SYasunori Goto 	int ret;
10907b78d335SYasunori Goto 	struct memory_notify arg;
10913947be19SDave Hansen 
1092dd8e2f23SOscar Salvador 	/*
1093dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1094041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1095dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1096dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1097dd8e2f23SOscar Salvador 	 * aligned.
1098dd8e2f23SOscar Salvador 	 */
1099ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
1100dd8e2f23SOscar Salvador 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
11014986fac1SDavid Hildenbrand 		return -EINVAL;
11024986fac1SDavid Hildenbrand 
1103381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
1104381eab4aSDavid Hildenbrand 
1105f1dd2cd1SMichal Hocko 	/* associate pfn range with the zone */
1106b30c5927SDavid Hildenbrand 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_ISOLATE);
1107511c2abaSLai Jiangshan 
11087b78d335SYasunori Goto 	arg.start_pfn = pfn;
11097b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1110d9713679SLai Jiangshan 	node_states_check_changes_online(nr_pages, zone, &arg);
11117b78d335SYasunori Goto 
11127b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_ONLINE, &arg);
11137b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
1114e33e33b4SChen Yucong 	if (ret)
1115e33e33b4SChen Yucong 		goto failed_addition;
1116e33e33b4SChen Yucong 
11173947be19SDave Hansen 	/*
1118b30c5927SDavid Hildenbrand 	 * Fixup the number of isolated pageblocks before marking the sections
1119b30c5927SDavid Hildenbrand 	 * onlining, such that undo_isolate_page_range() works correctly.
1120b30c5927SDavid Hildenbrand 	 */
1121b30c5927SDavid Hildenbrand 	spin_lock_irqsave(&zone->lock, flags);
1122b30c5927SDavid Hildenbrand 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
1123b30c5927SDavid Hildenbrand 	spin_unlock_irqrestore(&zone->lock, flags);
1124b30c5927SDavid Hildenbrand 
1125b30c5927SDavid Hildenbrand 	/*
11266811378eSYasunori Goto 	 * If this zone is not populated, then it is not in zonelist.
11276811378eSYasunori Goto 	 * This means the page allocator ignores this zone.
11286811378eSYasunori Goto 	 * So, zonelist must be updated after online.
11296811378eSYasunori Goto 	 */
11306dcd73d7SWen Congyang 	if (!populated_zone(zone)) {
11316811378eSYasunori Goto 		need_zonelists_rebuild = 1;
113272675e13SMichal Hocko 		setup_zone_pageset(zone);
11336dcd73d7SWen Congyang 	}
11346811378eSYasunori Goto 
1135aac65321SDavid Hildenbrand 	online_pages_range(pfn, nr_pages);
1136836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
1137aa47228aSCody P Schafer 
1138b30c5927SDavid Hildenbrand 	node_states_set_node(nid, &arg);
1139b30c5927SDavid Hildenbrand 	if (need_zonelists_rebuild)
1140b30c5927SDavid Hildenbrand 		build_all_zonelists(NULL);
1141b30c5927SDavid Hildenbrand 
1142b30c5927SDavid Hildenbrand 	/* Basic onlining is complete, allow allocation of onlined pages. */
1143b30c5927SDavid Hildenbrand 	undo_isolate_page_range(pfn, pfn + nr_pages, MIGRATE_MOVABLE);
1144b30c5927SDavid Hildenbrand 
114593146d98SDavid Hildenbrand 	/*
1146b86c5fc4SDavid Hildenbrand 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
1147b86c5fc4SDavid Hildenbrand 	 * the tail of the freelist when undoing isolation). Shuffle the whole
1148b86c5fc4SDavid Hildenbrand 	 * zone to make sure the just onlined pages are properly distributed
1149b86c5fc4SDavid Hildenbrand 	 * across the whole freelist - to create an initial shuffle.
115093146d98SDavid Hildenbrand 	 */
1151e900a918SDan Williams 	shuffle_zone(zone);
1152e900a918SDan Williams 
1153b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
11541b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
11551b79acc9SKOSAKI Motohiro 
1156e888ca35SVlastimil Babka 	kswapd_run(nid);
1157698b1b30SVlastimil Babka 	kcompactd_run(nid);
115861b13993SDave Hansen 
11592d1d43f6SChandra Seetharaman 	writeback_set_ratelimit();
11607b78d335SYasunori Goto 
11617b78d335SYasunori Goto 	memory_notify(MEM_ONLINE, &arg);
1162381eab4aSDavid Hildenbrand 	mem_hotplug_done();
116330467e0bSDavid Rientjes 	return 0;
1164e33e33b4SChen Yucong 
1165e33e33b4SChen Yucong failed_addition:
1166e33e33b4SChen Yucong 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1167e33e33b4SChen Yucong 		 (unsigned long long) pfn << PAGE_SHIFT,
1168e33e33b4SChen Yucong 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1169e33e33b4SChen Yucong 	memory_notify(MEM_CANCEL_ONLINE, &arg);
1170feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
1171381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1172e33e33b4SChen Yucong 	return ret;
11733947be19SDave Hansen }
1174bc02af93SYasunori Goto 
11750bd85420STang Chen static void reset_node_present_pages(pg_data_t *pgdat)
11760bd85420STang Chen {
11770bd85420STang Chen 	struct zone *z;
11780bd85420STang Chen 
11790bd85420STang Chen 	for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
11800bd85420STang Chen 		z->present_pages = 0;
11810bd85420STang Chen 
11820bd85420STang Chen 	pgdat->node_present_pages = 0;
11830bd85420STang Chen }
11840bd85420STang Chen 
1185e1319331SHidetoshi Seto /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
118609f49dcaSMichal Hocko static pg_data_t __ref *hotadd_init_pgdat(int nid)
11879af3c2deSYasunori Goto {
11889af3c2deSYasunori Goto 	struct pglist_data *pgdat;
11899af3c2deSYasunori Goto 
119009f49dcaSMichal Hocko 	/*
119109f49dcaSMichal Hocko 	 * NODE_DATA is preallocated (free_area_init) but its internal
119209f49dcaSMichal Hocko 	 * state is not allocated completely. Add missing pieces.
119309f49dcaSMichal Hocko 	 * Completely offline nodes stay around and they just need
119409f49dcaSMichal Hocko 	 * reintialization.
119509f49dcaSMichal Hocko 	 */
119670b5b46aSMichal Hocko 	pgdat = NODE_DATA(nid);
119703e85f9dSOscar Salvador 
11989af3c2deSYasunori Goto 	/* init node's zones as empty zones, we don't have any present pages.*/
119970b5b46aSMichal Hocko 	free_area_init_core_hotplug(pgdat);
12009af3c2deSYasunori Goto 
1201959ecc48SKAMEZAWA Hiroyuki 	/*
1202959ecc48SKAMEZAWA Hiroyuki 	 * The node we allocated has no zone fallback lists. For avoiding
1203959ecc48SKAMEZAWA Hiroyuki 	 * to access not-initialized zonelist, build here.
1204959ecc48SKAMEZAWA Hiroyuki 	 */
120572675e13SMichal Hocko 	build_all_zonelists(pgdat);
1206959ecc48SKAMEZAWA Hiroyuki 
1207f784a3f1STang Chen 	/*
12080bd85420STang Chen 	 * When memory is hot-added, all the memory is in offline state. So
12090bd85420STang Chen 	 * clear all zones' present_pages because they will be updated in
12100bd85420STang Chen 	 * online_pages() and offline_pages().
121170b5b46aSMichal Hocko 	 * TODO: should be in free_area_init_core_hotplug?
12120bd85420STang Chen 	 */
121303e85f9dSOscar Salvador 	reset_node_managed_pages(pgdat);
12140bd85420STang Chen 	reset_node_present_pages(pgdat);
12150bd85420STang Chen 
12169af3c2deSYasunori Goto 	return pgdat;
12179af3c2deSYasunori Goto }
12189af3c2deSYasunori Goto 
1219ba2d2666SMel Gorman /*
1220ba2d2666SMel Gorman  * __try_online_node - online a node if offlined
1221e8b098fcSMike Rapoport  * @nid: the node ID
1222b9ff0360SOscar Salvador  * @set_node_online: Whether we want to online the node
1223cf23422bSminskey guo  * called by cpu_up() to online a node without onlined memory.
1224b9ff0360SOscar Salvador  *
1225b9ff0360SOscar Salvador  * Returns:
1226b9ff0360SOscar Salvador  * 1 -> a new node has been allocated
1227b9ff0360SOscar Salvador  * 0 -> the node is already online
1228b9ff0360SOscar Salvador  * -ENOMEM -> the node could not be allocated
1229cf23422bSminskey guo  */
1230c68ab18cSDavid Hildenbrand static int __try_online_node(int nid, bool set_node_online)
1231cf23422bSminskey guo {
1232cf23422bSminskey guo 	pg_data_t *pgdat;
1233b9ff0360SOscar Salvador 	int ret = 1;
1234cf23422bSminskey guo 
123501b0f197SToshi Kani 	if (node_online(nid))
123601b0f197SToshi Kani 		return 0;
123701b0f197SToshi Kani 
123809f49dcaSMichal Hocko 	pgdat = hotadd_init_pgdat(nid);
12397553e8f2SDavid Rientjes 	if (!pgdat) {
124001b0f197SToshi Kani 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1241cf23422bSminskey guo 		ret = -ENOMEM;
1242cf23422bSminskey guo 		goto out;
1243cf23422bSminskey guo 	}
1244b9ff0360SOscar Salvador 
1245b9ff0360SOscar Salvador 	if (set_node_online) {
1246cf23422bSminskey guo 		node_set_online(nid);
1247cf23422bSminskey guo 		ret = register_one_node(nid);
1248cf23422bSminskey guo 		BUG_ON(ret);
1249b9ff0360SOscar Salvador 	}
1250cf23422bSminskey guo out:
1251b9ff0360SOscar Salvador 	return ret;
1252b9ff0360SOscar Salvador }
1253b9ff0360SOscar Salvador 
1254b9ff0360SOscar Salvador /*
1255b9ff0360SOscar Salvador  * Users of this function always want to online/register the node
1256b9ff0360SOscar Salvador  */
1257b9ff0360SOscar Salvador int try_online_node(int nid)
1258b9ff0360SOscar Salvador {
1259b9ff0360SOscar Salvador 	int ret;
1260b9ff0360SOscar Salvador 
1261b9ff0360SOscar Salvador 	mem_hotplug_begin();
1262c68ab18cSDavid Hildenbrand 	ret =  __try_online_node(nid, true);
1263bfc8c901SVladimir Davydov 	mem_hotplug_done();
1264cf23422bSminskey guo 	return ret;
1265cf23422bSminskey guo }
1266cf23422bSminskey guo 
126727356f54SToshi Kani static int check_hotplug_memory_range(u64 start, u64 size)
126827356f54SToshi Kani {
1269ba325585SPavel Tatashin 	/* memory range must be block size aligned */
1270cec3ebd0SDavid Hildenbrand 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1271cec3ebd0SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1272ba325585SPavel Tatashin 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1273cec3ebd0SDavid Hildenbrand 		       memory_block_size_bytes(), start, size);
127427356f54SToshi Kani 		return -EINVAL;
127527356f54SToshi Kani 	}
127627356f54SToshi Kani 
127727356f54SToshi Kani 	return 0;
127827356f54SToshi Kani }
127927356f54SToshi Kani 
128031bc3858SVitaly Kuznetsov static int online_memory_block(struct memory_block *mem, void *arg)
128131bc3858SVitaly Kuznetsov {
12821adf8b46SAnshuman Khandual 	mem->online_type = mhp_default_online_type;
1283dc18d706SNathan Fontenot 	return device_online(&mem->dev);
128431bc3858SVitaly Kuznetsov }
128531bc3858SVitaly Kuznetsov 
1286a08a2ae3SOscar Salvador bool mhp_supports_memmap_on_memory(unsigned long size)
1287a08a2ae3SOscar Salvador {
1288a08a2ae3SOscar Salvador 	unsigned long nr_vmemmap_pages = size / PAGE_SIZE;
1289a08a2ae3SOscar Salvador 	unsigned long vmemmap_size = nr_vmemmap_pages * sizeof(struct page);
1290a08a2ae3SOscar Salvador 	unsigned long remaining_size = size - vmemmap_size;
1291a08a2ae3SOscar Salvador 
1292a08a2ae3SOscar Salvador 	/*
1293a08a2ae3SOscar Salvador 	 * Besides having arch support and the feature enabled at runtime, we
1294a08a2ae3SOscar Salvador 	 * need a few more assumptions to hold true:
1295a08a2ae3SOscar Salvador 	 *
1296a08a2ae3SOscar Salvador 	 * a) We span a single memory block: memory onlining/offlinin;g happens
1297a08a2ae3SOscar Salvador 	 *    in memory block granularity. We don't want the vmemmap of online
1298a08a2ae3SOscar Salvador 	 *    memory blocks to reside on offline memory blocks. In the future,
1299a08a2ae3SOscar Salvador 	 *    we might want to support variable-sized memory blocks to make the
1300a08a2ae3SOscar Salvador 	 *    feature more versatile.
1301a08a2ae3SOscar Salvador 	 *
1302a08a2ae3SOscar Salvador 	 * b) The vmemmap pages span complete PMDs: We don't want vmemmap code
1303a08a2ae3SOscar Salvador 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1304a08a2ae3SOscar Salvador 	 *    other memory blocks)
1305a08a2ae3SOscar Salvador 	 *
1306a08a2ae3SOscar Salvador 	 * c) The vmemmap pages (and thereby the pages that will be exposed to
1307a08a2ae3SOscar Salvador 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1308a08a2ae3SOscar Salvador 	 *    code requires applicable ranges to be page-aligned, for example, to
1309a08a2ae3SOscar Salvador 	 *    set the migratetypes properly.
1310a08a2ae3SOscar Salvador 	 *
1311a08a2ae3SOscar Salvador 	 * TODO: Although we have a check here to make sure that vmemmap pages
1312a08a2ae3SOscar Salvador 	 *       fully populate a PMD, it is not the right place to check for
1313a08a2ae3SOscar Salvador 	 *       this. A much better solution involves improving vmemmap code
1314a08a2ae3SOscar Salvador 	 *       to fallback to base pages when trying to populate vmemmap using
1315a08a2ae3SOscar Salvador 	 *       altmap as an alternative source of memory, and we do not exactly
1316a08a2ae3SOscar Salvador 	 *       populate a single PMD.
1317a08a2ae3SOscar Salvador 	 */
13186e02c46bSMuchun Song 	return mhp_memmap_on_memory() &&
1319a08a2ae3SOscar Salvador 	       size == memory_block_size_bytes() &&
1320a08a2ae3SOscar Salvador 	       IS_ALIGNED(vmemmap_size, PMD_SIZE) &&
1321a08a2ae3SOscar Salvador 	       IS_ALIGNED(remaining_size, (pageblock_nr_pages << PAGE_SHIFT));
1322a08a2ae3SOscar Salvador }
1323a08a2ae3SOscar Salvador 
13248df1d0e4SDavid Hildenbrand /*
13258df1d0e4SDavid Hildenbrand  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
13268df1d0e4SDavid Hildenbrand  * and online/offline operations (triggered e.g. by sysfs).
13278df1d0e4SDavid Hildenbrand  *
13288df1d0e4SDavid Hildenbrand  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
13298df1d0e4SDavid Hildenbrand  */
1330b6117199SDavid Hildenbrand int __ref add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1331bc02af93SYasunori Goto {
1332d15dfd31SCatalin Marinas 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
133332befe9eSDavid Hildenbrand 	enum memblock_flags memblock_flags = MEMBLOCK_NONE;
1334a08a2ae3SOscar Salvador 	struct vmem_altmap mhp_altmap = {};
1335028fc57aSDavid Hildenbrand 	struct memory_group *group = NULL;
133662cedb9fSDavid Vrabel 	u64 start, size;
1337b9ff0360SOscar Salvador 	bool new_node = false;
1338bc02af93SYasunori Goto 	int ret;
1339bc02af93SYasunori Goto 
134062cedb9fSDavid Vrabel 	start = res->start;
134162cedb9fSDavid Vrabel 	size = resource_size(res);
134262cedb9fSDavid Vrabel 
134327356f54SToshi Kani 	ret = check_hotplug_memory_range(start, size);
134427356f54SToshi Kani 	if (ret)
134527356f54SToshi Kani 		return ret;
134627356f54SToshi Kani 
1347028fc57aSDavid Hildenbrand 	if (mhp_flags & MHP_NID_IS_MGID) {
1348028fc57aSDavid Hildenbrand 		group = memory_group_find_by_id(nid);
1349028fc57aSDavid Hildenbrand 		if (!group)
1350028fc57aSDavid Hildenbrand 			return -EINVAL;
1351028fc57aSDavid Hildenbrand 		nid = group->nid;
1352028fc57aSDavid Hildenbrand 	}
1353028fc57aSDavid Hildenbrand 
1354fa6d9ec7SVishal Verma 	if (!node_possible(nid)) {
1355fa6d9ec7SVishal Verma 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1356fa6d9ec7SVishal Verma 		return -EINVAL;
1357fa6d9ec7SVishal Verma 	}
1358fa6d9ec7SVishal Verma 
1359bfc8c901SVladimir Davydov 	mem_hotplug_begin();
1360ac13c462SNathan Zimmer 
136153d38316SDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
136232befe9eSDavid Hildenbrand 		if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
136332befe9eSDavid Hildenbrand 			memblock_flags = MEMBLOCK_DRIVER_MANAGED;
136432befe9eSDavid Hildenbrand 		ret = memblock_add_node(start, size, nid, memblock_flags);
136553d38316SDavid Hildenbrand 		if (ret)
136653d38316SDavid Hildenbrand 			goto error_mem_hotplug_end;
136753d38316SDavid Hildenbrand 	}
13687f36e3e5STang Chen 
1369c68ab18cSDavid Hildenbrand 	ret = __try_online_node(nid, false);
1370b9ff0360SOscar Salvador 	if (ret < 0)
137141b9e2d7SWen Congyang 		goto error;
1372b9ff0360SOscar Salvador 	new_node = ret;
13739af3c2deSYasunori Goto 
1374a08a2ae3SOscar Salvador 	/*
1375a08a2ae3SOscar Salvador 	 * Self hosted memmap array
1376a08a2ae3SOscar Salvador 	 */
1377a08a2ae3SOscar Salvador 	if (mhp_flags & MHP_MEMMAP_ON_MEMORY) {
1378a08a2ae3SOscar Salvador 		if (!mhp_supports_memmap_on_memory(size)) {
1379a08a2ae3SOscar Salvador 			ret = -EINVAL;
1380a08a2ae3SOscar Salvador 			goto error;
1381a08a2ae3SOscar Salvador 		}
1382a08a2ae3SOscar Salvador 		mhp_altmap.free = PHYS_PFN(size);
1383a08a2ae3SOscar Salvador 		mhp_altmap.base_pfn = PHYS_PFN(start);
1384a08a2ae3SOscar Salvador 		params.altmap = &mhp_altmap;
1385a08a2ae3SOscar Salvador 	}
1386a08a2ae3SOscar Salvador 
1387bc02af93SYasunori Goto 	/* call arch's memory hotadd */
1388f5637d3bSLogan Gunthorpe 	ret = arch_add_memory(nid, start, size, &params);
13899af3c2deSYasunori Goto 	if (ret < 0)
13909af3c2deSYasunori Goto 		goto error;
13919af3c2deSYasunori Goto 
1392db051a0dSDavid Hildenbrand 	/* create memory block devices after memory was added */
1393028fc57aSDavid Hildenbrand 	ret = create_memory_block_devices(start, size, mhp_altmap.alloc,
1394028fc57aSDavid Hildenbrand 					  group);
1395db051a0dSDavid Hildenbrand 	if (ret) {
139665a2aa5fSDavid Hildenbrand 		arch_remove_memory(start, size, NULL);
1397db051a0dSDavid Hildenbrand 		goto error;
1398db051a0dSDavid Hildenbrand 	}
1399db051a0dSDavid Hildenbrand 
1400a1e565aaSTang Chen 	if (new_node) {
1401d5b6f6a3SOscar Salvador 		/* If sysfs file of new node can't be created, cpu on the node
14020fc44159SYasunori Goto 		 * can't be hot-added. There is no rollback way now.
14030fc44159SYasunori Goto 		 * So, check by BUG_ON() to catch it reluctantly..
1404d5b6f6a3SOscar Salvador 		 * We online node here. We can't roll back from here.
14050fc44159SYasunori Goto 		 */
1406d5b6f6a3SOscar Salvador 		node_set_online(nid);
1407d5b6f6a3SOscar Salvador 		ret = __register_one_node(nid);
14080fc44159SYasunori Goto 		BUG_ON(ret);
14090fc44159SYasunori Goto 	}
14100fc44159SYasunori Goto 
1411cc651559SDavid Hildenbrand 	register_memory_blocks_under_node(nid, PFN_DOWN(start),
1412cc651559SDavid Hildenbrand 					  PFN_UP(start + size - 1),
1413f85086f9SLaurent Dufour 					  MEMINIT_HOTPLUG);
1414d5b6f6a3SOscar Salvador 
1415d96ae530Sakpm@linux-foundation.org 	/* create new memmap entry */
14167b7b2721SDavid Hildenbrand 	if (!strcmp(res->name, "System RAM"))
1417d96ae530Sakpm@linux-foundation.org 		firmware_map_add_hotplug(start, start + size, "System RAM");
1418d96ae530Sakpm@linux-foundation.org 
1419381eab4aSDavid Hildenbrand 	/* device_online() will take the lock when calling online_pages() */
1420381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1421381eab4aSDavid Hildenbrand 
14229ca6551eSDavid Hildenbrand 	/*
14239ca6551eSDavid Hildenbrand 	 * In case we're allowed to merge the resource, flag it and trigger
14249ca6551eSDavid Hildenbrand 	 * merging now that adding succeeded.
14259ca6551eSDavid Hildenbrand 	 */
142626011267SDavid Hildenbrand 	if (mhp_flags & MHP_MERGE_RESOURCE)
14279ca6551eSDavid Hildenbrand 		merge_system_ram_resource(res);
14289ca6551eSDavid Hildenbrand 
142931bc3858SVitaly Kuznetsov 	/* online pages if requested */
14301adf8b46SAnshuman Khandual 	if (mhp_default_online_type != MMOP_OFFLINE)
1431fbcf73ceSDavid Hildenbrand 		walk_memory_blocks(start, size, NULL, online_memory_block);
143231bc3858SVitaly Kuznetsov 
1433381eab4aSDavid Hildenbrand 	return ret;
14349af3c2deSYasunori Goto error:
143552219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
14367f36e3e5STang Chen 		memblock_remove(start, size);
143753d38316SDavid Hildenbrand error_mem_hotplug_end:
1438bfc8c901SVladimir Davydov 	mem_hotplug_done();
1439bc02af93SYasunori Goto 	return ret;
1440bc02af93SYasunori Goto }
144162cedb9fSDavid Vrabel 
14428df1d0e4SDavid Hildenbrand /* requires device_hotplug_lock, see add_memory_resource() */
1443b6117199SDavid Hildenbrand int __ref __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
144462cedb9fSDavid Vrabel {
144562cedb9fSDavid Vrabel 	struct resource *res;
144662cedb9fSDavid Vrabel 	int ret;
144762cedb9fSDavid Vrabel 
14487b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, "System RAM");
14496f754ba4SVitaly Kuznetsov 	if (IS_ERR(res))
14506f754ba4SVitaly Kuznetsov 		return PTR_ERR(res);
145162cedb9fSDavid Vrabel 
1452b6117199SDavid Hildenbrand 	ret = add_memory_resource(nid, res, mhp_flags);
145362cedb9fSDavid Vrabel 	if (ret < 0)
145462cedb9fSDavid Vrabel 		release_memory_resource(res);
145562cedb9fSDavid Vrabel 	return ret;
145662cedb9fSDavid Vrabel }
14578df1d0e4SDavid Hildenbrand 
1458b6117199SDavid Hildenbrand int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
14598df1d0e4SDavid Hildenbrand {
14608df1d0e4SDavid Hildenbrand 	int rc;
14618df1d0e4SDavid Hildenbrand 
14628df1d0e4SDavid Hildenbrand 	lock_device_hotplug();
1463b6117199SDavid Hildenbrand 	rc = __add_memory(nid, start, size, mhp_flags);
14648df1d0e4SDavid Hildenbrand 	unlock_device_hotplug();
14658df1d0e4SDavid Hildenbrand 
14668df1d0e4SDavid Hildenbrand 	return rc;
14678df1d0e4SDavid Hildenbrand }
1468bc02af93SYasunori Goto EXPORT_SYMBOL_GPL(add_memory);
14690c0e6195SKAMEZAWA Hiroyuki 
14707b7b2721SDavid Hildenbrand /*
14717b7b2721SDavid Hildenbrand  * Add special, driver-managed memory to the system as system RAM. Such
14727b7b2721SDavid Hildenbrand  * memory is not exposed via the raw firmware-provided memmap as system
14737b7b2721SDavid Hildenbrand  * RAM, instead, it is detected and added by a driver - during cold boot,
14747b7b2721SDavid Hildenbrand  * after a reboot, and after kexec.
14757b7b2721SDavid Hildenbrand  *
14767b7b2721SDavid Hildenbrand  * Reasons why this memory should not be used for the initial memmap of a
14777b7b2721SDavid Hildenbrand  * kexec kernel or for placing kexec images:
14787b7b2721SDavid Hildenbrand  * - The booting kernel is in charge of determining how this memory will be
14797b7b2721SDavid Hildenbrand  *   used (e.g., use persistent memory as system RAM)
14807b7b2721SDavid Hildenbrand  * - Coordination with a hypervisor is required before this memory
14817b7b2721SDavid Hildenbrand  *   can be used (e.g., inaccessible parts).
14827b7b2721SDavid Hildenbrand  *
14837b7b2721SDavid Hildenbrand  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
14847b7b2721SDavid Hildenbrand  * memory map") are created. Also, the created memory resource is flagged
14857cf603d1SDavid Hildenbrand  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
14867b7b2721SDavid Hildenbrand  * this memory as well (esp., not place kexec images onto it).
14877b7b2721SDavid Hildenbrand  *
14887b7b2721SDavid Hildenbrand  * The resource_name (visible via /proc/iomem) has to have the format
14897b7b2721SDavid Hildenbrand  * "System RAM ($DRIVER)".
14907b7b2721SDavid Hildenbrand  */
14917b7b2721SDavid Hildenbrand int add_memory_driver_managed(int nid, u64 start, u64 size,
1492b6117199SDavid Hildenbrand 			      const char *resource_name, mhp_t mhp_flags)
14937b7b2721SDavid Hildenbrand {
14947b7b2721SDavid Hildenbrand 	struct resource *res;
14957b7b2721SDavid Hildenbrand 	int rc;
14967b7b2721SDavid Hildenbrand 
14977b7b2721SDavid Hildenbrand 	if (!resource_name ||
14987b7b2721SDavid Hildenbrand 	    strstr(resource_name, "System RAM (") != resource_name ||
14997b7b2721SDavid Hildenbrand 	    resource_name[strlen(resource_name) - 1] != ')')
15007b7b2721SDavid Hildenbrand 		return -EINVAL;
15017b7b2721SDavid Hildenbrand 
15027b7b2721SDavid Hildenbrand 	lock_device_hotplug();
15037b7b2721SDavid Hildenbrand 
15047b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, resource_name);
15057b7b2721SDavid Hildenbrand 	if (IS_ERR(res)) {
15067b7b2721SDavid Hildenbrand 		rc = PTR_ERR(res);
15077b7b2721SDavid Hildenbrand 		goto out_unlock;
15087b7b2721SDavid Hildenbrand 	}
15097b7b2721SDavid Hildenbrand 
1510b6117199SDavid Hildenbrand 	rc = add_memory_resource(nid, res, mhp_flags);
15117b7b2721SDavid Hildenbrand 	if (rc < 0)
15127b7b2721SDavid Hildenbrand 		release_memory_resource(res);
15137b7b2721SDavid Hildenbrand 
15147b7b2721SDavid Hildenbrand out_unlock:
15157b7b2721SDavid Hildenbrand 	unlock_device_hotplug();
15167b7b2721SDavid Hildenbrand 	return rc;
15177b7b2721SDavid Hildenbrand }
15187b7b2721SDavid Hildenbrand EXPORT_SYMBOL_GPL(add_memory_driver_managed);
15197b7b2721SDavid Hildenbrand 
1520bca3feaaSAnshuman Khandual /*
1521bca3feaaSAnshuman Khandual  * Platforms should define arch_get_mappable_range() that provides
1522bca3feaaSAnshuman Khandual  * maximum possible addressable physical memory range for which the
1523bca3feaaSAnshuman Khandual  * linear mapping could be created. The platform returned address
1524bca3feaaSAnshuman Khandual  * range must adhere to these following semantics.
1525bca3feaaSAnshuman Khandual  *
1526bca3feaaSAnshuman Khandual  * - range.start <= range.end
1527bca3feaaSAnshuman Khandual  * - Range includes both end points [range.start..range.end]
1528bca3feaaSAnshuman Khandual  *
1529bca3feaaSAnshuman Khandual  * There is also a fallback definition provided here, allowing the
1530bca3feaaSAnshuman Khandual  * entire possible physical address range in case any platform does
1531bca3feaaSAnshuman Khandual  * not define arch_get_mappable_range().
1532bca3feaaSAnshuman Khandual  */
1533bca3feaaSAnshuman Khandual struct range __weak arch_get_mappable_range(void)
1534bca3feaaSAnshuman Khandual {
1535bca3feaaSAnshuman Khandual 	struct range mhp_range = {
1536bca3feaaSAnshuman Khandual 		.start = 0UL,
1537bca3feaaSAnshuman Khandual 		.end = -1ULL,
1538bca3feaaSAnshuman Khandual 	};
1539bca3feaaSAnshuman Khandual 	return mhp_range;
1540bca3feaaSAnshuman Khandual }
1541bca3feaaSAnshuman Khandual 
1542bca3feaaSAnshuman Khandual struct range mhp_get_pluggable_range(bool need_mapping)
1543bca3feaaSAnshuman Khandual {
1544bca3feaaSAnshuman Khandual 	const u64 max_phys = (1ULL << MAX_PHYSMEM_BITS) - 1;
1545bca3feaaSAnshuman Khandual 	struct range mhp_range;
1546bca3feaaSAnshuman Khandual 
1547bca3feaaSAnshuman Khandual 	if (need_mapping) {
1548bca3feaaSAnshuman Khandual 		mhp_range = arch_get_mappable_range();
1549bca3feaaSAnshuman Khandual 		if (mhp_range.start > max_phys) {
1550bca3feaaSAnshuman Khandual 			mhp_range.start = 0;
1551bca3feaaSAnshuman Khandual 			mhp_range.end = 0;
1552bca3feaaSAnshuman Khandual 		}
1553bca3feaaSAnshuman Khandual 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1554bca3feaaSAnshuman Khandual 	} else {
1555bca3feaaSAnshuman Khandual 		mhp_range.start = 0;
1556bca3feaaSAnshuman Khandual 		mhp_range.end = max_phys;
1557bca3feaaSAnshuman Khandual 	}
1558bca3feaaSAnshuman Khandual 	return mhp_range;
1559bca3feaaSAnshuman Khandual }
1560bca3feaaSAnshuman Khandual EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1561bca3feaaSAnshuman Khandual 
1562bca3feaaSAnshuman Khandual bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1563bca3feaaSAnshuman Khandual {
1564bca3feaaSAnshuman Khandual 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1565bca3feaaSAnshuman Khandual 	u64 end = start + size;
1566bca3feaaSAnshuman Khandual 
1567bca3feaaSAnshuman Khandual 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1568bca3feaaSAnshuman Khandual 		return true;
1569bca3feaaSAnshuman Khandual 
1570bca3feaaSAnshuman Khandual 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1571bca3feaaSAnshuman Khandual 		start, end, mhp_range.start, mhp_range.end);
1572bca3feaaSAnshuman Khandual 	return false;
1573bca3feaaSAnshuman Khandual }
1574bca3feaaSAnshuman Khandual 
15750c0e6195SKAMEZAWA Hiroyuki #ifdef CONFIG_MEMORY_HOTREMOVE
15760c0e6195SKAMEZAWA Hiroyuki /*
15770efadf48SYisheng Xie  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1578aa218795SDavid Hildenbrand  * non-lru movable pages and hugepages). Will skip over most unmovable
1579aa218795SDavid Hildenbrand  * pages (esp., pages that can be skipped when offlining), but bail out on
1580aa218795SDavid Hildenbrand  * definitely unmovable pages.
1581aa218795SDavid Hildenbrand  *
1582aa218795SDavid Hildenbrand  * Returns:
1583aa218795SDavid Hildenbrand  *	0 in case a movable page is found and movable_pfn was updated.
1584aa218795SDavid Hildenbrand  *	-ENOENT in case no movable page was found.
1585aa218795SDavid Hildenbrand  *	-EBUSY in case a definitely unmovable page was found.
15860c0e6195SKAMEZAWA Hiroyuki  */
1587aa218795SDavid Hildenbrand static int scan_movable_pages(unsigned long start, unsigned long end,
1588aa218795SDavid Hildenbrand 			      unsigned long *movable_pfn)
15890c0e6195SKAMEZAWA Hiroyuki {
15900c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
1591eeb0efd0SOscar Salvador 
15920c0e6195SKAMEZAWA Hiroyuki 	for (pfn = start; pfn < end; pfn++) {
1593eeb0efd0SOscar Salvador 		struct page *page, *head;
1594eeb0efd0SOscar Salvador 		unsigned long skip;
1595eeb0efd0SOscar Salvador 
1596eeb0efd0SOscar Salvador 		if (!pfn_valid(pfn))
1597eeb0efd0SOscar Salvador 			continue;
15980c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
15990c0e6195SKAMEZAWA Hiroyuki 		if (PageLRU(page))
1600aa218795SDavid Hildenbrand 			goto found;
16010efadf48SYisheng Xie 		if (__PageMovable(page))
1602aa218795SDavid Hildenbrand 			goto found;
1603aa218795SDavid Hildenbrand 
1604aa218795SDavid Hildenbrand 		/*
1605aa218795SDavid Hildenbrand 		 * PageOffline() pages that are not marked __PageMovable() and
1606aa218795SDavid Hildenbrand 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1607aa218795SDavid Hildenbrand 		 * definitely unmovable. If their reference count would be 0,
1608aa218795SDavid Hildenbrand 		 * they could at least be skipped when offlining memory.
1609aa218795SDavid Hildenbrand 		 */
1610aa218795SDavid Hildenbrand 		if (PageOffline(page) && page_count(page))
1611aa218795SDavid Hildenbrand 			return -EBUSY;
1612eeb0efd0SOscar Salvador 
1613eeb0efd0SOscar Salvador 		if (!PageHuge(page))
1614eeb0efd0SOscar Salvador 			continue;
1615eeb0efd0SOscar Salvador 		head = compound_head(page);
16168f251a3dSMike Kravetz 		/*
16178f251a3dSMike Kravetz 		 * This test is racy as we hold no reference or lock.  The
16188f251a3dSMike Kravetz 		 * hugetlb page could have been free'ed and head is no longer
16198f251a3dSMike Kravetz 		 * a hugetlb page before the following check.  In such unlikely
16208f251a3dSMike Kravetz 		 * cases false positives and negatives are possible.  Calling
16218f251a3dSMike Kravetz 		 * code must deal with these scenarios.
16228f251a3dSMike Kravetz 		 */
16238f251a3dSMike Kravetz 		if (HPageMigratable(head))
1624aa218795SDavid Hildenbrand 			goto found;
1625d8c6546bSMatthew Wilcox (Oracle) 		skip = compound_nr(head) - (page - head);
1626eeb0efd0SOscar Salvador 		pfn += skip - 1;
16270c0e6195SKAMEZAWA Hiroyuki 	}
1628aa218795SDavid Hildenbrand 	return -ENOENT;
1629aa218795SDavid Hildenbrand found:
1630aa218795SDavid Hildenbrand 	*movable_pfn = pfn;
16310c0e6195SKAMEZAWA Hiroyuki 	return 0;
16320c0e6195SKAMEZAWA Hiroyuki }
16330c0e6195SKAMEZAWA Hiroyuki 
163432cf666eSSeongJae Park static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
16350c0e6195SKAMEZAWA Hiroyuki {
16360c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
16376c357848SMatthew Wilcox (Oracle) 	struct page *page, *head;
16380c0e6195SKAMEZAWA Hiroyuki 	LIST_HEAD(source);
1639786dee86SLiam Mark 	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
1640786dee86SLiam Mark 				      DEFAULT_RATELIMIT_BURST);
16410c0e6195SKAMEZAWA Hiroyuki 
1642a85009c3SMichal Hocko 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1643869f7ee6SMatthew Wilcox (Oracle) 		struct folio *folio;
1644f7f9c00dSBaolin Wang 		bool isolated;
1645869f7ee6SMatthew Wilcox (Oracle) 
16460c0e6195SKAMEZAWA Hiroyuki 		if (!pfn_valid(pfn))
16470c0e6195SKAMEZAWA Hiroyuki 			continue;
16480c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
1649869f7ee6SMatthew Wilcox (Oracle) 		folio = page_folio(page);
1650869f7ee6SMatthew Wilcox (Oracle) 		head = &folio->page;
1651c8721bbbSNaoya Horiguchi 
1652c8721bbbSNaoya Horiguchi 		if (PageHuge(page)) {
1653d8c6546bSMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + compound_nr(head) - 1;
16546aa3a920SSidhartha Kumar 			isolate_hugetlb(folio, &source);
1655c8721bbbSNaoya Horiguchi 			continue;
165694723aafSMichal Hocko 		} else if (PageTransHuge(page))
16576c357848SMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + thp_nr_pages(page) - 1;
1658c8721bbbSNaoya Horiguchi 
1659b15c8726SMichal Hocko 		/*
1660b15c8726SMichal Hocko 		 * HWPoison pages have elevated reference counts so the migration would
1661b15c8726SMichal Hocko 		 * fail on them. It also doesn't make any sense to migrate them in the
1662b15c8726SMichal Hocko 		 * first place. Still try to unmap such a page in case it is still mapped
1663b15c8726SMichal Hocko 		 * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1664b15c8726SMichal Hocko 		 * the unmap as the catch all safety net).
1665b15c8726SMichal Hocko 		 */
1666b15c8726SMichal Hocko 		if (PageHWPoison(page)) {
1667869f7ee6SMatthew Wilcox (Oracle) 			if (WARN_ON(folio_test_lru(folio)))
1668869f7ee6SMatthew Wilcox (Oracle) 				folio_isolate_lru(folio);
1669869f7ee6SMatthew Wilcox (Oracle) 			if (folio_mapped(folio))
1670869f7ee6SMatthew Wilcox (Oracle) 				try_to_unmap(folio, TTU_IGNORE_MLOCK);
1671b15c8726SMichal Hocko 			continue;
1672b15c8726SMichal Hocko 		}
1673b15c8726SMichal Hocko 
1674700c2a46SKonstantin Khlebnikov 		if (!get_page_unless_zero(page))
16750c0e6195SKAMEZAWA Hiroyuki 			continue;
16760c0e6195SKAMEZAWA Hiroyuki 		/*
16770efadf48SYisheng Xie 		 * We can skip free pages. And we can deal with pages on
16780efadf48SYisheng Xie 		 * LRU and non-lru movable pages.
16790c0e6195SKAMEZAWA Hiroyuki 		 */
1680cd775580SBaolin Wang 		if (PageLRU(page))
1681f7f9c00dSBaolin Wang 			isolated = isolate_lru_page(page);
1682cd775580SBaolin Wang 		else
1683cd775580SBaolin Wang 			isolated = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1684cd775580SBaolin Wang 		if (isolated) {
168562695a84SNick Piggin 			list_add_tail(&page->lru, &source);
16860efadf48SYisheng Xie 			if (!__PageMovable(page))
1687599d0c95SMel Gorman 				inc_node_page_state(page, NR_ISOLATED_ANON +
16889de4f22aSHuang Ying 						    page_is_file_lru(page));
16896d9c285aSKOSAKI Motohiro 
16900c0e6195SKAMEZAWA Hiroyuki 		} else {
1691786dee86SLiam Mark 			if (__ratelimit(&migrate_rs)) {
16922932c8b0SMichal Hocko 				pr_warn("failed to isolate pfn %lx\n", pfn);
16930efadf48SYisheng Xie 				dump_page(page, "isolation failed");
16941723058eSOscar Salvador 			}
1695786dee86SLiam Mark 		}
1696700c2a46SKonstantin Khlebnikov 		put_page(page);
16970c0e6195SKAMEZAWA Hiroyuki 	}
1698f3ab2636SBob Liu 	if (!list_empty(&source)) {
1699203e6e5cSJoonsoo Kim 		nodemask_t nmask = node_states[N_MEMORY];
1700203e6e5cSJoonsoo Kim 		struct migration_target_control mtc = {
1701203e6e5cSJoonsoo Kim 			.nmask = &nmask,
1702203e6e5cSJoonsoo Kim 			.gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1703203e6e5cSJoonsoo Kim 		};
170432cf666eSSeongJae Park 		int ret;
1705203e6e5cSJoonsoo Kim 
1706203e6e5cSJoonsoo Kim 		/*
1707203e6e5cSJoonsoo Kim 		 * We have checked that migration range is on a single zone so
1708203e6e5cSJoonsoo Kim 		 * we can use the nid of the first page to all the others.
1709203e6e5cSJoonsoo Kim 		 */
1710203e6e5cSJoonsoo Kim 		mtc.nid = page_to_nid(list_first_entry(&source, struct page, lru));
1711203e6e5cSJoonsoo Kim 
1712203e6e5cSJoonsoo Kim 		/*
1713203e6e5cSJoonsoo Kim 		 * try to allocate from a different node but reuse this node
1714203e6e5cSJoonsoo Kim 		 * if there are no other online nodes to be used (e.g. we are
1715203e6e5cSJoonsoo Kim 		 * offlining a part of the only existing node)
1716203e6e5cSJoonsoo Kim 		 */
1717203e6e5cSJoonsoo Kim 		node_clear(mtc.nid, nmask);
1718203e6e5cSJoonsoo Kim 		if (nodes_empty(nmask))
1719203e6e5cSJoonsoo Kim 			node_set(mtc.nid, nmask);
1720203e6e5cSJoonsoo Kim 		ret = migrate_pages(&source, alloc_migration_target, NULL,
17215ac95884SYang Shi 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
17222932c8b0SMichal Hocko 		if (ret) {
17232932c8b0SMichal Hocko 			list_for_each_entry(page, &source, lru) {
1724786dee86SLiam Mark 				if (__ratelimit(&migrate_rs)) {
1725786dee86SLiam Mark 					pr_warn("migrating pfn %lx failed ret:%d\n",
17262932c8b0SMichal Hocko 						page_to_pfn(page), ret);
17272932c8b0SMichal Hocko 					dump_page(page, "migration failure");
17282932c8b0SMichal Hocko 				}
1729786dee86SLiam Mark 			}
1730c8721bbbSNaoya Horiguchi 			putback_movable_pages(&source);
1731f3ab2636SBob Liu 		}
17322932c8b0SMichal Hocko 	}
17330c0e6195SKAMEZAWA Hiroyuki }
17340c0e6195SKAMEZAWA Hiroyuki 
1735c5320926STang Chen static int __init cmdline_parse_movable_node(char *p)
1736c5320926STang Chen {
173755ac590cSTang Chen 	movable_node_enabled = true;
1738c5320926STang Chen 	return 0;
1739c5320926STang Chen }
1740c5320926STang Chen early_param("movable_node", cmdline_parse_movable_node);
1741c5320926STang Chen 
1742d9713679SLai Jiangshan /* check which state of node_states will be changed when offline memory */
1743d9713679SLai Jiangshan static void node_states_check_changes_offline(unsigned long nr_pages,
1744d9713679SLai Jiangshan 		struct zone *zone, struct memory_notify *arg)
1745d9713679SLai Jiangshan {
1746d9713679SLai Jiangshan 	struct pglist_data *pgdat = zone->zone_pgdat;
1747d9713679SLai Jiangshan 	unsigned long present_pages = 0;
174886b27beaSOscar Salvador 	enum zone_type zt;
1749d9713679SLai Jiangshan 
175098fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
175198fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
175286b27beaSOscar Salvador 
175386b27beaSOscar Salvador 	/*
175486b27beaSOscar Salvador 	 * Check whether node_states[N_NORMAL_MEMORY] will be changed.
175586b27beaSOscar Salvador 	 * If the memory to be offline is within the range
175686b27beaSOscar Salvador 	 * [0..ZONE_NORMAL], and it is the last present memory there,
175786b27beaSOscar Salvador 	 * the zones in that range will become empty after the offlining,
175886b27beaSOscar Salvador 	 * thus we can determine that we need to clear the node from
175986b27beaSOscar Salvador 	 * node_states[N_NORMAL_MEMORY].
176086b27beaSOscar Salvador 	 */
176186b27beaSOscar Salvador 	for (zt = 0; zt <= ZONE_NORMAL; zt++)
176286b27beaSOscar Salvador 		present_pages += pgdat->node_zones[zt].present_pages;
176386b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
176486b27beaSOscar Salvador 		arg->status_change_nid_normal = zone_to_nid(zone);
1765d9713679SLai Jiangshan 
17666715ddf9SLai Jiangshan 	/*
17676b740c6cSDavid Hildenbrand 	 * We have accounted the pages from [0..ZONE_NORMAL); ZONE_HIGHMEM
17686b740c6cSDavid Hildenbrand 	 * does not apply as we don't support 32bit.
176986b27beaSOscar Salvador 	 * Here we count the possible pages from ZONE_MOVABLE.
177086b27beaSOscar Salvador 	 * If after having accounted all the pages, we see that the nr_pages
177186b27beaSOscar Salvador 	 * to be offlined is over or equal to the accounted pages,
177286b27beaSOscar Salvador 	 * we know that the node will become empty, and so, we can clear
177386b27beaSOscar Salvador 	 * it for N_MEMORY as well.
1774d9713679SLai Jiangshan 	 */
177586b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1776d9713679SLai Jiangshan 
1777d9713679SLai Jiangshan 	if (nr_pages >= present_pages)
1778d9713679SLai Jiangshan 		arg->status_change_nid = zone_to_nid(zone);
1779d9713679SLai Jiangshan }
1780d9713679SLai Jiangshan 
1781d9713679SLai Jiangshan static void node_states_clear_node(int node, struct memory_notify *arg)
1782d9713679SLai Jiangshan {
1783d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
1784d9713679SLai Jiangshan 		node_clear_state(node, N_NORMAL_MEMORY);
1785d9713679SLai Jiangshan 
1786cf01f6f5SOscar Salvador 	if (arg->status_change_nid >= 0)
17876715ddf9SLai Jiangshan 		node_clear_state(node, N_MEMORY);
1788d9713679SLai Jiangshan }
1789d9713679SLai Jiangshan 
1790c5e79ef5SDavid Hildenbrand static int count_system_ram_pages_cb(unsigned long start_pfn,
1791c5e79ef5SDavid Hildenbrand 				     unsigned long nr_pages, void *data)
1792c5e79ef5SDavid Hildenbrand {
1793c5e79ef5SDavid Hildenbrand 	unsigned long *nr_system_ram_pages = data;
1794c5e79ef5SDavid Hildenbrand 
1795c5e79ef5SDavid Hildenbrand 	*nr_system_ram_pages += nr_pages;
1796c5e79ef5SDavid Hildenbrand 	return 0;
1797c5e79ef5SDavid Hildenbrand }
1798c5e79ef5SDavid Hildenbrand 
1799836809ecSDavid Hildenbrand int __ref offline_pages(unsigned long start_pfn, unsigned long nr_pages,
1800395f6081SDavid Hildenbrand 			struct zone *zone, struct memory_group *group)
18010c0e6195SKAMEZAWA Hiroyuki {
180273a11c96SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
18030a1a9a00SDavid Hildenbrand 	unsigned long pfn, system_ram_pages = 0;
1804395f6081SDavid Hildenbrand 	const int node = zone_to_nid(zone);
1805d702909fSCody P Schafer 	unsigned long flags;
18067b78d335SYasunori Goto 	struct memory_notify arg;
180779605093SMichal Hocko 	char *reason;
1808395f6081SDavid Hildenbrand 	int ret;
18090c0e6195SKAMEZAWA Hiroyuki 
1810dd8e2f23SOscar Salvador 	/*
1811dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1812041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1813dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1814dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1815dd8e2f23SOscar Salvador 	 * aligned.
1816dd8e2f23SOscar Salvador 	 */
1817ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
1818dd8e2f23SOscar Salvador 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
18194986fac1SDavid Hildenbrand 		return -EINVAL;
18204986fac1SDavid Hildenbrand 
1821381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
1822381eab4aSDavid Hildenbrand 
1823c5e79ef5SDavid Hildenbrand 	/*
1824c5e79ef5SDavid Hildenbrand 	 * Don't allow to offline memory blocks that contain holes.
1825c5e79ef5SDavid Hildenbrand 	 * Consequently, memory blocks with holes can never get onlined
1826c5e79ef5SDavid Hildenbrand 	 * via the hotplug path - online_pages() - as hotplugged memory has
1827c5e79ef5SDavid Hildenbrand 	 * no holes. This way, we e.g., don't have to worry about marking
1828c5e79ef5SDavid Hildenbrand 	 * memory holes PG_reserved, don't need pfn_valid() checks, and can
1829c5e79ef5SDavid Hildenbrand 	 * avoid using walk_system_ram_range() later.
1830c5e79ef5SDavid Hildenbrand 	 */
183173a11c96SDavid Hildenbrand 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1832c5e79ef5SDavid Hildenbrand 			      count_system_ram_pages_cb);
183373a11c96SDavid Hildenbrand 	if (system_ram_pages != nr_pages) {
1834c5e79ef5SDavid Hildenbrand 		ret = -EINVAL;
1835c5e79ef5SDavid Hildenbrand 		reason = "memory holes";
1836c5e79ef5SDavid Hildenbrand 		goto failed_removal;
1837c5e79ef5SDavid Hildenbrand 	}
1838c5e79ef5SDavid Hildenbrand 
1839395f6081SDavid Hildenbrand 	/*
1840395f6081SDavid Hildenbrand 	 * We only support offlining of memory blocks managed by a single zone,
1841395f6081SDavid Hildenbrand 	 * checked by calling code. This is just a sanity check that we might
1842395f6081SDavid Hildenbrand 	 * want to remove in the future.
1843395f6081SDavid Hildenbrand 	 */
1844395f6081SDavid Hildenbrand 	if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
1845395f6081SDavid Hildenbrand 			 page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
184679605093SMichal Hocko 		ret = -EINVAL;
184779605093SMichal Hocko 		reason = "multizone range";
184879605093SMichal Hocko 		goto failed_removal;
1849381eab4aSDavid Hildenbrand 	}
18507b78d335SYasunori Goto 
1851ec6e8c7eSVlastimil Babka 	/*
1852ec6e8c7eSVlastimil Babka 	 * Disable pcplists so that page isolation cannot race with freeing
1853ec6e8c7eSVlastimil Babka 	 * in a way that pages from isolated pageblock are left on pcplists.
1854ec6e8c7eSVlastimil Babka 	 */
1855ec6e8c7eSVlastimil Babka 	zone_pcp_disable(zone);
1856d479960eSMinchan Kim 	lru_cache_disable();
1857ec6e8c7eSVlastimil Babka 
18580c0e6195SKAMEZAWA Hiroyuki 	/* set above range as isolated */
1859b023f468SWen Congyang 	ret = start_isolate_page_range(start_pfn, end_pfn,
1860d381c547SMichal Hocko 				       MIGRATE_MOVABLE,
1861b2c9e2fbSZi Yan 				       MEMORY_OFFLINE | REPORT_FAILURE,
1862b2c9e2fbSZi Yan 				       GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL);
18633fa0c7c7SDavid Hildenbrand 	if (ret) {
186479605093SMichal Hocko 		reason = "failure to isolate range";
1865ec6e8c7eSVlastimil Babka 		goto failed_removal_pcplists_disabled;
1866381eab4aSDavid Hildenbrand 	}
18677b78d335SYasunori Goto 
18687b78d335SYasunori Goto 	arg.start_pfn = start_pfn;
18697b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1870d9713679SLai Jiangshan 	node_states_check_changes_offline(nr_pages, zone, &arg);
18717b78d335SYasunori Goto 
18727b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_OFFLINE, &arg);
18737b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
187479605093SMichal Hocko 	if (ret) {
187579605093SMichal Hocko 		reason = "notifier failure";
187679605093SMichal Hocko 		goto failed_removal_isolated;
187779605093SMichal Hocko 	}
18787b78d335SYasunori Goto 
1879bb8965bdSMichal Hocko 	do {
1880aa218795SDavid Hildenbrand 		pfn = start_pfn;
1881aa218795SDavid Hildenbrand 		do {
188279605093SMichal Hocko 			if (signal_pending(current)) {
1883bb8965bdSMichal Hocko 				ret = -EINTR;
188479605093SMichal Hocko 				reason = "signal backoff";
188579605093SMichal Hocko 				goto failed_removal_isolated;
188679605093SMichal Hocko 			}
188772b39cfcSMichal Hocko 
18880c0e6195SKAMEZAWA Hiroyuki 			cond_resched();
18890c0e6195SKAMEZAWA Hiroyuki 
1890aa218795SDavid Hildenbrand 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
1891aa218795SDavid Hildenbrand 			if (!ret) {
1892bb8965bdSMichal Hocko 				/*
1893bb8965bdSMichal Hocko 				 * TODO: fatal migration failures should bail
1894bb8965bdSMichal Hocko 				 * out
1895bb8965bdSMichal Hocko 				 */
1896bb8965bdSMichal Hocko 				do_migrate_range(pfn, end_pfn);
1897bb8965bdSMichal Hocko 			}
1898aa218795SDavid Hildenbrand 		} while (!ret);
1899aa218795SDavid Hildenbrand 
1900aa218795SDavid Hildenbrand 		if (ret != -ENOENT) {
1901aa218795SDavid Hildenbrand 			reason = "unmovable page";
1902aa218795SDavid Hildenbrand 			goto failed_removal_isolated;
19030c0e6195SKAMEZAWA Hiroyuki 		}
190472b39cfcSMichal Hocko 
1905c8721bbbSNaoya Horiguchi 		/*
1906bb8965bdSMichal Hocko 		 * Dissolve free hugepages in the memory block before doing
1907bb8965bdSMichal Hocko 		 * offlining actually in order to make hugetlbfs's object
1908bb8965bdSMichal Hocko 		 * counting consistent.
1909c8721bbbSNaoya Horiguchi 		 */
1910082d5b6bSGerald Schaefer 		ret = dissolve_free_huge_pages(start_pfn, end_pfn);
191179605093SMichal Hocko 		if (ret) {
191279605093SMichal Hocko 			reason = "failure to dissolve huge pages";
191379605093SMichal Hocko 			goto failed_removal_isolated;
191479605093SMichal Hocko 		}
19150a1a9a00SDavid Hildenbrand 
19160a1a9a00SDavid Hildenbrand 		ret = test_pages_isolated(start_pfn, end_pfn, MEMORY_OFFLINE);
1917ec6e8c7eSVlastimil Babka 
19185557c766SMichal Hocko 	} while (ret);
1919bb8965bdSMichal Hocko 
19200a1a9a00SDavid Hildenbrand 	/* Mark all sections offline and remove free pages from the buddy. */
19210a1a9a00SDavid Hildenbrand 	__offline_isolated_pages(start_pfn, end_pfn);
19227c33023aSLaurent Dufour 	pr_debug("Offlined Pages %ld\n", nr_pages);
19230a1a9a00SDavid Hildenbrand 
19249b7ea46aSQian Cai 	/*
1925b30c5927SDavid Hildenbrand 	 * The memory sections are marked offline, and the pageblock flags
1926b30c5927SDavid Hildenbrand 	 * effectively stale; nobody should be touching them. Fixup the number
1927b30c5927SDavid Hildenbrand 	 * of isolated pageblocks, memory onlining will properly revert this.
19289b7ea46aSQian Cai 	 */
19299b7ea46aSQian Cai 	spin_lock_irqsave(&zone->lock, flags);
1930ea15153cSDavid Hildenbrand 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
19319b7ea46aSQian Cai 	spin_unlock_irqrestore(&zone->lock, flags);
19329b7ea46aSQian Cai 
1933d479960eSMinchan Kim 	lru_cache_enable();
1934ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
1935ec6e8c7eSVlastimil Babka 
19360c0e6195SKAMEZAWA Hiroyuki 	/* removal success */
19370a1a9a00SDavid Hildenbrand 	adjust_managed_page_count(pfn_to_page(start_pfn), -nr_pages);
1938836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
19397b78d335SYasunori Goto 
1940b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
19411b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
19421b79acc9SKOSAKI Motohiro 
19431e8537baSXishi Qiu 	if (!populated_zone(zone)) {
1944340175b7SJiang Liu 		zone_pcp_reset(zone);
194572675e13SMichal Hocko 		build_all_zonelists(NULL);
1946b92ca18eSMel Gorman 	}
1947340175b7SJiang Liu 
1948d9713679SLai Jiangshan 	node_states_clear_node(node, &arg);
1949698b1b30SVlastimil Babka 	if (arg.status_change_nid >= 0) {
1950698b1b30SVlastimil Babka 		kcompactd_stop(node);
1951b4a0215eSKefeng Wang 		kswapd_stop(node);
1952698b1b30SVlastimil Babka 	}
1953bce7394aSMinchan Kim 
19540c0e6195SKAMEZAWA Hiroyuki 	writeback_set_ratelimit();
19557b78d335SYasunori Goto 
19567b78d335SYasunori Goto 	memory_notify(MEM_OFFLINE, &arg);
1957feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
1958381eab4aSDavid Hildenbrand 	mem_hotplug_done();
19590c0e6195SKAMEZAWA Hiroyuki 	return 0;
19600c0e6195SKAMEZAWA Hiroyuki 
196179605093SMichal Hocko failed_removal_isolated:
196236ba30bcSMiaohe Lin 	/* pushback to free area */
196379605093SMichal Hocko 	undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1964c4efe484SQian Cai 	memory_notify(MEM_CANCEL_OFFLINE, &arg);
1965ec6e8c7eSVlastimil Babka failed_removal_pcplists_disabled:
1966946746d1SMiaohe Lin 	lru_cache_enable();
1967ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
19680c0e6195SKAMEZAWA Hiroyuki failed_removal:
196979605093SMichal Hocko 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
1970a62e2f4fSBjorn Helgaas 		 (unsigned long long) start_pfn << PAGE_SHIFT,
197179605093SMichal Hocko 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
197279605093SMichal Hocko 		 reason);
1973381eab4aSDavid Hildenbrand 	mem_hotplug_done();
19740c0e6195SKAMEZAWA Hiroyuki 	return ret;
19750c0e6195SKAMEZAWA Hiroyuki }
197671088785SBadari Pulavarty 
1977d6de9d53SXishi Qiu static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
1978bbc76be6SWen Congyang {
1979e1c158e4SDavid Hildenbrand 	int *nid = arg;
1980bbc76be6SWen Congyang 
1981e1c158e4SDavid Hildenbrand 	*nid = mem->nid;
1982639118d1SKefeng Wang 	if (unlikely(mem->state != MEM_OFFLINE)) {
1983349daa0fSRandy Dunlap 		phys_addr_t beginpa, endpa;
1984349daa0fSRandy Dunlap 
1985349daa0fSRandy Dunlap 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
1986b6c88d3bSDavid Hildenbrand 		endpa = beginpa + memory_block_size_bytes() - 1;
1987756a025fSJoe Perches 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
1988349daa0fSRandy Dunlap 			&beginpa, &endpa);
1989bbc76be6SWen Congyang 
1990eca499abSPavel Tatashin 		return -EBUSY;
1991eca499abSPavel Tatashin 	}
1992eca499abSPavel Tatashin 	return 0;
1993bbc76be6SWen Congyang }
1994bbc76be6SWen Congyang 
1995a08a2ae3SOscar Salvador static int get_nr_vmemmap_pages_cb(struct memory_block *mem, void *arg)
1996a08a2ae3SOscar Salvador {
1997a08a2ae3SOscar Salvador 	/*
1998a08a2ae3SOscar Salvador 	 * If not set, continue with the next block.
1999a08a2ae3SOscar Salvador 	 */
2000a08a2ae3SOscar Salvador 	return mem->nr_vmemmap_pages;
2001a08a2ae3SOscar Salvador }
2002a08a2ae3SOscar Salvador 
2003b27340a5SMiaohe Lin static int check_cpu_on_node(int nid)
200460a5a19eSTang Chen {
200560a5a19eSTang Chen 	int cpu;
200660a5a19eSTang Chen 
200760a5a19eSTang Chen 	for_each_present_cpu(cpu) {
2008b27340a5SMiaohe Lin 		if (cpu_to_node(cpu) == nid)
200960a5a19eSTang Chen 			/*
201060a5a19eSTang Chen 			 * the cpu on this node isn't removed, and we can't
201160a5a19eSTang Chen 			 * offline this node.
201260a5a19eSTang Chen 			 */
201360a5a19eSTang Chen 			return -EBUSY;
201460a5a19eSTang Chen 	}
201560a5a19eSTang Chen 
201660a5a19eSTang Chen 	return 0;
201760a5a19eSTang Chen }
201860a5a19eSTang Chen 
20192c91f8fcSDavid Hildenbrand static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
20202c91f8fcSDavid Hildenbrand {
20212c91f8fcSDavid Hildenbrand 	int nid = *(int *)arg;
20222c91f8fcSDavid Hildenbrand 
20232c91f8fcSDavid Hildenbrand 	/*
20242c91f8fcSDavid Hildenbrand 	 * If a memory block belongs to multiple nodes, the stored nid is not
20252c91f8fcSDavid Hildenbrand 	 * reliable. However, such blocks are always online (e.g., cannot get
20262c91f8fcSDavid Hildenbrand 	 * offlined) and, therefore, are still spanned by the node.
20272c91f8fcSDavid Hildenbrand 	 */
20282c91f8fcSDavid Hildenbrand 	return mem->nid == nid ? -EEXIST : 0;
20292c91f8fcSDavid Hildenbrand }
20302c91f8fcSDavid Hildenbrand 
20310f1cfe9dSToshi Kani /**
20320f1cfe9dSToshi Kani  * try_offline_node
2033e8b098fcSMike Rapoport  * @nid: the node ID
20340f1cfe9dSToshi Kani  *
20350f1cfe9dSToshi Kani  * Offline a node if all memory sections and cpus of the node are removed.
20360f1cfe9dSToshi Kani  *
20370f1cfe9dSToshi Kani  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
20380f1cfe9dSToshi Kani  * and online/offline operations before this call.
20390f1cfe9dSToshi Kani  */
204090b30cdcSWen Congyang void try_offline_node(int nid)
204160a5a19eSTang Chen {
20422c91f8fcSDavid Hildenbrand 	int rc;
204360a5a19eSTang Chen 
204460a5a19eSTang Chen 	/*
20452c91f8fcSDavid Hildenbrand 	 * If the node still spans pages (especially ZONE_DEVICE), don't
20462c91f8fcSDavid Hildenbrand 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
20472c91f8fcSDavid Hildenbrand 	 * e.g., after the memory block was onlined.
204860a5a19eSTang Chen 	 */
2049b27340a5SMiaohe Lin 	if (node_spanned_pages(nid))
205060a5a19eSTang Chen 		return;
20512c91f8fcSDavid Hildenbrand 
20522c91f8fcSDavid Hildenbrand 	/*
20532c91f8fcSDavid Hildenbrand 	 * Especially offline memory blocks might not be spanned by the
20542c91f8fcSDavid Hildenbrand 	 * node. They will get spanned by the node once they get onlined.
20552c91f8fcSDavid Hildenbrand 	 * However, they link to the node in sysfs and can get onlined later.
20562c91f8fcSDavid Hildenbrand 	 */
20572c91f8fcSDavid Hildenbrand 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
20582c91f8fcSDavid Hildenbrand 	if (rc)
20592c91f8fcSDavid Hildenbrand 		return;
206060a5a19eSTang Chen 
2061b27340a5SMiaohe Lin 	if (check_cpu_on_node(nid))
206260a5a19eSTang Chen 		return;
206360a5a19eSTang Chen 
206460a5a19eSTang Chen 	/*
206560a5a19eSTang Chen 	 * all memory/cpu of this node are removed, we can offline this
206660a5a19eSTang Chen 	 * node now.
206760a5a19eSTang Chen 	 */
206860a5a19eSTang Chen 	node_set_offline(nid);
206960a5a19eSTang Chen 	unregister_one_node(nid);
207060a5a19eSTang Chen }
207190b30cdcSWen Congyang EXPORT_SYMBOL(try_offline_node);
207260a5a19eSTang Chen 
2073e1c158e4SDavid Hildenbrand static int __ref try_remove_memory(u64 start, u64 size)
2074bbc76be6SWen Congyang {
2075a08a2ae3SOscar Salvador 	struct vmem_altmap mhp_altmap = {};
2076a08a2ae3SOscar Salvador 	struct vmem_altmap *altmap = NULL;
2077a08a2ae3SOscar Salvador 	unsigned long nr_vmemmap_pages;
2078e1c158e4SDavid Hildenbrand 	int rc = 0, nid = NUMA_NO_NODE;
2079993c1aadSWen Congyang 
208027356f54SToshi Kani 	BUG_ON(check_hotplug_memory_range(start, size));
208127356f54SToshi Kani 
20826677e3eaSYasuaki Ishimatsu 	/*
2083242831ebSRafael J. Wysocki 	 * All memory blocks must be offlined before removing memory.  Check
2084eca499abSPavel Tatashin 	 * whether all memory blocks in question are offline and return error
2085242831ebSRafael J. Wysocki 	 * if this is not the case.
2086e1c158e4SDavid Hildenbrand 	 *
2087e1c158e4SDavid Hildenbrand 	 * While at it, determine the nid. Note that if we'd have mixed nodes,
2088e1c158e4SDavid Hildenbrand 	 * we'd only try to offline the last determined one -- which is good
2089e1c158e4SDavid Hildenbrand 	 * enough for the cases we care about.
20906677e3eaSYasuaki Ishimatsu 	 */
2091e1c158e4SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
2092eca499abSPavel Tatashin 	if (rc)
2093b4223a51SJia He 		return rc;
20946677e3eaSYasuaki Ishimatsu 
2095a08a2ae3SOscar Salvador 	/*
2096a08a2ae3SOscar Salvador 	 * We only support removing memory added with MHP_MEMMAP_ON_MEMORY in
2097a08a2ae3SOscar Salvador 	 * the same granularity it was added - a single memory block.
2098a08a2ae3SOscar Salvador 	 */
20996e02c46bSMuchun Song 	if (mhp_memmap_on_memory()) {
2100a08a2ae3SOscar Salvador 		nr_vmemmap_pages = walk_memory_blocks(start, size, NULL,
2101a08a2ae3SOscar Salvador 						      get_nr_vmemmap_pages_cb);
2102a08a2ae3SOscar Salvador 		if (nr_vmemmap_pages) {
2103a08a2ae3SOscar Salvador 			if (size != memory_block_size_bytes()) {
2104a08a2ae3SOscar Salvador 				pr_warn("Refuse to remove %#llx - %#llx,"
2105a08a2ae3SOscar Salvador 					"wrong granularity\n",
2106a08a2ae3SOscar Salvador 					start, start + size);
2107a08a2ae3SOscar Salvador 				return -EINVAL;
2108a08a2ae3SOscar Salvador 			}
2109a08a2ae3SOscar Salvador 
2110a08a2ae3SOscar Salvador 			/*
2111a08a2ae3SOscar Salvador 			 * Let remove_pmd_table->free_hugepage_table do the
2112a08a2ae3SOscar Salvador 			 * right thing if we used vmem_altmap when hot-adding
2113a08a2ae3SOscar Salvador 			 * the range.
2114a08a2ae3SOscar Salvador 			 */
2115a08a2ae3SOscar Salvador 			mhp_altmap.alloc = nr_vmemmap_pages;
2116a08a2ae3SOscar Salvador 			altmap = &mhp_altmap;
2117a08a2ae3SOscar Salvador 		}
2118a08a2ae3SOscar Salvador 	}
2119a08a2ae3SOscar Salvador 
212046c66c4bSYasuaki Ishimatsu 	/* remove memmap entry */
212146c66c4bSYasuaki Ishimatsu 	firmware_map_remove(start, start + size, "System RAM");
212246c66c4bSYasuaki Ishimatsu 
2123f1037ec0SDan Williams 	/*
2124f1037ec0SDan Williams 	 * Memory block device removal under the device_hotplug_lock is
2125f1037ec0SDan Williams 	 * a barrier against racing online attempts.
2126f1037ec0SDan Williams 	 */
21274c4b7f9bSDavid Hildenbrand 	remove_memory_block_devices(start, size);
21284c4b7f9bSDavid Hildenbrand 
2129f1037ec0SDan Williams 	mem_hotplug_begin();
2130f1037ec0SDan Williams 
213165a2aa5fSDavid Hildenbrand 	arch_remove_memory(start, size, altmap);
213252219aeaSDavid Hildenbrand 
213352219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
21343ecc6834SMike Rapoport 		memblock_phys_free(start, size);
213532d1fe8fSAnshuman Khandual 		memblock_remove(start, size);
213652219aeaSDavid Hildenbrand 	}
213752219aeaSDavid Hildenbrand 
2138cb8e3c8bSDavid Hildenbrand 	release_mem_region_adjustable(start, size);
213924d335caSWen Congyang 
2140e1c158e4SDavid Hildenbrand 	if (nid != NUMA_NO_NODE)
214160a5a19eSTang Chen 		try_offline_node(nid);
214260a5a19eSTang Chen 
2143bfc8c901SVladimir Davydov 	mem_hotplug_done();
2144b4223a51SJia He 	return 0;
214571088785SBadari Pulavarty }
2146d15e5926SDavid Hildenbrand 
2147eca499abSPavel Tatashin /**
21485640c9caSMel Gorman  * __remove_memory - Remove memory if every memory block is offline
2149eca499abSPavel Tatashin  * @start: physical address of the region to remove
2150eca499abSPavel Tatashin  * @size: size of the region to remove
2151eca499abSPavel Tatashin  *
2152eca499abSPavel Tatashin  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2153eca499abSPavel Tatashin  * and online/offline operations before this call, as required by
2154eca499abSPavel Tatashin  * try_offline_node().
2155eca499abSPavel Tatashin  */
2156e1c158e4SDavid Hildenbrand void __remove_memory(u64 start, u64 size)
2157d15e5926SDavid Hildenbrand {
2158eca499abSPavel Tatashin 
2159eca499abSPavel Tatashin 	/*
216029a90db9SSouptick Joarder 	 * trigger BUG() if some memory is not offlined prior to calling this
2161eca499abSPavel Tatashin 	 * function
2162eca499abSPavel Tatashin 	 */
2163e1c158e4SDavid Hildenbrand 	if (try_remove_memory(start, size))
2164eca499abSPavel Tatashin 		BUG();
2165eca499abSPavel Tatashin }
2166eca499abSPavel Tatashin 
2167eca499abSPavel Tatashin /*
2168eca499abSPavel Tatashin  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2169eca499abSPavel Tatashin  * some memory is not offline
2170eca499abSPavel Tatashin  */
2171e1c158e4SDavid Hildenbrand int remove_memory(u64 start, u64 size)
2172eca499abSPavel Tatashin {
2173eca499abSPavel Tatashin 	int rc;
2174eca499abSPavel Tatashin 
2175d15e5926SDavid Hildenbrand 	lock_device_hotplug();
2176e1c158e4SDavid Hildenbrand 	rc = try_remove_memory(start, size);
2177d15e5926SDavid Hildenbrand 	unlock_device_hotplug();
2178eca499abSPavel Tatashin 
2179eca499abSPavel Tatashin 	return rc;
2180d15e5926SDavid Hildenbrand }
218171088785SBadari Pulavarty EXPORT_SYMBOL_GPL(remove_memory);
218208b3acd7SDavid Hildenbrand 
21838dc4bb58SDavid Hildenbrand static int try_offline_memory_block(struct memory_block *mem, void *arg)
21848dc4bb58SDavid Hildenbrand {
21858dc4bb58SDavid Hildenbrand 	uint8_t online_type = MMOP_ONLINE_KERNEL;
21868dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
21878dc4bb58SDavid Hildenbrand 	struct page *page;
21888dc4bb58SDavid Hildenbrand 	int rc;
21898dc4bb58SDavid Hildenbrand 
219008b3acd7SDavid Hildenbrand 	/*
21918dc4bb58SDavid Hildenbrand 	 * Sense the online_type via the zone of the memory block. Offlining
21928dc4bb58SDavid Hildenbrand 	 * with multiple zones within one memory block will be rejected
21938dc4bb58SDavid Hildenbrand 	 * by offlining code ... so we don't care about that.
21948dc4bb58SDavid Hildenbrand 	 */
21958dc4bb58SDavid Hildenbrand 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
21968dc4bb58SDavid Hildenbrand 	if (page && zone_idx(page_zone(page)) == ZONE_MOVABLE)
21978dc4bb58SDavid Hildenbrand 		online_type = MMOP_ONLINE_MOVABLE;
21988dc4bb58SDavid Hildenbrand 
21998dc4bb58SDavid Hildenbrand 	rc = device_offline(&mem->dev);
22008dc4bb58SDavid Hildenbrand 	/*
22018dc4bb58SDavid Hildenbrand 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
22028dc4bb58SDavid Hildenbrand 	 * so try_reonline_memory_block() can do the right thing.
22038dc4bb58SDavid Hildenbrand 	 */
22048dc4bb58SDavid Hildenbrand 	if (!rc)
22058dc4bb58SDavid Hildenbrand 		**online_types = online_type;
22068dc4bb58SDavid Hildenbrand 
22078dc4bb58SDavid Hildenbrand 	(*online_types)++;
22088dc4bb58SDavid Hildenbrand 	/* Ignore if already offline. */
22098dc4bb58SDavid Hildenbrand 	return rc < 0 ? rc : 0;
22108dc4bb58SDavid Hildenbrand }
22118dc4bb58SDavid Hildenbrand 
22128dc4bb58SDavid Hildenbrand static int try_reonline_memory_block(struct memory_block *mem, void *arg)
22138dc4bb58SDavid Hildenbrand {
22148dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
22158dc4bb58SDavid Hildenbrand 	int rc;
22168dc4bb58SDavid Hildenbrand 
22178dc4bb58SDavid Hildenbrand 	if (**online_types != MMOP_OFFLINE) {
22188dc4bb58SDavid Hildenbrand 		mem->online_type = **online_types;
22198dc4bb58SDavid Hildenbrand 		rc = device_online(&mem->dev);
22208dc4bb58SDavid Hildenbrand 		if (rc < 0)
22218dc4bb58SDavid Hildenbrand 			pr_warn("%s: Failed to re-online memory: %d",
22228dc4bb58SDavid Hildenbrand 				__func__, rc);
22238dc4bb58SDavid Hildenbrand 	}
22248dc4bb58SDavid Hildenbrand 
22258dc4bb58SDavid Hildenbrand 	/* Continue processing all remaining memory blocks. */
22268dc4bb58SDavid Hildenbrand 	(*online_types)++;
22278dc4bb58SDavid Hildenbrand 	return 0;
22288dc4bb58SDavid Hildenbrand }
22298dc4bb58SDavid Hildenbrand 
22308dc4bb58SDavid Hildenbrand /*
22318dc4bb58SDavid Hildenbrand  * Try to offline and remove memory. Might take a long time to finish in case
22328dc4bb58SDavid Hildenbrand  * memory is still in use. Primarily useful for memory devices that logically
22338dc4bb58SDavid Hildenbrand  * unplugged all memory (so it's no longer in use) and want to offline + remove
22348dc4bb58SDavid Hildenbrand  * that memory.
223508b3acd7SDavid Hildenbrand  */
2236e1c158e4SDavid Hildenbrand int offline_and_remove_memory(u64 start, u64 size)
223708b3acd7SDavid Hildenbrand {
22388dc4bb58SDavid Hildenbrand 	const unsigned long mb_count = size / memory_block_size_bytes();
22398dc4bb58SDavid Hildenbrand 	uint8_t *online_types, *tmp;
22408dc4bb58SDavid Hildenbrand 	int rc;
224108b3acd7SDavid Hildenbrand 
224208b3acd7SDavid Hildenbrand 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
22438dc4bb58SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
22448dc4bb58SDavid Hildenbrand 		return -EINVAL;
224508b3acd7SDavid Hildenbrand 
224608b3acd7SDavid Hildenbrand 	/*
22478dc4bb58SDavid Hildenbrand 	 * We'll remember the old online type of each memory block, so we can
22488dc4bb58SDavid Hildenbrand 	 * try to revert whatever we did when offlining one memory block fails
22498dc4bb58SDavid Hildenbrand 	 * after offlining some others succeeded.
22508dc4bb58SDavid Hildenbrand 	 */
22518dc4bb58SDavid Hildenbrand 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
22528dc4bb58SDavid Hildenbrand 				     GFP_KERNEL);
22538dc4bb58SDavid Hildenbrand 	if (!online_types)
22548dc4bb58SDavid Hildenbrand 		return -ENOMEM;
22558dc4bb58SDavid Hildenbrand 	/*
22568dc4bb58SDavid Hildenbrand 	 * Initialize all states to MMOP_OFFLINE, so when we abort processing in
22578dc4bb58SDavid Hildenbrand 	 * try_offline_memory_block(), we'll skip all unprocessed blocks in
22588dc4bb58SDavid Hildenbrand 	 * try_reonline_memory_block().
22598dc4bb58SDavid Hildenbrand 	 */
22608dc4bb58SDavid Hildenbrand 	memset(online_types, MMOP_OFFLINE, mb_count);
22618dc4bb58SDavid Hildenbrand 
22628dc4bb58SDavid Hildenbrand 	lock_device_hotplug();
22638dc4bb58SDavid Hildenbrand 
22648dc4bb58SDavid Hildenbrand 	tmp = online_types;
22658dc4bb58SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
22668dc4bb58SDavid Hildenbrand 
22678dc4bb58SDavid Hildenbrand 	/*
22688dc4bb58SDavid Hildenbrand 	 * In case we succeeded to offline all memory, remove it.
226908b3acd7SDavid Hildenbrand 	 * This cannot fail as it cannot get onlined in the meantime.
227008b3acd7SDavid Hildenbrand 	 */
227108b3acd7SDavid Hildenbrand 	if (!rc) {
2272e1c158e4SDavid Hildenbrand 		rc = try_remove_memory(start, size);
22738dc4bb58SDavid Hildenbrand 		if (rc)
22748dc4bb58SDavid Hildenbrand 			pr_err("%s: Failed to remove memory: %d", __func__, rc);
22758dc4bb58SDavid Hildenbrand 	}
22768dc4bb58SDavid Hildenbrand 
22778dc4bb58SDavid Hildenbrand 	/*
22788dc4bb58SDavid Hildenbrand 	 * Rollback what we did. While memory onlining might theoretically fail
22798dc4bb58SDavid Hildenbrand 	 * (nacked by a notifier), it barely ever happens.
22808dc4bb58SDavid Hildenbrand 	 */
22818dc4bb58SDavid Hildenbrand 	if (rc) {
22828dc4bb58SDavid Hildenbrand 		tmp = online_types;
22838dc4bb58SDavid Hildenbrand 		walk_memory_blocks(start, size, &tmp,
22848dc4bb58SDavid Hildenbrand 				   try_reonline_memory_block);
228508b3acd7SDavid Hildenbrand 	}
228608b3acd7SDavid Hildenbrand 	unlock_device_hotplug();
228708b3acd7SDavid Hildenbrand 
22888dc4bb58SDavid Hildenbrand 	kfree(online_types);
228908b3acd7SDavid Hildenbrand 	return rc;
229008b3acd7SDavid Hildenbrand }
229108b3acd7SDavid Hildenbrand EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2292aba6efc4SRafael J. Wysocki #endif /* CONFIG_MEMORY_HOTREMOVE */
2293