xref: /openbmc/linux/mm/memory_hotplug.c (revision e0270ffad4266736ac2d2caa8c9a9ab091292c52)
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>
162d1d43f6SChandra Seetharaman #include <linux/writeback.h>
173947be19SDave Hansen #include <linux/slab.h>
183947be19SDave Hansen #include <linux/sysctl.h>
193947be19SDave Hansen #include <linux/cpu.h>
203947be19SDave Hansen #include <linux/memory.h>
214b94ffdcSDan Williams #include <linux/memremap.h>
223947be19SDave Hansen #include <linux/memory_hotplug.h>
233947be19SDave Hansen #include <linux/vmalloc.h>
240a547039SKAMEZAWA Hiroyuki #include <linux/ioport.h>
250c0e6195SKAMEZAWA Hiroyuki #include <linux/delay.h>
260c0e6195SKAMEZAWA Hiroyuki #include <linux/migrate.h>
270c0e6195SKAMEZAWA Hiroyuki #include <linux/page-isolation.h>
2871088785SBadari Pulavarty #include <linux/pfn.h>
296ad696d2SAndi Kleen #include <linux/suspend.h>
306d9c285aSKOSAKI Motohiro #include <linux/mm_inline.h>
31d96ae530Sakpm@linux-foundation.org #include <linux/firmware-map.h>
3260a5a19eSTang Chen #include <linux/stop_machine.h>
33c8721bbbSNaoya Horiguchi #include <linux/hugetlb.h>
34c5320926STang Chen #include <linux/memblock.h>
35698b1b30SVlastimil Babka #include <linux/compaction.h>
36b15c8726SMichal Hocko #include <linux/rmap.h>
378581fd40SJakub Kicinski #include <linux/module.h>
383947be19SDave Hansen 
393947be19SDave Hansen #include <asm/tlbflush.h>
403947be19SDave Hansen 
411e5ad9a3SAdrian Bunk #include "internal.h"
42e900a918SDan Williams #include "shuffle.h"
431e5ad9a3SAdrian Bunk 
442d1f649cSAneesh Kumar K.V enum {
452d1f649cSAneesh Kumar K.V 	MEMMAP_ON_MEMORY_DISABLE = 0,
462d1f649cSAneesh Kumar K.V 	MEMMAP_ON_MEMORY_ENABLE,
472d1f649cSAneesh Kumar K.V 	MEMMAP_ON_MEMORY_FORCE,
482d1f649cSAneesh Kumar K.V };
492d1f649cSAneesh Kumar K.V 
502d1f649cSAneesh Kumar K.V static int memmap_mode __read_mostly = MEMMAP_ON_MEMORY_DISABLE;
512d1f649cSAneesh Kumar K.V 
522d1f649cSAneesh Kumar K.V static inline unsigned long memory_block_memmap_size(void)
532d1f649cSAneesh Kumar K.V {
542d1f649cSAneesh Kumar K.V 	return PHYS_PFN(memory_block_size_bytes()) * sizeof(struct page);
552d1f649cSAneesh Kumar K.V }
562d1f649cSAneesh Kumar K.V 
572d1f649cSAneesh Kumar K.V static inline unsigned long memory_block_memmap_on_memory_pages(void)
582d1f649cSAneesh Kumar K.V {
592d1f649cSAneesh Kumar K.V 	unsigned long nr_pages = PFN_UP(memory_block_memmap_size());
602d1f649cSAneesh Kumar K.V 
612d1f649cSAneesh Kumar K.V 	/*
622d1f649cSAneesh Kumar K.V 	 * In "forced" memmap_on_memory mode, we add extra pages to align the
632d1f649cSAneesh Kumar K.V 	 * vmemmap size to cover full pageblocks. That way, we can add memory
642d1f649cSAneesh Kumar K.V 	 * even if the vmemmap size is not properly aligned, however, we might waste
652d1f649cSAneesh Kumar K.V 	 * memory.
662d1f649cSAneesh Kumar K.V 	 */
672d1f649cSAneesh Kumar K.V 	if (memmap_mode == MEMMAP_ON_MEMORY_FORCE)
682d1f649cSAneesh Kumar K.V 		return pageblock_align(nr_pages);
692d1f649cSAneesh Kumar K.V 	return nr_pages;
702d1f649cSAneesh Kumar K.V }
712d1f649cSAneesh Kumar K.V 
726e02c46bSMuchun Song #ifdef CONFIG_MHP_MEMMAP_ON_MEMORY
73e3a9d9fcSOscar Salvador /*
74e3a9d9fcSOscar Salvador  * memory_hotplug.memmap_on_memory parameter
75e3a9d9fcSOscar Salvador  */
762d1f649cSAneesh Kumar K.V static int set_memmap_mode(const char *val, const struct kernel_param *kp)
772d1f649cSAneesh Kumar K.V {
782d1f649cSAneesh Kumar K.V 	int ret, mode;
792d1f649cSAneesh Kumar K.V 	bool enabled;
802d1f649cSAneesh Kumar K.V 
812d1f649cSAneesh Kumar K.V 	if (sysfs_streq(val, "force") ||  sysfs_streq(val, "FORCE")) {
822d1f649cSAneesh Kumar K.V 		mode = MEMMAP_ON_MEMORY_FORCE;
832d1f649cSAneesh Kumar K.V 	} else {
842d1f649cSAneesh Kumar K.V 		ret = kstrtobool(val, &enabled);
852d1f649cSAneesh Kumar K.V 		if (ret < 0)
862d1f649cSAneesh Kumar K.V 			return ret;
872d1f649cSAneesh Kumar K.V 		if (enabled)
882d1f649cSAneesh Kumar K.V 			mode = MEMMAP_ON_MEMORY_ENABLE;
892d1f649cSAneesh Kumar K.V 		else
902d1f649cSAneesh Kumar K.V 			mode = MEMMAP_ON_MEMORY_DISABLE;
912d1f649cSAneesh Kumar K.V 	}
922d1f649cSAneesh Kumar K.V 	*((int *)kp->arg) = mode;
932d1f649cSAneesh Kumar K.V 	if (mode == MEMMAP_ON_MEMORY_FORCE) {
942d1f649cSAneesh Kumar K.V 		unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
952d1f649cSAneesh Kumar K.V 
962d1f649cSAneesh Kumar K.V 		pr_info_once("Memory hotplug will waste %ld pages in each memory block\n",
972d1f649cSAneesh Kumar K.V 			     memmap_pages - PFN_UP(memory_block_memmap_size()));
982d1f649cSAneesh Kumar K.V 	}
992d1f649cSAneesh Kumar K.V 	return 0;
1002d1f649cSAneesh Kumar K.V }
1012d1f649cSAneesh Kumar K.V 
1022d1f649cSAneesh Kumar K.V static int get_memmap_mode(char *buffer, const struct kernel_param *kp)
1032d1f649cSAneesh Kumar K.V {
1042d1f649cSAneesh Kumar K.V 	if (*((int *)kp->arg) == MEMMAP_ON_MEMORY_FORCE)
1052d1f649cSAneesh Kumar K.V 		return sprintf(buffer,  "force\n");
1062d1f649cSAneesh Kumar K.V 	return param_get_bool(buffer, kp);
1072d1f649cSAneesh Kumar K.V }
1082d1f649cSAneesh Kumar K.V 
1092d1f649cSAneesh Kumar K.V static const struct kernel_param_ops memmap_mode_ops = {
1102d1f649cSAneesh Kumar K.V 	.set = set_memmap_mode,
1112d1f649cSAneesh Kumar K.V 	.get = get_memmap_mode,
1122d1f649cSAneesh Kumar K.V };
1132d1f649cSAneesh Kumar K.V module_param_cb(memmap_on_memory, &memmap_mode_ops, &memmap_mode, 0444);
1142d1f649cSAneesh Kumar K.V MODULE_PARM_DESC(memmap_on_memory, "Enable memmap on memory for memory hotplug\n"
1152d1f649cSAneesh Kumar K.V 		 "With value \"force\" it could result in memory wastage due "
1162d1f649cSAneesh Kumar K.V 		 "to memmap size limitations (Y/N/force)");
1176e02c46bSMuchun Song 
11866361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
1196e02c46bSMuchun Song {
1202d1f649cSAneesh Kumar K.V 	return memmap_mode != MEMMAP_ON_MEMORY_DISABLE;
1216e02c46bSMuchun Song }
12266361095SMuchun Song #else
12366361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
12466361095SMuchun Song {
12566361095SMuchun Song 	return false;
12666361095SMuchun Song }
127e3a9d9fcSOscar Salvador #endif
128a08a2ae3SOscar Salvador 
129e83a437fSDavid Hildenbrand enum {
130e83a437fSDavid Hildenbrand 	ONLINE_POLICY_CONTIG_ZONES = 0,
131e83a437fSDavid Hildenbrand 	ONLINE_POLICY_AUTO_MOVABLE,
132e83a437fSDavid Hildenbrand };
133e83a437fSDavid Hildenbrand 
134ac62554bSTang Yizhou static const char * const online_policy_to_str[] = {
135e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_CONTIG_ZONES] = "contig-zones",
136e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_AUTO_MOVABLE] = "auto-movable",
137e83a437fSDavid Hildenbrand };
138e83a437fSDavid Hildenbrand 
139e83a437fSDavid Hildenbrand static int set_online_policy(const char *val, const struct kernel_param *kp)
140e83a437fSDavid Hildenbrand {
141e83a437fSDavid Hildenbrand 	int ret = sysfs_match_string(online_policy_to_str, val);
142e83a437fSDavid Hildenbrand 
143e83a437fSDavid Hildenbrand 	if (ret < 0)
144e83a437fSDavid Hildenbrand 		return ret;
145e83a437fSDavid Hildenbrand 	*((int *)kp->arg) = ret;
146e83a437fSDavid Hildenbrand 	return 0;
147e83a437fSDavid Hildenbrand }
148e83a437fSDavid Hildenbrand 
149e83a437fSDavid Hildenbrand static int get_online_policy(char *buffer, const struct kernel_param *kp)
150e83a437fSDavid Hildenbrand {
151e83a437fSDavid Hildenbrand 	return sprintf(buffer, "%s\n", online_policy_to_str[*((int *)kp->arg)]);
152e83a437fSDavid Hildenbrand }
153e83a437fSDavid Hildenbrand 
154e83a437fSDavid Hildenbrand /*
155e83a437fSDavid Hildenbrand  * memory_hotplug.online_policy: configure online behavior when onlining without
156e83a437fSDavid Hildenbrand  * specifying a zone (MMOP_ONLINE)
157e83a437fSDavid Hildenbrand  *
158e83a437fSDavid Hildenbrand  * "contig-zones": keep zone contiguous
159e83a437fSDavid Hildenbrand  * "auto-movable": online memory to ZONE_MOVABLE if the configuration
160e83a437fSDavid Hildenbrand  *                 (auto_movable_ratio, auto_movable_numa_aware) allows for it
161e83a437fSDavid Hildenbrand  */
162e83a437fSDavid Hildenbrand static int online_policy __read_mostly = ONLINE_POLICY_CONTIG_ZONES;
163e83a437fSDavid Hildenbrand static const struct kernel_param_ops online_policy_ops = {
164e83a437fSDavid Hildenbrand 	.set = set_online_policy,
165e83a437fSDavid Hildenbrand 	.get = get_online_policy,
166e83a437fSDavid Hildenbrand };
167e83a437fSDavid Hildenbrand module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
168e83a437fSDavid Hildenbrand MODULE_PARM_DESC(online_policy,
169e83a437fSDavid Hildenbrand 		"Set the online policy (\"contig-zones\", \"auto-movable\") "
170e83a437fSDavid Hildenbrand 		"Default: \"contig-zones\"");
171e83a437fSDavid Hildenbrand 
172e83a437fSDavid Hildenbrand /*
173e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio
174e83a437fSDavid Hildenbrand  *
175e83a437fSDavid Hildenbrand  * The ratio represent an upper limit and the kernel might decide to not
176e83a437fSDavid Hildenbrand  * online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory
177e83a437fSDavid Hildenbrand  * doesn't allow for more MOVABLE memory.
178e83a437fSDavid Hildenbrand  */
179e83a437fSDavid Hildenbrand static unsigned int auto_movable_ratio __read_mostly = 301;
180e83a437fSDavid Hildenbrand module_param(auto_movable_ratio, uint, 0644);
181e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_ratio,
182e83a437fSDavid Hildenbrand 		"Set the maximum ratio of MOVABLE:KERNEL memory in the system "
183e83a437fSDavid Hildenbrand 		"in percent for \"auto-movable\" online policy. Default: 301");
184e83a437fSDavid Hildenbrand 
185e83a437fSDavid Hildenbrand /*
186e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_numa_aware: consider numa node stats
187e83a437fSDavid Hildenbrand  */
188e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
189e83a437fSDavid Hildenbrand static bool auto_movable_numa_aware __read_mostly = true;
190e83a437fSDavid Hildenbrand module_param(auto_movable_numa_aware, bool, 0644);
191e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_numa_aware,
192e83a437fSDavid Hildenbrand 		"Consider numa node stats in addition to global stats in "
193e83a437fSDavid Hildenbrand 		"\"auto-movable\" online policy. Default: true");
194e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
195e83a437fSDavid Hildenbrand 
1969d0ad8caSDaniel Kiper /*
1979d0ad8caSDaniel Kiper  * online_page_callback contains pointer to current page onlining function.
1989d0ad8caSDaniel Kiper  * Initially it is generic_online_page(). If it is required it could be
1999d0ad8caSDaniel Kiper  * changed by calling set_online_page_callback() for callback registration
2009d0ad8caSDaniel Kiper  * and restore_online_page_callback() for generic callback restore.
2019d0ad8caSDaniel Kiper  */
2029d0ad8caSDaniel Kiper 
2039d0ad8caSDaniel Kiper static online_page_callback_t online_page_callback = generic_online_page;
204bfc8c901SVladimir Davydov static DEFINE_MUTEX(online_page_callback_lock);
2059d0ad8caSDaniel Kiper 
2063f906ba2SThomas Gleixner DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
20720d6c96bSKOSAKI Motohiro 
2083f906ba2SThomas Gleixner void get_online_mems(void)
2093f906ba2SThomas Gleixner {
2103f906ba2SThomas Gleixner 	percpu_down_read(&mem_hotplug_lock);
2113f906ba2SThomas Gleixner }
212bfc8c901SVladimir Davydov 
2133f906ba2SThomas Gleixner void put_online_mems(void)
2143f906ba2SThomas Gleixner {
2153f906ba2SThomas Gleixner 	percpu_up_read(&mem_hotplug_lock);
2163f906ba2SThomas Gleixner }
217bfc8c901SVladimir Davydov 
2184932381eSMichal Hocko bool movable_node_enabled = false;
2194932381eSMichal Hocko 
2208604d9e5SVitaly Kuznetsov #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
2211adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_OFFLINE;
2228604d9e5SVitaly Kuznetsov #else
2231adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_ONLINE;
2248604d9e5SVitaly Kuznetsov #endif
22531bc3858SVitaly Kuznetsov 
22686dd995dSVitaly Kuznetsov static int __init setup_memhp_default_state(char *str)
22786dd995dSVitaly Kuznetsov {
2281adf8b46SAnshuman Khandual 	const int online_type = mhp_online_type_from_str(str);
2295f47adf7SDavid Hildenbrand 
2305f47adf7SDavid Hildenbrand 	if (online_type >= 0)
2311adf8b46SAnshuman Khandual 		mhp_default_online_type = online_type;
23286dd995dSVitaly Kuznetsov 
23386dd995dSVitaly Kuznetsov 	return 1;
23486dd995dSVitaly Kuznetsov }
23586dd995dSVitaly Kuznetsov __setup("memhp_default_state=", setup_memhp_default_state);
23686dd995dSVitaly Kuznetsov 
23730467e0bSDavid Rientjes void mem_hotplug_begin(void)
238bfc8c901SVladimir Davydov {
2393f906ba2SThomas Gleixner 	cpus_read_lock();
2403f906ba2SThomas Gleixner 	percpu_down_write(&mem_hotplug_lock);
241bfc8c901SVladimir Davydov }
242bfc8c901SVladimir Davydov 
24330467e0bSDavid Rientjes void mem_hotplug_done(void)
244bfc8c901SVladimir Davydov {
2453f906ba2SThomas Gleixner 	percpu_up_write(&mem_hotplug_lock);
2463f906ba2SThomas Gleixner 	cpus_read_unlock();
247bfc8c901SVladimir Davydov }
24820d6c96bSKOSAKI Motohiro 
249357b4da5SJuergen Gross u64 max_mem_size = U64_MAX;
250357b4da5SJuergen Gross 
25145e0b78bSKeith Mannthey /* add this memory to iomem resource */
2527b7b2721SDavid Hildenbrand static struct resource *register_memory_resource(u64 start, u64 size,
2537b7b2721SDavid Hildenbrand 						 const char *resource_name)
25445e0b78bSKeith Mannthey {
2552794129eSDave Hansen 	struct resource *res;
2562794129eSDave Hansen 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
2577b7b2721SDavid Hildenbrand 
2587b7b2721SDavid Hildenbrand 	if (strcmp(resource_name, "System RAM"))
2597cf603d1SDavid Hildenbrand 		flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
260357b4da5SJuergen Gross 
261bca3feaaSAnshuman Khandual 	if (!mhp_range_allowed(start, size, true))
262bca3feaaSAnshuman Khandual 		return ERR_PTR(-E2BIG);
263bca3feaaSAnshuman Khandual 
264f3cd4c86SBaoquan He 	/*
265f3cd4c86SBaoquan He 	 * Make sure value parsed from 'mem=' only restricts memory adding
266f3cd4c86SBaoquan He 	 * while booting, so that memory hotplug won't be impacted. Please
267f3cd4c86SBaoquan He 	 * refer to document of 'mem=' in kernel-parameters.txt for more
268f3cd4c86SBaoquan He 	 * details.
269f3cd4c86SBaoquan He 	 */
270f3cd4c86SBaoquan He 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
271357b4da5SJuergen Gross 		return ERR_PTR(-E2BIG);
272357b4da5SJuergen Gross 
2732794129eSDave Hansen 	/*
2742794129eSDave Hansen 	 * Request ownership of the new memory range.  This might be
2752794129eSDave Hansen 	 * a child of an existing resource that was present but
2762794129eSDave Hansen 	 * not marked as busy.
2772794129eSDave Hansen 	 */
2782794129eSDave Hansen 	res = __request_region(&iomem_resource, start, size,
2792794129eSDave Hansen 			       resource_name, flags);
28045e0b78bSKeith Mannthey 
2812794129eSDave Hansen 	if (!res) {
2822794129eSDave Hansen 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
2832794129eSDave Hansen 				start, start + size);
2846f754ba4SVitaly Kuznetsov 		return ERR_PTR(-EEXIST);
28545e0b78bSKeith Mannthey 	}
28645e0b78bSKeith Mannthey 	return res;
28745e0b78bSKeith Mannthey }
28845e0b78bSKeith Mannthey 
28945e0b78bSKeith Mannthey static void release_memory_resource(struct resource *res)
29045e0b78bSKeith Mannthey {
29145e0b78bSKeith Mannthey 	if (!res)
29245e0b78bSKeith Mannthey 		return;
29345e0b78bSKeith Mannthey 	release_resource(res);
29445e0b78bSKeith Mannthey 	kfree(res);
29545e0b78bSKeith Mannthey }
29645e0b78bSKeith Mannthey 
297943189dbSAnshuman Khandual static int check_pfn_span(unsigned long pfn, unsigned long nr_pages)
2987ea62160SDan Williams {
2997ea62160SDan Williams 	/*
3007ea62160SDan Williams 	 * Disallow all operations smaller than a sub-section and only
3017ea62160SDan Williams 	 * allow operations smaller than a section for
3027ea62160SDan Williams 	 * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
3037ea62160SDan Williams 	 * enforces a larger memory_block_size_bytes() granularity for
3047ea62160SDan Williams 	 * memory that will be marked online, so this check should only
3057ea62160SDan Williams 	 * fire for direct arch_{add,remove}_memory() users outside of
3067ea62160SDan Williams 	 * add_memory_resource().
3077ea62160SDan Williams 	 */
3087ea62160SDan Williams 	unsigned long min_align;
3097ea62160SDan Williams 
3107ea62160SDan Williams 	if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
3117ea62160SDan Williams 		min_align = PAGES_PER_SUBSECTION;
3127ea62160SDan Williams 	else
3137ea62160SDan Williams 		min_align = PAGES_PER_SECTION;
314943189dbSAnshuman Khandual 	if (!IS_ALIGNED(pfn | nr_pages, min_align))
3157ea62160SDan Williams 		return -EINVAL;
3167ea62160SDan Williams 	return 0;
3177ea62160SDan Williams }
3187ea62160SDan Williams 
3194edd7cefSDavid Rientjes /*
3209f605f26SDan Williams  * Return page for the valid pfn only if the page is online. All pfn
3219f605f26SDan Williams  * walkers which rely on the fully initialized page->flags and others
3229f605f26SDan Williams  * should use this rather than pfn_valid && pfn_to_page
3239f605f26SDan Williams  */
3249f605f26SDan Williams struct page *pfn_to_online_page(unsigned long pfn)
3259f605f26SDan Williams {
3269f605f26SDan Williams 	unsigned long nr = pfn_to_section_nr(pfn);
3271f90a347SDan Williams 	struct dev_pagemap *pgmap;
3289f9b02e5SDan Williams 	struct mem_section *ms;
3299f605f26SDan Williams 
3309f9b02e5SDan Williams 	if (nr >= NR_MEM_SECTIONS)
3319f605f26SDan Williams 		return NULL;
3329f9b02e5SDan Williams 
3339f9b02e5SDan Williams 	ms = __nr_to_section(nr);
3349f9b02e5SDan Williams 	if (!online_section(ms))
3359f9b02e5SDan Williams 		return NULL;
3369f9b02e5SDan Williams 
3379f9b02e5SDan Williams 	/*
3389f9b02e5SDan Williams 	 * Save some code text when online_section() +
3399f9b02e5SDan Williams 	 * pfn_section_valid() are sufficient.
3409f9b02e5SDan Williams 	 */
3419f9b02e5SDan Williams 	if (IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID) && !pfn_valid(pfn))
3429f9b02e5SDan Williams 		return NULL;
3439f9b02e5SDan Williams 
3449f9b02e5SDan Williams 	if (!pfn_section_valid(ms, pfn))
3459f9b02e5SDan Williams 		return NULL;
3469f9b02e5SDan Williams 
3471f90a347SDan Williams 	if (!online_device_section(ms))
3481f90a347SDan Williams 		return pfn_to_page(pfn);
3491f90a347SDan Williams 
3501f90a347SDan Williams 	/*
3511f90a347SDan Williams 	 * Slowpath: when ZONE_DEVICE collides with
3521f90a347SDan Williams 	 * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
3531f90a347SDan Williams 	 * the section may be 'offline' but 'valid'. Only
3541f90a347SDan Williams 	 * get_dev_pagemap() can determine sub-section online status.
3551f90a347SDan Williams 	 */
3561f90a347SDan Williams 	pgmap = get_dev_pagemap(pfn, NULL);
3571f90a347SDan Williams 	put_dev_pagemap(pgmap);
3581f90a347SDan Williams 
3591f90a347SDan Williams 	/* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
3601f90a347SDan Williams 	if (pgmap)
3611f90a347SDan Williams 		return NULL;
3621f90a347SDan Williams 
3639f9b02e5SDan Williams 	return pfn_to_page(pfn);
3649f605f26SDan Williams }
3659f605f26SDan Williams EXPORT_SYMBOL_GPL(pfn_to_online_page);
3669f605f26SDan Williams 
3677ea62160SDan Williams int __ref __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
368f5637d3bSLogan Gunthorpe 		struct mhp_params *params)
3694edd7cefSDavid Rientjes {
3706cdd0b30SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
3716cdd0b30SDavid Hildenbrand 	unsigned long cur_nr_pages;
3729a845030SDan Williams 	int err;
373f5637d3bSLogan Gunthorpe 	struct vmem_altmap *altmap = params->altmap;
3744b94ffdcSDan Williams 
3756366238bSliusongtang 	if (WARN_ON_ONCE(!pgprot_val(params->pgprot)))
376bfeb022fSLogan Gunthorpe 		return -EINVAL;
377bfeb022fSLogan Gunthorpe 
378bca3feaaSAnshuman Khandual 	VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
379dca4436dSAlastair D'Silva 
3804b94ffdcSDan Williams 	if (altmap) {
3814b94ffdcSDan Williams 		/*
3824b94ffdcSDan Williams 		 * Validate altmap is within bounds of the total request
3834b94ffdcSDan Williams 		 */
3847ea62160SDan Williams 		if (altmap->base_pfn != pfn
3854b94ffdcSDan Williams 				|| vmem_altmap_offset(altmap) > nr_pages) {
3864b94ffdcSDan Williams 			pr_warn_once("memory add fail, invalid altmap\n");
3877ea62160SDan Williams 			return -EINVAL;
3884b94ffdcSDan Williams 		}
3894b94ffdcSDan Williams 		altmap->alloc = 0;
3904b94ffdcSDan Williams 	}
3914b94ffdcSDan Williams 
392943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
39350135045SRick Wertenbroek 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
394943189dbSAnshuman Khandual 		return -EINVAL;
395943189dbSAnshuman Khandual 	}
3967ea62160SDan Williams 
3976cdd0b30SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
3986cdd0b30SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
3996cdd0b30SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
4006cdd0b30SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
401e3246d8fSJoao Martins 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
402e3246d8fSJoao Martins 					 params->pgmap);
403ba72b4c8SDan Williams 		if (err)
404ba72b4c8SDan Williams 			break;
405f64ac5e6SMichal Hocko 		cond_resched();
4064edd7cefSDavid Rientjes 	}
407c435a390SZhu Guihua 	vmemmap_populate_print_last();
4084edd7cefSDavid Rientjes 	return err;
4094edd7cefSDavid Rientjes }
4104edd7cefSDavid Rientjes 
411815121d2SYasuaki Ishimatsu /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
412d09b0137SYASUAKI ISHIMATSU static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
413815121d2SYasuaki Ishimatsu 				     unsigned long start_pfn,
414815121d2SYasuaki Ishimatsu 				     unsigned long end_pfn)
415815121d2SYasuaki Ishimatsu {
41649ba3c6bSDan Williams 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
4177ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(start_pfn)))
418815121d2SYasuaki Ishimatsu 			continue;
419815121d2SYasuaki Ishimatsu 
420815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(start_pfn) != nid))
421815121d2SYasuaki Ishimatsu 			continue;
422815121d2SYasuaki Ishimatsu 
4239b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(start_pfn)))
424815121d2SYasuaki Ishimatsu 			continue;
425815121d2SYasuaki Ishimatsu 
426815121d2SYasuaki Ishimatsu 		return start_pfn;
427815121d2SYasuaki Ishimatsu 	}
428815121d2SYasuaki Ishimatsu 
429815121d2SYasuaki Ishimatsu 	return 0;
430815121d2SYasuaki Ishimatsu }
431815121d2SYasuaki Ishimatsu 
432815121d2SYasuaki Ishimatsu /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
433d09b0137SYASUAKI ISHIMATSU static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
434815121d2SYasuaki Ishimatsu 				    unsigned long start_pfn,
435815121d2SYasuaki Ishimatsu 				    unsigned long end_pfn)
436815121d2SYasuaki Ishimatsu {
437815121d2SYasuaki Ishimatsu 	unsigned long pfn;
438815121d2SYasuaki Ishimatsu 
439815121d2SYasuaki Ishimatsu 	/* pfn is the end pfn of a memory section. */
440815121d2SYasuaki Ishimatsu 	pfn = end_pfn - 1;
44149ba3c6bSDan Williams 	for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
4427ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(pfn)))
443815121d2SYasuaki Ishimatsu 			continue;
444815121d2SYasuaki Ishimatsu 
445815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(pfn) != nid))
446815121d2SYasuaki Ishimatsu 			continue;
447815121d2SYasuaki Ishimatsu 
4489b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(pfn)))
449815121d2SYasuaki Ishimatsu 			continue;
450815121d2SYasuaki Ishimatsu 
451815121d2SYasuaki Ishimatsu 		return pfn;
452815121d2SYasuaki Ishimatsu 	}
453815121d2SYasuaki Ishimatsu 
454815121d2SYasuaki Ishimatsu 	return 0;
455815121d2SYasuaki Ishimatsu }
456815121d2SYasuaki Ishimatsu 
457815121d2SYasuaki Ishimatsu static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
458815121d2SYasuaki Ishimatsu 			     unsigned long end_pfn)
459815121d2SYasuaki Ishimatsu {
460815121d2SYasuaki Ishimatsu 	unsigned long pfn;
461815121d2SYasuaki Ishimatsu 	int nid = zone_to_nid(zone);
462815121d2SYasuaki Ishimatsu 
4635d12071cSDavid Hildenbrand 	if (zone->zone_start_pfn == start_pfn) {
464815121d2SYasuaki Ishimatsu 		/*
465815121d2SYasuaki Ishimatsu 		 * If the section is smallest section in the zone, it need
466815121d2SYasuaki Ishimatsu 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
467815121d2SYasuaki Ishimatsu 		 * In this case, we find second smallest valid mem_section
468815121d2SYasuaki Ishimatsu 		 * for shrinking zone.
469815121d2SYasuaki Ishimatsu 		 */
470815121d2SYasuaki Ishimatsu 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
4715d12071cSDavid Hildenbrand 						zone_end_pfn(zone));
472815121d2SYasuaki Ishimatsu 		if (pfn) {
4735d12071cSDavid Hildenbrand 			zone->spanned_pages = zone_end_pfn(zone) - pfn;
474815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = pfn;
475950b68d9SDavid Hildenbrand 		} else {
476950b68d9SDavid Hildenbrand 			zone->zone_start_pfn = 0;
477950b68d9SDavid Hildenbrand 			zone->spanned_pages = 0;
478815121d2SYasuaki Ishimatsu 		}
4795d12071cSDavid Hildenbrand 	} else if (zone_end_pfn(zone) == end_pfn) {
480815121d2SYasuaki Ishimatsu 		/*
481815121d2SYasuaki Ishimatsu 		 * If the section is biggest section in the zone, it need
482815121d2SYasuaki Ishimatsu 		 * shrink zone->spanned_pages.
483815121d2SYasuaki Ishimatsu 		 * In this case, we find second biggest valid mem_section for
484815121d2SYasuaki Ishimatsu 		 * shrinking zone.
485815121d2SYasuaki Ishimatsu 		 */
4865d12071cSDavid Hildenbrand 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
487815121d2SYasuaki Ishimatsu 					       start_pfn);
488815121d2SYasuaki Ishimatsu 		if (pfn)
4895d12071cSDavid Hildenbrand 			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
490950b68d9SDavid Hildenbrand 		else {
491815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = 0;
492815121d2SYasuaki Ishimatsu 			zone->spanned_pages = 0;
493950b68d9SDavid Hildenbrand 		}
494950b68d9SDavid Hildenbrand 	}
495815121d2SYasuaki Ishimatsu }
496815121d2SYasuaki Ishimatsu 
49700d6c019SDavid Hildenbrand static void update_pgdat_span(struct pglist_data *pgdat)
498815121d2SYasuaki Ishimatsu {
49900d6c019SDavid Hildenbrand 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
50000d6c019SDavid Hildenbrand 	struct zone *zone;
501815121d2SYasuaki Ishimatsu 
50200d6c019SDavid Hildenbrand 	for (zone = pgdat->node_zones;
50300d6c019SDavid Hildenbrand 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
5046c922cf7SMiaohe Lin 		unsigned long end_pfn = zone_end_pfn(zone);
50500d6c019SDavid Hildenbrand 
50600d6c019SDavid Hildenbrand 		/* No need to lock the zones, they can't change. */
507656d5711SDavid Hildenbrand 		if (!zone->spanned_pages)
508656d5711SDavid Hildenbrand 			continue;
509656d5711SDavid Hildenbrand 		if (!node_end_pfn) {
510656d5711SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
5116c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
512656d5711SDavid Hildenbrand 			continue;
513656d5711SDavid Hildenbrand 		}
514656d5711SDavid Hildenbrand 
5156c922cf7SMiaohe Lin 		if (end_pfn > node_end_pfn)
5166c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
51700d6c019SDavid Hildenbrand 		if (zone->zone_start_pfn < node_start_pfn)
51800d6c019SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
519815121d2SYasuaki Ishimatsu 	}
520815121d2SYasuaki Ishimatsu 
52100d6c019SDavid Hildenbrand 	pgdat->node_start_pfn = node_start_pfn;
52200d6c019SDavid Hildenbrand 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
523815121d2SYasuaki Ishimatsu }
524815121d2SYasuaki Ishimatsu 
525feee6b29SDavid Hildenbrand void __ref remove_pfn_range_from_zone(struct zone *zone,
526feee6b29SDavid Hildenbrand 				      unsigned long start_pfn,
5277ea62160SDan Williams 				      unsigned long nr_pages)
528815121d2SYasuaki Ishimatsu {
529b7e3debdSBen Widawsky 	const unsigned long end_pfn = start_pfn + nr_pages;
530815121d2SYasuaki Ishimatsu 	struct pglist_data *pgdat = zone->zone_pgdat;
53127cacaadSOscar Salvador 	unsigned long pfn, cur_nr_pages;
532815121d2SYasuaki Ishimatsu 
533d33695b1SDavid Hildenbrand 	/* Poison struct pages because they are now uninitialized again. */
534b7e3debdSBen Widawsky 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
535b7e3debdSBen Widawsky 		cond_resched();
536b7e3debdSBen Widawsky 
537b7e3debdSBen Widawsky 		/* Select all remaining pages up to the next section boundary */
538b7e3debdSBen Widawsky 		cur_nr_pages =
539b7e3debdSBen Widawsky 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
540b7e3debdSBen Widawsky 		page_init_poison(pfn_to_page(pfn),
541b7e3debdSBen Widawsky 				 sizeof(struct page) * cur_nr_pages);
542b7e3debdSBen Widawsky 	}
543d33695b1SDavid Hildenbrand 
5447ce700bfSDavid Hildenbrand 	/*
5457ce700bfSDavid Hildenbrand 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
5467ce700bfSDavid Hildenbrand 	 * we will not try to shrink the zones - which is okay as
5477ce700bfSDavid Hildenbrand 	 * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
5487ce700bfSDavid Hildenbrand 	 */
5495ef5f810SMiaohe Lin 	if (zone_is_zone_device(zone))
5507ce700bfSDavid Hildenbrand 		return;
5517ce700bfSDavid Hildenbrand 
552feee6b29SDavid Hildenbrand 	clear_zone_contiguous(zone);
553feee6b29SDavid Hildenbrand 
554815121d2SYasuaki Ishimatsu 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
55500d6c019SDavid Hildenbrand 	update_pgdat_span(pgdat);
556feee6b29SDavid Hildenbrand 
557feee6b29SDavid Hildenbrand 	set_zone_contiguous(zone);
558815121d2SYasuaki Ishimatsu }
559815121d2SYasuaki Ishimatsu 
560ea01ea93SBadari Pulavarty /**
561feee6b29SDavid Hildenbrand  * __remove_pages() - remove sections of pages
5627ea62160SDan Williams  * @pfn: starting pageframe (must be aligned to start of a section)
563ea01ea93SBadari Pulavarty  * @nr_pages: number of pages to remove (must be multiple of section size)
564e8b098fcSMike Rapoport  * @altmap: alternative device page map or %NULL if default memmap is used
565ea01ea93SBadari Pulavarty  *
566ea01ea93SBadari Pulavarty  * Generic helper function to remove section mappings and sysfs entries
567ea01ea93SBadari Pulavarty  * for the section of the memory we are removing. Caller needs to make
568ea01ea93SBadari Pulavarty  * sure that pages are marked reserved and zones are adjust properly by
569ea01ea93SBadari Pulavarty  * calling offline_pages().
570ea01ea93SBadari Pulavarty  */
571feee6b29SDavid Hildenbrand void __remove_pages(unsigned long pfn, unsigned long nr_pages,
572feee6b29SDavid Hildenbrand 		    struct vmem_altmap *altmap)
573ea01ea93SBadari Pulavarty {
57452fb87c8SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
57552fb87c8SDavid Hildenbrand 	unsigned long cur_nr_pages;
576ea01ea93SBadari Pulavarty 
577943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
57850135045SRick Wertenbroek 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
5797ea62160SDan Williams 		return;
580943189dbSAnshuman Khandual 	}
581ea01ea93SBadari Pulavarty 
58252fb87c8SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
583dd33ad7bSMichal Hocko 		cond_resched();
58452fb87c8SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
585a11b9419SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
586a11b9419SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
587bd5f79abSYajun Deng 		sparse_remove_section(pfn, cur_nr_pages, altmap);
588ea01ea93SBadari Pulavarty 	}
589ea01ea93SBadari Pulavarty }
590ea01ea93SBadari Pulavarty 
5919d0ad8caSDaniel Kiper int set_online_page_callback(online_page_callback_t callback)
5929d0ad8caSDaniel Kiper {
5939d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5949d0ad8caSDaniel Kiper 
595bfc8c901SVladimir Davydov 	get_online_mems();
596bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5979d0ad8caSDaniel Kiper 
5989d0ad8caSDaniel Kiper 	if (online_page_callback == generic_online_page) {
5999d0ad8caSDaniel Kiper 		online_page_callback = callback;
6009d0ad8caSDaniel Kiper 		rc = 0;
6019d0ad8caSDaniel Kiper 	}
6029d0ad8caSDaniel Kiper 
603bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
604bfc8c901SVladimir Davydov 	put_online_mems();
6059d0ad8caSDaniel Kiper 
6069d0ad8caSDaniel Kiper 	return rc;
6079d0ad8caSDaniel Kiper }
6089d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(set_online_page_callback);
6099d0ad8caSDaniel Kiper 
6109d0ad8caSDaniel Kiper int restore_online_page_callback(online_page_callback_t callback)
6119d0ad8caSDaniel Kiper {
6129d0ad8caSDaniel Kiper 	int rc = -EINVAL;
6139d0ad8caSDaniel Kiper 
614bfc8c901SVladimir Davydov 	get_online_mems();
615bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
6169d0ad8caSDaniel Kiper 
6179d0ad8caSDaniel Kiper 	if (online_page_callback == callback) {
6189d0ad8caSDaniel Kiper 		online_page_callback = generic_online_page;
6199d0ad8caSDaniel Kiper 		rc = 0;
6209d0ad8caSDaniel Kiper 	}
6219d0ad8caSDaniel Kiper 
622bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
623bfc8c901SVladimir Davydov 	put_online_mems();
6249d0ad8caSDaniel Kiper 
6259d0ad8caSDaniel Kiper 	return rc;
6269d0ad8caSDaniel Kiper }
6279d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(restore_online_page_callback);
6289d0ad8caSDaniel Kiper 
62918db1491SDavid Hildenbrand void generic_online_page(struct page *page, unsigned int order)
6309d0ad8caSDaniel Kiper {
631c87cbc1fSVlastimil Babka 	/*
632c87cbc1fSVlastimil Babka 	 * Freeing the page with debug_pagealloc enabled will try to unmap it,
633c87cbc1fSVlastimil Babka 	 * so we should map it first. This is better than introducing a special
634c87cbc1fSVlastimil Babka 	 * case in page freeing fast path.
635c87cbc1fSVlastimil Babka 	 */
63677bc7fd6SMike Rapoport 	debug_pagealloc_map_pages(page, 1 << order);
637a9cd410aSArun KS 	__free_pages_core(page, order);
638a9cd410aSArun KS 	totalram_pages_add(1UL << order);
639a9cd410aSArun KS }
64018db1491SDavid Hildenbrand EXPORT_SYMBOL_GPL(generic_online_page);
641a9cd410aSArun KS 
642aac65321SDavid Hildenbrand static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
6433947be19SDave Hansen {
644b2c2ab20SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
645b2c2ab20SDavid Hildenbrand 	unsigned long pfn;
6462d070eabSMichal Hocko 
647b2c2ab20SDavid Hildenbrand 	/*
64823baf831SKirill A. Shutemov 	 * Online the pages in MAX_ORDER aligned chunks. The callback might
649aac65321SDavid Hildenbrand 	 * decide to not expose all pages to the buddy (e.g., expose them
650aac65321SDavid Hildenbrand 	 * later). We account all pages as being online and belonging to this
651aac65321SDavid Hildenbrand 	 * zone ("present").
652a08a2ae3SOscar Salvador 	 * When using memmap_on_memory, the range might not be aligned to
653a08a2ae3SOscar Salvador 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
654a08a2ae3SOscar Salvador 	 * this and the first chunk to online will be pageblock_nr_pages.
655b2c2ab20SDavid Hildenbrand 	 */
656a08a2ae3SOscar Salvador 	for (pfn = start_pfn; pfn < end_pfn;) {
65759f876fbSKirill A. Shutemov 		int order;
65859f876fbSKirill A. Shutemov 
65959f876fbSKirill A. Shutemov 		/*
66059f876fbSKirill A. Shutemov 		 * Free to online pages in the largest chunks alignment allows.
66159f876fbSKirill A. Shutemov 		 *
66259f876fbSKirill A. Shutemov 		 * __ffs() behaviour is undefined for 0. start == 0 is
66359f876fbSKirill A. Shutemov 		 * MAX_ORDER-aligned, Set order to MAX_ORDER for the case.
66459f876fbSKirill A. Shutemov 		 */
66559f876fbSKirill A. Shutemov 		if (pfn)
66659f876fbSKirill A. Shutemov 			order = min_t(int, MAX_ORDER, __ffs(pfn));
66759f876fbSKirill A. Shutemov 		else
66859f876fbSKirill A. Shutemov 			order = MAX_ORDER;
669a08a2ae3SOscar Salvador 
670a08a2ae3SOscar Salvador 		(*online_page_callback)(pfn_to_page(pfn), order);
671a08a2ae3SOscar Salvador 		pfn += (1UL << order);
672a08a2ae3SOscar Salvador 	}
6732d070eabSMichal Hocko 
674b2c2ab20SDavid Hildenbrand 	/* mark all involved sections as online */
675b2c2ab20SDavid Hildenbrand 	online_mem_sections(start_pfn, end_pfn);
67675884fb1SKAMEZAWA Hiroyuki }
67775884fb1SKAMEZAWA Hiroyuki 
678d9713679SLai Jiangshan /* check which state of node_states will be changed when online memory */
679d9713679SLai Jiangshan static void node_states_check_changes_online(unsigned long nr_pages,
680d9713679SLai Jiangshan 	struct zone *zone, struct memory_notify *arg)
681d9713679SLai Jiangshan {
682d9713679SLai Jiangshan 	int nid = zone_to_nid(zone);
683d9713679SLai Jiangshan 
68498fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
68598fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
6866715ddf9SLai Jiangshan 
6876715ddf9SLai Jiangshan 	if (!node_state(nid, N_MEMORY))
688d9713679SLai Jiangshan 		arg->status_change_nid = nid;
6898efe33f4SOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
6908efe33f4SOscar Salvador 		arg->status_change_nid_normal = nid;
691d9713679SLai Jiangshan }
692d9713679SLai Jiangshan 
693d9713679SLai Jiangshan static void node_states_set_node(int node, struct memory_notify *arg)
694d9713679SLai Jiangshan {
695d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
696d9713679SLai Jiangshan 		node_set_state(node, N_NORMAL_MEMORY);
697d9713679SLai Jiangshan 
69883d83612SOscar Salvador 	if (arg->status_change_nid >= 0)
6996715ddf9SLai Jiangshan 		node_set_state(node, N_MEMORY);
700d9713679SLai Jiangshan }
701d9713679SLai Jiangshan 
702f1dd2cd1SMichal Hocko static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
703f1dd2cd1SMichal Hocko 		unsigned long nr_pages)
704f1dd2cd1SMichal Hocko {
705f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = zone_end_pfn(zone);
706f1dd2cd1SMichal Hocko 
707f1dd2cd1SMichal Hocko 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
708f1dd2cd1SMichal Hocko 		zone->zone_start_pfn = start_pfn;
709f1dd2cd1SMichal Hocko 
710f1dd2cd1SMichal Hocko 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
711f1dd2cd1SMichal Hocko }
712f1dd2cd1SMichal Hocko 
713f1dd2cd1SMichal Hocko static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
714f1dd2cd1SMichal Hocko                                      unsigned long nr_pages)
715f1dd2cd1SMichal Hocko {
716f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
717f1dd2cd1SMichal Hocko 
718f1dd2cd1SMichal Hocko 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
719f1dd2cd1SMichal Hocko 		pgdat->node_start_pfn = start_pfn;
720f1dd2cd1SMichal Hocko 
721f1dd2cd1SMichal Hocko 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
722f1dd2cd1SMichal Hocko 
7233fccb74cSDavid Hildenbrand }
7241f90a347SDan Williams 
725ed7802ddSMuchun Song #ifdef CONFIG_ZONE_DEVICE
7261f90a347SDan Williams static void section_taint_zone_device(unsigned long pfn)
7271f90a347SDan Williams {
7281f90a347SDan Williams 	struct mem_section *ms = __pfn_to_section(pfn);
7291f90a347SDan Williams 
7301f90a347SDan Williams 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
7311f90a347SDan Williams }
732ed7802ddSMuchun Song #else
733ed7802ddSMuchun Song static inline void section_taint_zone_device(unsigned long pfn)
734ed7802ddSMuchun Song {
735ed7802ddSMuchun Song }
736ed7802ddSMuchun Song #endif
7371f90a347SDan Williams 
7383fccb74cSDavid Hildenbrand /*
7393fccb74cSDavid Hildenbrand  * Associate the pfn range with the given zone, initializing the memmaps
7403fccb74cSDavid Hildenbrand  * and resizing the pgdat/zone data to span the added pages. After this
7413fccb74cSDavid Hildenbrand  * call, all affected pages are PG_reserved.
742d882c006SDavid Hildenbrand  *
743d882c006SDavid Hildenbrand  * All aligned pageblocks are initialized to the specified migratetype
744d882c006SDavid Hildenbrand  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
745d882c006SDavid Hildenbrand  * zone stats (e.g., nr_isolate_pageblock) are touched.
7463fccb74cSDavid Hildenbrand  */
747a99583e7SChristoph Hellwig void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
748d882c006SDavid Hildenbrand 				  unsigned long nr_pages,
749d882c006SDavid Hildenbrand 				  struct vmem_altmap *altmap, int migratetype)
750f1dd2cd1SMichal Hocko {
751f1dd2cd1SMichal Hocko 	struct pglist_data *pgdat = zone->zone_pgdat;
752f1dd2cd1SMichal Hocko 	int nid = pgdat->node_id;
753f1dd2cd1SMichal Hocko 
754f1dd2cd1SMichal Hocko 	clear_zone_contiguous(zone);
755f1dd2cd1SMichal Hocko 
756fa004ab7SWei Yang 	if (zone_is_empty(zone))
757fa004ab7SWei Yang 		init_currently_empty_zone(zone, start_pfn, nr_pages);
758f1dd2cd1SMichal Hocko 	resize_zone_range(zone, start_pfn, nr_pages);
759f1dd2cd1SMichal Hocko 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
760f1dd2cd1SMichal Hocko 
761f1dd2cd1SMichal Hocko 	/*
7621f90a347SDan Williams 	 * Subsection population requires care in pfn_to_online_page().
7631f90a347SDan Williams 	 * Set the taint to enable the slow path detection of
7641f90a347SDan Williams 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
7651f90a347SDan Williams 	 * section.
7661f90a347SDan Williams 	 */
7671f90a347SDan Williams 	if (zone_is_zone_device(zone)) {
7681f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
7691f90a347SDan Williams 			section_taint_zone_device(start_pfn);
7701f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
7711f90a347SDan Williams 			section_taint_zone_device(start_pfn + nr_pages);
7721f90a347SDan Williams 	}
7731f90a347SDan Williams 
7741f90a347SDan Williams 	/*
775f1dd2cd1SMichal Hocko 	 * TODO now we have a visible range of pages which are not associated
776f1dd2cd1SMichal Hocko 	 * with their zone properly. Not nice but set_pfnblock_flags_mask
777f1dd2cd1SMichal Hocko 	 * expects the zone spans the pfn range. All the pages in the range
778f1dd2cd1SMichal Hocko 	 * are reserved so nobody should be touching them so we should be safe
779f1dd2cd1SMichal Hocko 	 */
780ab28cb6eSBaoquan He 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
781d882c006SDavid Hildenbrand 			 MEMINIT_HOTPLUG, altmap, migratetype);
782f1dd2cd1SMichal Hocko 
783f1dd2cd1SMichal Hocko 	set_zone_contiguous(zone);
784f1dd2cd1SMichal Hocko }
785f1dd2cd1SMichal Hocko 
786e83a437fSDavid Hildenbrand struct auto_movable_stats {
787e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages;
788e83a437fSDavid Hildenbrand 	unsigned long movable_pages;
789e83a437fSDavid Hildenbrand };
790e83a437fSDavid Hildenbrand 
791e83a437fSDavid Hildenbrand static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
792e83a437fSDavid Hildenbrand 					    struct zone *zone)
793e83a437fSDavid Hildenbrand {
794e83a437fSDavid Hildenbrand 	if (zone_idx(zone) == ZONE_MOVABLE) {
795e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->present_pages;
796e83a437fSDavid Hildenbrand 	} else {
797e83a437fSDavid Hildenbrand 		stats->kernel_early_pages += zone->present_early_pages;
798e83a437fSDavid Hildenbrand #ifdef CONFIG_CMA
799e83a437fSDavid Hildenbrand 		/*
800e83a437fSDavid Hildenbrand 		 * CMA pages (never on hotplugged memory) behave like
801e83a437fSDavid Hildenbrand 		 * ZONE_MOVABLE.
802e83a437fSDavid Hildenbrand 		 */
803e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->cma_pages;
804e83a437fSDavid Hildenbrand 		stats->kernel_early_pages -= zone->cma_pages;
805e83a437fSDavid Hildenbrand #endif /* CONFIG_CMA */
806e83a437fSDavid Hildenbrand 	}
807e83a437fSDavid Hildenbrand }
8083fcebf90SDavid Hildenbrand struct auto_movable_group_stats {
8093fcebf90SDavid Hildenbrand 	unsigned long movable_pages;
8103fcebf90SDavid Hildenbrand 	unsigned long req_kernel_early_pages;
8113fcebf90SDavid Hildenbrand };
812e83a437fSDavid Hildenbrand 
8133fcebf90SDavid Hildenbrand static int auto_movable_stats_account_group(struct memory_group *group,
8143fcebf90SDavid Hildenbrand 					   void *arg)
815e83a437fSDavid Hildenbrand {
8163fcebf90SDavid Hildenbrand 	const int ratio = READ_ONCE(auto_movable_ratio);
8173fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats *stats = arg;
8183fcebf90SDavid Hildenbrand 	long pages;
8193fcebf90SDavid Hildenbrand 
8203fcebf90SDavid Hildenbrand 	/*
8213fcebf90SDavid Hildenbrand 	 * We don't support modifying the config while the auto-movable online
8223fcebf90SDavid Hildenbrand 	 * policy is already enabled. Just avoid the division by zero below.
8233fcebf90SDavid Hildenbrand 	 */
8243fcebf90SDavid Hildenbrand 	if (!ratio)
8253fcebf90SDavid Hildenbrand 		return 0;
8263fcebf90SDavid Hildenbrand 
8273fcebf90SDavid Hildenbrand 	/*
8283fcebf90SDavid Hildenbrand 	 * Calculate how many early kernel pages this group requires to
8293fcebf90SDavid Hildenbrand 	 * satisfy the configured zone ratio.
8303fcebf90SDavid Hildenbrand 	 */
8313fcebf90SDavid Hildenbrand 	pages = group->present_movable_pages * 100 / ratio;
8323fcebf90SDavid Hildenbrand 	pages -= group->present_kernel_pages;
8333fcebf90SDavid Hildenbrand 
8343fcebf90SDavid Hildenbrand 	if (pages > 0)
8353fcebf90SDavid Hildenbrand 		stats->req_kernel_early_pages += pages;
8363fcebf90SDavid Hildenbrand 	stats->movable_pages += group->present_movable_pages;
8373fcebf90SDavid Hildenbrand 	return 0;
8383fcebf90SDavid Hildenbrand }
8393fcebf90SDavid Hildenbrand 
8403fcebf90SDavid Hildenbrand static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
8413fcebf90SDavid Hildenbrand 					    unsigned long nr_pages)
8423fcebf90SDavid Hildenbrand {
843e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages, movable_pages;
8443fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats group_stats = {};
8453fcebf90SDavid Hildenbrand 	struct auto_movable_stats stats = {};
846e83a437fSDavid Hildenbrand 	pg_data_t *pgdat = NODE_DATA(nid);
847e83a437fSDavid Hildenbrand 	struct zone *zone;
848e83a437fSDavid Hildenbrand 	int i;
849e83a437fSDavid Hildenbrand 
850e83a437fSDavid Hildenbrand 	/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
851e83a437fSDavid Hildenbrand 	if (nid == NUMA_NO_NODE) {
852e83a437fSDavid Hildenbrand 		/* TODO: cache values */
853e83a437fSDavid Hildenbrand 		for_each_populated_zone(zone)
854e83a437fSDavid Hildenbrand 			auto_movable_stats_account_zone(&stats, zone);
855e83a437fSDavid Hildenbrand 	} else {
856e83a437fSDavid Hildenbrand 		for (i = 0; i < MAX_NR_ZONES; i++) {
857e83a437fSDavid Hildenbrand 			zone = pgdat->node_zones + i;
858e83a437fSDavid Hildenbrand 			if (populated_zone(zone))
859e83a437fSDavid Hildenbrand 				auto_movable_stats_account_zone(&stats, zone);
860e83a437fSDavid Hildenbrand 		}
861e83a437fSDavid Hildenbrand 	}
862e83a437fSDavid Hildenbrand 
863e83a437fSDavid Hildenbrand 	kernel_early_pages = stats.kernel_early_pages;
864e83a437fSDavid Hildenbrand 	movable_pages = stats.movable_pages;
865e83a437fSDavid Hildenbrand 
866e83a437fSDavid Hildenbrand 	/*
8673fcebf90SDavid Hildenbrand 	 * Kernel memory inside dynamic memory group allows for more MOVABLE
8683fcebf90SDavid Hildenbrand 	 * memory within the same group. Remove the effect of all but the
8693fcebf90SDavid Hildenbrand 	 * current group from the stats.
8703fcebf90SDavid Hildenbrand 	 */
8713fcebf90SDavid Hildenbrand 	walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
8723fcebf90SDavid Hildenbrand 				   group, &group_stats);
8733fcebf90SDavid Hildenbrand 	if (kernel_early_pages <= group_stats.req_kernel_early_pages)
8743fcebf90SDavid Hildenbrand 		return false;
8753fcebf90SDavid Hildenbrand 	kernel_early_pages -= group_stats.req_kernel_early_pages;
8763fcebf90SDavid Hildenbrand 	movable_pages -= group_stats.movable_pages;
8773fcebf90SDavid Hildenbrand 
8783fcebf90SDavid Hildenbrand 	if (group && group->is_dynamic)
8793fcebf90SDavid Hildenbrand 		kernel_early_pages += group->present_kernel_pages;
8803fcebf90SDavid Hildenbrand 
8813fcebf90SDavid Hildenbrand 	/*
882e83a437fSDavid Hildenbrand 	 * Test if we could online the given number of pages to ZONE_MOVABLE
883e83a437fSDavid Hildenbrand 	 * and still stay in the configured ratio.
884e83a437fSDavid Hildenbrand 	 */
885e83a437fSDavid Hildenbrand 	movable_pages += nr_pages;
886e83a437fSDavid Hildenbrand 	return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
887e83a437fSDavid Hildenbrand }
888e83a437fSDavid Hildenbrand 
889f1dd2cd1SMichal Hocko /*
890c246a213SMichal Hocko  * Returns a default kernel memory zone for the given pfn range.
891c246a213SMichal Hocko  * If no kernel zone covers this pfn range it will automatically go
892c246a213SMichal Hocko  * to the ZONE_NORMAL.
893c246a213SMichal Hocko  */
894c6f03e29SMichal Hocko static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
895c246a213SMichal Hocko 		unsigned long nr_pages)
896c246a213SMichal Hocko {
897c246a213SMichal Hocko 	struct pglist_data *pgdat = NODE_DATA(nid);
898c246a213SMichal Hocko 	int zid;
899c246a213SMichal Hocko 
900d6aad201SMiaohe Lin 	for (zid = 0; zid < ZONE_NORMAL; zid++) {
901c246a213SMichal Hocko 		struct zone *zone = &pgdat->node_zones[zid];
902c246a213SMichal Hocko 
903c246a213SMichal Hocko 		if (zone_intersects(zone, start_pfn, nr_pages))
904c246a213SMichal Hocko 			return zone;
905c246a213SMichal Hocko 	}
906c246a213SMichal Hocko 
907c246a213SMichal Hocko 	return &pgdat->node_zones[ZONE_NORMAL];
908c246a213SMichal Hocko }
909c246a213SMichal Hocko 
910e83a437fSDavid Hildenbrand /*
911e83a437fSDavid Hildenbrand  * Determine to which zone to online memory dynamically based on user
912e83a437fSDavid Hildenbrand  * configuration and system stats. We care about the following ratio:
913e83a437fSDavid Hildenbrand  *
914e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL
915e83a437fSDavid Hildenbrand  *
916e83a437fSDavid Hildenbrand  * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
917e83a437fSDavid Hildenbrand  * one of the kernel zones. CMA pages inside one of the kernel zones really
918e83a437fSDavid Hildenbrand  * behaves like ZONE_MOVABLE, so we treat them accordingly.
919e83a437fSDavid Hildenbrand  *
920e83a437fSDavid Hildenbrand  * We don't allow for hotplugged memory in a KERNEL zone to increase the
921e83a437fSDavid Hildenbrand  * amount of MOVABLE memory we can have, so we end up with:
922e83a437fSDavid Hildenbrand  *
923e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL_EARLY
924e83a437fSDavid Hildenbrand  *
925e83a437fSDavid Hildenbrand  * Whereby KERNEL_EARLY is memory in one of the kernel zones, available sinze
926e83a437fSDavid Hildenbrand  * boot. We base our calculation on KERNEL_EARLY internally, because:
927e83a437fSDavid Hildenbrand  *
928e83a437fSDavid Hildenbrand  * a) Hotplugged memory in one of the kernel zones can sometimes still get
929e83a437fSDavid Hildenbrand  *    hotunplugged, especially when hot(un)plugging individual memory blocks.
930e83a437fSDavid Hildenbrand  *    There is no coordination across memory devices, therefore "automatic"
931e83a437fSDavid Hildenbrand  *    hotunplugging, as implemented in hypervisors, could result in zone
932e83a437fSDavid Hildenbrand  *    imbalances.
933e83a437fSDavid Hildenbrand  * b) Early/boot memory in one of the kernel zones can usually not get
934e83a437fSDavid Hildenbrand  *    hotunplugged again (e.g., no firmware interface to unplug, fragmented
935e83a437fSDavid Hildenbrand  *    with unmovable allocations). While there are corner cases where it might
936e83a437fSDavid Hildenbrand  *    still work, it is barely relevant in practice.
937e83a437fSDavid Hildenbrand  *
9383fcebf90SDavid Hildenbrand  * Exceptions are dynamic memory groups, which allow for more MOVABLE
9393fcebf90SDavid Hildenbrand  * memory within the same memory group -- because in that case, there is
9403fcebf90SDavid Hildenbrand  * coordination within the single memory device managed by a single driver.
9413fcebf90SDavid Hildenbrand  *
942e83a437fSDavid Hildenbrand  * We rely on "present pages" instead of "managed pages", as the latter is
943e83a437fSDavid Hildenbrand  * highly unreliable and dynamic in virtualized environments, and does not
944e83a437fSDavid Hildenbrand  * consider boot time allocations. For example, memory ballooning adjusts the
945e83a437fSDavid Hildenbrand  * managed pages when inflating/deflating the balloon, and balloon compaction
946e83a437fSDavid Hildenbrand  * can even migrate inflated pages between zones.
947e83a437fSDavid Hildenbrand  *
948e83a437fSDavid Hildenbrand  * Using "present pages" is better but some things to keep in mind are:
949e83a437fSDavid Hildenbrand  *
950e83a437fSDavid Hildenbrand  * a) Some memblock allocations, such as for the crashkernel area, are
951e83a437fSDavid Hildenbrand  *    effectively unused by the kernel, yet they account to "present pages".
952e83a437fSDavid Hildenbrand  *    Fortunately, these allocations are comparatively small in relevant setups
953e83a437fSDavid Hildenbrand  *    (e.g., fraction of system memory).
954e83a437fSDavid Hildenbrand  * b) Some hotplugged memory blocks in virtualized environments, esecially
955e83a437fSDavid Hildenbrand  *    hotplugged by virtio-mem, look like they are completely present, however,
956e83a437fSDavid Hildenbrand  *    only parts of the memory block are actually currently usable.
957e83a437fSDavid Hildenbrand  *    "present pages" is an upper limit that can get reached at runtime. As
958e83a437fSDavid Hildenbrand  *    we base our calculations on KERNEL_EARLY, this is not an issue.
959e83a437fSDavid Hildenbrand  */
960445fcf7cSDavid Hildenbrand static struct zone *auto_movable_zone_for_pfn(int nid,
961445fcf7cSDavid Hildenbrand 					      struct memory_group *group,
962445fcf7cSDavid Hildenbrand 					      unsigned long pfn,
963e83a437fSDavid Hildenbrand 					      unsigned long nr_pages)
964e83a437fSDavid Hildenbrand {
965445fcf7cSDavid Hildenbrand 	unsigned long online_pages = 0, max_pages, end_pfn;
966445fcf7cSDavid Hildenbrand 	struct page *page;
967445fcf7cSDavid Hildenbrand 
968e83a437fSDavid Hildenbrand 	if (!auto_movable_ratio)
969e83a437fSDavid Hildenbrand 		goto kernel_zone;
970e83a437fSDavid Hildenbrand 
971445fcf7cSDavid Hildenbrand 	if (group && !group->is_dynamic) {
972445fcf7cSDavid Hildenbrand 		max_pages = group->s.max_pages;
973445fcf7cSDavid Hildenbrand 		online_pages = group->present_movable_pages;
974445fcf7cSDavid Hildenbrand 
975445fcf7cSDavid Hildenbrand 		/* If anything is !MOVABLE online the rest !MOVABLE. */
976445fcf7cSDavid Hildenbrand 		if (group->present_kernel_pages)
977445fcf7cSDavid Hildenbrand 			goto kernel_zone;
978445fcf7cSDavid Hildenbrand 	} else if (!group || group->d.unit_pages == nr_pages) {
979445fcf7cSDavid Hildenbrand 		max_pages = nr_pages;
980445fcf7cSDavid Hildenbrand 	} else {
981445fcf7cSDavid Hildenbrand 		max_pages = group->d.unit_pages;
982445fcf7cSDavid Hildenbrand 		/*
983445fcf7cSDavid Hildenbrand 		 * Take a look at all online sections in the current unit.
984445fcf7cSDavid Hildenbrand 		 * We can safely assume that all pages within a section belong
985445fcf7cSDavid Hildenbrand 		 * to the same zone, because dynamic memory groups only deal
986445fcf7cSDavid Hildenbrand 		 * with hotplugged memory.
987445fcf7cSDavid Hildenbrand 		 */
988445fcf7cSDavid Hildenbrand 		pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
989445fcf7cSDavid Hildenbrand 		end_pfn = pfn + group->d.unit_pages;
990445fcf7cSDavid Hildenbrand 		for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
991445fcf7cSDavid Hildenbrand 			page = pfn_to_online_page(pfn);
992445fcf7cSDavid Hildenbrand 			if (!page)
993445fcf7cSDavid Hildenbrand 				continue;
994445fcf7cSDavid Hildenbrand 			/* If anything is !MOVABLE online the rest !MOVABLE. */
99507252dfeSKefeng Wang 			if (!is_zone_movable_page(page))
996445fcf7cSDavid Hildenbrand 				goto kernel_zone;
997445fcf7cSDavid Hildenbrand 			online_pages += PAGES_PER_SECTION;
998445fcf7cSDavid Hildenbrand 		}
999445fcf7cSDavid Hildenbrand 	}
1000445fcf7cSDavid Hildenbrand 
1001445fcf7cSDavid Hildenbrand 	/*
1002445fcf7cSDavid Hildenbrand 	 * Online MOVABLE if we could *currently* online all remaining parts
1003445fcf7cSDavid Hildenbrand 	 * MOVABLE. We expect to (add+) online them immediately next, so if
1004445fcf7cSDavid Hildenbrand 	 * nobody interferes, all will be MOVABLE if possible.
1005445fcf7cSDavid Hildenbrand 	 */
1006445fcf7cSDavid Hildenbrand 	nr_pages = max_pages - online_pages;
10073fcebf90SDavid Hildenbrand 	if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
1008e83a437fSDavid Hildenbrand 		goto kernel_zone;
1009e83a437fSDavid Hildenbrand 
1010e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
1011e83a437fSDavid Hildenbrand 	if (auto_movable_numa_aware &&
10123fcebf90SDavid Hildenbrand 	    !auto_movable_can_online_movable(nid, group, nr_pages))
1013e83a437fSDavid Hildenbrand 		goto kernel_zone;
1014e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
1015e83a437fSDavid Hildenbrand 
1016e83a437fSDavid Hildenbrand 	return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1017e83a437fSDavid Hildenbrand kernel_zone:
1018e83a437fSDavid Hildenbrand 	return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
1019e83a437fSDavid Hildenbrand }
1020e83a437fSDavid Hildenbrand 
1021c6f03e29SMichal Hocko static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
1022c6f03e29SMichal Hocko 		unsigned long nr_pages)
1023e5e68930SMichal Hocko {
1024c6f03e29SMichal Hocko 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
1025c6f03e29SMichal Hocko 			nr_pages);
1026c6f03e29SMichal Hocko 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1027c6f03e29SMichal Hocko 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
1028c6f03e29SMichal Hocko 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
1029e5e68930SMichal Hocko 
1030e5e68930SMichal Hocko 	/*
1031c6f03e29SMichal Hocko 	 * We inherit the existing zone in a simple case where zones do not
1032c6f03e29SMichal Hocko 	 * overlap in the given range
1033e5e68930SMichal Hocko 	 */
1034c6f03e29SMichal Hocko 	if (in_kernel ^ in_movable)
1035c6f03e29SMichal Hocko 		return (in_kernel) ? kernel_zone : movable_zone;
1036e5e68930SMichal Hocko 
1037c6f03e29SMichal Hocko 	/*
1038c6f03e29SMichal Hocko 	 * If the range doesn't belong to any zone or two zones overlap in the
1039c6f03e29SMichal Hocko 	 * given range then we use movable zone only if movable_node is
1040c6f03e29SMichal Hocko 	 * enabled because we always online to a kernel zone by default.
1041c6f03e29SMichal Hocko 	 */
1042c6f03e29SMichal Hocko 	return movable_node_enabled ? movable_zone : kernel_zone;
10439f123ab5SMichal Hocko }
10449f123ab5SMichal Hocko 
10457cf209baSDavid Hildenbrand struct zone *zone_for_pfn_range(int online_type, int nid,
1046445fcf7cSDavid Hildenbrand 		struct memory_group *group, unsigned long start_pfn,
1047e5e68930SMichal Hocko 		unsigned long nr_pages)
1048f1dd2cd1SMichal Hocko {
1049c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_KERNEL)
1050c6f03e29SMichal Hocko 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
1051f1dd2cd1SMichal Hocko 
1052c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_MOVABLE)
1053c6f03e29SMichal Hocko 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1054f1dd2cd1SMichal Hocko 
1055e83a437fSDavid Hildenbrand 	if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
1056445fcf7cSDavid Hildenbrand 		return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
1057e83a437fSDavid Hildenbrand 
1058c6f03e29SMichal Hocko 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
1059e5e68930SMichal Hocko }
1060e5e68930SMichal Hocko 
1061a08a2ae3SOscar Salvador /*
1062a08a2ae3SOscar Salvador  * This function should only be called by memory_block_{online,offline},
1063a08a2ae3SOscar Salvador  * and {online,offline}_pages.
1064a08a2ae3SOscar Salvador  */
1065836809ecSDavid Hildenbrand void adjust_present_page_count(struct page *page, struct memory_group *group,
1066836809ecSDavid Hildenbrand 			       long nr_pages)
1067f9901144SDavid Hildenbrand {
10684b097002SDavid Hildenbrand 	struct zone *zone = page_zone(page);
1069836809ecSDavid Hildenbrand 	const bool movable = zone_idx(zone) == ZONE_MOVABLE;
10704b097002SDavid Hildenbrand 
10714b097002SDavid Hildenbrand 	/*
10724b097002SDavid Hildenbrand 	 * We only support onlining/offlining/adding/removing of complete
10734b097002SDavid Hildenbrand 	 * memory blocks; therefore, either all is either early or hotplugged.
10744b097002SDavid Hildenbrand 	 */
10754b097002SDavid Hildenbrand 	if (early_section(__pfn_to_section(page_to_pfn(page))))
10764b097002SDavid Hildenbrand 		zone->present_early_pages += nr_pages;
1077f9901144SDavid Hildenbrand 	zone->present_pages += nr_pages;
1078f9901144SDavid Hildenbrand 	zone->zone_pgdat->node_present_pages += nr_pages;
1079836809ecSDavid Hildenbrand 
1080836809ecSDavid Hildenbrand 	if (group && movable)
1081836809ecSDavid Hildenbrand 		group->present_movable_pages += nr_pages;
1082836809ecSDavid Hildenbrand 	else if (group && !movable)
1083836809ecSDavid Hildenbrand 		group->present_kernel_pages += nr_pages;
1084f9901144SDavid Hildenbrand }
1085f9901144SDavid Hildenbrand 
1086a08a2ae3SOscar Salvador int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
1087a08a2ae3SOscar Salvador 			      struct zone *zone)
1088a08a2ae3SOscar Salvador {
1089a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
109066361095SMuchun Song 	int ret, i;
1091a08a2ae3SOscar Salvador 
1092a08a2ae3SOscar Salvador 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1093a08a2ae3SOscar Salvador 	if (ret)
1094a08a2ae3SOscar Salvador 		return ret;
1095a08a2ae3SOscar Salvador 
1096a08a2ae3SOscar Salvador 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE);
1097a08a2ae3SOscar Salvador 
109866361095SMuchun Song 	for (i = 0; i < nr_pages; i++)
109966361095SMuchun Song 		SetPageVmemmapSelfHosted(pfn_to_page(pfn + i));
110066361095SMuchun Song 
1101a08a2ae3SOscar Salvador 	/*
1102a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1103a08a2ae3SOscar Salvador 	 * the case, mark those sections online here as otherwise they will be
1104a08a2ae3SOscar Salvador 	 * left offline.
1105a08a2ae3SOscar Salvador 	 */
1106a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1107a08a2ae3SOscar Salvador 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1108a08a2ae3SOscar Salvador 
1109a08a2ae3SOscar Salvador 	return ret;
1110a08a2ae3SOscar Salvador }
1111a08a2ae3SOscar Salvador 
1112a08a2ae3SOscar Salvador void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
1113a08a2ae3SOscar Salvador {
1114a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
1115a08a2ae3SOscar Salvador 
1116a08a2ae3SOscar Salvador 	/*
1117a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1118a08a2ae3SOscar Salvador 	 * the case, mark those sections offline here as otherwise they will be
1119a08a2ae3SOscar Salvador 	 * left online.
1120a08a2ae3SOscar Salvador 	 */
1121a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1122a08a2ae3SOscar Salvador 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1123a08a2ae3SOscar Salvador 
1124a08a2ae3SOscar Salvador         /*
1125a08a2ae3SOscar Salvador 	 * The pages associated with this vmemmap have been offlined, so
1126a08a2ae3SOscar Salvador 	 * we can reset its state here.
1127a08a2ae3SOscar Salvador 	 */
1128a08a2ae3SOscar Salvador 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
1129a08a2ae3SOscar Salvador 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1130a08a2ae3SOscar Salvador }
1131a08a2ae3SOscar Salvador 
1132*e0270ffaSSumanth Korikkar /*
1133*e0270ffaSSumanth Korikkar  * Must be called with mem_hotplug_lock in write mode.
1134*e0270ffaSSumanth Korikkar  */
1135836809ecSDavid Hildenbrand int __ref online_pages(unsigned long pfn, unsigned long nr_pages,
1136836809ecSDavid Hildenbrand 		       struct zone *zone, struct memory_group *group)
113775884fb1SKAMEZAWA Hiroyuki {
1138aa47228aSCody P Schafer 	unsigned long flags;
11396811378eSYasunori Goto 	int need_zonelists_rebuild = 0;
1140a08a2ae3SOscar Salvador 	const int nid = zone_to_nid(zone);
11417b78d335SYasunori Goto 	int ret;
11427b78d335SYasunori Goto 	struct memory_notify arg;
11433947be19SDave Hansen 
1144dd8e2f23SOscar Salvador 	/*
1145dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1146041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1147dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1148dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1149dd8e2f23SOscar Salvador 	 * aligned.
1150dd8e2f23SOscar Salvador 	 */
1151ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
1152dd8e2f23SOscar Salvador 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
11534986fac1SDavid Hildenbrand 		return -EINVAL;
11544986fac1SDavid Hildenbrand 
1155381eab4aSDavid Hildenbrand 
1156f1dd2cd1SMichal Hocko 	/* associate pfn range with the zone */
1157b30c5927SDavid Hildenbrand 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_ISOLATE);
1158511c2abaSLai Jiangshan 
11597b78d335SYasunori Goto 	arg.start_pfn = pfn;
11607b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1161d9713679SLai Jiangshan 	node_states_check_changes_online(nr_pages, zone, &arg);
11627b78d335SYasunori Goto 
11637b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_ONLINE, &arg);
11647b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
1165e33e33b4SChen Yucong 	if (ret)
1166e33e33b4SChen Yucong 		goto failed_addition;
1167e33e33b4SChen Yucong 
11683947be19SDave Hansen 	/*
1169b30c5927SDavid Hildenbrand 	 * Fixup the number of isolated pageblocks before marking the sections
1170b30c5927SDavid Hildenbrand 	 * onlining, such that undo_isolate_page_range() works correctly.
1171b30c5927SDavid Hildenbrand 	 */
1172b30c5927SDavid Hildenbrand 	spin_lock_irqsave(&zone->lock, flags);
1173b30c5927SDavid Hildenbrand 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
1174b30c5927SDavid Hildenbrand 	spin_unlock_irqrestore(&zone->lock, flags);
1175b30c5927SDavid Hildenbrand 
1176b30c5927SDavid Hildenbrand 	/*
11776811378eSYasunori Goto 	 * If this zone is not populated, then it is not in zonelist.
11786811378eSYasunori Goto 	 * This means the page allocator ignores this zone.
11796811378eSYasunori Goto 	 * So, zonelist must be updated after online.
11806811378eSYasunori Goto 	 */
11816dcd73d7SWen Congyang 	if (!populated_zone(zone)) {
11826811378eSYasunori Goto 		need_zonelists_rebuild = 1;
118372675e13SMichal Hocko 		setup_zone_pageset(zone);
11846dcd73d7SWen Congyang 	}
11856811378eSYasunori Goto 
1186aac65321SDavid Hildenbrand 	online_pages_range(pfn, nr_pages);
1187836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
1188aa47228aSCody P Schafer 
1189b30c5927SDavid Hildenbrand 	node_states_set_node(nid, &arg);
1190b30c5927SDavid Hildenbrand 	if (need_zonelists_rebuild)
1191b30c5927SDavid Hildenbrand 		build_all_zonelists(NULL);
1192b30c5927SDavid Hildenbrand 
1193b30c5927SDavid Hildenbrand 	/* Basic onlining is complete, allow allocation of onlined pages. */
1194b30c5927SDavid Hildenbrand 	undo_isolate_page_range(pfn, pfn + nr_pages, MIGRATE_MOVABLE);
1195b30c5927SDavid Hildenbrand 
119693146d98SDavid Hildenbrand 	/*
1197b86c5fc4SDavid Hildenbrand 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
1198b86c5fc4SDavid Hildenbrand 	 * the tail of the freelist when undoing isolation). Shuffle the whole
1199b86c5fc4SDavid Hildenbrand 	 * zone to make sure the just onlined pages are properly distributed
1200b86c5fc4SDavid Hildenbrand 	 * across the whole freelist - to create an initial shuffle.
120193146d98SDavid Hildenbrand 	 */
1202e900a918SDan Williams 	shuffle_zone(zone);
1203e900a918SDan Williams 
1204b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
12051b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
12061b79acc9SKOSAKI Motohiro 
1207e888ca35SVlastimil Babka 	kswapd_run(nid);
1208698b1b30SVlastimil Babka 	kcompactd_run(nid);
120961b13993SDave Hansen 
12102d1d43f6SChandra Seetharaman 	writeback_set_ratelimit();
12117b78d335SYasunori Goto 
12127b78d335SYasunori Goto 	memory_notify(MEM_ONLINE, &arg);
121330467e0bSDavid Rientjes 	return 0;
1214e33e33b4SChen Yucong 
1215e33e33b4SChen Yucong failed_addition:
1216e33e33b4SChen Yucong 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1217e33e33b4SChen Yucong 		 (unsigned long long) pfn << PAGE_SHIFT,
1218e33e33b4SChen Yucong 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1219e33e33b4SChen Yucong 	memory_notify(MEM_CANCEL_ONLINE, &arg);
1220feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
1221e33e33b4SChen Yucong 	return ret;
12223947be19SDave Hansen }
1223bc02af93SYasunori Goto 
1224e1319331SHidetoshi Seto /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
122509f49dcaSMichal Hocko static pg_data_t __ref *hotadd_init_pgdat(int nid)
12269af3c2deSYasunori Goto {
12279af3c2deSYasunori Goto 	struct pglist_data *pgdat;
12289af3c2deSYasunori Goto 
122909f49dcaSMichal Hocko 	/*
123009f49dcaSMichal Hocko 	 * NODE_DATA is preallocated (free_area_init) but its internal
123109f49dcaSMichal Hocko 	 * state is not allocated completely. Add missing pieces.
123209f49dcaSMichal Hocko 	 * Completely offline nodes stay around and they just need
123309f49dcaSMichal Hocko 	 * reintialization.
123409f49dcaSMichal Hocko 	 */
123570b5b46aSMichal Hocko 	pgdat = NODE_DATA(nid);
123603e85f9dSOscar Salvador 
12379af3c2deSYasunori Goto 	/* init node's zones as empty zones, we don't have any present pages.*/
123870b5b46aSMichal Hocko 	free_area_init_core_hotplug(pgdat);
12399af3c2deSYasunori Goto 
1240959ecc48SKAMEZAWA Hiroyuki 	/*
1241959ecc48SKAMEZAWA Hiroyuki 	 * The node we allocated has no zone fallback lists. For avoiding
1242959ecc48SKAMEZAWA Hiroyuki 	 * to access not-initialized zonelist, build here.
1243959ecc48SKAMEZAWA Hiroyuki 	 */
124472675e13SMichal Hocko 	build_all_zonelists(pgdat);
1245959ecc48SKAMEZAWA Hiroyuki 
12469af3c2deSYasunori Goto 	return pgdat;
12479af3c2deSYasunori Goto }
12489af3c2deSYasunori Goto 
1249ba2d2666SMel Gorman /*
1250ba2d2666SMel Gorman  * __try_online_node - online a node if offlined
1251e8b098fcSMike Rapoport  * @nid: the node ID
1252b9ff0360SOscar Salvador  * @set_node_online: Whether we want to online the node
1253cf23422bSminskey guo  * called by cpu_up() to online a node without onlined memory.
1254b9ff0360SOscar Salvador  *
1255b9ff0360SOscar Salvador  * Returns:
1256b9ff0360SOscar Salvador  * 1 -> a new node has been allocated
1257b9ff0360SOscar Salvador  * 0 -> the node is already online
1258b9ff0360SOscar Salvador  * -ENOMEM -> the node could not be allocated
1259cf23422bSminskey guo  */
1260c68ab18cSDavid Hildenbrand static int __try_online_node(int nid, bool set_node_online)
1261cf23422bSminskey guo {
1262cf23422bSminskey guo 	pg_data_t *pgdat;
1263b9ff0360SOscar Salvador 	int ret = 1;
1264cf23422bSminskey guo 
126501b0f197SToshi Kani 	if (node_online(nid))
126601b0f197SToshi Kani 		return 0;
126701b0f197SToshi Kani 
126809f49dcaSMichal Hocko 	pgdat = hotadd_init_pgdat(nid);
12697553e8f2SDavid Rientjes 	if (!pgdat) {
127001b0f197SToshi Kani 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1271cf23422bSminskey guo 		ret = -ENOMEM;
1272cf23422bSminskey guo 		goto out;
1273cf23422bSminskey guo 	}
1274b9ff0360SOscar Salvador 
1275b9ff0360SOscar Salvador 	if (set_node_online) {
1276cf23422bSminskey guo 		node_set_online(nid);
1277cf23422bSminskey guo 		ret = register_one_node(nid);
1278cf23422bSminskey guo 		BUG_ON(ret);
1279b9ff0360SOscar Salvador 	}
1280cf23422bSminskey guo out:
1281b9ff0360SOscar Salvador 	return ret;
1282b9ff0360SOscar Salvador }
1283b9ff0360SOscar Salvador 
1284b9ff0360SOscar Salvador /*
1285b9ff0360SOscar Salvador  * Users of this function always want to online/register the node
1286b9ff0360SOscar Salvador  */
1287b9ff0360SOscar Salvador int try_online_node(int nid)
1288b9ff0360SOscar Salvador {
1289b9ff0360SOscar Salvador 	int ret;
1290b9ff0360SOscar Salvador 
1291b9ff0360SOscar Salvador 	mem_hotplug_begin();
1292c68ab18cSDavid Hildenbrand 	ret =  __try_online_node(nid, true);
1293bfc8c901SVladimir Davydov 	mem_hotplug_done();
1294cf23422bSminskey guo 	return ret;
1295cf23422bSminskey guo }
1296cf23422bSminskey guo 
129727356f54SToshi Kani static int check_hotplug_memory_range(u64 start, u64 size)
129827356f54SToshi Kani {
1299ba325585SPavel Tatashin 	/* memory range must be block size aligned */
1300cec3ebd0SDavid Hildenbrand 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1301cec3ebd0SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1302ba325585SPavel Tatashin 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1303cec3ebd0SDavid Hildenbrand 		       memory_block_size_bytes(), start, size);
130427356f54SToshi Kani 		return -EINVAL;
130527356f54SToshi Kani 	}
130627356f54SToshi Kani 
130727356f54SToshi Kani 	return 0;
130827356f54SToshi Kani }
130927356f54SToshi Kani 
131031bc3858SVitaly Kuznetsov static int online_memory_block(struct memory_block *mem, void *arg)
131131bc3858SVitaly Kuznetsov {
13121adf8b46SAnshuman Khandual 	mem->online_type = mhp_default_online_type;
1313dc18d706SNathan Fontenot 	return device_online(&mem->dev);
131431bc3858SVitaly Kuznetsov }
131531bc3858SVitaly Kuznetsov 
131685a2b4b0SAneesh Kumar K.V #ifndef arch_supports_memmap_on_memory
131785a2b4b0SAneesh Kumar K.V static inline bool arch_supports_memmap_on_memory(unsigned long vmemmap_size)
131885a2b4b0SAneesh Kumar K.V {
131985a2b4b0SAneesh Kumar K.V 	/*
132085a2b4b0SAneesh Kumar K.V 	 * As default, we want the vmemmap to span a complete PMD such that we
132185a2b4b0SAneesh Kumar K.V 	 * can map the vmemmap using a single PMD if supported by the
132285a2b4b0SAneesh Kumar K.V 	 * architecture.
132385a2b4b0SAneesh Kumar K.V 	 */
132485a2b4b0SAneesh Kumar K.V 	return IS_ALIGNED(vmemmap_size, PMD_SIZE);
132585a2b4b0SAneesh Kumar K.V }
132685a2b4b0SAneesh Kumar K.V #endif
132785a2b4b0SAneesh Kumar K.V 
1328e3c2bfddSAneesh Kumar K.V static bool mhp_supports_memmap_on_memory(unsigned long size)
1329a08a2ae3SOscar Salvador {
133085a2b4b0SAneesh Kumar K.V 	unsigned long vmemmap_size = memory_block_memmap_size();
13312d1f649cSAneesh Kumar K.V 	unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
1332a08a2ae3SOscar Salvador 
1333a08a2ae3SOscar Salvador 	/*
1334a08a2ae3SOscar Salvador 	 * Besides having arch support and the feature enabled at runtime, we
1335a08a2ae3SOscar Salvador 	 * need a few more assumptions to hold true:
1336a08a2ae3SOscar Salvador 	 *
1337a08a2ae3SOscar Salvador 	 * a) We span a single memory block: memory onlining/offlinin;g happens
1338a08a2ae3SOscar Salvador 	 *    in memory block granularity. We don't want the vmemmap of online
1339a08a2ae3SOscar Salvador 	 *    memory blocks to reside on offline memory blocks. In the future,
1340a08a2ae3SOscar Salvador 	 *    we might want to support variable-sized memory blocks to make the
1341a08a2ae3SOscar Salvador 	 *    feature more versatile.
1342a08a2ae3SOscar Salvador 	 *
1343a08a2ae3SOscar Salvador 	 * b) The vmemmap pages span complete PMDs: We don't want vmemmap code
1344a08a2ae3SOscar Salvador 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1345a08a2ae3SOscar Salvador 	 *    other memory blocks)
1346a08a2ae3SOscar Salvador 	 *
1347a08a2ae3SOscar Salvador 	 * c) The vmemmap pages (and thereby the pages that will be exposed to
1348a08a2ae3SOscar Salvador 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1349a08a2ae3SOscar Salvador 	 *    code requires applicable ranges to be page-aligned, for example, to
1350a08a2ae3SOscar Salvador 	 *    set the migratetypes properly.
1351a08a2ae3SOscar Salvador 	 *
1352a08a2ae3SOscar Salvador 	 * TODO: Although we have a check here to make sure that vmemmap pages
1353a08a2ae3SOscar Salvador 	 *       fully populate a PMD, it is not the right place to check for
1354a08a2ae3SOscar Salvador 	 *       this. A much better solution involves improving vmemmap code
1355a08a2ae3SOscar Salvador 	 *       to fallback to base pages when trying to populate vmemmap using
1356a08a2ae3SOscar Salvador 	 *       altmap as an alternative source of memory, and we do not exactly
1357a08a2ae3SOscar Salvador 	 *       populate a single PMD.
1358a08a2ae3SOscar Salvador 	 */
13592d1f649cSAneesh Kumar K.V 	if (!mhp_memmap_on_memory() || size != memory_block_size_bytes())
13602d1f649cSAneesh Kumar K.V 		return false;
13612d1f649cSAneesh Kumar K.V 
13622d1f649cSAneesh Kumar K.V 	/*
13632d1f649cSAneesh Kumar K.V 	 * Make sure the vmemmap allocation is fully contained
13642d1f649cSAneesh Kumar K.V 	 * so that we always allocate vmemmap memory from altmap area.
13652d1f649cSAneesh Kumar K.V 	 */
13662d1f649cSAneesh Kumar K.V 	if (!IS_ALIGNED(vmemmap_size, PAGE_SIZE))
13672d1f649cSAneesh Kumar K.V 		return false;
13682d1f649cSAneesh Kumar K.V 
13692d1f649cSAneesh Kumar K.V 	/*
13702d1f649cSAneesh Kumar K.V 	 * start pfn should be pageblock_nr_pages aligned for correctly
13712d1f649cSAneesh Kumar K.V 	 * setting migrate types
13722d1f649cSAneesh Kumar K.V 	 */
13732d1f649cSAneesh Kumar K.V 	if (!pageblock_aligned(memmap_pages))
13742d1f649cSAneesh Kumar K.V 		return false;
13752d1f649cSAneesh Kumar K.V 
13762d1f649cSAneesh Kumar K.V 	if (memmap_pages == PHYS_PFN(memory_block_size_bytes()))
13772d1f649cSAneesh Kumar K.V 		/* No effective hotplugged memory doesn't make sense. */
13782d1f649cSAneesh Kumar K.V 		return false;
13792d1f649cSAneesh Kumar K.V 
13802d1f649cSAneesh Kumar K.V 	return arch_supports_memmap_on_memory(vmemmap_size);
1381a08a2ae3SOscar Salvador }
1382a08a2ae3SOscar Salvador 
13838df1d0e4SDavid Hildenbrand /*
13848df1d0e4SDavid Hildenbrand  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
13858df1d0e4SDavid Hildenbrand  * and online/offline operations (triggered e.g. by sysfs).
13868df1d0e4SDavid Hildenbrand  *
13878df1d0e4SDavid Hildenbrand  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
13888df1d0e4SDavid Hildenbrand  */
1389b6117199SDavid Hildenbrand int __ref add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1390bc02af93SYasunori Goto {
1391d15dfd31SCatalin Marinas 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
139232befe9eSDavid Hildenbrand 	enum memblock_flags memblock_flags = MEMBLOCK_NONE;
13932d1f649cSAneesh Kumar K.V 	struct vmem_altmap mhp_altmap = {
13942d1f649cSAneesh Kumar K.V 		.base_pfn =  PHYS_PFN(res->start),
13952d1f649cSAneesh Kumar K.V 		.end_pfn  =  PHYS_PFN(res->end),
13962d1f649cSAneesh Kumar K.V 	};
1397028fc57aSDavid Hildenbrand 	struct memory_group *group = NULL;
139862cedb9fSDavid Vrabel 	u64 start, size;
1399b9ff0360SOscar Salvador 	bool new_node = false;
1400bc02af93SYasunori Goto 	int ret;
1401bc02af93SYasunori Goto 
140262cedb9fSDavid Vrabel 	start = res->start;
140362cedb9fSDavid Vrabel 	size = resource_size(res);
140462cedb9fSDavid Vrabel 
140527356f54SToshi Kani 	ret = check_hotplug_memory_range(start, size);
140627356f54SToshi Kani 	if (ret)
140727356f54SToshi Kani 		return ret;
140827356f54SToshi Kani 
1409028fc57aSDavid Hildenbrand 	if (mhp_flags & MHP_NID_IS_MGID) {
1410028fc57aSDavid Hildenbrand 		group = memory_group_find_by_id(nid);
1411028fc57aSDavid Hildenbrand 		if (!group)
1412028fc57aSDavid Hildenbrand 			return -EINVAL;
1413028fc57aSDavid Hildenbrand 		nid = group->nid;
1414028fc57aSDavid Hildenbrand 	}
1415028fc57aSDavid Hildenbrand 
1416fa6d9ec7SVishal Verma 	if (!node_possible(nid)) {
1417fa6d9ec7SVishal Verma 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1418fa6d9ec7SVishal Verma 		return -EINVAL;
1419fa6d9ec7SVishal Verma 	}
1420fa6d9ec7SVishal Verma 
1421bfc8c901SVladimir Davydov 	mem_hotplug_begin();
1422ac13c462SNathan Zimmer 
142353d38316SDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
142432befe9eSDavid Hildenbrand 		if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
142532befe9eSDavid Hildenbrand 			memblock_flags = MEMBLOCK_DRIVER_MANAGED;
142632befe9eSDavid Hildenbrand 		ret = memblock_add_node(start, size, nid, memblock_flags);
142753d38316SDavid Hildenbrand 		if (ret)
142853d38316SDavid Hildenbrand 			goto error_mem_hotplug_end;
142953d38316SDavid Hildenbrand 	}
14307f36e3e5STang Chen 
1431c68ab18cSDavid Hildenbrand 	ret = __try_online_node(nid, false);
1432b9ff0360SOscar Salvador 	if (ret < 0)
143341b9e2d7SWen Congyang 		goto error;
1434b9ff0360SOscar Salvador 	new_node = ret;
14359af3c2deSYasunori Goto 
1436a08a2ae3SOscar Salvador 	/*
1437a08a2ae3SOscar Salvador 	 * Self hosted memmap array
1438a08a2ae3SOscar Salvador 	 */
1439a08a2ae3SOscar Salvador 	if (mhp_flags & MHP_MEMMAP_ON_MEMORY) {
1440e3c2bfddSAneesh Kumar K.V 		if (mhp_supports_memmap_on_memory(size)) {
14412d1f649cSAneesh Kumar K.V 			mhp_altmap.free = memory_block_memmap_on_memory_pages();
14421a8c64e1SAneesh Kumar K.V 			params.altmap = kmalloc(sizeof(struct vmem_altmap), GFP_KERNEL);
14431a8c64e1SAneesh Kumar K.V 			if (!params.altmap) {
14441a8c64e1SAneesh Kumar K.V 				ret = -ENOMEM;
14451a8c64e1SAneesh Kumar K.V 				goto error;
14461a8c64e1SAneesh Kumar K.V 			}
14471a8c64e1SAneesh Kumar K.V 
14481a8c64e1SAneesh Kumar K.V 			memcpy(params.altmap, &mhp_altmap, sizeof(mhp_altmap));
1449a08a2ae3SOscar Salvador 		}
1450e3c2bfddSAneesh Kumar K.V 		/* fallback to not using altmap  */
1451e3c2bfddSAneesh Kumar K.V 	}
1452a08a2ae3SOscar Salvador 
1453bc02af93SYasunori Goto 	/* call arch's memory hotadd */
1454f5637d3bSLogan Gunthorpe 	ret = arch_add_memory(nid, start, size, &params);
14559af3c2deSYasunori Goto 	if (ret < 0)
14561a8c64e1SAneesh Kumar K.V 		goto error_free;
14579af3c2deSYasunori Goto 
1458db051a0dSDavid Hildenbrand 	/* create memory block devices after memory was added */
14591a8c64e1SAneesh Kumar K.V 	ret = create_memory_block_devices(start, size, params.altmap, group);
1460db051a0dSDavid Hildenbrand 	if (ret) {
146165a2aa5fSDavid Hildenbrand 		arch_remove_memory(start, size, NULL);
14621a8c64e1SAneesh Kumar K.V 		goto error_free;
1463db051a0dSDavid Hildenbrand 	}
1464db051a0dSDavid Hildenbrand 
1465a1e565aaSTang Chen 	if (new_node) {
1466d5b6f6a3SOscar Salvador 		/* If sysfs file of new node can't be created, cpu on the node
14670fc44159SYasunori Goto 		 * can't be hot-added. There is no rollback way now.
14680fc44159SYasunori Goto 		 * So, check by BUG_ON() to catch it reluctantly..
1469d5b6f6a3SOscar Salvador 		 * We online node here. We can't roll back from here.
14700fc44159SYasunori Goto 		 */
1471d5b6f6a3SOscar Salvador 		node_set_online(nid);
1472d5b6f6a3SOscar Salvador 		ret = __register_one_node(nid);
14730fc44159SYasunori Goto 		BUG_ON(ret);
14740fc44159SYasunori Goto 	}
14750fc44159SYasunori Goto 
1476cc651559SDavid Hildenbrand 	register_memory_blocks_under_node(nid, PFN_DOWN(start),
1477cc651559SDavid Hildenbrand 					  PFN_UP(start + size - 1),
1478f85086f9SLaurent Dufour 					  MEMINIT_HOTPLUG);
1479d5b6f6a3SOscar Salvador 
1480d96ae530Sakpm@linux-foundation.org 	/* create new memmap entry */
14817b7b2721SDavid Hildenbrand 	if (!strcmp(res->name, "System RAM"))
1482d96ae530Sakpm@linux-foundation.org 		firmware_map_add_hotplug(start, start + size, "System RAM");
1483d96ae530Sakpm@linux-foundation.org 
1484381eab4aSDavid Hildenbrand 	/* device_online() will take the lock when calling online_pages() */
1485381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1486381eab4aSDavid Hildenbrand 
14879ca6551eSDavid Hildenbrand 	/*
14889ca6551eSDavid Hildenbrand 	 * In case we're allowed to merge the resource, flag it and trigger
14899ca6551eSDavid Hildenbrand 	 * merging now that adding succeeded.
14909ca6551eSDavid Hildenbrand 	 */
149126011267SDavid Hildenbrand 	if (mhp_flags & MHP_MERGE_RESOURCE)
14929ca6551eSDavid Hildenbrand 		merge_system_ram_resource(res);
14939ca6551eSDavid Hildenbrand 
149431bc3858SVitaly Kuznetsov 	/* online pages if requested */
14951adf8b46SAnshuman Khandual 	if (mhp_default_online_type != MMOP_OFFLINE)
1496fbcf73ceSDavid Hildenbrand 		walk_memory_blocks(start, size, NULL, online_memory_block);
149731bc3858SVitaly Kuznetsov 
1498381eab4aSDavid Hildenbrand 	return ret;
14991a8c64e1SAneesh Kumar K.V error_free:
15001a8c64e1SAneesh Kumar K.V 	kfree(params.altmap);
15019af3c2deSYasunori Goto error:
150252219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
15037f36e3e5STang Chen 		memblock_remove(start, size);
150453d38316SDavid Hildenbrand error_mem_hotplug_end:
1505bfc8c901SVladimir Davydov 	mem_hotplug_done();
1506bc02af93SYasunori Goto 	return ret;
1507bc02af93SYasunori Goto }
150862cedb9fSDavid Vrabel 
15098df1d0e4SDavid Hildenbrand /* requires device_hotplug_lock, see add_memory_resource() */
1510b6117199SDavid Hildenbrand int __ref __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
151162cedb9fSDavid Vrabel {
151262cedb9fSDavid Vrabel 	struct resource *res;
151362cedb9fSDavid Vrabel 	int ret;
151462cedb9fSDavid Vrabel 
15157b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, "System RAM");
15166f754ba4SVitaly Kuznetsov 	if (IS_ERR(res))
15176f754ba4SVitaly Kuznetsov 		return PTR_ERR(res);
151862cedb9fSDavid Vrabel 
1519b6117199SDavid Hildenbrand 	ret = add_memory_resource(nid, res, mhp_flags);
152062cedb9fSDavid Vrabel 	if (ret < 0)
152162cedb9fSDavid Vrabel 		release_memory_resource(res);
152262cedb9fSDavid Vrabel 	return ret;
152362cedb9fSDavid Vrabel }
15248df1d0e4SDavid Hildenbrand 
1525b6117199SDavid Hildenbrand int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
15268df1d0e4SDavid Hildenbrand {
15278df1d0e4SDavid Hildenbrand 	int rc;
15288df1d0e4SDavid Hildenbrand 
15298df1d0e4SDavid Hildenbrand 	lock_device_hotplug();
1530b6117199SDavid Hildenbrand 	rc = __add_memory(nid, start, size, mhp_flags);
15318df1d0e4SDavid Hildenbrand 	unlock_device_hotplug();
15328df1d0e4SDavid Hildenbrand 
15338df1d0e4SDavid Hildenbrand 	return rc;
15348df1d0e4SDavid Hildenbrand }
1535bc02af93SYasunori Goto EXPORT_SYMBOL_GPL(add_memory);
15360c0e6195SKAMEZAWA Hiroyuki 
15377b7b2721SDavid Hildenbrand /*
15387b7b2721SDavid Hildenbrand  * Add special, driver-managed memory to the system as system RAM. Such
15397b7b2721SDavid Hildenbrand  * memory is not exposed via the raw firmware-provided memmap as system
15407b7b2721SDavid Hildenbrand  * RAM, instead, it is detected and added by a driver - during cold boot,
15417b7b2721SDavid Hildenbrand  * after a reboot, and after kexec.
15427b7b2721SDavid Hildenbrand  *
15437b7b2721SDavid Hildenbrand  * Reasons why this memory should not be used for the initial memmap of a
15447b7b2721SDavid Hildenbrand  * kexec kernel or for placing kexec images:
15457b7b2721SDavid Hildenbrand  * - The booting kernel is in charge of determining how this memory will be
15467b7b2721SDavid Hildenbrand  *   used (e.g., use persistent memory as system RAM)
15477b7b2721SDavid Hildenbrand  * - Coordination with a hypervisor is required before this memory
15487b7b2721SDavid Hildenbrand  *   can be used (e.g., inaccessible parts).
15497b7b2721SDavid Hildenbrand  *
15507b7b2721SDavid Hildenbrand  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
15517b7b2721SDavid Hildenbrand  * memory map") are created. Also, the created memory resource is flagged
15527cf603d1SDavid Hildenbrand  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
15537b7b2721SDavid Hildenbrand  * this memory as well (esp., not place kexec images onto it).
15547b7b2721SDavid Hildenbrand  *
15557b7b2721SDavid Hildenbrand  * The resource_name (visible via /proc/iomem) has to have the format
15567b7b2721SDavid Hildenbrand  * "System RAM ($DRIVER)".
15577b7b2721SDavid Hildenbrand  */
15587b7b2721SDavid Hildenbrand int add_memory_driver_managed(int nid, u64 start, u64 size,
1559b6117199SDavid Hildenbrand 			      const char *resource_name, mhp_t mhp_flags)
15607b7b2721SDavid Hildenbrand {
15617b7b2721SDavid Hildenbrand 	struct resource *res;
15627b7b2721SDavid Hildenbrand 	int rc;
15637b7b2721SDavid Hildenbrand 
15647b7b2721SDavid Hildenbrand 	if (!resource_name ||
15657b7b2721SDavid Hildenbrand 	    strstr(resource_name, "System RAM (") != resource_name ||
15667b7b2721SDavid Hildenbrand 	    resource_name[strlen(resource_name) - 1] != ')')
15677b7b2721SDavid Hildenbrand 		return -EINVAL;
15687b7b2721SDavid Hildenbrand 
15697b7b2721SDavid Hildenbrand 	lock_device_hotplug();
15707b7b2721SDavid Hildenbrand 
15717b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, resource_name);
15727b7b2721SDavid Hildenbrand 	if (IS_ERR(res)) {
15737b7b2721SDavid Hildenbrand 		rc = PTR_ERR(res);
15747b7b2721SDavid Hildenbrand 		goto out_unlock;
15757b7b2721SDavid Hildenbrand 	}
15767b7b2721SDavid Hildenbrand 
1577b6117199SDavid Hildenbrand 	rc = add_memory_resource(nid, res, mhp_flags);
15787b7b2721SDavid Hildenbrand 	if (rc < 0)
15797b7b2721SDavid Hildenbrand 		release_memory_resource(res);
15807b7b2721SDavid Hildenbrand 
15817b7b2721SDavid Hildenbrand out_unlock:
15827b7b2721SDavid Hildenbrand 	unlock_device_hotplug();
15837b7b2721SDavid Hildenbrand 	return rc;
15847b7b2721SDavid Hildenbrand }
15857b7b2721SDavid Hildenbrand EXPORT_SYMBOL_GPL(add_memory_driver_managed);
15867b7b2721SDavid Hildenbrand 
1587bca3feaaSAnshuman Khandual /*
1588bca3feaaSAnshuman Khandual  * Platforms should define arch_get_mappable_range() that provides
1589bca3feaaSAnshuman Khandual  * maximum possible addressable physical memory range for which the
1590bca3feaaSAnshuman Khandual  * linear mapping could be created. The platform returned address
1591bca3feaaSAnshuman Khandual  * range must adhere to these following semantics.
1592bca3feaaSAnshuman Khandual  *
1593bca3feaaSAnshuman Khandual  * - range.start <= range.end
1594bca3feaaSAnshuman Khandual  * - Range includes both end points [range.start..range.end]
1595bca3feaaSAnshuman Khandual  *
1596bca3feaaSAnshuman Khandual  * There is also a fallback definition provided here, allowing the
1597bca3feaaSAnshuman Khandual  * entire possible physical address range in case any platform does
1598bca3feaaSAnshuman Khandual  * not define arch_get_mappable_range().
1599bca3feaaSAnshuman Khandual  */
1600bca3feaaSAnshuman Khandual struct range __weak arch_get_mappable_range(void)
1601bca3feaaSAnshuman Khandual {
1602bca3feaaSAnshuman Khandual 	struct range mhp_range = {
1603bca3feaaSAnshuman Khandual 		.start = 0UL,
1604bca3feaaSAnshuman Khandual 		.end = -1ULL,
1605bca3feaaSAnshuman Khandual 	};
1606bca3feaaSAnshuman Khandual 	return mhp_range;
1607bca3feaaSAnshuman Khandual }
1608bca3feaaSAnshuman Khandual 
1609bca3feaaSAnshuman Khandual struct range mhp_get_pluggable_range(bool need_mapping)
1610bca3feaaSAnshuman Khandual {
1611bca3feaaSAnshuman Khandual 	const u64 max_phys = (1ULL << MAX_PHYSMEM_BITS) - 1;
1612bca3feaaSAnshuman Khandual 	struct range mhp_range;
1613bca3feaaSAnshuman Khandual 
1614bca3feaaSAnshuman Khandual 	if (need_mapping) {
1615bca3feaaSAnshuman Khandual 		mhp_range = arch_get_mappable_range();
1616bca3feaaSAnshuman Khandual 		if (mhp_range.start > max_phys) {
1617bca3feaaSAnshuman Khandual 			mhp_range.start = 0;
1618bca3feaaSAnshuman Khandual 			mhp_range.end = 0;
1619bca3feaaSAnshuman Khandual 		}
1620bca3feaaSAnshuman Khandual 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1621bca3feaaSAnshuman Khandual 	} else {
1622bca3feaaSAnshuman Khandual 		mhp_range.start = 0;
1623bca3feaaSAnshuman Khandual 		mhp_range.end = max_phys;
1624bca3feaaSAnshuman Khandual 	}
1625bca3feaaSAnshuman Khandual 	return mhp_range;
1626bca3feaaSAnshuman Khandual }
1627bca3feaaSAnshuman Khandual EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1628bca3feaaSAnshuman Khandual 
1629bca3feaaSAnshuman Khandual bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1630bca3feaaSAnshuman Khandual {
1631bca3feaaSAnshuman Khandual 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1632bca3feaaSAnshuman Khandual 	u64 end = start + size;
1633bca3feaaSAnshuman Khandual 
1634bca3feaaSAnshuman Khandual 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1635bca3feaaSAnshuman Khandual 		return true;
1636bca3feaaSAnshuman Khandual 
1637bca3feaaSAnshuman Khandual 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1638bca3feaaSAnshuman Khandual 		start, end, mhp_range.start, mhp_range.end);
1639bca3feaaSAnshuman Khandual 	return false;
1640bca3feaaSAnshuman Khandual }
1641bca3feaaSAnshuman Khandual 
16420c0e6195SKAMEZAWA Hiroyuki #ifdef CONFIG_MEMORY_HOTREMOVE
16430c0e6195SKAMEZAWA Hiroyuki /*
16440efadf48SYisheng Xie  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1645aa218795SDavid Hildenbrand  * non-lru movable pages and hugepages). Will skip over most unmovable
1646aa218795SDavid Hildenbrand  * pages (esp., pages that can be skipped when offlining), but bail out on
1647aa218795SDavid Hildenbrand  * definitely unmovable pages.
1648aa218795SDavid Hildenbrand  *
1649aa218795SDavid Hildenbrand  * Returns:
1650aa218795SDavid Hildenbrand  *	0 in case a movable page is found and movable_pfn was updated.
1651aa218795SDavid Hildenbrand  *	-ENOENT in case no movable page was found.
1652aa218795SDavid Hildenbrand  *	-EBUSY in case a definitely unmovable page was found.
16530c0e6195SKAMEZAWA Hiroyuki  */
1654aa218795SDavid Hildenbrand static int scan_movable_pages(unsigned long start, unsigned long end,
1655aa218795SDavid Hildenbrand 			      unsigned long *movable_pfn)
16560c0e6195SKAMEZAWA Hiroyuki {
16570c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
1658eeb0efd0SOscar Salvador 
16590c0e6195SKAMEZAWA Hiroyuki 	for (pfn = start; pfn < end; pfn++) {
1660eeb0efd0SOscar Salvador 		struct page *page, *head;
1661eeb0efd0SOscar Salvador 		unsigned long skip;
1662eeb0efd0SOscar Salvador 
1663eeb0efd0SOscar Salvador 		if (!pfn_valid(pfn))
1664eeb0efd0SOscar Salvador 			continue;
16650c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
16660c0e6195SKAMEZAWA Hiroyuki 		if (PageLRU(page))
1667aa218795SDavid Hildenbrand 			goto found;
16680efadf48SYisheng Xie 		if (__PageMovable(page))
1669aa218795SDavid Hildenbrand 			goto found;
1670aa218795SDavid Hildenbrand 
1671aa218795SDavid Hildenbrand 		/*
1672aa218795SDavid Hildenbrand 		 * PageOffline() pages that are not marked __PageMovable() and
1673aa218795SDavid Hildenbrand 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1674aa218795SDavid Hildenbrand 		 * definitely unmovable. If their reference count would be 0,
1675aa218795SDavid Hildenbrand 		 * they could at least be skipped when offlining memory.
1676aa218795SDavid Hildenbrand 		 */
1677aa218795SDavid Hildenbrand 		if (PageOffline(page) && page_count(page))
1678aa218795SDavid Hildenbrand 			return -EBUSY;
1679eeb0efd0SOscar Salvador 
1680eeb0efd0SOscar Salvador 		if (!PageHuge(page))
1681eeb0efd0SOscar Salvador 			continue;
1682eeb0efd0SOscar Salvador 		head = compound_head(page);
16838f251a3dSMike Kravetz 		/*
16848f251a3dSMike Kravetz 		 * This test is racy as we hold no reference or lock.  The
16858f251a3dSMike Kravetz 		 * hugetlb page could have been free'ed and head is no longer
16868f251a3dSMike Kravetz 		 * a hugetlb page before the following check.  In such unlikely
16878f251a3dSMike Kravetz 		 * cases false positives and negatives are possible.  Calling
16888f251a3dSMike Kravetz 		 * code must deal with these scenarios.
16898f251a3dSMike Kravetz 		 */
16908f251a3dSMike Kravetz 		if (HPageMigratable(head))
1691aa218795SDavid Hildenbrand 			goto found;
16922c1589c7SZi Yan 		skip = compound_nr(head) - (pfn - page_to_pfn(head));
1693eeb0efd0SOscar Salvador 		pfn += skip - 1;
16940c0e6195SKAMEZAWA Hiroyuki 	}
1695aa218795SDavid Hildenbrand 	return -ENOENT;
1696aa218795SDavid Hildenbrand found:
1697aa218795SDavid Hildenbrand 	*movable_pfn = pfn;
16980c0e6195SKAMEZAWA Hiroyuki 	return 0;
16990c0e6195SKAMEZAWA Hiroyuki }
17000c0e6195SKAMEZAWA Hiroyuki 
170132cf666eSSeongJae Park static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
17020c0e6195SKAMEZAWA Hiroyuki {
17030c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
17046c357848SMatthew Wilcox (Oracle) 	struct page *page, *head;
17050c0e6195SKAMEZAWA Hiroyuki 	LIST_HEAD(source);
1706786dee86SLiam Mark 	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
1707786dee86SLiam Mark 				      DEFAULT_RATELIMIT_BURST);
17080c0e6195SKAMEZAWA Hiroyuki 
1709a85009c3SMichal Hocko 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1710869f7ee6SMatthew Wilcox (Oracle) 		struct folio *folio;
1711f7f9c00dSBaolin Wang 		bool isolated;
1712869f7ee6SMatthew Wilcox (Oracle) 
17130c0e6195SKAMEZAWA Hiroyuki 		if (!pfn_valid(pfn))
17140c0e6195SKAMEZAWA Hiroyuki 			continue;
17150c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
1716869f7ee6SMatthew Wilcox (Oracle) 		folio = page_folio(page);
1717869f7ee6SMatthew Wilcox (Oracle) 		head = &folio->page;
1718c8721bbbSNaoya Horiguchi 
1719c8721bbbSNaoya Horiguchi 		if (PageHuge(page)) {
1720d8c6546bSMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + compound_nr(head) - 1;
17216aa3a920SSidhartha Kumar 			isolate_hugetlb(folio, &source);
1722c8721bbbSNaoya Horiguchi 			continue;
172394723aafSMichal Hocko 		} else if (PageTransHuge(page))
17246c357848SMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + thp_nr_pages(page) - 1;
1725c8721bbbSNaoya Horiguchi 
1726b15c8726SMichal Hocko 		/*
1727b15c8726SMichal Hocko 		 * HWPoison pages have elevated reference counts so the migration would
1728b15c8726SMichal Hocko 		 * fail on them. It also doesn't make any sense to migrate them in the
1729b15c8726SMichal Hocko 		 * first place. Still try to unmap such a page in case it is still mapped
1730b15c8726SMichal Hocko 		 * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1731b15c8726SMichal Hocko 		 * the unmap as the catch all safety net).
1732b15c8726SMichal Hocko 		 */
1733b15c8726SMichal Hocko 		if (PageHWPoison(page)) {
1734869f7ee6SMatthew Wilcox (Oracle) 			if (WARN_ON(folio_test_lru(folio)))
1735869f7ee6SMatthew Wilcox (Oracle) 				folio_isolate_lru(folio);
1736869f7ee6SMatthew Wilcox (Oracle) 			if (folio_mapped(folio))
1737869f7ee6SMatthew Wilcox (Oracle) 				try_to_unmap(folio, TTU_IGNORE_MLOCK);
1738b15c8726SMichal Hocko 			continue;
1739b15c8726SMichal Hocko 		}
1740b15c8726SMichal Hocko 
1741700c2a46SKonstantin Khlebnikov 		if (!get_page_unless_zero(page))
17420c0e6195SKAMEZAWA Hiroyuki 			continue;
17430c0e6195SKAMEZAWA Hiroyuki 		/*
17440efadf48SYisheng Xie 		 * We can skip free pages. And we can deal with pages on
17450efadf48SYisheng Xie 		 * LRU and non-lru movable pages.
17460c0e6195SKAMEZAWA Hiroyuki 		 */
1747cd775580SBaolin Wang 		if (PageLRU(page))
1748f7f9c00dSBaolin Wang 			isolated = isolate_lru_page(page);
1749cd775580SBaolin Wang 		else
1750cd775580SBaolin Wang 			isolated = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1751cd775580SBaolin Wang 		if (isolated) {
175262695a84SNick Piggin 			list_add_tail(&page->lru, &source);
17530efadf48SYisheng Xie 			if (!__PageMovable(page))
1754599d0c95SMel Gorman 				inc_node_page_state(page, NR_ISOLATED_ANON +
17559de4f22aSHuang Ying 						    page_is_file_lru(page));
17566d9c285aSKOSAKI Motohiro 
17570c0e6195SKAMEZAWA Hiroyuki 		} else {
1758786dee86SLiam Mark 			if (__ratelimit(&migrate_rs)) {
17592932c8b0SMichal Hocko 				pr_warn("failed to isolate pfn %lx\n", pfn);
17600efadf48SYisheng Xie 				dump_page(page, "isolation failed");
17611723058eSOscar Salvador 			}
1762786dee86SLiam Mark 		}
1763700c2a46SKonstantin Khlebnikov 		put_page(page);
17640c0e6195SKAMEZAWA Hiroyuki 	}
1765f3ab2636SBob Liu 	if (!list_empty(&source)) {
1766203e6e5cSJoonsoo Kim 		nodemask_t nmask = node_states[N_MEMORY];
1767203e6e5cSJoonsoo Kim 		struct migration_target_control mtc = {
1768203e6e5cSJoonsoo Kim 			.nmask = &nmask,
1769203e6e5cSJoonsoo Kim 			.gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1770203e6e5cSJoonsoo Kim 		};
177132cf666eSSeongJae Park 		int ret;
1772203e6e5cSJoonsoo Kim 
1773203e6e5cSJoonsoo Kim 		/*
1774203e6e5cSJoonsoo Kim 		 * We have checked that migration range is on a single zone so
1775203e6e5cSJoonsoo Kim 		 * we can use the nid of the first page to all the others.
1776203e6e5cSJoonsoo Kim 		 */
1777203e6e5cSJoonsoo Kim 		mtc.nid = page_to_nid(list_first_entry(&source, struct page, lru));
1778203e6e5cSJoonsoo Kim 
1779203e6e5cSJoonsoo Kim 		/*
1780203e6e5cSJoonsoo Kim 		 * try to allocate from a different node but reuse this node
1781203e6e5cSJoonsoo Kim 		 * if there are no other online nodes to be used (e.g. we are
1782203e6e5cSJoonsoo Kim 		 * offlining a part of the only existing node)
1783203e6e5cSJoonsoo Kim 		 */
1784203e6e5cSJoonsoo Kim 		node_clear(mtc.nid, nmask);
1785203e6e5cSJoonsoo Kim 		if (nodes_empty(nmask))
1786203e6e5cSJoonsoo Kim 			node_set(mtc.nid, nmask);
1787203e6e5cSJoonsoo Kim 		ret = migrate_pages(&source, alloc_migration_target, NULL,
17885ac95884SYang Shi 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
17892932c8b0SMichal Hocko 		if (ret) {
17902932c8b0SMichal Hocko 			list_for_each_entry(page, &source, lru) {
1791786dee86SLiam Mark 				if (__ratelimit(&migrate_rs)) {
1792786dee86SLiam Mark 					pr_warn("migrating pfn %lx failed ret:%d\n",
17932932c8b0SMichal Hocko 						page_to_pfn(page), ret);
17942932c8b0SMichal Hocko 					dump_page(page, "migration failure");
17952932c8b0SMichal Hocko 				}
1796786dee86SLiam Mark 			}
1797c8721bbbSNaoya Horiguchi 			putback_movable_pages(&source);
1798f3ab2636SBob Liu 		}
17992932c8b0SMichal Hocko 	}
18000c0e6195SKAMEZAWA Hiroyuki }
18010c0e6195SKAMEZAWA Hiroyuki 
1802c5320926STang Chen static int __init cmdline_parse_movable_node(char *p)
1803c5320926STang Chen {
180455ac590cSTang Chen 	movable_node_enabled = true;
1805c5320926STang Chen 	return 0;
1806c5320926STang Chen }
1807c5320926STang Chen early_param("movable_node", cmdline_parse_movable_node);
1808c5320926STang Chen 
1809d9713679SLai Jiangshan /* check which state of node_states will be changed when offline memory */
1810d9713679SLai Jiangshan static void node_states_check_changes_offline(unsigned long nr_pages,
1811d9713679SLai Jiangshan 		struct zone *zone, struct memory_notify *arg)
1812d9713679SLai Jiangshan {
1813d9713679SLai Jiangshan 	struct pglist_data *pgdat = zone->zone_pgdat;
1814d9713679SLai Jiangshan 	unsigned long present_pages = 0;
181586b27beaSOscar Salvador 	enum zone_type zt;
1816d9713679SLai Jiangshan 
181798fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
181898fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
181986b27beaSOscar Salvador 
182086b27beaSOscar Salvador 	/*
182186b27beaSOscar Salvador 	 * Check whether node_states[N_NORMAL_MEMORY] will be changed.
182286b27beaSOscar Salvador 	 * If the memory to be offline is within the range
182386b27beaSOscar Salvador 	 * [0..ZONE_NORMAL], and it is the last present memory there,
182486b27beaSOscar Salvador 	 * the zones in that range will become empty after the offlining,
182586b27beaSOscar Salvador 	 * thus we can determine that we need to clear the node from
182686b27beaSOscar Salvador 	 * node_states[N_NORMAL_MEMORY].
182786b27beaSOscar Salvador 	 */
182886b27beaSOscar Salvador 	for (zt = 0; zt <= ZONE_NORMAL; zt++)
182986b27beaSOscar Salvador 		present_pages += pgdat->node_zones[zt].present_pages;
183086b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
183186b27beaSOscar Salvador 		arg->status_change_nid_normal = zone_to_nid(zone);
1832d9713679SLai Jiangshan 
18336715ddf9SLai Jiangshan 	/*
18346b740c6cSDavid Hildenbrand 	 * We have accounted the pages from [0..ZONE_NORMAL); ZONE_HIGHMEM
18356b740c6cSDavid Hildenbrand 	 * does not apply as we don't support 32bit.
183686b27beaSOscar Salvador 	 * Here we count the possible pages from ZONE_MOVABLE.
183786b27beaSOscar Salvador 	 * If after having accounted all the pages, we see that the nr_pages
183886b27beaSOscar Salvador 	 * to be offlined is over or equal to the accounted pages,
183986b27beaSOscar Salvador 	 * we know that the node will become empty, and so, we can clear
184086b27beaSOscar Salvador 	 * it for N_MEMORY as well.
1841d9713679SLai Jiangshan 	 */
184286b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1843d9713679SLai Jiangshan 
1844d9713679SLai Jiangshan 	if (nr_pages >= present_pages)
1845d9713679SLai Jiangshan 		arg->status_change_nid = zone_to_nid(zone);
1846d9713679SLai Jiangshan }
1847d9713679SLai Jiangshan 
1848d9713679SLai Jiangshan static void node_states_clear_node(int node, struct memory_notify *arg)
1849d9713679SLai Jiangshan {
1850d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
1851d9713679SLai Jiangshan 		node_clear_state(node, N_NORMAL_MEMORY);
1852d9713679SLai Jiangshan 
1853cf01f6f5SOscar Salvador 	if (arg->status_change_nid >= 0)
18546715ddf9SLai Jiangshan 		node_clear_state(node, N_MEMORY);
1855d9713679SLai Jiangshan }
1856d9713679SLai Jiangshan 
1857c5e79ef5SDavid Hildenbrand static int count_system_ram_pages_cb(unsigned long start_pfn,
1858c5e79ef5SDavid Hildenbrand 				     unsigned long nr_pages, void *data)
1859c5e79ef5SDavid Hildenbrand {
1860c5e79ef5SDavid Hildenbrand 	unsigned long *nr_system_ram_pages = data;
1861c5e79ef5SDavid Hildenbrand 
1862c5e79ef5SDavid Hildenbrand 	*nr_system_ram_pages += nr_pages;
1863c5e79ef5SDavid Hildenbrand 	return 0;
1864c5e79ef5SDavid Hildenbrand }
1865c5e79ef5SDavid Hildenbrand 
1866*e0270ffaSSumanth Korikkar /*
1867*e0270ffaSSumanth Korikkar  * Must be called with mem_hotplug_lock in write mode.
1868*e0270ffaSSumanth Korikkar  */
1869836809ecSDavid Hildenbrand int __ref offline_pages(unsigned long start_pfn, unsigned long nr_pages,
1870395f6081SDavid Hildenbrand 			struct zone *zone, struct memory_group *group)
18710c0e6195SKAMEZAWA Hiroyuki {
187273a11c96SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
18730a1a9a00SDavid Hildenbrand 	unsigned long pfn, system_ram_pages = 0;
1874395f6081SDavid Hildenbrand 	const int node = zone_to_nid(zone);
1875d702909fSCody P Schafer 	unsigned long flags;
18767b78d335SYasunori Goto 	struct memory_notify arg;
187779605093SMichal Hocko 	char *reason;
1878395f6081SDavid Hildenbrand 	int ret;
18790c0e6195SKAMEZAWA Hiroyuki 
1880dd8e2f23SOscar Salvador 	/*
1881dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1882041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1883dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1884dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1885dd8e2f23SOscar Salvador 	 * aligned.
1886dd8e2f23SOscar Salvador 	 */
1887ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
1888dd8e2f23SOscar Salvador 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
18894986fac1SDavid Hildenbrand 		return -EINVAL;
18904986fac1SDavid Hildenbrand 
1891c5e79ef5SDavid Hildenbrand 	/*
1892c5e79ef5SDavid Hildenbrand 	 * Don't allow to offline memory blocks that contain holes.
1893c5e79ef5SDavid Hildenbrand 	 * Consequently, memory blocks with holes can never get onlined
1894c5e79ef5SDavid Hildenbrand 	 * via the hotplug path - online_pages() - as hotplugged memory has
1895c5e79ef5SDavid Hildenbrand 	 * no holes. This way, we e.g., don't have to worry about marking
1896c5e79ef5SDavid Hildenbrand 	 * memory holes PG_reserved, don't need pfn_valid() checks, and can
1897c5e79ef5SDavid Hildenbrand 	 * avoid using walk_system_ram_range() later.
1898c5e79ef5SDavid Hildenbrand 	 */
189973a11c96SDavid Hildenbrand 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1900c5e79ef5SDavid Hildenbrand 			      count_system_ram_pages_cb);
190173a11c96SDavid Hildenbrand 	if (system_ram_pages != nr_pages) {
1902c5e79ef5SDavid Hildenbrand 		ret = -EINVAL;
1903c5e79ef5SDavid Hildenbrand 		reason = "memory holes";
1904c5e79ef5SDavid Hildenbrand 		goto failed_removal;
1905c5e79ef5SDavid Hildenbrand 	}
1906c5e79ef5SDavid Hildenbrand 
1907395f6081SDavid Hildenbrand 	/*
1908395f6081SDavid Hildenbrand 	 * We only support offlining of memory blocks managed by a single zone,
1909395f6081SDavid Hildenbrand 	 * checked by calling code. This is just a sanity check that we might
1910395f6081SDavid Hildenbrand 	 * want to remove in the future.
1911395f6081SDavid Hildenbrand 	 */
1912395f6081SDavid Hildenbrand 	if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
1913395f6081SDavid Hildenbrand 			 page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
191479605093SMichal Hocko 		ret = -EINVAL;
191579605093SMichal Hocko 		reason = "multizone range";
191679605093SMichal Hocko 		goto failed_removal;
1917381eab4aSDavid Hildenbrand 	}
19187b78d335SYasunori Goto 
1919ec6e8c7eSVlastimil Babka 	/*
1920ec6e8c7eSVlastimil Babka 	 * Disable pcplists so that page isolation cannot race with freeing
1921ec6e8c7eSVlastimil Babka 	 * in a way that pages from isolated pageblock are left on pcplists.
1922ec6e8c7eSVlastimil Babka 	 */
1923ec6e8c7eSVlastimil Babka 	zone_pcp_disable(zone);
1924d479960eSMinchan Kim 	lru_cache_disable();
1925ec6e8c7eSVlastimil Babka 
19260c0e6195SKAMEZAWA Hiroyuki 	/* set above range as isolated */
1927b023f468SWen Congyang 	ret = start_isolate_page_range(start_pfn, end_pfn,
1928d381c547SMichal Hocko 				       MIGRATE_MOVABLE,
1929b2c9e2fbSZi Yan 				       MEMORY_OFFLINE | REPORT_FAILURE,
1930b2c9e2fbSZi Yan 				       GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL);
19313fa0c7c7SDavid Hildenbrand 	if (ret) {
193279605093SMichal Hocko 		reason = "failure to isolate range";
1933ec6e8c7eSVlastimil Babka 		goto failed_removal_pcplists_disabled;
1934381eab4aSDavid Hildenbrand 	}
19357b78d335SYasunori Goto 
19367b78d335SYasunori Goto 	arg.start_pfn = start_pfn;
19377b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1938d9713679SLai Jiangshan 	node_states_check_changes_offline(nr_pages, zone, &arg);
19397b78d335SYasunori Goto 
19407b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_OFFLINE, &arg);
19417b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
194279605093SMichal Hocko 	if (ret) {
194379605093SMichal Hocko 		reason = "notifier failure";
194479605093SMichal Hocko 		goto failed_removal_isolated;
194579605093SMichal Hocko 	}
19467b78d335SYasunori Goto 
1947bb8965bdSMichal Hocko 	do {
1948aa218795SDavid Hildenbrand 		pfn = start_pfn;
1949aa218795SDavid Hildenbrand 		do {
1950de7cb03dSDavid Hildenbrand 			/*
1951de7cb03dSDavid Hildenbrand 			 * Historically we always checked for any signal and
1952de7cb03dSDavid Hildenbrand 			 * can't limit it to fatal signals without eventually
1953de7cb03dSDavid Hildenbrand 			 * breaking user space.
1954de7cb03dSDavid Hildenbrand 			 */
195579605093SMichal Hocko 			if (signal_pending(current)) {
1956bb8965bdSMichal Hocko 				ret = -EINTR;
195779605093SMichal Hocko 				reason = "signal backoff";
195879605093SMichal Hocko 				goto failed_removal_isolated;
195979605093SMichal Hocko 			}
196072b39cfcSMichal Hocko 
19610c0e6195SKAMEZAWA Hiroyuki 			cond_resched();
19620c0e6195SKAMEZAWA Hiroyuki 
1963aa218795SDavid Hildenbrand 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
1964aa218795SDavid Hildenbrand 			if (!ret) {
1965bb8965bdSMichal Hocko 				/*
1966bb8965bdSMichal Hocko 				 * TODO: fatal migration failures should bail
1967bb8965bdSMichal Hocko 				 * out
1968bb8965bdSMichal Hocko 				 */
1969bb8965bdSMichal Hocko 				do_migrate_range(pfn, end_pfn);
1970bb8965bdSMichal Hocko 			}
1971aa218795SDavid Hildenbrand 		} while (!ret);
1972aa218795SDavid Hildenbrand 
1973aa218795SDavid Hildenbrand 		if (ret != -ENOENT) {
1974aa218795SDavid Hildenbrand 			reason = "unmovable page";
1975aa218795SDavid Hildenbrand 			goto failed_removal_isolated;
19760c0e6195SKAMEZAWA Hiroyuki 		}
197772b39cfcSMichal Hocko 
1978c8721bbbSNaoya Horiguchi 		/*
1979bb8965bdSMichal Hocko 		 * Dissolve free hugepages in the memory block before doing
1980bb8965bdSMichal Hocko 		 * offlining actually in order to make hugetlbfs's object
1981bb8965bdSMichal Hocko 		 * counting consistent.
1982c8721bbbSNaoya Horiguchi 		 */
1983082d5b6bSGerald Schaefer 		ret = dissolve_free_huge_pages(start_pfn, end_pfn);
198479605093SMichal Hocko 		if (ret) {
198579605093SMichal Hocko 			reason = "failure to dissolve huge pages";
198679605093SMichal Hocko 			goto failed_removal_isolated;
198779605093SMichal Hocko 		}
19880a1a9a00SDavid Hildenbrand 
19890a1a9a00SDavid Hildenbrand 		ret = test_pages_isolated(start_pfn, end_pfn, MEMORY_OFFLINE);
1990ec6e8c7eSVlastimil Babka 
19915557c766SMichal Hocko 	} while (ret);
1992bb8965bdSMichal Hocko 
19930a1a9a00SDavid Hildenbrand 	/* Mark all sections offline and remove free pages from the buddy. */
19940a1a9a00SDavid Hildenbrand 	__offline_isolated_pages(start_pfn, end_pfn);
19957c33023aSLaurent Dufour 	pr_debug("Offlined Pages %ld\n", nr_pages);
19960a1a9a00SDavid Hildenbrand 
19979b7ea46aSQian Cai 	/*
1998b30c5927SDavid Hildenbrand 	 * The memory sections are marked offline, and the pageblock flags
1999b30c5927SDavid Hildenbrand 	 * effectively stale; nobody should be touching them. Fixup the number
2000b30c5927SDavid Hildenbrand 	 * of isolated pageblocks, memory onlining will properly revert this.
20019b7ea46aSQian Cai 	 */
20029b7ea46aSQian Cai 	spin_lock_irqsave(&zone->lock, flags);
2003ea15153cSDavid Hildenbrand 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
20049b7ea46aSQian Cai 	spin_unlock_irqrestore(&zone->lock, flags);
20059b7ea46aSQian Cai 
2006d479960eSMinchan Kim 	lru_cache_enable();
2007ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
2008ec6e8c7eSVlastimil Babka 
20090c0e6195SKAMEZAWA Hiroyuki 	/* removal success */
20100a1a9a00SDavid Hildenbrand 	adjust_managed_page_count(pfn_to_page(start_pfn), -nr_pages);
2011836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
20127b78d335SYasunori Goto 
2013b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
20141b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
20151b79acc9SKOSAKI Motohiro 
20161e8537baSXishi Qiu 	if (!populated_zone(zone)) {
2017340175b7SJiang Liu 		zone_pcp_reset(zone);
201872675e13SMichal Hocko 		build_all_zonelists(NULL);
2019b92ca18eSMel Gorman 	}
2020340175b7SJiang Liu 
2021d9713679SLai Jiangshan 	node_states_clear_node(node, &arg);
2022698b1b30SVlastimil Babka 	if (arg.status_change_nid >= 0) {
2023698b1b30SVlastimil Babka 		kcompactd_stop(node);
2024b4a0215eSKefeng Wang 		kswapd_stop(node);
2025698b1b30SVlastimil Babka 	}
2026bce7394aSMinchan Kim 
20270c0e6195SKAMEZAWA Hiroyuki 	writeback_set_ratelimit();
20287b78d335SYasunori Goto 
20297b78d335SYasunori Goto 	memory_notify(MEM_OFFLINE, &arg);
2030feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
20310c0e6195SKAMEZAWA Hiroyuki 	return 0;
20320c0e6195SKAMEZAWA Hiroyuki 
203379605093SMichal Hocko failed_removal_isolated:
203436ba30bcSMiaohe Lin 	/* pushback to free area */
203579605093SMichal Hocko 	undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
2036c4efe484SQian Cai 	memory_notify(MEM_CANCEL_OFFLINE, &arg);
2037ec6e8c7eSVlastimil Babka failed_removal_pcplists_disabled:
2038946746d1SMiaohe Lin 	lru_cache_enable();
2039ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
20400c0e6195SKAMEZAWA Hiroyuki failed_removal:
204179605093SMichal Hocko 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
2042a62e2f4fSBjorn Helgaas 		 (unsigned long long) start_pfn << PAGE_SHIFT,
204379605093SMichal Hocko 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
204479605093SMichal Hocko 		 reason);
20450c0e6195SKAMEZAWA Hiroyuki 	return ret;
20460c0e6195SKAMEZAWA Hiroyuki }
204771088785SBadari Pulavarty 
2048d6de9d53SXishi Qiu static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
2049bbc76be6SWen Congyang {
2050e1c158e4SDavid Hildenbrand 	int *nid = arg;
2051bbc76be6SWen Congyang 
2052e1c158e4SDavid Hildenbrand 	*nid = mem->nid;
2053639118d1SKefeng Wang 	if (unlikely(mem->state != MEM_OFFLINE)) {
2054349daa0fSRandy Dunlap 		phys_addr_t beginpa, endpa;
2055349daa0fSRandy Dunlap 
2056349daa0fSRandy Dunlap 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
2057b6c88d3bSDavid Hildenbrand 		endpa = beginpa + memory_block_size_bytes() - 1;
2058756a025fSJoe Perches 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
2059349daa0fSRandy Dunlap 			&beginpa, &endpa);
2060bbc76be6SWen Congyang 
2061eca499abSPavel Tatashin 		return -EBUSY;
2062eca499abSPavel Tatashin 	}
2063eca499abSPavel Tatashin 	return 0;
2064bbc76be6SWen Congyang }
2065bbc76be6SWen Congyang 
20661a8c64e1SAneesh Kumar K.V static int test_has_altmap_cb(struct memory_block *mem, void *arg)
2067a08a2ae3SOscar Salvador {
20681a8c64e1SAneesh Kumar K.V 	struct memory_block **mem_ptr = (struct memory_block **)arg;
2069a08a2ae3SOscar Salvador 	/*
20701a8c64e1SAneesh Kumar K.V 	 * return the memblock if we have altmap
20711a8c64e1SAneesh Kumar K.V 	 * and break callback.
2072a08a2ae3SOscar Salvador 	 */
20731a8c64e1SAneesh Kumar K.V 	if (mem->altmap) {
20741a8c64e1SAneesh Kumar K.V 		*mem_ptr = mem;
20751a8c64e1SAneesh Kumar K.V 		return 1;
20761a8c64e1SAneesh Kumar K.V 	}
20771a8c64e1SAneesh Kumar K.V 	return 0;
2078a08a2ae3SOscar Salvador }
2079a08a2ae3SOscar Salvador 
2080b27340a5SMiaohe Lin static int check_cpu_on_node(int nid)
208160a5a19eSTang Chen {
208260a5a19eSTang Chen 	int cpu;
208360a5a19eSTang Chen 
208460a5a19eSTang Chen 	for_each_present_cpu(cpu) {
2085b27340a5SMiaohe Lin 		if (cpu_to_node(cpu) == nid)
208660a5a19eSTang Chen 			/*
208760a5a19eSTang Chen 			 * the cpu on this node isn't removed, and we can't
208860a5a19eSTang Chen 			 * offline this node.
208960a5a19eSTang Chen 			 */
209060a5a19eSTang Chen 			return -EBUSY;
209160a5a19eSTang Chen 	}
209260a5a19eSTang Chen 
209360a5a19eSTang Chen 	return 0;
209460a5a19eSTang Chen }
209560a5a19eSTang Chen 
20962c91f8fcSDavid Hildenbrand static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
20972c91f8fcSDavid Hildenbrand {
20982c91f8fcSDavid Hildenbrand 	int nid = *(int *)arg;
20992c91f8fcSDavid Hildenbrand 
21002c91f8fcSDavid Hildenbrand 	/*
21012c91f8fcSDavid Hildenbrand 	 * If a memory block belongs to multiple nodes, the stored nid is not
21022c91f8fcSDavid Hildenbrand 	 * reliable. However, such blocks are always online (e.g., cannot get
21032c91f8fcSDavid Hildenbrand 	 * offlined) and, therefore, are still spanned by the node.
21042c91f8fcSDavid Hildenbrand 	 */
21052c91f8fcSDavid Hildenbrand 	return mem->nid == nid ? -EEXIST : 0;
21062c91f8fcSDavid Hildenbrand }
21072c91f8fcSDavid Hildenbrand 
21080f1cfe9dSToshi Kani /**
21090f1cfe9dSToshi Kani  * try_offline_node
2110e8b098fcSMike Rapoport  * @nid: the node ID
21110f1cfe9dSToshi Kani  *
21120f1cfe9dSToshi Kani  * Offline a node if all memory sections and cpus of the node are removed.
21130f1cfe9dSToshi Kani  *
21140f1cfe9dSToshi Kani  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
21150f1cfe9dSToshi Kani  * and online/offline operations before this call.
21160f1cfe9dSToshi Kani  */
211790b30cdcSWen Congyang void try_offline_node(int nid)
211860a5a19eSTang Chen {
21192c91f8fcSDavid Hildenbrand 	int rc;
212060a5a19eSTang Chen 
212160a5a19eSTang Chen 	/*
21222c91f8fcSDavid Hildenbrand 	 * If the node still spans pages (especially ZONE_DEVICE), don't
21232c91f8fcSDavid Hildenbrand 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
21242c91f8fcSDavid Hildenbrand 	 * e.g., after the memory block was onlined.
212560a5a19eSTang Chen 	 */
2126b27340a5SMiaohe Lin 	if (node_spanned_pages(nid))
212760a5a19eSTang Chen 		return;
21282c91f8fcSDavid Hildenbrand 
21292c91f8fcSDavid Hildenbrand 	/*
21302c91f8fcSDavid Hildenbrand 	 * Especially offline memory blocks might not be spanned by the
21312c91f8fcSDavid Hildenbrand 	 * node. They will get spanned by the node once they get onlined.
21322c91f8fcSDavid Hildenbrand 	 * However, they link to the node in sysfs and can get onlined later.
21332c91f8fcSDavid Hildenbrand 	 */
21342c91f8fcSDavid Hildenbrand 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
21352c91f8fcSDavid Hildenbrand 	if (rc)
21362c91f8fcSDavid Hildenbrand 		return;
213760a5a19eSTang Chen 
2138b27340a5SMiaohe Lin 	if (check_cpu_on_node(nid))
213960a5a19eSTang Chen 		return;
214060a5a19eSTang Chen 
214160a5a19eSTang Chen 	/*
214260a5a19eSTang Chen 	 * all memory/cpu of this node are removed, we can offline this
214360a5a19eSTang Chen 	 * node now.
214460a5a19eSTang Chen 	 */
214560a5a19eSTang Chen 	node_set_offline(nid);
214660a5a19eSTang Chen 	unregister_one_node(nid);
214760a5a19eSTang Chen }
214890b30cdcSWen Congyang EXPORT_SYMBOL(try_offline_node);
214960a5a19eSTang Chen 
2150e1c158e4SDavid Hildenbrand static int __ref try_remove_memory(u64 start, u64 size)
2151bbc76be6SWen Congyang {
21521a8c64e1SAneesh Kumar K.V 	struct memory_block *mem;
2153e1c158e4SDavid Hildenbrand 	int rc = 0, nid = NUMA_NO_NODE;
21541a8c64e1SAneesh Kumar K.V 	struct vmem_altmap *altmap = NULL;
2155993c1aadSWen Congyang 
215627356f54SToshi Kani 	BUG_ON(check_hotplug_memory_range(start, size));
215727356f54SToshi Kani 
21586677e3eaSYasuaki Ishimatsu 	/*
2159242831ebSRafael J. Wysocki 	 * All memory blocks must be offlined before removing memory.  Check
2160eca499abSPavel Tatashin 	 * whether all memory blocks in question are offline and return error
2161242831ebSRafael J. Wysocki 	 * if this is not the case.
2162e1c158e4SDavid Hildenbrand 	 *
2163e1c158e4SDavid Hildenbrand 	 * While at it, determine the nid. Note that if we'd have mixed nodes,
2164e1c158e4SDavid Hildenbrand 	 * we'd only try to offline the last determined one -- which is good
2165e1c158e4SDavid Hildenbrand 	 * enough for the cases we care about.
21666677e3eaSYasuaki Ishimatsu 	 */
2167e1c158e4SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
2168eca499abSPavel Tatashin 	if (rc)
2169b4223a51SJia He 		return rc;
21706677e3eaSYasuaki Ishimatsu 
2171a08a2ae3SOscar Salvador 	/*
2172a08a2ae3SOscar Salvador 	 * We only support removing memory added with MHP_MEMMAP_ON_MEMORY in
2173a08a2ae3SOscar Salvador 	 * the same granularity it was added - a single memory block.
2174a08a2ae3SOscar Salvador 	 */
21756e02c46bSMuchun Song 	if (mhp_memmap_on_memory()) {
21761a8c64e1SAneesh Kumar K.V 		rc = walk_memory_blocks(start, size, &mem, test_has_altmap_cb);
21771a8c64e1SAneesh Kumar K.V 		if (rc) {
2178a08a2ae3SOscar Salvador 			if (size != memory_block_size_bytes()) {
2179a08a2ae3SOscar Salvador 				pr_warn("Refuse to remove %#llx - %#llx,"
2180a08a2ae3SOscar Salvador 					"wrong granularity\n",
2181a08a2ae3SOscar Salvador 					start, start + size);
2182a08a2ae3SOscar Salvador 				return -EINVAL;
2183a08a2ae3SOscar Salvador 			}
21841a8c64e1SAneesh Kumar K.V 			altmap = mem->altmap;
2185a08a2ae3SOscar Salvador 			/*
21861a8c64e1SAneesh Kumar K.V 			 * Mark altmap NULL so that we can add a debug
21871a8c64e1SAneesh Kumar K.V 			 * check on memblock free.
2188a08a2ae3SOscar Salvador 			 */
21891a8c64e1SAneesh Kumar K.V 			mem->altmap = NULL;
2190a08a2ae3SOscar Salvador 		}
2191a08a2ae3SOscar Salvador 	}
2192a08a2ae3SOscar Salvador 
219346c66c4bSYasuaki Ishimatsu 	/* remove memmap entry */
219446c66c4bSYasuaki Ishimatsu 	firmware_map_remove(start, start + size, "System RAM");
219546c66c4bSYasuaki Ishimatsu 
2196f1037ec0SDan Williams 	/*
2197f1037ec0SDan Williams 	 * Memory block device removal under the device_hotplug_lock is
2198f1037ec0SDan Williams 	 * a barrier against racing online attempts.
2199f1037ec0SDan Williams 	 */
22004c4b7f9bSDavid Hildenbrand 	remove_memory_block_devices(start, size);
22014c4b7f9bSDavid Hildenbrand 
2202f1037ec0SDan Williams 	mem_hotplug_begin();
2203f1037ec0SDan Williams 
220465a2aa5fSDavid Hildenbrand 	arch_remove_memory(start, size, altmap);
220552219aeaSDavid Hildenbrand 
22061a8c64e1SAneesh Kumar K.V 	/* Verify that all vmemmap pages have actually been freed. */
22071a8c64e1SAneesh Kumar K.V 	if (altmap) {
22081a8c64e1SAneesh Kumar K.V 		WARN(altmap->alloc, "Altmap not fully unmapped");
22091a8c64e1SAneesh Kumar K.V 		kfree(altmap);
22101a8c64e1SAneesh Kumar K.V 	}
22111a8c64e1SAneesh Kumar K.V 
221252219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
22133ecc6834SMike Rapoport 		memblock_phys_free(start, size);
221432d1fe8fSAnshuman Khandual 		memblock_remove(start, size);
221552219aeaSDavid Hildenbrand 	}
221652219aeaSDavid Hildenbrand 
2217cb8e3c8bSDavid Hildenbrand 	release_mem_region_adjustable(start, size);
221824d335caSWen Congyang 
2219e1c158e4SDavid Hildenbrand 	if (nid != NUMA_NO_NODE)
222060a5a19eSTang Chen 		try_offline_node(nid);
222160a5a19eSTang Chen 
2222bfc8c901SVladimir Davydov 	mem_hotplug_done();
2223b4223a51SJia He 	return 0;
222471088785SBadari Pulavarty }
2225d15e5926SDavid Hildenbrand 
2226eca499abSPavel Tatashin /**
22275640c9caSMel Gorman  * __remove_memory - Remove memory if every memory block is offline
2228eca499abSPavel Tatashin  * @start: physical address of the region to remove
2229eca499abSPavel Tatashin  * @size: size of the region to remove
2230eca499abSPavel Tatashin  *
2231eca499abSPavel Tatashin  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2232eca499abSPavel Tatashin  * and online/offline operations before this call, as required by
2233eca499abSPavel Tatashin  * try_offline_node().
2234eca499abSPavel Tatashin  */
2235e1c158e4SDavid Hildenbrand void __remove_memory(u64 start, u64 size)
2236d15e5926SDavid Hildenbrand {
2237eca499abSPavel Tatashin 
2238eca499abSPavel Tatashin 	/*
223929a90db9SSouptick Joarder 	 * trigger BUG() if some memory is not offlined prior to calling this
2240eca499abSPavel Tatashin 	 * function
2241eca499abSPavel Tatashin 	 */
2242e1c158e4SDavid Hildenbrand 	if (try_remove_memory(start, size))
2243eca499abSPavel Tatashin 		BUG();
2244eca499abSPavel Tatashin }
2245eca499abSPavel Tatashin 
2246eca499abSPavel Tatashin /*
2247eca499abSPavel Tatashin  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2248eca499abSPavel Tatashin  * some memory is not offline
2249eca499abSPavel Tatashin  */
2250e1c158e4SDavid Hildenbrand int remove_memory(u64 start, u64 size)
2251eca499abSPavel Tatashin {
2252eca499abSPavel Tatashin 	int rc;
2253eca499abSPavel Tatashin 
2254d15e5926SDavid Hildenbrand 	lock_device_hotplug();
2255e1c158e4SDavid Hildenbrand 	rc = try_remove_memory(start, size);
2256d15e5926SDavid Hildenbrand 	unlock_device_hotplug();
2257eca499abSPavel Tatashin 
2258eca499abSPavel Tatashin 	return rc;
2259d15e5926SDavid Hildenbrand }
226071088785SBadari Pulavarty EXPORT_SYMBOL_GPL(remove_memory);
226108b3acd7SDavid Hildenbrand 
22628dc4bb58SDavid Hildenbrand static int try_offline_memory_block(struct memory_block *mem, void *arg)
22638dc4bb58SDavid Hildenbrand {
22648dc4bb58SDavid Hildenbrand 	uint8_t online_type = MMOP_ONLINE_KERNEL;
22658dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
22668dc4bb58SDavid Hildenbrand 	struct page *page;
22678dc4bb58SDavid Hildenbrand 	int rc;
22688dc4bb58SDavid Hildenbrand 
226908b3acd7SDavid Hildenbrand 	/*
22708dc4bb58SDavid Hildenbrand 	 * Sense the online_type via the zone of the memory block. Offlining
22718dc4bb58SDavid Hildenbrand 	 * with multiple zones within one memory block will be rejected
22728dc4bb58SDavid Hildenbrand 	 * by offlining code ... so we don't care about that.
22738dc4bb58SDavid Hildenbrand 	 */
22748dc4bb58SDavid Hildenbrand 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
22758dc4bb58SDavid Hildenbrand 	if (page && zone_idx(page_zone(page)) == ZONE_MOVABLE)
22768dc4bb58SDavid Hildenbrand 		online_type = MMOP_ONLINE_MOVABLE;
22778dc4bb58SDavid Hildenbrand 
22788dc4bb58SDavid Hildenbrand 	rc = device_offline(&mem->dev);
22798dc4bb58SDavid Hildenbrand 	/*
22808dc4bb58SDavid Hildenbrand 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
22818dc4bb58SDavid Hildenbrand 	 * so try_reonline_memory_block() can do the right thing.
22828dc4bb58SDavid Hildenbrand 	 */
22838dc4bb58SDavid Hildenbrand 	if (!rc)
22848dc4bb58SDavid Hildenbrand 		**online_types = online_type;
22858dc4bb58SDavid Hildenbrand 
22868dc4bb58SDavid Hildenbrand 	(*online_types)++;
22878dc4bb58SDavid Hildenbrand 	/* Ignore if already offline. */
22888dc4bb58SDavid Hildenbrand 	return rc < 0 ? rc : 0;
22898dc4bb58SDavid Hildenbrand }
22908dc4bb58SDavid Hildenbrand 
22918dc4bb58SDavid Hildenbrand static int try_reonline_memory_block(struct memory_block *mem, void *arg)
22928dc4bb58SDavid Hildenbrand {
22938dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
22948dc4bb58SDavid Hildenbrand 	int rc;
22958dc4bb58SDavid Hildenbrand 
22968dc4bb58SDavid Hildenbrand 	if (**online_types != MMOP_OFFLINE) {
22978dc4bb58SDavid Hildenbrand 		mem->online_type = **online_types;
22988dc4bb58SDavid Hildenbrand 		rc = device_online(&mem->dev);
22998dc4bb58SDavid Hildenbrand 		if (rc < 0)
23008dc4bb58SDavid Hildenbrand 			pr_warn("%s: Failed to re-online memory: %d",
23018dc4bb58SDavid Hildenbrand 				__func__, rc);
23028dc4bb58SDavid Hildenbrand 	}
23038dc4bb58SDavid Hildenbrand 
23048dc4bb58SDavid Hildenbrand 	/* Continue processing all remaining memory blocks. */
23058dc4bb58SDavid Hildenbrand 	(*online_types)++;
23068dc4bb58SDavid Hildenbrand 	return 0;
23078dc4bb58SDavid Hildenbrand }
23088dc4bb58SDavid Hildenbrand 
23098dc4bb58SDavid Hildenbrand /*
23108dc4bb58SDavid Hildenbrand  * Try to offline and remove memory. Might take a long time to finish in case
23118dc4bb58SDavid Hildenbrand  * memory is still in use. Primarily useful for memory devices that logically
23128dc4bb58SDavid Hildenbrand  * unplugged all memory (so it's no longer in use) and want to offline + remove
23138dc4bb58SDavid Hildenbrand  * that memory.
231408b3acd7SDavid Hildenbrand  */
2315e1c158e4SDavid Hildenbrand int offline_and_remove_memory(u64 start, u64 size)
231608b3acd7SDavid Hildenbrand {
23178dc4bb58SDavid Hildenbrand 	const unsigned long mb_count = size / memory_block_size_bytes();
23188dc4bb58SDavid Hildenbrand 	uint8_t *online_types, *tmp;
23198dc4bb58SDavid Hildenbrand 	int rc;
232008b3acd7SDavid Hildenbrand 
232108b3acd7SDavid Hildenbrand 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
23228dc4bb58SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
23238dc4bb58SDavid Hildenbrand 		return -EINVAL;
232408b3acd7SDavid Hildenbrand 
232508b3acd7SDavid Hildenbrand 	/*
23268dc4bb58SDavid Hildenbrand 	 * We'll remember the old online type of each memory block, so we can
23278dc4bb58SDavid Hildenbrand 	 * try to revert whatever we did when offlining one memory block fails
23288dc4bb58SDavid Hildenbrand 	 * after offlining some others succeeded.
23298dc4bb58SDavid Hildenbrand 	 */
23308dc4bb58SDavid Hildenbrand 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
23318dc4bb58SDavid Hildenbrand 				     GFP_KERNEL);
23328dc4bb58SDavid Hildenbrand 	if (!online_types)
23338dc4bb58SDavid Hildenbrand 		return -ENOMEM;
23348dc4bb58SDavid Hildenbrand 	/*
23358dc4bb58SDavid Hildenbrand 	 * Initialize all states to MMOP_OFFLINE, so when we abort processing in
23368dc4bb58SDavid Hildenbrand 	 * try_offline_memory_block(), we'll skip all unprocessed blocks in
23378dc4bb58SDavid Hildenbrand 	 * try_reonline_memory_block().
23388dc4bb58SDavid Hildenbrand 	 */
23398dc4bb58SDavid Hildenbrand 	memset(online_types, MMOP_OFFLINE, mb_count);
23408dc4bb58SDavid Hildenbrand 
23418dc4bb58SDavid Hildenbrand 	lock_device_hotplug();
23428dc4bb58SDavid Hildenbrand 
23438dc4bb58SDavid Hildenbrand 	tmp = online_types;
23448dc4bb58SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
23458dc4bb58SDavid Hildenbrand 
23468dc4bb58SDavid Hildenbrand 	/*
23478dc4bb58SDavid Hildenbrand 	 * In case we succeeded to offline all memory, remove it.
234808b3acd7SDavid Hildenbrand 	 * This cannot fail as it cannot get onlined in the meantime.
234908b3acd7SDavid Hildenbrand 	 */
235008b3acd7SDavid Hildenbrand 	if (!rc) {
2351e1c158e4SDavid Hildenbrand 		rc = try_remove_memory(start, size);
23528dc4bb58SDavid Hildenbrand 		if (rc)
23538dc4bb58SDavid Hildenbrand 			pr_err("%s: Failed to remove memory: %d", __func__, rc);
23548dc4bb58SDavid Hildenbrand 	}
23558dc4bb58SDavid Hildenbrand 
23568dc4bb58SDavid Hildenbrand 	/*
23578dc4bb58SDavid Hildenbrand 	 * Rollback what we did. While memory onlining might theoretically fail
23588dc4bb58SDavid Hildenbrand 	 * (nacked by a notifier), it barely ever happens.
23598dc4bb58SDavid Hildenbrand 	 */
23608dc4bb58SDavid Hildenbrand 	if (rc) {
23618dc4bb58SDavid Hildenbrand 		tmp = online_types;
23628dc4bb58SDavid Hildenbrand 		walk_memory_blocks(start, size, &tmp,
23638dc4bb58SDavid Hildenbrand 				   try_reonline_memory_block);
236408b3acd7SDavid Hildenbrand 	}
236508b3acd7SDavid Hildenbrand 	unlock_device_hotplug();
236608b3acd7SDavid Hildenbrand 
23678dc4bb58SDavid Hildenbrand 	kfree(online_types);
236808b3acd7SDavid Hildenbrand 	return rc;
236908b3acd7SDavid Hildenbrand }
237008b3acd7SDavid Hildenbrand EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2371aba6efc4SRafael J. Wysocki #endif /* CONFIG_MEMORY_HOTREMOVE */
2372