xref: /linux/mm/memory_hotplug.c (revision 11684134140bb708b6e6de969a060535630b1b53)
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 {
104*11684134SSumanth Korikkar 	int mode = *((int *)kp->arg);
105*11684134SSumanth Korikkar 
106*11684134SSumanth Korikkar 	if (mode == MEMMAP_ON_MEMORY_FORCE)
1072d1f649cSAneesh Kumar K.V 		return sprintf(buffer, "force\n");
108*11684134SSumanth Korikkar 	return sprintf(buffer, "%c\n", mode ? 'Y' : 'N');
1092d1f649cSAneesh Kumar K.V }
1102d1f649cSAneesh Kumar K.V 
1112d1f649cSAneesh Kumar K.V static const struct kernel_param_ops memmap_mode_ops = {
1122d1f649cSAneesh Kumar K.V 	.set = set_memmap_mode,
1132d1f649cSAneesh Kumar K.V 	.get = get_memmap_mode,
1142d1f649cSAneesh Kumar K.V };
1152d1f649cSAneesh Kumar K.V module_param_cb(memmap_on_memory, &memmap_mode_ops, &memmap_mode, 0444);
1162d1f649cSAneesh Kumar K.V MODULE_PARM_DESC(memmap_on_memory, "Enable memmap on memory for memory hotplug\n"
1172d1f649cSAneesh Kumar K.V 		 "With value \"force\" it could result in memory wastage due "
1182d1f649cSAneesh Kumar K.V 		 "to memmap size limitations (Y/N/force)");
1196e02c46bSMuchun Song 
12066361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
1216e02c46bSMuchun Song {
1222d1f649cSAneesh Kumar K.V 	return memmap_mode != MEMMAP_ON_MEMORY_DISABLE;
1236e02c46bSMuchun Song }
12466361095SMuchun Song #else
12566361095SMuchun Song static inline bool mhp_memmap_on_memory(void)
12666361095SMuchun Song {
12766361095SMuchun Song 	return false;
12866361095SMuchun Song }
129e3a9d9fcSOscar Salvador #endif
130a08a2ae3SOscar Salvador 
131e83a437fSDavid Hildenbrand enum {
132e83a437fSDavid Hildenbrand 	ONLINE_POLICY_CONTIG_ZONES = 0,
133e83a437fSDavid Hildenbrand 	ONLINE_POLICY_AUTO_MOVABLE,
134e83a437fSDavid Hildenbrand };
135e83a437fSDavid Hildenbrand 
136ac62554bSTang Yizhou static const char * const online_policy_to_str[] = {
137e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_CONTIG_ZONES] = "contig-zones",
138e83a437fSDavid Hildenbrand 	[ONLINE_POLICY_AUTO_MOVABLE] = "auto-movable",
139e83a437fSDavid Hildenbrand };
140e83a437fSDavid Hildenbrand 
141e83a437fSDavid Hildenbrand static int set_online_policy(const char *val, const struct kernel_param *kp)
142e83a437fSDavid Hildenbrand {
143e83a437fSDavid Hildenbrand 	int ret = sysfs_match_string(online_policy_to_str, val);
144e83a437fSDavid Hildenbrand 
145e83a437fSDavid Hildenbrand 	if (ret < 0)
146e83a437fSDavid Hildenbrand 		return ret;
147e83a437fSDavid Hildenbrand 	*((int *)kp->arg) = ret;
148e83a437fSDavid Hildenbrand 	return 0;
149e83a437fSDavid Hildenbrand }
150e83a437fSDavid Hildenbrand 
151e83a437fSDavid Hildenbrand static int get_online_policy(char *buffer, const struct kernel_param *kp)
152e83a437fSDavid Hildenbrand {
153e83a437fSDavid Hildenbrand 	return sprintf(buffer, "%s\n", online_policy_to_str[*((int *)kp->arg)]);
154e83a437fSDavid Hildenbrand }
155e83a437fSDavid Hildenbrand 
156e83a437fSDavid Hildenbrand /*
157e83a437fSDavid Hildenbrand  * memory_hotplug.online_policy: configure online behavior when onlining without
158e83a437fSDavid Hildenbrand  * specifying a zone (MMOP_ONLINE)
159e83a437fSDavid Hildenbrand  *
160e83a437fSDavid Hildenbrand  * "contig-zones": keep zone contiguous
161e83a437fSDavid Hildenbrand  * "auto-movable": online memory to ZONE_MOVABLE if the configuration
162e83a437fSDavid Hildenbrand  *                 (auto_movable_ratio, auto_movable_numa_aware) allows for it
163e83a437fSDavid Hildenbrand  */
164e83a437fSDavid Hildenbrand static int online_policy __read_mostly = ONLINE_POLICY_CONTIG_ZONES;
165e83a437fSDavid Hildenbrand static const struct kernel_param_ops online_policy_ops = {
166e83a437fSDavid Hildenbrand 	.set = set_online_policy,
167e83a437fSDavid Hildenbrand 	.get = get_online_policy,
168e83a437fSDavid Hildenbrand };
169e83a437fSDavid Hildenbrand module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
170e83a437fSDavid Hildenbrand MODULE_PARM_DESC(online_policy,
171e83a437fSDavid Hildenbrand 		"Set the online policy (\"contig-zones\", \"auto-movable\") "
172e83a437fSDavid Hildenbrand 		"Default: \"contig-zones\"");
173e83a437fSDavid Hildenbrand 
174e83a437fSDavid Hildenbrand /*
175e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio
176e83a437fSDavid Hildenbrand  *
177e83a437fSDavid Hildenbrand  * The ratio represent an upper limit and the kernel might decide to not
178e83a437fSDavid Hildenbrand  * online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory
179e83a437fSDavid Hildenbrand  * doesn't allow for more MOVABLE memory.
180e83a437fSDavid Hildenbrand  */
181e83a437fSDavid Hildenbrand static unsigned int auto_movable_ratio __read_mostly = 301;
182e83a437fSDavid Hildenbrand module_param(auto_movable_ratio, uint, 0644);
183e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_ratio,
184e83a437fSDavid Hildenbrand 		"Set the maximum ratio of MOVABLE:KERNEL memory in the system "
185e83a437fSDavid Hildenbrand 		"in percent for \"auto-movable\" online policy. Default: 301");
186e83a437fSDavid Hildenbrand 
187e83a437fSDavid Hildenbrand /*
188e83a437fSDavid Hildenbrand  * memory_hotplug.auto_movable_numa_aware: consider numa node stats
189e83a437fSDavid Hildenbrand  */
190e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
191e83a437fSDavid Hildenbrand static bool auto_movable_numa_aware __read_mostly = true;
192e83a437fSDavid Hildenbrand module_param(auto_movable_numa_aware, bool, 0644);
193e83a437fSDavid Hildenbrand MODULE_PARM_DESC(auto_movable_numa_aware,
194e83a437fSDavid Hildenbrand 		"Consider numa node stats in addition to global stats in "
195e83a437fSDavid Hildenbrand 		"\"auto-movable\" online policy. Default: true");
196e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
197e83a437fSDavid Hildenbrand 
1989d0ad8caSDaniel Kiper /*
1999d0ad8caSDaniel Kiper  * online_page_callback contains pointer to current page onlining function.
2009d0ad8caSDaniel Kiper  * Initially it is generic_online_page(). If it is required it could be
2019d0ad8caSDaniel Kiper  * changed by calling set_online_page_callback() for callback registration
2029d0ad8caSDaniel Kiper  * and restore_online_page_callback() for generic callback restore.
2039d0ad8caSDaniel Kiper  */
2049d0ad8caSDaniel Kiper 
2059d0ad8caSDaniel Kiper static online_page_callback_t online_page_callback = generic_online_page;
206bfc8c901SVladimir Davydov static DEFINE_MUTEX(online_page_callback_lock);
2079d0ad8caSDaniel Kiper 
2083f906ba2SThomas Gleixner DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
20920d6c96bSKOSAKI Motohiro 
2103f906ba2SThomas Gleixner void get_online_mems(void)
2113f906ba2SThomas Gleixner {
2123f906ba2SThomas Gleixner 	percpu_down_read(&mem_hotplug_lock);
2133f906ba2SThomas Gleixner }
214bfc8c901SVladimir Davydov 
2153f906ba2SThomas Gleixner void put_online_mems(void)
2163f906ba2SThomas Gleixner {
2173f906ba2SThomas Gleixner 	percpu_up_read(&mem_hotplug_lock);
2183f906ba2SThomas Gleixner }
219bfc8c901SVladimir Davydov 
2204932381eSMichal Hocko bool movable_node_enabled = false;
2214932381eSMichal Hocko 
2228604d9e5SVitaly Kuznetsov #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
2231adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_OFFLINE;
2248604d9e5SVitaly Kuznetsov #else
2251adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_ONLINE;
2268604d9e5SVitaly Kuznetsov #endif
22731bc3858SVitaly Kuznetsov 
22886dd995dSVitaly Kuznetsov static int __init setup_memhp_default_state(char *str)
22986dd995dSVitaly Kuznetsov {
2301adf8b46SAnshuman Khandual 	const int online_type = mhp_online_type_from_str(str);
2315f47adf7SDavid Hildenbrand 
2325f47adf7SDavid Hildenbrand 	if (online_type >= 0)
2331adf8b46SAnshuman Khandual 		mhp_default_online_type = online_type;
23486dd995dSVitaly Kuznetsov 
23586dd995dSVitaly Kuznetsov 	return 1;
23686dd995dSVitaly Kuznetsov }
23786dd995dSVitaly Kuznetsov __setup("memhp_default_state=", setup_memhp_default_state);
23886dd995dSVitaly Kuznetsov 
23930467e0bSDavid Rientjes void mem_hotplug_begin(void)
240bfc8c901SVladimir Davydov {
2413f906ba2SThomas Gleixner 	cpus_read_lock();
2423f906ba2SThomas Gleixner 	percpu_down_write(&mem_hotplug_lock);
243bfc8c901SVladimir Davydov }
244bfc8c901SVladimir Davydov 
24530467e0bSDavid Rientjes void mem_hotplug_done(void)
246bfc8c901SVladimir Davydov {
2473f906ba2SThomas Gleixner 	percpu_up_write(&mem_hotplug_lock);
2483f906ba2SThomas Gleixner 	cpus_read_unlock();
249bfc8c901SVladimir Davydov }
25020d6c96bSKOSAKI Motohiro 
251357b4da5SJuergen Gross u64 max_mem_size = U64_MAX;
252357b4da5SJuergen Gross 
25345e0b78bSKeith Mannthey /* add this memory to iomem resource */
2547b7b2721SDavid Hildenbrand static struct resource *register_memory_resource(u64 start, u64 size,
2557b7b2721SDavid Hildenbrand 						 const char *resource_name)
25645e0b78bSKeith Mannthey {
2572794129eSDave Hansen 	struct resource *res;
2582794129eSDave Hansen 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
2597b7b2721SDavid Hildenbrand 
2607b7b2721SDavid Hildenbrand 	if (strcmp(resource_name, "System RAM"))
2617cf603d1SDavid Hildenbrand 		flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
262357b4da5SJuergen Gross 
263bca3feaaSAnshuman Khandual 	if (!mhp_range_allowed(start, size, true))
264bca3feaaSAnshuman Khandual 		return ERR_PTR(-E2BIG);
265bca3feaaSAnshuman Khandual 
266f3cd4c86SBaoquan He 	/*
267f3cd4c86SBaoquan He 	 * Make sure value parsed from 'mem=' only restricts memory adding
268f3cd4c86SBaoquan He 	 * while booting, so that memory hotplug won't be impacted. Please
269f3cd4c86SBaoquan He 	 * refer to document of 'mem=' in kernel-parameters.txt for more
270f3cd4c86SBaoquan He 	 * details.
271f3cd4c86SBaoquan He 	 */
272f3cd4c86SBaoquan He 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
273357b4da5SJuergen Gross 		return ERR_PTR(-E2BIG);
274357b4da5SJuergen Gross 
2752794129eSDave Hansen 	/*
2762794129eSDave Hansen 	 * Request ownership of the new memory range.  This might be
2772794129eSDave Hansen 	 * a child of an existing resource that was present but
2782794129eSDave Hansen 	 * not marked as busy.
2792794129eSDave Hansen 	 */
2802794129eSDave Hansen 	res = __request_region(&iomem_resource, start, size,
2812794129eSDave Hansen 			       resource_name, flags);
28245e0b78bSKeith Mannthey 
2832794129eSDave Hansen 	if (!res) {
2842794129eSDave Hansen 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
2852794129eSDave Hansen 				start, start + size);
2866f754ba4SVitaly Kuznetsov 		return ERR_PTR(-EEXIST);
28745e0b78bSKeith Mannthey 	}
28845e0b78bSKeith Mannthey 	return res;
28945e0b78bSKeith Mannthey }
29045e0b78bSKeith Mannthey 
29145e0b78bSKeith Mannthey static void release_memory_resource(struct resource *res)
29245e0b78bSKeith Mannthey {
29345e0b78bSKeith Mannthey 	if (!res)
29445e0b78bSKeith Mannthey 		return;
29545e0b78bSKeith Mannthey 	release_resource(res);
29645e0b78bSKeith Mannthey 	kfree(res);
29745e0b78bSKeith Mannthey }
29845e0b78bSKeith Mannthey 
299943189dbSAnshuman Khandual static int check_pfn_span(unsigned long pfn, unsigned long nr_pages)
3007ea62160SDan Williams {
3017ea62160SDan Williams 	/*
3027ea62160SDan Williams 	 * Disallow all operations smaller than a sub-section and only
3037ea62160SDan Williams 	 * allow operations smaller than a section for
3047ea62160SDan Williams 	 * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
3057ea62160SDan Williams 	 * enforces a larger memory_block_size_bytes() granularity for
3067ea62160SDan Williams 	 * memory that will be marked online, so this check should only
3077ea62160SDan Williams 	 * fire for direct arch_{add,remove}_memory() users outside of
3087ea62160SDan Williams 	 * add_memory_resource().
3097ea62160SDan Williams 	 */
3107ea62160SDan Williams 	unsigned long min_align;
3117ea62160SDan Williams 
3127ea62160SDan Williams 	if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
3137ea62160SDan Williams 		min_align = PAGES_PER_SUBSECTION;
3147ea62160SDan Williams 	else
3157ea62160SDan Williams 		min_align = PAGES_PER_SECTION;
316943189dbSAnshuman Khandual 	if (!IS_ALIGNED(pfn | nr_pages, min_align))
3177ea62160SDan Williams 		return -EINVAL;
3187ea62160SDan Williams 	return 0;
3197ea62160SDan Williams }
3207ea62160SDan Williams 
3214edd7cefSDavid Rientjes /*
3229f605f26SDan Williams  * Return page for the valid pfn only if the page is online. All pfn
3239f605f26SDan Williams  * walkers which rely on the fully initialized page->flags and others
3249f605f26SDan Williams  * should use this rather than pfn_valid && pfn_to_page
3259f605f26SDan Williams  */
3269f605f26SDan Williams struct page *pfn_to_online_page(unsigned long pfn)
3279f605f26SDan Williams {
3289f605f26SDan Williams 	unsigned long nr = pfn_to_section_nr(pfn);
3291f90a347SDan Williams 	struct dev_pagemap *pgmap;
3309f9b02e5SDan Williams 	struct mem_section *ms;
3319f605f26SDan Williams 
3329f9b02e5SDan Williams 	if (nr >= NR_MEM_SECTIONS)
3339f605f26SDan Williams 		return NULL;
3349f9b02e5SDan Williams 
3359f9b02e5SDan Williams 	ms = __nr_to_section(nr);
3369f9b02e5SDan Williams 	if (!online_section(ms))
3379f9b02e5SDan Williams 		return NULL;
3389f9b02e5SDan Williams 
3399f9b02e5SDan Williams 	/*
3409f9b02e5SDan Williams 	 * Save some code text when online_section() +
3419f9b02e5SDan Williams 	 * pfn_section_valid() are sufficient.
3429f9b02e5SDan Williams 	 */
3439f9b02e5SDan Williams 	if (IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID) && !pfn_valid(pfn))
3449f9b02e5SDan Williams 		return NULL;
3459f9b02e5SDan Williams 
3469f9b02e5SDan Williams 	if (!pfn_section_valid(ms, pfn))
3479f9b02e5SDan Williams 		return NULL;
3489f9b02e5SDan Williams 
3491f90a347SDan Williams 	if (!online_device_section(ms))
3501f90a347SDan Williams 		return pfn_to_page(pfn);
3511f90a347SDan Williams 
3521f90a347SDan Williams 	/*
3531f90a347SDan Williams 	 * Slowpath: when ZONE_DEVICE collides with
3541f90a347SDan Williams 	 * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
3551f90a347SDan Williams 	 * the section may be 'offline' but 'valid'. Only
3561f90a347SDan Williams 	 * get_dev_pagemap() can determine sub-section online status.
3571f90a347SDan Williams 	 */
3581f90a347SDan Williams 	pgmap = get_dev_pagemap(pfn, NULL);
3591f90a347SDan Williams 	put_dev_pagemap(pgmap);
3601f90a347SDan Williams 
3611f90a347SDan Williams 	/* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
3621f90a347SDan Williams 	if (pgmap)
3631f90a347SDan Williams 		return NULL;
3641f90a347SDan Williams 
3659f9b02e5SDan Williams 	return pfn_to_page(pfn);
3669f605f26SDan Williams }
3679f605f26SDan Williams EXPORT_SYMBOL_GPL(pfn_to_online_page);
3689f605f26SDan Williams 
3697ea62160SDan Williams int __ref __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
370f5637d3bSLogan Gunthorpe 		struct mhp_params *params)
3714edd7cefSDavid Rientjes {
3726cdd0b30SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
3736cdd0b30SDavid Hildenbrand 	unsigned long cur_nr_pages;
3749a845030SDan Williams 	int err;
375f5637d3bSLogan Gunthorpe 	struct vmem_altmap *altmap = params->altmap;
3764b94ffdcSDan Williams 
3776366238bSliusongtang 	if (WARN_ON_ONCE(!pgprot_val(params->pgprot)))
378bfeb022fSLogan Gunthorpe 		return -EINVAL;
379bfeb022fSLogan Gunthorpe 
380bca3feaaSAnshuman Khandual 	VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
381dca4436dSAlastair D'Silva 
3824b94ffdcSDan Williams 	if (altmap) {
3834b94ffdcSDan Williams 		/*
3844b94ffdcSDan Williams 		 * Validate altmap is within bounds of the total request
3854b94ffdcSDan Williams 		 */
3867ea62160SDan Williams 		if (altmap->base_pfn != pfn
3874b94ffdcSDan Williams 				|| vmem_altmap_offset(altmap) > nr_pages) {
3884b94ffdcSDan Williams 			pr_warn_once("memory add fail, invalid altmap\n");
3897ea62160SDan Williams 			return -EINVAL;
3904b94ffdcSDan Williams 		}
3914b94ffdcSDan Williams 		altmap->alloc = 0;
3924b94ffdcSDan Williams 	}
3934b94ffdcSDan Williams 
394943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
39550135045SRick Wertenbroek 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
396943189dbSAnshuman Khandual 		return -EINVAL;
397943189dbSAnshuman Khandual 	}
3987ea62160SDan Williams 
3996cdd0b30SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
4006cdd0b30SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
4016cdd0b30SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
4026cdd0b30SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
403e3246d8fSJoao Martins 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
404e3246d8fSJoao Martins 					 params->pgmap);
405ba72b4c8SDan Williams 		if (err)
406ba72b4c8SDan Williams 			break;
407f64ac5e6SMichal Hocko 		cond_resched();
4084edd7cefSDavid Rientjes 	}
409c435a390SZhu Guihua 	vmemmap_populate_print_last();
4104edd7cefSDavid Rientjes 	return err;
4114edd7cefSDavid Rientjes }
4124edd7cefSDavid Rientjes 
413815121d2SYasuaki Ishimatsu /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
414d09b0137SYASUAKI ISHIMATSU static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
415815121d2SYasuaki Ishimatsu 				     unsigned long start_pfn,
416815121d2SYasuaki Ishimatsu 				     unsigned long end_pfn)
417815121d2SYasuaki Ishimatsu {
41849ba3c6bSDan Williams 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
4197ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(start_pfn)))
420815121d2SYasuaki Ishimatsu 			continue;
421815121d2SYasuaki Ishimatsu 
422815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(start_pfn) != nid))
423815121d2SYasuaki Ishimatsu 			continue;
424815121d2SYasuaki Ishimatsu 
4259b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(start_pfn)))
426815121d2SYasuaki Ishimatsu 			continue;
427815121d2SYasuaki Ishimatsu 
428815121d2SYasuaki Ishimatsu 		return start_pfn;
429815121d2SYasuaki Ishimatsu 	}
430815121d2SYasuaki Ishimatsu 
431815121d2SYasuaki Ishimatsu 	return 0;
432815121d2SYasuaki Ishimatsu }
433815121d2SYasuaki Ishimatsu 
434815121d2SYasuaki Ishimatsu /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
435d09b0137SYASUAKI ISHIMATSU static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
436815121d2SYasuaki Ishimatsu 				    unsigned long start_pfn,
437815121d2SYasuaki Ishimatsu 				    unsigned long end_pfn)
438815121d2SYasuaki Ishimatsu {
439815121d2SYasuaki Ishimatsu 	unsigned long pfn;
440815121d2SYasuaki Ishimatsu 
441815121d2SYasuaki Ishimatsu 	/* pfn is the end pfn of a memory section. */
442815121d2SYasuaki Ishimatsu 	pfn = end_pfn - 1;
44349ba3c6bSDan Williams 	for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
4447ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(pfn)))
445815121d2SYasuaki Ishimatsu 			continue;
446815121d2SYasuaki Ishimatsu 
447815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(pfn) != nid))
448815121d2SYasuaki Ishimatsu 			continue;
449815121d2SYasuaki Ishimatsu 
4509b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(pfn)))
451815121d2SYasuaki Ishimatsu 			continue;
452815121d2SYasuaki Ishimatsu 
453815121d2SYasuaki Ishimatsu 		return pfn;
454815121d2SYasuaki Ishimatsu 	}
455815121d2SYasuaki Ishimatsu 
456815121d2SYasuaki Ishimatsu 	return 0;
457815121d2SYasuaki Ishimatsu }
458815121d2SYasuaki Ishimatsu 
459815121d2SYasuaki Ishimatsu static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
460815121d2SYasuaki Ishimatsu 			     unsigned long end_pfn)
461815121d2SYasuaki Ishimatsu {
462815121d2SYasuaki Ishimatsu 	unsigned long pfn;
463815121d2SYasuaki Ishimatsu 	int nid = zone_to_nid(zone);
464815121d2SYasuaki Ishimatsu 
4655d12071cSDavid Hildenbrand 	if (zone->zone_start_pfn == start_pfn) {
466815121d2SYasuaki Ishimatsu 		/*
467815121d2SYasuaki Ishimatsu 		 * If the section is smallest section in the zone, it need
468815121d2SYasuaki Ishimatsu 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
469815121d2SYasuaki Ishimatsu 		 * In this case, we find second smallest valid mem_section
470815121d2SYasuaki Ishimatsu 		 * for shrinking zone.
471815121d2SYasuaki Ishimatsu 		 */
472815121d2SYasuaki Ishimatsu 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
4735d12071cSDavid Hildenbrand 						zone_end_pfn(zone));
474815121d2SYasuaki Ishimatsu 		if (pfn) {
4755d12071cSDavid Hildenbrand 			zone->spanned_pages = zone_end_pfn(zone) - pfn;
476815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = pfn;
477950b68d9SDavid Hildenbrand 		} else {
478950b68d9SDavid Hildenbrand 			zone->zone_start_pfn = 0;
479950b68d9SDavid Hildenbrand 			zone->spanned_pages = 0;
480815121d2SYasuaki Ishimatsu 		}
4815d12071cSDavid Hildenbrand 	} else if (zone_end_pfn(zone) == end_pfn) {
482815121d2SYasuaki Ishimatsu 		/*
483815121d2SYasuaki Ishimatsu 		 * If the section is biggest section in the zone, it need
484815121d2SYasuaki Ishimatsu 		 * shrink zone->spanned_pages.
485815121d2SYasuaki Ishimatsu 		 * In this case, we find second biggest valid mem_section for
486815121d2SYasuaki Ishimatsu 		 * shrinking zone.
487815121d2SYasuaki Ishimatsu 		 */
4885d12071cSDavid Hildenbrand 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
489815121d2SYasuaki Ishimatsu 					       start_pfn);
490815121d2SYasuaki Ishimatsu 		if (pfn)
4915d12071cSDavid Hildenbrand 			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
492950b68d9SDavid Hildenbrand 		else {
493815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = 0;
494815121d2SYasuaki Ishimatsu 			zone->spanned_pages = 0;
495950b68d9SDavid Hildenbrand 		}
496950b68d9SDavid Hildenbrand 	}
497815121d2SYasuaki Ishimatsu }
498815121d2SYasuaki Ishimatsu 
49900d6c019SDavid Hildenbrand static void update_pgdat_span(struct pglist_data *pgdat)
500815121d2SYasuaki Ishimatsu {
50100d6c019SDavid Hildenbrand 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
50200d6c019SDavid Hildenbrand 	struct zone *zone;
503815121d2SYasuaki Ishimatsu 
50400d6c019SDavid Hildenbrand 	for (zone = pgdat->node_zones;
50500d6c019SDavid Hildenbrand 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
5066c922cf7SMiaohe Lin 		unsigned long end_pfn = zone_end_pfn(zone);
50700d6c019SDavid Hildenbrand 
50800d6c019SDavid Hildenbrand 		/* No need to lock the zones, they can't change. */
509656d5711SDavid Hildenbrand 		if (!zone->spanned_pages)
510656d5711SDavid Hildenbrand 			continue;
511656d5711SDavid Hildenbrand 		if (!node_end_pfn) {
512656d5711SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
5136c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
514656d5711SDavid Hildenbrand 			continue;
515656d5711SDavid Hildenbrand 		}
516656d5711SDavid Hildenbrand 
5176c922cf7SMiaohe Lin 		if (end_pfn > node_end_pfn)
5186c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
51900d6c019SDavid Hildenbrand 		if (zone->zone_start_pfn < node_start_pfn)
52000d6c019SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
521815121d2SYasuaki Ishimatsu 	}
522815121d2SYasuaki Ishimatsu 
52300d6c019SDavid Hildenbrand 	pgdat->node_start_pfn = node_start_pfn;
52400d6c019SDavid Hildenbrand 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
525815121d2SYasuaki Ishimatsu }
526815121d2SYasuaki Ishimatsu 
527feee6b29SDavid Hildenbrand void __ref remove_pfn_range_from_zone(struct zone *zone,
528feee6b29SDavid Hildenbrand 				      unsigned long start_pfn,
5297ea62160SDan Williams 				      unsigned long nr_pages)
530815121d2SYasuaki Ishimatsu {
531b7e3debdSBen Widawsky 	const unsigned long end_pfn = start_pfn + nr_pages;
532815121d2SYasuaki Ishimatsu 	struct pglist_data *pgdat = zone->zone_pgdat;
53327cacaadSOscar Salvador 	unsigned long pfn, cur_nr_pages;
534815121d2SYasuaki Ishimatsu 
535d33695b1SDavid Hildenbrand 	/* Poison struct pages because they are now uninitialized again. */
536b7e3debdSBen Widawsky 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
537b7e3debdSBen Widawsky 		cond_resched();
538b7e3debdSBen Widawsky 
539b7e3debdSBen Widawsky 		/* Select all remaining pages up to the next section boundary */
540b7e3debdSBen Widawsky 		cur_nr_pages =
541b7e3debdSBen Widawsky 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
542b7e3debdSBen Widawsky 		page_init_poison(pfn_to_page(pfn),
543b7e3debdSBen Widawsky 				 sizeof(struct page) * cur_nr_pages);
544b7e3debdSBen Widawsky 	}
545d33695b1SDavid Hildenbrand 
5467ce700bfSDavid Hildenbrand 	/*
5477ce700bfSDavid Hildenbrand 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
5487ce700bfSDavid Hildenbrand 	 * we will not try to shrink the zones - which is okay as
5497ce700bfSDavid Hildenbrand 	 * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
5507ce700bfSDavid Hildenbrand 	 */
5515ef5f810SMiaohe Lin 	if (zone_is_zone_device(zone))
5527ce700bfSDavid Hildenbrand 		return;
5537ce700bfSDavid Hildenbrand 
554feee6b29SDavid Hildenbrand 	clear_zone_contiguous(zone);
555feee6b29SDavid Hildenbrand 
556815121d2SYasuaki Ishimatsu 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
55700d6c019SDavid Hildenbrand 	update_pgdat_span(pgdat);
558feee6b29SDavid Hildenbrand 
559feee6b29SDavid Hildenbrand 	set_zone_contiguous(zone);
560815121d2SYasuaki Ishimatsu }
561815121d2SYasuaki Ishimatsu 
562ea01ea93SBadari Pulavarty /**
563feee6b29SDavid Hildenbrand  * __remove_pages() - remove sections of pages
5647ea62160SDan Williams  * @pfn: starting pageframe (must be aligned to start of a section)
565ea01ea93SBadari Pulavarty  * @nr_pages: number of pages to remove (must be multiple of section size)
566e8b098fcSMike Rapoport  * @altmap: alternative device page map or %NULL if default memmap is used
567ea01ea93SBadari Pulavarty  *
568ea01ea93SBadari Pulavarty  * Generic helper function to remove section mappings and sysfs entries
569ea01ea93SBadari Pulavarty  * for the section of the memory we are removing. Caller needs to make
570ea01ea93SBadari Pulavarty  * sure that pages are marked reserved and zones are adjust properly by
571ea01ea93SBadari Pulavarty  * calling offline_pages().
572ea01ea93SBadari Pulavarty  */
573feee6b29SDavid Hildenbrand void __remove_pages(unsigned long pfn, unsigned long nr_pages,
574feee6b29SDavid Hildenbrand 		    struct vmem_altmap *altmap)
575ea01ea93SBadari Pulavarty {
57652fb87c8SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
57752fb87c8SDavid Hildenbrand 	unsigned long cur_nr_pages;
578ea01ea93SBadari Pulavarty 
579943189dbSAnshuman Khandual 	if (check_pfn_span(pfn, nr_pages)) {
58050135045SRick Wertenbroek 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
5817ea62160SDan Williams 		return;
582943189dbSAnshuman Khandual 	}
583ea01ea93SBadari Pulavarty 
58452fb87c8SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
585dd33ad7bSMichal Hocko 		cond_resched();
58652fb87c8SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
587a11b9419SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
588a11b9419SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
589bd5f79abSYajun Deng 		sparse_remove_section(pfn, cur_nr_pages, altmap);
590ea01ea93SBadari Pulavarty 	}
591ea01ea93SBadari Pulavarty }
592ea01ea93SBadari Pulavarty 
5939d0ad8caSDaniel Kiper int set_online_page_callback(online_page_callback_t callback)
5949d0ad8caSDaniel Kiper {
5959d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5969d0ad8caSDaniel Kiper 
597bfc8c901SVladimir Davydov 	get_online_mems();
598bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5999d0ad8caSDaniel Kiper 
6009d0ad8caSDaniel Kiper 	if (online_page_callback == generic_online_page) {
6019d0ad8caSDaniel Kiper 		online_page_callback = callback;
6029d0ad8caSDaniel Kiper 		rc = 0;
6039d0ad8caSDaniel Kiper 	}
6049d0ad8caSDaniel Kiper 
605bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
606bfc8c901SVladimir Davydov 	put_online_mems();
6079d0ad8caSDaniel Kiper 
6089d0ad8caSDaniel Kiper 	return rc;
6099d0ad8caSDaniel Kiper }
6109d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(set_online_page_callback);
6119d0ad8caSDaniel Kiper 
6129d0ad8caSDaniel Kiper int restore_online_page_callback(online_page_callback_t callback)
6139d0ad8caSDaniel Kiper {
6149d0ad8caSDaniel Kiper 	int rc = -EINVAL;
6159d0ad8caSDaniel Kiper 
616bfc8c901SVladimir Davydov 	get_online_mems();
617bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
6189d0ad8caSDaniel Kiper 
6199d0ad8caSDaniel Kiper 	if (online_page_callback == callback) {
6209d0ad8caSDaniel Kiper 		online_page_callback = generic_online_page;
6219d0ad8caSDaniel Kiper 		rc = 0;
6229d0ad8caSDaniel Kiper 	}
6239d0ad8caSDaniel Kiper 
624bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
625bfc8c901SVladimir Davydov 	put_online_mems();
6269d0ad8caSDaniel Kiper 
6279d0ad8caSDaniel Kiper 	return rc;
6289d0ad8caSDaniel Kiper }
6299d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(restore_online_page_callback);
6309d0ad8caSDaniel Kiper 
63118db1491SDavid Hildenbrand void generic_online_page(struct page *page, unsigned int order)
6329d0ad8caSDaniel Kiper {
633c87cbc1fSVlastimil Babka 	/*
634c87cbc1fSVlastimil Babka 	 * Freeing the page with debug_pagealloc enabled will try to unmap it,
635c87cbc1fSVlastimil Babka 	 * so we should map it first. This is better than introducing a special
636c87cbc1fSVlastimil Babka 	 * case in page freeing fast path.
637c87cbc1fSVlastimil Babka 	 */
63877bc7fd6SMike Rapoport 	debug_pagealloc_map_pages(page, 1 << order);
639a9cd410aSArun KS 	__free_pages_core(page, order);
640a9cd410aSArun KS 	totalram_pages_add(1UL << order);
641a9cd410aSArun KS }
64218db1491SDavid Hildenbrand EXPORT_SYMBOL_GPL(generic_online_page);
643a9cd410aSArun KS 
644aac65321SDavid Hildenbrand static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
6453947be19SDave Hansen {
646b2c2ab20SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
647b2c2ab20SDavid Hildenbrand 	unsigned long pfn;
6482d070eabSMichal Hocko 
649b2c2ab20SDavid Hildenbrand 	/*
6505e0a760bSKirill A. Shutemov 	 * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
651aac65321SDavid Hildenbrand 	 * decide to not expose all pages to the buddy (e.g., expose them
652aac65321SDavid Hildenbrand 	 * later). We account all pages as being online and belonging to this
653aac65321SDavid Hildenbrand 	 * zone ("present").
654a08a2ae3SOscar Salvador 	 * When using memmap_on_memory, the range might not be aligned to
655a08a2ae3SOscar Salvador 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
656a08a2ae3SOscar Salvador 	 * this and the first chunk to online will be pageblock_nr_pages.
657b2c2ab20SDavid Hildenbrand 	 */
658a08a2ae3SOscar Salvador 	for (pfn = start_pfn; pfn < end_pfn;) {
65959f876fbSKirill A. Shutemov 		int order;
66059f876fbSKirill A. Shutemov 
66159f876fbSKirill A. Shutemov 		/*
66259f876fbSKirill A. Shutemov 		 * Free to online pages in the largest chunks alignment allows.
66359f876fbSKirill A. Shutemov 		 *
66459f876fbSKirill A. Shutemov 		 * __ffs() behaviour is undefined for 0. start == 0 is
6655e0a760bSKirill A. Shutemov 		 * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
6665e0a760bSKirill A. Shutemov 		 * the case.
66759f876fbSKirill A. Shutemov 		 */
66859f876fbSKirill A. Shutemov 		if (pfn)
6695e0a760bSKirill A. Shutemov 			order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
67059f876fbSKirill A. Shutemov 		else
6715e0a760bSKirill A. Shutemov 			order = MAX_PAGE_ORDER;
672a08a2ae3SOscar Salvador 
673a08a2ae3SOscar Salvador 		(*online_page_callback)(pfn_to_page(pfn), order);
674a08a2ae3SOscar Salvador 		pfn += (1UL << order);
675a08a2ae3SOscar Salvador 	}
6762d070eabSMichal Hocko 
677b2c2ab20SDavid Hildenbrand 	/* mark all involved sections as online */
678b2c2ab20SDavid Hildenbrand 	online_mem_sections(start_pfn, end_pfn);
67975884fb1SKAMEZAWA Hiroyuki }
68075884fb1SKAMEZAWA Hiroyuki 
681d9713679SLai Jiangshan /* check which state of node_states will be changed when online memory */
682d9713679SLai Jiangshan static void node_states_check_changes_online(unsigned long nr_pages,
683d9713679SLai Jiangshan 	struct zone *zone, struct memory_notify *arg)
684d9713679SLai Jiangshan {
685d9713679SLai Jiangshan 	int nid = zone_to_nid(zone);
686d9713679SLai Jiangshan 
68798fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
68898fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
6896715ddf9SLai Jiangshan 
6906715ddf9SLai Jiangshan 	if (!node_state(nid, N_MEMORY))
691d9713679SLai Jiangshan 		arg->status_change_nid = nid;
6928efe33f4SOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
6938efe33f4SOscar Salvador 		arg->status_change_nid_normal = nid;
694d9713679SLai Jiangshan }
695d9713679SLai Jiangshan 
696d9713679SLai Jiangshan static void node_states_set_node(int node, struct memory_notify *arg)
697d9713679SLai Jiangshan {
698d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
699d9713679SLai Jiangshan 		node_set_state(node, N_NORMAL_MEMORY);
700d9713679SLai Jiangshan 
70183d83612SOscar Salvador 	if (arg->status_change_nid >= 0)
7026715ddf9SLai Jiangshan 		node_set_state(node, N_MEMORY);
703d9713679SLai Jiangshan }
704d9713679SLai Jiangshan 
705f1dd2cd1SMichal Hocko static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
706f1dd2cd1SMichal Hocko 		unsigned long nr_pages)
707f1dd2cd1SMichal Hocko {
708f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = zone_end_pfn(zone);
709f1dd2cd1SMichal Hocko 
710f1dd2cd1SMichal Hocko 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
711f1dd2cd1SMichal Hocko 		zone->zone_start_pfn = start_pfn;
712f1dd2cd1SMichal Hocko 
713f1dd2cd1SMichal Hocko 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
714f1dd2cd1SMichal Hocko }
715f1dd2cd1SMichal Hocko 
716f1dd2cd1SMichal Hocko static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
717f1dd2cd1SMichal Hocko                                      unsigned long nr_pages)
718f1dd2cd1SMichal Hocko {
719f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
720f1dd2cd1SMichal Hocko 
721f1dd2cd1SMichal Hocko 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
722f1dd2cd1SMichal Hocko 		pgdat->node_start_pfn = start_pfn;
723f1dd2cd1SMichal Hocko 
724f1dd2cd1SMichal Hocko 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
725f1dd2cd1SMichal Hocko 
7263fccb74cSDavid Hildenbrand }
7271f90a347SDan Williams 
728ed7802ddSMuchun Song #ifdef CONFIG_ZONE_DEVICE
7291f90a347SDan Williams static void section_taint_zone_device(unsigned long pfn)
7301f90a347SDan Williams {
7311f90a347SDan Williams 	struct mem_section *ms = __pfn_to_section(pfn);
7321f90a347SDan Williams 
7331f90a347SDan Williams 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
7341f90a347SDan Williams }
735ed7802ddSMuchun Song #else
736ed7802ddSMuchun Song static inline void section_taint_zone_device(unsigned long pfn)
737ed7802ddSMuchun Song {
738ed7802ddSMuchun Song }
739ed7802ddSMuchun Song #endif
7401f90a347SDan Williams 
7413fccb74cSDavid Hildenbrand /*
7423fccb74cSDavid Hildenbrand  * Associate the pfn range with the given zone, initializing the memmaps
7433fccb74cSDavid Hildenbrand  * and resizing the pgdat/zone data to span the added pages. After this
7443fccb74cSDavid Hildenbrand  * call, all affected pages are PG_reserved.
745d882c006SDavid Hildenbrand  *
746d882c006SDavid Hildenbrand  * All aligned pageblocks are initialized to the specified migratetype
747d882c006SDavid Hildenbrand  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
748d882c006SDavid Hildenbrand  * zone stats (e.g., nr_isolate_pageblock) are touched.
7493fccb74cSDavid Hildenbrand  */
750a99583e7SChristoph Hellwig void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
751d882c006SDavid Hildenbrand 				  unsigned long nr_pages,
752d882c006SDavid Hildenbrand 				  struct vmem_altmap *altmap, int migratetype)
753f1dd2cd1SMichal Hocko {
754f1dd2cd1SMichal Hocko 	struct pglist_data *pgdat = zone->zone_pgdat;
755f1dd2cd1SMichal Hocko 	int nid = pgdat->node_id;
756f1dd2cd1SMichal Hocko 
757f1dd2cd1SMichal Hocko 	clear_zone_contiguous(zone);
758f1dd2cd1SMichal Hocko 
759fa004ab7SWei Yang 	if (zone_is_empty(zone))
760fa004ab7SWei Yang 		init_currently_empty_zone(zone, start_pfn, nr_pages);
761f1dd2cd1SMichal Hocko 	resize_zone_range(zone, start_pfn, nr_pages);
762f1dd2cd1SMichal Hocko 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
763f1dd2cd1SMichal Hocko 
764f1dd2cd1SMichal Hocko 	/*
7651f90a347SDan Williams 	 * Subsection population requires care in pfn_to_online_page().
7661f90a347SDan Williams 	 * Set the taint to enable the slow path detection of
7671f90a347SDan Williams 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
7681f90a347SDan Williams 	 * section.
7691f90a347SDan Williams 	 */
7701f90a347SDan Williams 	if (zone_is_zone_device(zone)) {
7711f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
7721f90a347SDan Williams 			section_taint_zone_device(start_pfn);
7731f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
7741f90a347SDan Williams 			section_taint_zone_device(start_pfn + nr_pages);
7751f90a347SDan Williams 	}
7761f90a347SDan Williams 
7771f90a347SDan Williams 	/*
778f1dd2cd1SMichal Hocko 	 * TODO now we have a visible range of pages which are not associated
779f1dd2cd1SMichal Hocko 	 * with their zone properly. Not nice but set_pfnblock_flags_mask
780f1dd2cd1SMichal Hocko 	 * expects the zone spans the pfn range. All the pages in the range
781f1dd2cd1SMichal Hocko 	 * are reserved so nobody should be touching them so we should be safe
782f1dd2cd1SMichal Hocko 	 */
783ab28cb6eSBaoquan He 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
784d882c006SDavid Hildenbrand 			 MEMINIT_HOTPLUG, altmap, migratetype);
785f1dd2cd1SMichal Hocko 
786f1dd2cd1SMichal Hocko 	set_zone_contiguous(zone);
787f1dd2cd1SMichal Hocko }
788f1dd2cd1SMichal Hocko 
789e83a437fSDavid Hildenbrand struct auto_movable_stats {
790e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages;
791e83a437fSDavid Hildenbrand 	unsigned long movable_pages;
792e83a437fSDavid Hildenbrand };
793e83a437fSDavid Hildenbrand 
794e83a437fSDavid Hildenbrand static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
795e83a437fSDavid Hildenbrand 					    struct zone *zone)
796e83a437fSDavid Hildenbrand {
797e83a437fSDavid Hildenbrand 	if (zone_idx(zone) == ZONE_MOVABLE) {
798e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->present_pages;
799e83a437fSDavid Hildenbrand 	} else {
800e83a437fSDavid Hildenbrand 		stats->kernel_early_pages += zone->present_early_pages;
801e83a437fSDavid Hildenbrand #ifdef CONFIG_CMA
802e83a437fSDavid Hildenbrand 		/*
803e83a437fSDavid Hildenbrand 		 * CMA pages (never on hotplugged memory) behave like
804e83a437fSDavid Hildenbrand 		 * ZONE_MOVABLE.
805e83a437fSDavid Hildenbrand 		 */
806e83a437fSDavid Hildenbrand 		stats->movable_pages += zone->cma_pages;
807e83a437fSDavid Hildenbrand 		stats->kernel_early_pages -= zone->cma_pages;
808e83a437fSDavid Hildenbrand #endif /* CONFIG_CMA */
809e83a437fSDavid Hildenbrand 	}
810e83a437fSDavid Hildenbrand }
8113fcebf90SDavid Hildenbrand struct auto_movable_group_stats {
8123fcebf90SDavid Hildenbrand 	unsigned long movable_pages;
8133fcebf90SDavid Hildenbrand 	unsigned long req_kernel_early_pages;
8143fcebf90SDavid Hildenbrand };
815e83a437fSDavid Hildenbrand 
8163fcebf90SDavid Hildenbrand static int auto_movable_stats_account_group(struct memory_group *group,
8173fcebf90SDavid Hildenbrand 					   void *arg)
818e83a437fSDavid Hildenbrand {
8193fcebf90SDavid Hildenbrand 	const int ratio = READ_ONCE(auto_movable_ratio);
8203fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats *stats = arg;
8213fcebf90SDavid Hildenbrand 	long pages;
8223fcebf90SDavid Hildenbrand 
8233fcebf90SDavid Hildenbrand 	/*
8243fcebf90SDavid Hildenbrand 	 * We don't support modifying the config while the auto-movable online
8253fcebf90SDavid Hildenbrand 	 * policy is already enabled. Just avoid the division by zero below.
8263fcebf90SDavid Hildenbrand 	 */
8273fcebf90SDavid Hildenbrand 	if (!ratio)
8283fcebf90SDavid Hildenbrand 		return 0;
8293fcebf90SDavid Hildenbrand 
8303fcebf90SDavid Hildenbrand 	/*
8313fcebf90SDavid Hildenbrand 	 * Calculate how many early kernel pages this group requires to
8323fcebf90SDavid Hildenbrand 	 * satisfy the configured zone ratio.
8333fcebf90SDavid Hildenbrand 	 */
8343fcebf90SDavid Hildenbrand 	pages = group->present_movable_pages * 100 / ratio;
8353fcebf90SDavid Hildenbrand 	pages -= group->present_kernel_pages;
8363fcebf90SDavid Hildenbrand 
8373fcebf90SDavid Hildenbrand 	if (pages > 0)
8383fcebf90SDavid Hildenbrand 		stats->req_kernel_early_pages += pages;
8393fcebf90SDavid Hildenbrand 	stats->movable_pages += group->present_movable_pages;
8403fcebf90SDavid Hildenbrand 	return 0;
8413fcebf90SDavid Hildenbrand }
8423fcebf90SDavid Hildenbrand 
8433fcebf90SDavid Hildenbrand static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
8443fcebf90SDavid Hildenbrand 					    unsigned long nr_pages)
8453fcebf90SDavid Hildenbrand {
846e83a437fSDavid Hildenbrand 	unsigned long kernel_early_pages, movable_pages;
8473fcebf90SDavid Hildenbrand 	struct auto_movable_group_stats group_stats = {};
8483fcebf90SDavid Hildenbrand 	struct auto_movable_stats stats = {};
849e83a437fSDavid Hildenbrand 	pg_data_t *pgdat = NODE_DATA(nid);
850e83a437fSDavid Hildenbrand 	struct zone *zone;
851e83a437fSDavid Hildenbrand 	int i;
852e83a437fSDavid Hildenbrand 
853e83a437fSDavid Hildenbrand 	/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
854e83a437fSDavid Hildenbrand 	if (nid == NUMA_NO_NODE) {
855e83a437fSDavid Hildenbrand 		/* TODO: cache values */
856e83a437fSDavid Hildenbrand 		for_each_populated_zone(zone)
857e83a437fSDavid Hildenbrand 			auto_movable_stats_account_zone(&stats, zone);
858e83a437fSDavid Hildenbrand 	} else {
859e83a437fSDavid Hildenbrand 		for (i = 0; i < MAX_NR_ZONES; i++) {
860e83a437fSDavid Hildenbrand 			zone = pgdat->node_zones + i;
861e83a437fSDavid Hildenbrand 			if (populated_zone(zone))
862e83a437fSDavid Hildenbrand 				auto_movable_stats_account_zone(&stats, zone);
863e83a437fSDavid Hildenbrand 		}
864e83a437fSDavid Hildenbrand 	}
865e83a437fSDavid Hildenbrand 
866e83a437fSDavid Hildenbrand 	kernel_early_pages = stats.kernel_early_pages;
867e83a437fSDavid Hildenbrand 	movable_pages = stats.movable_pages;
868e83a437fSDavid Hildenbrand 
869e83a437fSDavid Hildenbrand 	/*
8703fcebf90SDavid Hildenbrand 	 * Kernel memory inside dynamic memory group allows for more MOVABLE
8713fcebf90SDavid Hildenbrand 	 * memory within the same group. Remove the effect of all but the
8723fcebf90SDavid Hildenbrand 	 * current group from the stats.
8733fcebf90SDavid Hildenbrand 	 */
8743fcebf90SDavid Hildenbrand 	walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
8753fcebf90SDavid Hildenbrand 				   group, &group_stats);
8763fcebf90SDavid Hildenbrand 	if (kernel_early_pages <= group_stats.req_kernel_early_pages)
8773fcebf90SDavid Hildenbrand 		return false;
8783fcebf90SDavid Hildenbrand 	kernel_early_pages -= group_stats.req_kernel_early_pages;
8793fcebf90SDavid Hildenbrand 	movable_pages -= group_stats.movable_pages;
8803fcebf90SDavid Hildenbrand 
8813fcebf90SDavid Hildenbrand 	if (group && group->is_dynamic)
8823fcebf90SDavid Hildenbrand 		kernel_early_pages += group->present_kernel_pages;
8833fcebf90SDavid Hildenbrand 
8843fcebf90SDavid Hildenbrand 	/*
885e83a437fSDavid Hildenbrand 	 * Test if we could online the given number of pages to ZONE_MOVABLE
886e83a437fSDavid Hildenbrand 	 * and still stay in the configured ratio.
887e83a437fSDavid Hildenbrand 	 */
888e83a437fSDavid Hildenbrand 	movable_pages += nr_pages;
889e83a437fSDavid Hildenbrand 	return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
890e83a437fSDavid Hildenbrand }
891e83a437fSDavid Hildenbrand 
892f1dd2cd1SMichal Hocko /*
893c246a213SMichal Hocko  * Returns a default kernel memory zone for the given pfn range.
894c246a213SMichal Hocko  * If no kernel zone covers this pfn range it will automatically go
895c246a213SMichal Hocko  * to the ZONE_NORMAL.
896c246a213SMichal Hocko  */
897c6f03e29SMichal Hocko static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
898c246a213SMichal Hocko 		unsigned long nr_pages)
899c246a213SMichal Hocko {
900c246a213SMichal Hocko 	struct pglist_data *pgdat = NODE_DATA(nid);
901c246a213SMichal Hocko 	int zid;
902c246a213SMichal Hocko 
903d6aad201SMiaohe Lin 	for (zid = 0; zid < ZONE_NORMAL; zid++) {
904c246a213SMichal Hocko 		struct zone *zone = &pgdat->node_zones[zid];
905c246a213SMichal Hocko 
906c246a213SMichal Hocko 		if (zone_intersects(zone, start_pfn, nr_pages))
907c246a213SMichal Hocko 			return zone;
908c246a213SMichal Hocko 	}
909c246a213SMichal Hocko 
910c246a213SMichal Hocko 	return &pgdat->node_zones[ZONE_NORMAL];
911c246a213SMichal Hocko }
912c246a213SMichal Hocko 
913e83a437fSDavid Hildenbrand /*
914e83a437fSDavid Hildenbrand  * Determine to which zone to online memory dynamically based on user
915e83a437fSDavid Hildenbrand  * configuration and system stats. We care about the following ratio:
916e83a437fSDavid Hildenbrand  *
917e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL
918e83a437fSDavid Hildenbrand  *
919e83a437fSDavid Hildenbrand  * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
920e83a437fSDavid Hildenbrand  * one of the kernel zones. CMA pages inside one of the kernel zones really
921e83a437fSDavid Hildenbrand  * behaves like ZONE_MOVABLE, so we treat them accordingly.
922e83a437fSDavid Hildenbrand  *
923e83a437fSDavid Hildenbrand  * We don't allow for hotplugged memory in a KERNEL zone to increase the
924e83a437fSDavid Hildenbrand  * amount of MOVABLE memory we can have, so we end up with:
925e83a437fSDavid Hildenbrand  *
926e83a437fSDavid Hildenbrand  *   MOVABLE : KERNEL_EARLY
927e83a437fSDavid Hildenbrand  *
928e83a437fSDavid Hildenbrand  * Whereby KERNEL_EARLY is memory in one of the kernel zones, available sinze
929e83a437fSDavid Hildenbrand  * boot. We base our calculation on KERNEL_EARLY internally, because:
930e83a437fSDavid Hildenbrand  *
931e83a437fSDavid Hildenbrand  * a) Hotplugged memory in one of the kernel zones can sometimes still get
932e83a437fSDavid Hildenbrand  *    hotunplugged, especially when hot(un)plugging individual memory blocks.
933e83a437fSDavid Hildenbrand  *    There is no coordination across memory devices, therefore "automatic"
934e83a437fSDavid Hildenbrand  *    hotunplugging, as implemented in hypervisors, could result in zone
935e83a437fSDavid Hildenbrand  *    imbalances.
936e83a437fSDavid Hildenbrand  * b) Early/boot memory in one of the kernel zones can usually not get
937e83a437fSDavid Hildenbrand  *    hotunplugged again (e.g., no firmware interface to unplug, fragmented
938e83a437fSDavid Hildenbrand  *    with unmovable allocations). While there are corner cases where it might
939e83a437fSDavid Hildenbrand  *    still work, it is barely relevant in practice.
940e83a437fSDavid Hildenbrand  *
9413fcebf90SDavid Hildenbrand  * Exceptions are dynamic memory groups, which allow for more MOVABLE
9423fcebf90SDavid Hildenbrand  * memory within the same memory group -- because in that case, there is
9433fcebf90SDavid Hildenbrand  * coordination within the single memory device managed by a single driver.
9443fcebf90SDavid Hildenbrand  *
945e83a437fSDavid Hildenbrand  * We rely on "present pages" instead of "managed pages", as the latter is
946e83a437fSDavid Hildenbrand  * highly unreliable and dynamic in virtualized environments, and does not
947e83a437fSDavid Hildenbrand  * consider boot time allocations. For example, memory ballooning adjusts the
948e83a437fSDavid Hildenbrand  * managed pages when inflating/deflating the balloon, and balloon compaction
949e83a437fSDavid Hildenbrand  * can even migrate inflated pages between zones.
950e83a437fSDavid Hildenbrand  *
951e83a437fSDavid Hildenbrand  * Using "present pages" is better but some things to keep in mind are:
952e83a437fSDavid Hildenbrand  *
953e83a437fSDavid Hildenbrand  * a) Some memblock allocations, such as for the crashkernel area, are
954e83a437fSDavid Hildenbrand  *    effectively unused by the kernel, yet they account to "present pages".
955e83a437fSDavid Hildenbrand  *    Fortunately, these allocations are comparatively small in relevant setups
956e83a437fSDavid Hildenbrand  *    (e.g., fraction of system memory).
957e83a437fSDavid Hildenbrand  * b) Some hotplugged memory blocks in virtualized environments, esecially
958e83a437fSDavid Hildenbrand  *    hotplugged by virtio-mem, look like they are completely present, however,
959e83a437fSDavid Hildenbrand  *    only parts of the memory block are actually currently usable.
960e83a437fSDavid Hildenbrand  *    "present pages" is an upper limit that can get reached at runtime. As
961e83a437fSDavid Hildenbrand  *    we base our calculations on KERNEL_EARLY, this is not an issue.
962e83a437fSDavid Hildenbrand  */
963445fcf7cSDavid Hildenbrand static struct zone *auto_movable_zone_for_pfn(int nid,
964445fcf7cSDavid Hildenbrand 					      struct memory_group *group,
965445fcf7cSDavid Hildenbrand 					      unsigned long pfn,
966e83a437fSDavid Hildenbrand 					      unsigned long nr_pages)
967e83a437fSDavid Hildenbrand {
968445fcf7cSDavid Hildenbrand 	unsigned long online_pages = 0, max_pages, end_pfn;
969445fcf7cSDavid Hildenbrand 	struct page *page;
970445fcf7cSDavid Hildenbrand 
971e83a437fSDavid Hildenbrand 	if (!auto_movable_ratio)
972e83a437fSDavid Hildenbrand 		goto kernel_zone;
973e83a437fSDavid Hildenbrand 
974445fcf7cSDavid Hildenbrand 	if (group && !group->is_dynamic) {
975445fcf7cSDavid Hildenbrand 		max_pages = group->s.max_pages;
976445fcf7cSDavid Hildenbrand 		online_pages = group->present_movable_pages;
977445fcf7cSDavid Hildenbrand 
978445fcf7cSDavid Hildenbrand 		/* If anything is !MOVABLE online the rest !MOVABLE. */
979445fcf7cSDavid Hildenbrand 		if (group->present_kernel_pages)
980445fcf7cSDavid Hildenbrand 			goto kernel_zone;
981445fcf7cSDavid Hildenbrand 	} else if (!group || group->d.unit_pages == nr_pages) {
982445fcf7cSDavid Hildenbrand 		max_pages = nr_pages;
983445fcf7cSDavid Hildenbrand 	} else {
984445fcf7cSDavid Hildenbrand 		max_pages = group->d.unit_pages;
985445fcf7cSDavid Hildenbrand 		/*
986445fcf7cSDavid Hildenbrand 		 * Take a look at all online sections in the current unit.
987445fcf7cSDavid Hildenbrand 		 * We can safely assume that all pages within a section belong
988445fcf7cSDavid Hildenbrand 		 * to the same zone, because dynamic memory groups only deal
989445fcf7cSDavid Hildenbrand 		 * with hotplugged memory.
990445fcf7cSDavid Hildenbrand 		 */
991445fcf7cSDavid Hildenbrand 		pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
992445fcf7cSDavid Hildenbrand 		end_pfn = pfn + group->d.unit_pages;
993445fcf7cSDavid Hildenbrand 		for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
994445fcf7cSDavid Hildenbrand 			page = pfn_to_online_page(pfn);
995445fcf7cSDavid Hildenbrand 			if (!page)
996445fcf7cSDavid Hildenbrand 				continue;
997445fcf7cSDavid Hildenbrand 			/* If anything is !MOVABLE online the rest !MOVABLE. */
99807252dfeSKefeng Wang 			if (!is_zone_movable_page(page))
999445fcf7cSDavid Hildenbrand 				goto kernel_zone;
1000445fcf7cSDavid Hildenbrand 			online_pages += PAGES_PER_SECTION;
1001445fcf7cSDavid Hildenbrand 		}
1002445fcf7cSDavid Hildenbrand 	}
1003445fcf7cSDavid Hildenbrand 
1004445fcf7cSDavid Hildenbrand 	/*
1005445fcf7cSDavid Hildenbrand 	 * Online MOVABLE if we could *currently* online all remaining parts
1006445fcf7cSDavid Hildenbrand 	 * MOVABLE. We expect to (add+) online them immediately next, so if
1007445fcf7cSDavid Hildenbrand 	 * nobody interferes, all will be MOVABLE if possible.
1008445fcf7cSDavid Hildenbrand 	 */
1009445fcf7cSDavid Hildenbrand 	nr_pages = max_pages - online_pages;
10103fcebf90SDavid Hildenbrand 	if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
1011e83a437fSDavid Hildenbrand 		goto kernel_zone;
1012e83a437fSDavid Hildenbrand 
1013e83a437fSDavid Hildenbrand #ifdef CONFIG_NUMA
1014e83a437fSDavid Hildenbrand 	if (auto_movable_numa_aware &&
10153fcebf90SDavid Hildenbrand 	    !auto_movable_can_online_movable(nid, group, nr_pages))
1016e83a437fSDavid Hildenbrand 		goto kernel_zone;
1017e83a437fSDavid Hildenbrand #endif /* CONFIG_NUMA */
1018e83a437fSDavid Hildenbrand 
1019e83a437fSDavid Hildenbrand 	return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1020e83a437fSDavid Hildenbrand kernel_zone:
1021e83a437fSDavid Hildenbrand 	return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
1022e83a437fSDavid Hildenbrand }
1023e83a437fSDavid Hildenbrand 
1024c6f03e29SMichal Hocko static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
1025c6f03e29SMichal Hocko 		unsigned long nr_pages)
1026e5e68930SMichal Hocko {
1027c6f03e29SMichal Hocko 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
1028c6f03e29SMichal Hocko 			nr_pages);
1029c6f03e29SMichal Hocko 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1030c6f03e29SMichal Hocko 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
1031c6f03e29SMichal Hocko 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
1032e5e68930SMichal Hocko 
1033e5e68930SMichal Hocko 	/*
1034c6f03e29SMichal Hocko 	 * We inherit the existing zone in a simple case where zones do not
1035c6f03e29SMichal Hocko 	 * overlap in the given range
1036e5e68930SMichal Hocko 	 */
1037c6f03e29SMichal Hocko 	if (in_kernel ^ in_movable)
1038c6f03e29SMichal Hocko 		return (in_kernel) ? kernel_zone : movable_zone;
1039e5e68930SMichal Hocko 
1040c6f03e29SMichal Hocko 	/*
1041c6f03e29SMichal Hocko 	 * If the range doesn't belong to any zone or two zones overlap in the
1042c6f03e29SMichal Hocko 	 * given range then we use movable zone only if movable_node is
1043c6f03e29SMichal Hocko 	 * enabled because we always online to a kernel zone by default.
1044c6f03e29SMichal Hocko 	 */
1045c6f03e29SMichal Hocko 	return movable_node_enabled ? movable_zone : kernel_zone;
10469f123ab5SMichal Hocko }
10479f123ab5SMichal Hocko 
10487cf209baSDavid Hildenbrand struct zone *zone_for_pfn_range(int online_type, int nid,
1049445fcf7cSDavid Hildenbrand 		struct memory_group *group, unsigned long start_pfn,
1050e5e68930SMichal Hocko 		unsigned long nr_pages)
1051f1dd2cd1SMichal Hocko {
1052c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_KERNEL)
1053c6f03e29SMichal Hocko 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
1054f1dd2cd1SMichal Hocko 
1055c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_MOVABLE)
1056c6f03e29SMichal Hocko 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1057f1dd2cd1SMichal Hocko 
1058e83a437fSDavid Hildenbrand 	if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
1059445fcf7cSDavid Hildenbrand 		return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
1060e83a437fSDavid Hildenbrand 
1061c6f03e29SMichal Hocko 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
1062e5e68930SMichal Hocko }
1063e5e68930SMichal Hocko 
1064a08a2ae3SOscar Salvador /*
1065a08a2ae3SOscar Salvador  * This function should only be called by memory_block_{online,offline},
1066a08a2ae3SOscar Salvador  * and {online,offline}_pages.
1067a08a2ae3SOscar Salvador  */
1068836809ecSDavid Hildenbrand void adjust_present_page_count(struct page *page, struct memory_group *group,
1069836809ecSDavid Hildenbrand 			       long nr_pages)
1070f9901144SDavid Hildenbrand {
10714b097002SDavid Hildenbrand 	struct zone *zone = page_zone(page);
1072836809ecSDavid Hildenbrand 	const bool movable = zone_idx(zone) == ZONE_MOVABLE;
10734b097002SDavid Hildenbrand 
10744b097002SDavid Hildenbrand 	/*
10754b097002SDavid Hildenbrand 	 * We only support onlining/offlining/adding/removing of complete
10764b097002SDavid Hildenbrand 	 * memory blocks; therefore, either all is either early or hotplugged.
10774b097002SDavid Hildenbrand 	 */
10784b097002SDavid Hildenbrand 	if (early_section(__pfn_to_section(page_to_pfn(page))))
10794b097002SDavid Hildenbrand 		zone->present_early_pages += nr_pages;
1080f9901144SDavid Hildenbrand 	zone->present_pages += nr_pages;
1081f9901144SDavid Hildenbrand 	zone->zone_pgdat->node_present_pages += nr_pages;
1082836809ecSDavid Hildenbrand 
1083836809ecSDavid Hildenbrand 	if (group && movable)
1084836809ecSDavid Hildenbrand 		group->present_movable_pages += nr_pages;
1085836809ecSDavid Hildenbrand 	else if (group && !movable)
1086836809ecSDavid Hildenbrand 		group->present_kernel_pages += nr_pages;
1087f9901144SDavid Hildenbrand }
1088f9901144SDavid Hildenbrand 
1089a08a2ae3SOscar Salvador int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
1090a08a2ae3SOscar Salvador 			      struct zone *zone)
1091a08a2ae3SOscar Salvador {
1092a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
109366361095SMuchun Song 	int ret, i;
1094a08a2ae3SOscar Salvador 
1095a08a2ae3SOscar Salvador 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1096a08a2ae3SOscar Salvador 	if (ret)
1097a08a2ae3SOscar Salvador 		return ret;
1098a08a2ae3SOscar Salvador 
1099a08a2ae3SOscar Salvador 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE);
1100a08a2ae3SOscar Salvador 
110166361095SMuchun Song 	for (i = 0; i < nr_pages; i++)
110266361095SMuchun Song 		SetPageVmemmapSelfHosted(pfn_to_page(pfn + i));
110366361095SMuchun Song 
1104a08a2ae3SOscar Salvador 	/*
1105a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1106a08a2ae3SOscar Salvador 	 * the case, mark those sections online here as otherwise they will be
1107a08a2ae3SOscar Salvador 	 * left offline.
1108a08a2ae3SOscar Salvador 	 */
1109a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1110a08a2ae3SOscar Salvador 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1111a08a2ae3SOscar Salvador 
1112a08a2ae3SOscar Salvador 	return ret;
1113a08a2ae3SOscar Salvador }
1114a08a2ae3SOscar Salvador 
1115a08a2ae3SOscar Salvador void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
1116a08a2ae3SOscar Salvador {
1117a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
1118a08a2ae3SOscar Salvador 
1119a08a2ae3SOscar Salvador 	/*
1120a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
1121a08a2ae3SOscar Salvador 	 * the case, mark those sections offline here as otherwise they will be
1122a08a2ae3SOscar Salvador 	 * left online.
1123a08a2ae3SOscar Salvador 	 */
1124a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
1125a08a2ae3SOscar Salvador 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1126a08a2ae3SOscar Salvador 
1127a08a2ae3SOscar Salvador         /*
1128a08a2ae3SOscar Salvador 	 * The pages associated with this vmemmap have been offlined, so
1129a08a2ae3SOscar Salvador 	 * we can reset its state here.
1130a08a2ae3SOscar Salvador 	 */
1131a08a2ae3SOscar Salvador 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
1132a08a2ae3SOscar Salvador 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1133a08a2ae3SOscar Salvador }
1134a08a2ae3SOscar Salvador 
1135001002e7SSumanth Korikkar /*
1136001002e7SSumanth Korikkar  * Must be called with mem_hotplug_lock in write mode.
1137001002e7SSumanth Korikkar  */
1138836809ecSDavid Hildenbrand int __ref online_pages(unsigned long pfn, unsigned long nr_pages,
1139836809ecSDavid Hildenbrand 		       struct zone *zone, struct memory_group *group)
114075884fb1SKAMEZAWA Hiroyuki {
1141aa47228aSCody P Schafer 	unsigned long flags;
11426811378eSYasunori Goto 	int need_zonelists_rebuild = 0;
1143a08a2ae3SOscar Salvador 	const int nid = zone_to_nid(zone);
11447b78d335SYasunori Goto 	int ret;
11457b78d335SYasunori Goto 	struct memory_notify arg;
11463947be19SDave Hansen 
1147dd8e2f23SOscar Salvador 	/*
1148dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1149041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1150dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1151dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1152dd8e2f23SOscar Salvador 	 * aligned.
1153dd8e2f23SOscar Salvador 	 */
1154ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
1155dd8e2f23SOscar Salvador 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
11564986fac1SDavid Hildenbrand 		return -EINVAL;
11574986fac1SDavid Hildenbrand 
1158381eab4aSDavid Hildenbrand 
1159f1dd2cd1SMichal Hocko 	/* associate pfn range with the zone */
1160b30c5927SDavid Hildenbrand 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_ISOLATE);
1161511c2abaSLai Jiangshan 
11627b78d335SYasunori Goto 	arg.start_pfn = pfn;
11637b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1164d9713679SLai Jiangshan 	node_states_check_changes_online(nr_pages, zone, &arg);
11657b78d335SYasunori Goto 
11667b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_ONLINE, &arg);
11677b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
1168e33e33b4SChen Yucong 	if (ret)
1169e33e33b4SChen Yucong 		goto failed_addition;
1170e33e33b4SChen Yucong 
11713947be19SDave Hansen 	/*
1172b30c5927SDavid Hildenbrand 	 * Fixup the number of isolated pageblocks before marking the sections
1173b30c5927SDavid Hildenbrand 	 * onlining, such that undo_isolate_page_range() works correctly.
1174b30c5927SDavid Hildenbrand 	 */
1175b30c5927SDavid Hildenbrand 	spin_lock_irqsave(&zone->lock, flags);
1176b30c5927SDavid Hildenbrand 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
1177b30c5927SDavid Hildenbrand 	spin_unlock_irqrestore(&zone->lock, flags);
1178b30c5927SDavid Hildenbrand 
1179b30c5927SDavid Hildenbrand 	/*
11806811378eSYasunori Goto 	 * If this zone is not populated, then it is not in zonelist.
11816811378eSYasunori Goto 	 * This means the page allocator ignores this zone.
11826811378eSYasunori Goto 	 * So, zonelist must be updated after online.
11836811378eSYasunori Goto 	 */
11846dcd73d7SWen Congyang 	if (!populated_zone(zone)) {
11856811378eSYasunori Goto 		need_zonelists_rebuild = 1;
118672675e13SMichal Hocko 		setup_zone_pageset(zone);
11876dcd73d7SWen Congyang 	}
11886811378eSYasunori Goto 
1189aac65321SDavid Hildenbrand 	online_pages_range(pfn, nr_pages);
1190836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
1191aa47228aSCody P Schafer 
1192b30c5927SDavid Hildenbrand 	node_states_set_node(nid, &arg);
1193b30c5927SDavid Hildenbrand 	if (need_zonelists_rebuild)
1194b30c5927SDavid Hildenbrand 		build_all_zonelists(NULL);
1195b30c5927SDavid Hildenbrand 
1196b30c5927SDavid Hildenbrand 	/* Basic onlining is complete, allow allocation of onlined pages. */
1197b30c5927SDavid Hildenbrand 	undo_isolate_page_range(pfn, pfn + nr_pages, MIGRATE_MOVABLE);
1198b30c5927SDavid Hildenbrand 
119993146d98SDavid Hildenbrand 	/*
1200b86c5fc4SDavid Hildenbrand 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
1201b86c5fc4SDavid Hildenbrand 	 * the tail of the freelist when undoing isolation). Shuffle the whole
1202b86c5fc4SDavid Hildenbrand 	 * zone to make sure the just onlined pages are properly distributed
1203b86c5fc4SDavid Hildenbrand 	 * across the whole freelist - to create an initial shuffle.
120493146d98SDavid Hildenbrand 	 */
1205e900a918SDan Williams 	shuffle_zone(zone);
1206e900a918SDan Williams 
1207b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
12081b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
12091b79acc9SKOSAKI Motohiro 
1210e888ca35SVlastimil Babka 	kswapd_run(nid);
1211698b1b30SVlastimil Babka 	kcompactd_run(nid);
121261b13993SDave Hansen 
12132d1d43f6SChandra Seetharaman 	writeback_set_ratelimit();
12147b78d335SYasunori Goto 
12157b78d335SYasunori Goto 	memory_notify(MEM_ONLINE, &arg);
121630467e0bSDavid Rientjes 	return 0;
1217e33e33b4SChen Yucong 
1218e33e33b4SChen Yucong failed_addition:
1219e33e33b4SChen Yucong 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1220e33e33b4SChen Yucong 		 (unsigned long long) pfn << PAGE_SHIFT,
1221e33e33b4SChen Yucong 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1222e33e33b4SChen Yucong 	memory_notify(MEM_CANCEL_ONLINE, &arg);
1223feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
1224e33e33b4SChen Yucong 	return ret;
12253947be19SDave Hansen }
1226bc02af93SYasunori Goto 
1227e1319331SHidetoshi Seto /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
122809f49dcaSMichal Hocko static pg_data_t __ref *hotadd_init_pgdat(int nid)
12299af3c2deSYasunori Goto {
12309af3c2deSYasunori Goto 	struct pglist_data *pgdat;
12319af3c2deSYasunori Goto 
123209f49dcaSMichal Hocko 	/*
123309f49dcaSMichal Hocko 	 * NODE_DATA is preallocated (free_area_init) but its internal
123409f49dcaSMichal Hocko 	 * state is not allocated completely. Add missing pieces.
123509f49dcaSMichal Hocko 	 * Completely offline nodes stay around and they just need
123609f49dcaSMichal Hocko 	 * reintialization.
123709f49dcaSMichal Hocko 	 */
123870b5b46aSMichal Hocko 	pgdat = NODE_DATA(nid);
123903e85f9dSOscar Salvador 
12409af3c2deSYasunori Goto 	/* init node's zones as empty zones, we don't have any present pages.*/
124170b5b46aSMichal Hocko 	free_area_init_core_hotplug(pgdat);
12429af3c2deSYasunori Goto 
1243959ecc48SKAMEZAWA Hiroyuki 	/*
1244959ecc48SKAMEZAWA Hiroyuki 	 * The node we allocated has no zone fallback lists. For avoiding
1245959ecc48SKAMEZAWA Hiroyuki 	 * to access not-initialized zonelist, build here.
1246959ecc48SKAMEZAWA Hiroyuki 	 */
124772675e13SMichal Hocko 	build_all_zonelists(pgdat);
1248959ecc48SKAMEZAWA Hiroyuki 
12499af3c2deSYasunori Goto 	return pgdat;
12509af3c2deSYasunori Goto }
12519af3c2deSYasunori Goto 
1252ba2d2666SMel Gorman /*
1253ba2d2666SMel Gorman  * __try_online_node - online a node if offlined
1254e8b098fcSMike Rapoport  * @nid: the node ID
1255b9ff0360SOscar Salvador  * @set_node_online: Whether we want to online the node
1256cf23422bSminskey guo  * called by cpu_up() to online a node without onlined memory.
1257b9ff0360SOscar Salvador  *
1258b9ff0360SOscar Salvador  * Returns:
1259b9ff0360SOscar Salvador  * 1 -> a new node has been allocated
1260b9ff0360SOscar Salvador  * 0 -> the node is already online
1261b9ff0360SOscar Salvador  * -ENOMEM -> the node could not be allocated
1262cf23422bSminskey guo  */
1263c68ab18cSDavid Hildenbrand static int __try_online_node(int nid, bool set_node_online)
1264cf23422bSminskey guo {
1265cf23422bSminskey guo 	pg_data_t *pgdat;
1266b9ff0360SOscar Salvador 	int ret = 1;
1267cf23422bSminskey guo 
126801b0f197SToshi Kani 	if (node_online(nid))
126901b0f197SToshi Kani 		return 0;
127001b0f197SToshi Kani 
127109f49dcaSMichal Hocko 	pgdat = hotadd_init_pgdat(nid);
12727553e8f2SDavid Rientjes 	if (!pgdat) {
127301b0f197SToshi Kani 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1274cf23422bSminskey guo 		ret = -ENOMEM;
1275cf23422bSminskey guo 		goto out;
1276cf23422bSminskey guo 	}
1277b9ff0360SOscar Salvador 
1278b9ff0360SOscar Salvador 	if (set_node_online) {
1279cf23422bSminskey guo 		node_set_online(nid);
1280cf23422bSminskey guo 		ret = register_one_node(nid);
1281cf23422bSminskey guo 		BUG_ON(ret);
1282b9ff0360SOscar Salvador 	}
1283cf23422bSminskey guo out:
1284b9ff0360SOscar Salvador 	return ret;
1285b9ff0360SOscar Salvador }
1286b9ff0360SOscar Salvador 
1287b9ff0360SOscar Salvador /*
1288b9ff0360SOscar Salvador  * Users of this function always want to online/register the node
1289b9ff0360SOscar Salvador  */
1290b9ff0360SOscar Salvador int try_online_node(int nid)
1291b9ff0360SOscar Salvador {
1292b9ff0360SOscar Salvador 	int ret;
1293b9ff0360SOscar Salvador 
1294b9ff0360SOscar Salvador 	mem_hotplug_begin();
1295c68ab18cSDavid Hildenbrand 	ret =  __try_online_node(nid, true);
1296bfc8c901SVladimir Davydov 	mem_hotplug_done();
1297cf23422bSminskey guo 	return ret;
1298cf23422bSminskey guo }
1299cf23422bSminskey guo 
130027356f54SToshi Kani static int check_hotplug_memory_range(u64 start, u64 size)
130127356f54SToshi Kani {
1302ba325585SPavel Tatashin 	/* memory range must be block size aligned */
1303cec3ebd0SDavid Hildenbrand 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1304cec3ebd0SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1305ba325585SPavel Tatashin 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1306cec3ebd0SDavid Hildenbrand 		       memory_block_size_bytes(), start, size);
130727356f54SToshi Kani 		return -EINVAL;
130827356f54SToshi Kani 	}
130927356f54SToshi Kani 
131027356f54SToshi Kani 	return 0;
131127356f54SToshi Kani }
131227356f54SToshi Kani 
131331bc3858SVitaly Kuznetsov static int online_memory_block(struct memory_block *mem, void *arg)
131431bc3858SVitaly Kuznetsov {
13151adf8b46SAnshuman Khandual 	mem->online_type = mhp_default_online_type;
1316dc18d706SNathan Fontenot 	return device_online(&mem->dev);
131731bc3858SVitaly Kuznetsov }
131831bc3858SVitaly Kuznetsov 
131985a2b4b0SAneesh Kumar K.V #ifndef arch_supports_memmap_on_memory
132085a2b4b0SAneesh Kumar K.V static inline bool arch_supports_memmap_on_memory(unsigned long vmemmap_size)
132185a2b4b0SAneesh Kumar K.V {
132285a2b4b0SAneesh Kumar K.V 	/*
132385a2b4b0SAneesh Kumar K.V 	 * As default, we want the vmemmap to span a complete PMD such that we
132485a2b4b0SAneesh Kumar K.V 	 * can map the vmemmap using a single PMD if supported by the
132585a2b4b0SAneesh Kumar K.V 	 * architecture.
132685a2b4b0SAneesh Kumar K.V 	 */
132785a2b4b0SAneesh Kumar K.V 	return IS_ALIGNED(vmemmap_size, PMD_SIZE);
132885a2b4b0SAneesh Kumar K.V }
132985a2b4b0SAneesh Kumar K.V #endif
133085a2b4b0SAneesh Kumar K.V 
1331e3c2bfddSAneesh Kumar K.V static bool mhp_supports_memmap_on_memory(unsigned long size)
1332a08a2ae3SOscar Salvador {
133385a2b4b0SAneesh Kumar K.V 	unsigned long vmemmap_size = memory_block_memmap_size();
13342d1f649cSAneesh Kumar K.V 	unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
1335a08a2ae3SOscar Salvador 
1336a08a2ae3SOscar Salvador 	/*
1337a08a2ae3SOscar Salvador 	 * Besides having arch support and the feature enabled at runtime, we
1338a08a2ae3SOscar Salvador 	 * need a few more assumptions to hold true:
1339a08a2ae3SOscar Salvador 	 *
1340a08a2ae3SOscar Salvador 	 * a) We span a single memory block: memory onlining/offlinin;g happens
1341a08a2ae3SOscar Salvador 	 *    in memory block granularity. We don't want the vmemmap of online
1342a08a2ae3SOscar Salvador 	 *    memory blocks to reside on offline memory blocks. In the future,
1343a08a2ae3SOscar Salvador 	 *    we might want to support variable-sized memory blocks to make the
1344a08a2ae3SOscar Salvador 	 *    feature more versatile.
1345a08a2ae3SOscar Salvador 	 *
1346a08a2ae3SOscar Salvador 	 * b) The vmemmap pages span complete PMDs: We don't want vmemmap code
1347a08a2ae3SOscar Salvador 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1348a08a2ae3SOscar Salvador 	 *    other memory blocks)
1349a08a2ae3SOscar Salvador 	 *
1350a08a2ae3SOscar Salvador 	 * c) The vmemmap pages (and thereby the pages that will be exposed to
1351a08a2ae3SOscar Salvador 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1352a08a2ae3SOscar Salvador 	 *    code requires applicable ranges to be page-aligned, for example, to
1353a08a2ae3SOscar Salvador 	 *    set the migratetypes properly.
1354a08a2ae3SOscar Salvador 	 *
1355a08a2ae3SOscar Salvador 	 * TODO: Although we have a check here to make sure that vmemmap pages
1356a08a2ae3SOscar Salvador 	 *       fully populate a PMD, it is not the right place to check for
1357a08a2ae3SOscar Salvador 	 *       this. A much better solution involves improving vmemmap code
1358a08a2ae3SOscar Salvador 	 *       to fallback to base pages when trying to populate vmemmap using
1359a08a2ae3SOscar Salvador 	 *       altmap as an alternative source of memory, and we do not exactly
1360a08a2ae3SOscar Salvador 	 *       populate a single PMD.
1361a08a2ae3SOscar Salvador 	 */
13622d1f649cSAneesh Kumar K.V 	if (!mhp_memmap_on_memory() || size != memory_block_size_bytes())
13632d1f649cSAneesh Kumar K.V 		return false;
13642d1f649cSAneesh Kumar K.V 
13652d1f649cSAneesh Kumar K.V 	/*
13662d1f649cSAneesh Kumar K.V 	 * Make sure the vmemmap allocation is fully contained
13672d1f649cSAneesh Kumar K.V 	 * so that we always allocate vmemmap memory from altmap area.
13682d1f649cSAneesh Kumar K.V 	 */
13692d1f649cSAneesh Kumar K.V 	if (!IS_ALIGNED(vmemmap_size, PAGE_SIZE))
13702d1f649cSAneesh Kumar K.V 		return false;
13712d1f649cSAneesh Kumar K.V 
13722d1f649cSAneesh Kumar K.V 	/*
13732d1f649cSAneesh Kumar K.V 	 * start pfn should be pageblock_nr_pages aligned for correctly
13742d1f649cSAneesh Kumar K.V 	 * setting migrate types
13752d1f649cSAneesh Kumar K.V 	 */
13762d1f649cSAneesh Kumar K.V 	if (!pageblock_aligned(memmap_pages))
13772d1f649cSAneesh Kumar K.V 		return false;
13782d1f649cSAneesh Kumar K.V 
13792d1f649cSAneesh Kumar K.V 	if (memmap_pages == PHYS_PFN(memory_block_size_bytes()))
13802d1f649cSAneesh Kumar K.V 		/* No effective hotplugged memory doesn't make sense. */
13812d1f649cSAneesh Kumar K.V 		return false;
13822d1f649cSAneesh Kumar K.V 
13832d1f649cSAneesh Kumar K.V 	return arch_supports_memmap_on_memory(vmemmap_size);
1384a08a2ae3SOscar Salvador }
1385a08a2ae3SOscar Salvador 
13866b8f0798SVishal Verma static void __ref remove_memory_blocks_and_altmaps(u64 start, u64 size)
13876b8f0798SVishal Verma {
13886b8f0798SVishal Verma 	unsigned long memblock_size = memory_block_size_bytes();
13896b8f0798SVishal Verma 	u64 cur_start;
13906b8f0798SVishal Verma 
13916b8f0798SVishal Verma 	/*
13926b8f0798SVishal Verma 	 * For memmap_on_memory, the altmaps were added on a per-memblock
13936b8f0798SVishal Verma 	 * basis; we have to process each individual memory block.
13946b8f0798SVishal Verma 	 */
13956b8f0798SVishal Verma 	for (cur_start = start; cur_start < start + size;
13966b8f0798SVishal Verma 	     cur_start += memblock_size) {
13976b8f0798SVishal Verma 		struct vmem_altmap *altmap = NULL;
13986b8f0798SVishal Verma 		struct memory_block *mem;
13996b8f0798SVishal Verma 
14006b8f0798SVishal Verma 		mem = find_memory_block(pfn_to_section_nr(PFN_DOWN(cur_start)));
14016b8f0798SVishal Verma 		if (WARN_ON_ONCE(!mem))
14026b8f0798SVishal Verma 			continue;
14036b8f0798SVishal Verma 
14046b8f0798SVishal Verma 		altmap = mem->altmap;
14056b8f0798SVishal Verma 		mem->altmap = NULL;
14066b8f0798SVishal Verma 
14076b8f0798SVishal Verma 		remove_memory_block_devices(cur_start, memblock_size);
14086b8f0798SVishal Verma 
14096b8f0798SVishal Verma 		arch_remove_memory(cur_start, memblock_size, altmap);
14106b8f0798SVishal Verma 
14116b8f0798SVishal Verma 		/* Verify that all vmemmap pages have actually been freed. */
14126b8f0798SVishal Verma 		WARN(altmap->alloc, "Altmap not fully unmapped");
14136b8f0798SVishal Verma 		kfree(altmap);
14146b8f0798SVishal Verma 	}
14156b8f0798SVishal Verma }
14166b8f0798SVishal Verma 
14176b8f0798SVishal Verma static int create_altmaps_and_memory_blocks(int nid, struct memory_group *group,
14186b8f0798SVishal Verma 					    u64 start, u64 size)
14196b8f0798SVishal Verma {
14206b8f0798SVishal Verma 	unsigned long memblock_size = memory_block_size_bytes();
14216b8f0798SVishal Verma 	u64 cur_start;
14226b8f0798SVishal Verma 	int ret;
14236b8f0798SVishal Verma 
14246b8f0798SVishal Verma 	for (cur_start = start; cur_start < start + size;
14256b8f0798SVishal Verma 	     cur_start += memblock_size) {
14266b8f0798SVishal Verma 		struct mhp_params params = { .pgprot =
14276b8f0798SVishal Verma 						     pgprot_mhp(PAGE_KERNEL) };
14286b8f0798SVishal Verma 		struct vmem_altmap mhp_altmap = {
14296b8f0798SVishal Verma 			.base_pfn = PHYS_PFN(cur_start),
14306b8f0798SVishal Verma 			.end_pfn = PHYS_PFN(cur_start + memblock_size - 1),
14316b8f0798SVishal Verma 		};
14326b8f0798SVishal Verma 
14336b8f0798SVishal Verma 		mhp_altmap.free = memory_block_memmap_on_memory_pages();
14346b8f0798SVishal Verma 		params.altmap = kmemdup(&mhp_altmap, sizeof(struct vmem_altmap),
14356b8f0798SVishal Verma 					GFP_KERNEL);
14366b8f0798SVishal Verma 		if (!params.altmap) {
14376b8f0798SVishal Verma 			ret = -ENOMEM;
14386b8f0798SVishal Verma 			goto out;
14396b8f0798SVishal Verma 		}
14406b8f0798SVishal Verma 
14416b8f0798SVishal Verma 		/* call arch's memory hotadd */
14426b8f0798SVishal Verma 		ret = arch_add_memory(nid, cur_start, memblock_size, &params);
14436b8f0798SVishal Verma 		if (ret < 0) {
14446b8f0798SVishal Verma 			kfree(params.altmap);
14456b8f0798SVishal Verma 			goto out;
14466b8f0798SVishal Verma 		}
14476b8f0798SVishal Verma 
14486b8f0798SVishal Verma 		/* create memory block devices after memory was added */
14496b8f0798SVishal Verma 		ret = create_memory_block_devices(cur_start, memblock_size,
14506b8f0798SVishal Verma 						  params.altmap, group);
14516b8f0798SVishal Verma 		if (ret) {
14526b8f0798SVishal Verma 			arch_remove_memory(cur_start, memblock_size, NULL);
14536b8f0798SVishal Verma 			kfree(params.altmap);
14546b8f0798SVishal Verma 			goto out;
14556b8f0798SVishal Verma 		}
14566b8f0798SVishal Verma 	}
14576b8f0798SVishal Verma 
14586b8f0798SVishal Verma 	return 0;
14596b8f0798SVishal Verma out:
14606b8f0798SVishal Verma 	if (ret && cur_start != start)
14616b8f0798SVishal Verma 		remove_memory_blocks_and_altmaps(start, cur_start - start);
14626b8f0798SVishal Verma 	return ret;
14636b8f0798SVishal Verma }
14646b8f0798SVishal Verma 
14658df1d0e4SDavid Hildenbrand /*
14668df1d0e4SDavid Hildenbrand  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
14678df1d0e4SDavid Hildenbrand  * and online/offline operations (triggered e.g. by sysfs).
14688df1d0e4SDavid Hildenbrand  *
14698df1d0e4SDavid Hildenbrand  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
14708df1d0e4SDavid Hildenbrand  */
1471b6117199SDavid Hildenbrand int __ref add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1472bc02af93SYasunori Goto {
1473d15dfd31SCatalin Marinas 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
147432befe9eSDavid Hildenbrand 	enum memblock_flags memblock_flags = MEMBLOCK_NONE;
1475028fc57aSDavid Hildenbrand 	struct memory_group *group = NULL;
147662cedb9fSDavid Vrabel 	u64 start, size;
1477b9ff0360SOscar Salvador 	bool new_node = false;
1478bc02af93SYasunori Goto 	int ret;
1479bc02af93SYasunori Goto 
148062cedb9fSDavid Vrabel 	start = res->start;
148162cedb9fSDavid Vrabel 	size = resource_size(res);
148262cedb9fSDavid Vrabel 
148327356f54SToshi Kani 	ret = check_hotplug_memory_range(start, size);
148427356f54SToshi Kani 	if (ret)
148527356f54SToshi Kani 		return ret;
148627356f54SToshi Kani 
1487028fc57aSDavid Hildenbrand 	if (mhp_flags & MHP_NID_IS_MGID) {
1488028fc57aSDavid Hildenbrand 		group = memory_group_find_by_id(nid);
1489028fc57aSDavid Hildenbrand 		if (!group)
1490028fc57aSDavid Hildenbrand 			return -EINVAL;
1491028fc57aSDavid Hildenbrand 		nid = group->nid;
1492028fc57aSDavid Hildenbrand 	}
1493028fc57aSDavid Hildenbrand 
1494fa6d9ec7SVishal Verma 	if (!node_possible(nid)) {
1495fa6d9ec7SVishal Verma 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1496fa6d9ec7SVishal Verma 		return -EINVAL;
1497fa6d9ec7SVishal Verma 	}
1498fa6d9ec7SVishal Verma 
1499bfc8c901SVladimir Davydov 	mem_hotplug_begin();
1500ac13c462SNathan Zimmer 
150153d38316SDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
150232befe9eSDavid Hildenbrand 		if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
150332befe9eSDavid Hildenbrand 			memblock_flags = MEMBLOCK_DRIVER_MANAGED;
150432befe9eSDavid Hildenbrand 		ret = memblock_add_node(start, size, nid, memblock_flags);
150553d38316SDavid Hildenbrand 		if (ret)
150653d38316SDavid Hildenbrand 			goto error_mem_hotplug_end;
150753d38316SDavid Hildenbrand 	}
15087f36e3e5STang Chen 
1509c68ab18cSDavid Hildenbrand 	ret = __try_online_node(nid, false);
1510b9ff0360SOscar Salvador 	if (ret < 0)
151141b9e2d7SWen Congyang 		goto error;
1512b9ff0360SOscar Salvador 	new_node = ret;
15139af3c2deSYasunori Goto 
1514a08a2ae3SOscar Salvador 	/*
1515a08a2ae3SOscar Salvador 	 * Self hosted memmap array
1516a08a2ae3SOscar Salvador 	 */
15176b8f0798SVishal Verma 	if ((mhp_flags & MHP_MEMMAP_ON_MEMORY) &&
15186b8f0798SVishal Verma 	    mhp_supports_memmap_on_memory(memory_block_size_bytes())) {
15196b8f0798SVishal Verma 		ret = create_altmaps_and_memory_blocks(nid, group, start, size);
15206b8f0798SVishal Verma 		if (ret)
15211a8c64e1SAneesh Kumar K.V 			goto error;
15226b8f0798SVishal Verma 	} else {
1523f5637d3bSLogan Gunthorpe 		ret = arch_add_memory(nid, start, size, &params);
15249af3c2deSYasunori Goto 		if (ret < 0)
15256b8f0798SVishal Verma 			goto error;
15269af3c2deSYasunori Goto 
1527db051a0dSDavid Hildenbrand 		/* create memory block devices after memory was added */
15286b8f0798SVishal Verma 		ret = create_memory_block_devices(start, size, NULL, group);
1529db051a0dSDavid Hildenbrand 		if (ret) {
1530f42ce5f0SSumanth Korikkar 			arch_remove_memory(start, size, params.altmap);
15316b8f0798SVishal Verma 			goto error;
15326b8f0798SVishal Verma 		}
1533db051a0dSDavid Hildenbrand 	}
1534db051a0dSDavid Hildenbrand 
1535a1e565aaSTang Chen 	if (new_node) {
1536d5b6f6a3SOscar Salvador 		/* If sysfs file of new node can't be created, cpu on the node
15370fc44159SYasunori Goto 		 * can't be hot-added. There is no rollback way now.
15380fc44159SYasunori Goto 		 * So, check by BUG_ON() to catch it reluctantly..
1539d5b6f6a3SOscar Salvador 		 * We online node here. We can't roll back from here.
15400fc44159SYasunori Goto 		 */
1541d5b6f6a3SOscar Salvador 		node_set_online(nid);
1542d5b6f6a3SOscar Salvador 		ret = __register_one_node(nid);
15430fc44159SYasunori Goto 		BUG_ON(ret);
15440fc44159SYasunori Goto 	}
15450fc44159SYasunori Goto 
1546cc651559SDavid Hildenbrand 	register_memory_blocks_under_node(nid, PFN_DOWN(start),
1547cc651559SDavid Hildenbrand 					  PFN_UP(start + size - 1),
1548f85086f9SLaurent Dufour 					  MEMINIT_HOTPLUG);
1549d5b6f6a3SOscar Salvador 
1550d96ae530Sakpm@linux-foundation.org 	/* create new memmap entry */
15517b7b2721SDavid Hildenbrand 	if (!strcmp(res->name, "System RAM"))
1552d96ae530Sakpm@linux-foundation.org 		firmware_map_add_hotplug(start, start + size, "System RAM");
1553d96ae530Sakpm@linux-foundation.org 
1554381eab4aSDavid Hildenbrand 	/* device_online() will take the lock when calling online_pages() */
1555381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1556381eab4aSDavid Hildenbrand 
15579ca6551eSDavid Hildenbrand 	/*
15589ca6551eSDavid Hildenbrand 	 * In case we're allowed to merge the resource, flag it and trigger
15599ca6551eSDavid Hildenbrand 	 * merging now that adding succeeded.
15609ca6551eSDavid Hildenbrand 	 */
156126011267SDavid Hildenbrand 	if (mhp_flags & MHP_MERGE_RESOURCE)
15629ca6551eSDavid Hildenbrand 		merge_system_ram_resource(res);
15639ca6551eSDavid Hildenbrand 
156431bc3858SVitaly Kuznetsov 	/* online pages if requested */
15651adf8b46SAnshuman Khandual 	if (mhp_default_online_type != MMOP_OFFLINE)
1566fbcf73ceSDavid Hildenbrand 		walk_memory_blocks(start, size, NULL, online_memory_block);
156731bc3858SVitaly Kuznetsov 
1568381eab4aSDavid Hildenbrand 	return ret;
15699af3c2deSYasunori Goto error:
157052219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
15717f36e3e5STang Chen 		memblock_remove(start, size);
157253d38316SDavid Hildenbrand error_mem_hotplug_end:
1573bfc8c901SVladimir Davydov 	mem_hotplug_done();
1574bc02af93SYasunori Goto 	return ret;
1575bc02af93SYasunori Goto }
157662cedb9fSDavid Vrabel 
15778df1d0e4SDavid Hildenbrand /* requires device_hotplug_lock, see add_memory_resource() */
1578b6117199SDavid Hildenbrand int __ref __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
157962cedb9fSDavid Vrabel {
158062cedb9fSDavid Vrabel 	struct resource *res;
158162cedb9fSDavid Vrabel 	int ret;
158262cedb9fSDavid Vrabel 
15837b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, "System RAM");
15846f754ba4SVitaly Kuznetsov 	if (IS_ERR(res))
15856f754ba4SVitaly Kuznetsov 		return PTR_ERR(res);
158662cedb9fSDavid Vrabel 
1587b6117199SDavid Hildenbrand 	ret = add_memory_resource(nid, res, mhp_flags);
158862cedb9fSDavid Vrabel 	if (ret < 0)
158962cedb9fSDavid Vrabel 		release_memory_resource(res);
159062cedb9fSDavid Vrabel 	return ret;
159162cedb9fSDavid Vrabel }
15928df1d0e4SDavid Hildenbrand 
1593b6117199SDavid Hildenbrand int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
15948df1d0e4SDavid Hildenbrand {
15958df1d0e4SDavid Hildenbrand 	int rc;
15968df1d0e4SDavid Hildenbrand 
15978df1d0e4SDavid Hildenbrand 	lock_device_hotplug();
1598b6117199SDavid Hildenbrand 	rc = __add_memory(nid, start, size, mhp_flags);
15998df1d0e4SDavid Hildenbrand 	unlock_device_hotplug();
16008df1d0e4SDavid Hildenbrand 
16018df1d0e4SDavid Hildenbrand 	return rc;
16028df1d0e4SDavid Hildenbrand }
1603bc02af93SYasunori Goto EXPORT_SYMBOL_GPL(add_memory);
16040c0e6195SKAMEZAWA Hiroyuki 
16057b7b2721SDavid Hildenbrand /*
16067b7b2721SDavid Hildenbrand  * Add special, driver-managed memory to the system as system RAM. Such
16077b7b2721SDavid Hildenbrand  * memory is not exposed via the raw firmware-provided memmap as system
16087b7b2721SDavid Hildenbrand  * RAM, instead, it is detected and added by a driver - during cold boot,
16097b7b2721SDavid Hildenbrand  * after a reboot, and after kexec.
16107b7b2721SDavid Hildenbrand  *
16117b7b2721SDavid Hildenbrand  * Reasons why this memory should not be used for the initial memmap of a
16127b7b2721SDavid Hildenbrand  * kexec kernel or for placing kexec images:
16137b7b2721SDavid Hildenbrand  * - The booting kernel is in charge of determining how this memory will be
16147b7b2721SDavid Hildenbrand  *   used (e.g., use persistent memory as system RAM)
16157b7b2721SDavid Hildenbrand  * - Coordination with a hypervisor is required before this memory
16167b7b2721SDavid Hildenbrand  *   can be used (e.g., inaccessible parts).
16177b7b2721SDavid Hildenbrand  *
16187b7b2721SDavid Hildenbrand  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
16197b7b2721SDavid Hildenbrand  * memory map") are created. Also, the created memory resource is flagged
16207cf603d1SDavid Hildenbrand  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
16217b7b2721SDavid Hildenbrand  * this memory as well (esp., not place kexec images onto it).
16227b7b2721SDavid Hildenbrand  *
16237b7b2721SDavid Hildenbrand  * The resource_name (visible via /proc/iomem) has to have the format
16247b7b2721SDavid Hildenbrand  * "System RAM ($DRIVER)".
16257b7b2721SDavid Hildenbrand  */
16267b7b2721SDavid Hildenbrand int add_memory_driver_managed(int nid, u64 start, u64 size,
1627b6117199SDavid Hildenbrand 			      const char *resource_name, mhp_t mhp_flags)
16287b7b2721SDavid Hildenbrand {
16297b7b2721SDavid Hildenbrand 	struct resource *res;
16307b7b2721SDavid Hildenbrand 	int rc;
16317b7b2721SDavid Hildenbrand 
16327b7b2721SDavid Hildenbrand 	if (!resource_name ||
16337b7b2721SDavid Hildenbrand 	    strstr(resource_name, "System RAM (") != resource_name ||
16347b7b2721SDavid Hildenbrand 	    resource_name[strlen(resource_name) - 1] != ')')
16357b7b2721SDavid Hildenbrand 		return -EINVAL;
16367b7b2721SDavid Hildenbrand 
16377b7b2721SDavid Hildenbrand 	lock_device_hotplug();
16387b7b2721SDavid Hildenbrand 
16397b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, resource_name);
16407b7b2721SDavid Hildenbrand 	if (IS_ERR(res)) {
16417b7b2721SDavid Hildenbrand 		rc = PTR_ERR(res);
16427b7b2721SDavid Hildenbrand 		goto out_unlock;
16437b7b2721SDavid Hildenbrand 	}
16447b7b2721SDavid Hildenbrand 
1645b6117199SDavid Hildenbrand 	rc = add_memory_resource(nid, res, mhp_flags);
16467b7b2721SDavid Hildenbrand 	if (rc < 0)
16477b7b2721SDavid Hildenbrand 		release_memory_resource(res);
16487b7b2721SDavid Hildenbrand 
16497b7b2721SDavid Hildenbrand out_unlock:
16507b7b2721SDavid Hildenbrand 	unlock_device_hotplug();
16517b7b2721SDavid Hildenbrand 	return rc;
16527b7b2721SDavid Hildenbrand }
16537b7b2721SDavid Hildenbrand EXPORT_SYMBOL_GPL(add_memory_driver_managed);
16547b7b2721SDavid Hildenbrand 
1655bca3feaaSAnshuman Khandual /*
1656bca3feaaSAnshuman Khandual  * Platforms should define arch_get_mappable_range() that provides
1657bca3feaaSAnshuman Khandual  * maximum possible addressable physical memory range for which the
1658bca3feaaSAnshuman Khandual  * linear mapping could be created. The platform returned address
1659bca3feaaSAnshuman Khandual  * range must adhere to these following semantics.
1660bca3feaaSAnshuman Khandual  *
1661bca3feaaSAnshuman Khandual  * - range.start <= range.end
1662bca3feaaSAnshuman Khandual  * - Range includes both end points [range.start..range.end]
1663bca3feaaSAnshuman Khandual  *
1664bca3feaaSAnshuman Khandual  * There is also a fallback definition provided here, allowing the
1665bca3feaaSAnshuman Khandual  * entire possible physical address range in case any platform does
1666bca3feaaSAnshuman Khandual  * not define arch_get_mappable_range().
1667bca3feaaSAnshuman Khandual  */
1668bca3feaaSAnshuman Khandual struct range __weak arch_get_mappable_range(void)
1669bca3feaaSAnshuman Khandual {
1670bca3feaaSAnshuman Khandual 	struct range mhp_range = {
1671bca3feaaSAnshuman Khandual 		.start = 0UL,
1672bca3feaaSAnshuman Khandual 		.end = -1ULL,
1673bca3feaaSAnshuman Khandual 	};
1674bca3feaaSAnshuman Khandual 	return mhp_range;
1675bca3feaaSAnshuman Khandual }
1676bca3feaaSAnshuman Khandual 
1677bca3feaaSAnshuman Khandual struct range mhp_get_pluggable_range(bool need_mapping)
1678bca3feaaSAnshuman Khandual {
1679bca3feaaSAnshuman Khandual 	const u64 max_phys = (1ULL << MAX_PHYSMEM_BITS) - 1;
1680bca3feaaSAnshuman Khandual 	struct range mhp_range;
1681bca3feaaSAnshuman Khandual 
1682bca3feaaSAnshuman Khandual 	if (need_mapping) {
1683bca3feaaSAnshuman Khandual 		mhp_range = arch_get_mappable_range();
1684bca3feaaSAnshuman Khandual 		if (mhp_range.start > max_phys) {
1685bca3feaaSAnshuman Khandual 			mhp_range.start = 0;
1686bca3feaaSAnshuman Khandual 			mhp_range.end = 0;
1687bca3feaaSAnshuman Khandual 		}
1688bca3feaaSAnshuman Khandual 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1689bca3feaaSAnshuman Khandual 	} else {
1690bca3feaaSAnshuman Khandual 		mhp_range.start = 0;
1691bca3feaaSAnshuman Khandual 		mhp_range.end = max_phys;
1692bca3feaaSAnshuman Khandual 	}
1693bca3feaaSAnshuman Khandual 	return mhp_range;
1694bca3feaaSAnshuman Khandual }
1695bca3feaaSAnshuman Khandual EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1696bca3feaaSAnshuman Khandual 
1697bca3feaaSAnshuman Khandual bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1698bca3feaaSAnshuman Khandual {
1699bca3feaaSAnshuman Khandual 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1700bca3feaaSAnshuman Khandual 	u64 end = start + size;
1701bca3feaaSAnshuman Khandual 
1702bca3feaaSAnshuman Khandual 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1703bca3feaaSAnshuman Khandual 		return true;
1704bca3feaaSAnshuman Khandual 
1705bca3feaaSAnshuman Khandual 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1706bca3feaaSAnshuman Khandual 		start, end, mhp_range.start, mhp_range.end);
1707bca3feaaSAnshuman Khandual 	return false;
1708bca3feaaSAnshuman Khandual }
1709bca3feaaSAnshuman Khandual 
17100c0e6195SKAMEZAWA Hiroyuki #ifdef CONFIG_MEMORY_HOTREMOVE
17110c0e6195SKAMEZAWA Hiroyuki /*
17120efadf48SYisheng Xie  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1713aa218795SDavid Hildenbrand  * non-lru movable pages and hugepages). Will skip over most unmovable
1714aa218795SDavid Hildenbrand  * pages (esp., pages that can be skipped when offlining), but bail out on
1715aa218795SDavid Hildenbrand  * definitely unmovable pages.
1716aa218795SDavid Hildenbrand  *
1717aa218795SDavid Hildenbrand  * Returns:
1718aa218795SDavid Hildenbrand  *	0 in case a movable page is found and movable_pfn was updated.
1719aa218795SDavid Hildenbrand  *	-ENOENT in case no movable page was found.
1720aa218795SDavid Hildenbrand  *	-EBUSY in case a definitely unmovable page was found.
17210c0e6195SKAMEZAWA Hiroyuki  */
1722aa218795SDavid Hildenbrand static int scan_movable_pages(unsigned long start, unsigned long end,
1723aa218795SDavid Hildenbrand 			      unsigned long *movable_pfn)
17240c0e6195SKAMEZAWA Hiroyuki {
17250c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
1726eeb0efd0SOscar Salvador 
17270c0e6195SKAMEZAWA Hiroyuki 	for (pfn = start; pfn < end; pfn++) {
1728eeb0efd0SOscar Salvador 		struct page *page, *head;
1729eeb0efd0SOscar Salvador 		unsigned long skip;
1730eeb0efd0SOscar Salvador 
1731eeb0efd0SOscar Salvador 		if (!pfn_valid(pfn))
1732eeb0efd0SOscar Salvador 			continue;
17330c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
17340c0e6195SKAMEZAWA Hiroyuki 		if (PageLRU(page))
1735aa218795SDavid Hildenbrand 			goto found;
17360efadf48SYisheng Xie 		if (__PageMovable(page))
1737aa218795SDavid Hildenbrand 			goto found;
1738aa218795SDavid Hildenbrand 
1739aa218795SDavid Hildenbrand 		/*
1740aa218795SDavid Hildenbrand 		 * PageOffline() pages that are not marked __PageMovable() and
1741aa218795SDavid Hildenbrand 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1742aa218795SDavid Hildenbrand 		 * definitely unmovable. If their reference count would be 0,
1743aa218795SDavid Hildenbrand 		 * they could at least be skipped when offlining memory.
1744aa218795SDavid Hildenbrand 		 */
1745aa218795SDavid Hildenbrand 		if (PageOffline(page) && page_count(page))
1746aa218795SDavid Hildenbrand 			return -EBUSY;
1747eeb0efd0SOscar Salvador 
1748eeb0efd0SOscar Salvador 		if (!PageHuge(page))
1749eeb0efd0SOscar Salvador 			continue;
1750eeb0efd0SOscar Salvador 		head = compound_head(page);
17518f251a3dSMike Kravetz 		/*
17528f251a3dSMike Kravetz 		 * This test is racy as we hold no reference or lock.  The
17538f251a3dSMike Kravetz 		 * hugetlb page could have been free'ed and head is no longer
17548f251a3dSMike Kravetz 		 * a hugetlb page before the following check.  In such unlikely
17558f251a3dSMike Kravetz 		 * cases false positives and negatives are possible.  Calling
17568f251a3dSMike Kravetz 		 * code must deal with these scenarios.
17578f251a3dSMike Kravetz 		 */
17588f251a3dSMike Kravetz 		if (HPageMigratable(head))
1759aa218795SDavid Hildenbrand 			goto found;
17601640a0efSZi Yan 		skip = compound_nr(head) - (pfn - page_to_pfn(head));
1761eeb0efd0SOscar Salvador 		pfn += skip - 1;
17620c0e6195SKAMEZAWA Hiroyuki 	}
1763aa218795SDavid Hildenbrand 	return -ENOENT;
1764aa218795SDavid Hildenbrand found:
1765aa218795SDavid Hildenbrand 	*movable_pfn = pfn;
17660c0e6195SKAMEZAWA Hiroyuki 	return 0;
17670c0e6195SKAMEZAWA Hiroyuki }
17680c0e6195SKAMEZAWA Hiroyuki 
176932cf666eSSeongJae Park static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
17700c0e6195SKAMEZAWA Hiroyuki {
17710c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
17726c357848SMatthew Wilcox (Oracle) 	struct page *page, *head;
17730c0e6195SKAMEZAWA Hiroyuki 	LIST_HEAD(source);
1774786dee86SLiam Mark 	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
1775786dee86SLiam Mark 				      DEFAULT_RATELIMIT_BURST);
17760c0e6195SKAMEZAWA Hiroyuki 
1777a85009c3SMichal Hocko 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1778869f7ee6SMatthew Wilcox (Oracle) 		struct folio *folio;
1779f7f9c00dSBaolin Wang 		bool isolated;
1780869f7ee6SMatthew Wilcox (Oracle) 
17810c0e6195SKAMEZAWA Hiroyuki 		if (!pfn_valid(pfn))
17820c0e6195SKAMEZAWA Hiroyuki 			continue;
17830c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
1784869f7ee6SMatthew Wilcox (Oracle) 		folio = page_folio(page);
1785869f7ee6SMatthew Wilcox (Oracle) 		head = &folio->page;
1786c8721bbbSNaoya Horiguchi 
1787c8721bbbSNaoya Horiguchi 		if (PageHuge(page)) {
1788d8c6546bSMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + compound_nr(head) - 1;
17896aa3a920SSidhartha Kumar 			isolate_hugetlb(folio, &source);
1790c8721bbbSNaoya Horiguchi 			continue;
179194723aafSMichal Hocko 		} else if (PageTransHuge(page))
17926c357848SMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + thp_nr_pages(page) - 1;
1793c8721bbbSNaoya Horiguchi 
1794b15c8726SMichal Hocko 		/*
1795b15c8726SMichal Hocko 		 * HWPoison pages have elevated reference counts so the migration would
1796b15c8726SMichal Hocko 		 * fail on them. It also doesn't make any sense to migrate them in the
1797b15c8726SMichal Hocko 		 * first place. Still try to unmap such a page in case it is still mapped
1798b15c8726SMichal Hocko 		 * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1799b15c8726SMichal Hocko 		 * the unmap as the catch all safety net).
1800b15c8726SMichal Hocko 		 */
1801b15c8726SMichal Hocko 		if (PageHWPoison(page)) {
1802869f7ee6SMatthew Wilcox (Oracle) 			if (WARN_ON(folio_test_lru(folio)))
1803869f7ee6SMatthew Wilcox (Oracle) 				folio_isolate_lru(folio);
1804869f7ee6SMatthew Wilcox (Oracle) 			if (folio_mapped(folio))
1805869f7ee6SMatthew Wilcox (Oracle) 				try_to_unmap(folio, TTU_IGNORE_MLOCK);
1806b15c8726SMichal Hocko 			continue;
1807b15c8726SMichal Hocko 		}
1808b15c8726SMichal Hocko 
1809700c2a46SKonstantin Khlebnikov 		if (!get_page_unless_zero(page))
18100c0e6195SKAMEZAWA Hiroyuki 			continue;
18110c0e6195SKAMEZAWA Hiroyuki 		/*
18120efadf48SYisheng Xie 		 * We can skip free pages. And we can deal with pages on
18130efadf48SYisheng Xie 		 * LRU and non-lru movable pages.
18140c0e6195SKAMEZAWA Hiroyuki 		 */
1815cd775580SBaolin Wang 		if (PageLRU(page))
1816f7f9c00dSBaolin Wang 			isolated = isolate_lru_page(page);
1817cd775580SBaolin Wang 		else
1818cd775580SBaolin Wang 			isolated = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1819cd775580SBaolin Wang 		if (isolated) {
182062695a84SNick Piggin 			list_add_tail(&page->lru, &source);
18210efadf48SYisheng Xie 			if (!__PageMovable(page))
1822599d0c95SMel Gorman 				inc_node_page_state(page, NR_ISOLATED_ANON +
18239de4f22aSHuang Ying 						    page_is_file_lru(page));
18246d9c285aSKOSAKI Motohiro 
18250c0e6195SKAMEZAWA Hiroyuki 		} else {
1826786dee86SLiam Mark 			if (__ratelimit(&migrate_rs)) {
18272932c8b0SMichal Hocko 				pr_warn("failed to isolate pfn %lx\n", pfn);
18280efadf48SYisheng Xie 				dump_page(page, "isolation failed");
18291723058eSOscar Salvador 			}
1830786dee86SLiam Mark 		}
1831700c2a46SKonstantin Khlebnikov 		put_page(page);
18320c0e6195SKAMEZAWA Hiroyuki 	}
1833f3ab2636SBob Liu 	if (!list_empty(&source)) {
1834203e6e5cSJoonsoo Kim 		nodemask_t nmask = node_states[N_MEMORY];
1835203e6e5cSJoonsoo Kim 		struct migration_target_control mtc = {
1836203e6e5cSJoonsoo Kim 			.nmask = &nmask,
1837203e6e5cSJoonsoo Kim 			.gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1838203e6e5cSJoonsoo Kim 		};
183932cf666eSSeongJae Park 		int ret;
1840203e6e5cSJoonsoo Kim 
1841203e6e5cSJoonsoo Kim 		/*
1842203e6e5cSJoonsoo Kim 		 * We have checked that migration range is on a single zone so
1843203e6e5cSJoonsoo Kim 		 * we can use the nid of the first page to all the others.
1844203e6e5cSJoonsoo Kim 		 */
1845203e6e5cSJoonsoo Kim 		mtc.nid = page_to_nid(list_first_entry(&source, struct page, lru));
1846203e6e5cSJoonsoo Kim 
1847203e6e5cSJoonsoo Kim 		/*
1848203e6e5cSJoonsoo Kim 		 * try to allocate from a different node but reuse this node
1849203e6e5cSJoonsoo Kim 		 * if there are no other online nodes to be used (e.g. we are
1850203e6e5cSJoonsoo Kim 		 * offlining a part of the only existing node)
1851203e6e5cSJoonsoo Kim 		 */
1852203e6e5cSJoonsoo Kim 		node_clear(mtc.nid, nmask);
1853203e6e5cSJoonsoo Kim 		if (nodes_empty(nmask))
1854203e6e5cSJoonsoo Kim 			node_set(mtc.nid, nmask);
1855203e6e5cSJoonsoo Kim 		ret = migrate_pages(&source, alloc_migration_target, NULL,
18565ac95884SYang Shi 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
18572932c8b0SMichal Hocko 		if (ret) {
18582932c8b0SMichal Hocko 			list_for_each_entry(page, &source, lru) {
1859786dee86SLiam Mark 				if (__ratelimit(&migrate_rs)) {
1860786dee86SLiam Mark 					pr_warn("migrating pfn %lx failed ret:%d\n",
18612932c8b0SMichal Hocko 						page_to_pfn(page), ret);
18622932c8b0SMichal Hocko 					dump_page(page, "migration failure");
18632932c8b0SMichal Hocko 				}
1864786dee86SLiam Mark 			}
1865c8721bbbSNaoya Horiguchi 			putback_movable_pages(&source);
1866f3ab2636SBob Liu 		}
18672932c8b0SMichal Hocko 	}
18680c0e6195SKAMEZAWA Hiroyuki }
18690c0e6195SKAMEZAWA Hiroyuki 
1870c5320926STang Chen static int __init cmdline_parse_movable_node(char *p)
1871c5320926STang Chen {
187255ac590cSTang Chen 	movable_node_enabled = true;
1873c5320926STang Chen 	return 0;
1874c5320926STang Chen }
1875c5320926STang Chen early_param("movable_node", cmdline_parse_movable_node);
1876c5320926STang Chen 
1877d9713679SLai Jiangshan /* check which state of node_states will be changed when offline memory */
1878d9713679SLai Jiangshan static void node_states_check_changes_offline(unsigned long nr_pages,
1879d9713679SLai Jiangshan 		struct zone *zone, struct memory_notify *arg)
1880d9713679SLai Jiangshan {
1881d9713679SLai Jiangshan 	struct pglist_data *pgdat = zone->zone_pgdat;
1882d9713679SLai Jiangshan 	unsigned long present_pages = 0;
188386b27beaSOscar Salvador 	enum zone_type zt;
1884d9713679SLai Jiangshan 
188598fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
188698fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
188786b27beaSOscar Salvador 
188886b27beaSOscar Salvador 	/*
188986b27beaSOscar Salvador 	 * Check whether node_states[N_NORMAL_MEMORY] will be changed.
189086b27beaSOscar Salvador 	 * If the memory to be offline is within the range
189186b27beaSOscar Salvador 	 * [0..ZONE_NORMAL], and it is the last present memory there,
189286b27beaSOscar Salvador 	 * the zones in that range will become empty after the offlining,
189386b27beaSOscar Salvador 	 * thus we can determine that we need to clear the node from
189486b27beaSOscar Salvador 	 * node_states[N_NORMAL_MEMORY].
189586b27beaSOscar Salvador 	 */
189686b27beaSOscar Salvador 	for (zt = 0; zt <= ZONE_NORMAL; zt++)
189786b27beaSOscar Salvador 		present_pages += pgdat->node_zones[zt].present_pages;
189886b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
189986b27beaSOscar Salvador 		arg->status_change_nid_normal = zone_to_nid(zone);
1900d9713679SLai Jiangshan 
19016715ddf9SLai Jiangshan 	/*
19026b740c6cSDavid Hildenbrand 	 * We have accounted the pages from [0..ZONE_NORMAL); ZONE_HIGHMEM
19036b740c6cSDavid Hildenbrand 	 * does not apply as we don't support 32bit.
190486b27beaSOscar Salvador 	 * Here we count the possible pages from ZONE_MOVABLE.
190586b27beaSOscar Salvador 	 * If after having accounted all the pages, we see that the nr_pages
190686b27beaSOscar Salvador 	 * to be offlined is over or equal to the accounted pages,
190786b27beaSOscar Salvador 	 * we know that the node will become empty, and so, we can clear
190886b27beaSOscar Salvador 	 * it for N_MEMORY as well.
1909d9713679SLai Jiangshan 	 */
191086b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1911d9713679SLai Jiangshan 
1912d9713679SLai Jiangshan 	if (nr_pages >= present_pages)
1913d9713679SLai Jiangshan 		arg->status_change_nid = zone_to_nid(zone);
1914d9713679SLai Jiangshan }
1915d9713679SLai Jiangshan 
1916d9713679SLai Jiangshan static void node_states_clear_node(int node, struct memory_notify *arg)
1917d9713679SLai Jiangshan {
1918d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
1919d9713679SLai Jiangshan 		node_clear_state(node, N_NORMAL_MEMORY);
1920d9713679SLai Jiangshan 
1921cf01f6f5SOscar Salvador 	if (arg->status_change_nid >= 0)
19226715ddf9SLai Jiangshan 		node_clear_state(node, N_MEMORY);
1923d9713679SLai Jiangshan }
1924d9713679SLai Jiangshan 
1925c5e79ef5SDavid Hildenbrand static int count_system_ram_pages_cb(unsigned long start_pfn,
1926c5e79ef5SDavid Hildenbrand 				     unsigned long nr_pages, void *data)
1927c5e79ef5SDavid Hildenbrand {
1928c5e79ef5SDavid Hildenbrand 	unsigned long *nr_system_ram_pages = data;
1929c5e79ef5SDavid Hildenbrand 
1930c5e79ef5SDavid Hildenbrand 	*nr_system_ram_pages += nr_pages;
1931c5e79ef5SDavid Hildenbrand 	return 0;
1932c5e79ef5SDavid Hildenbrand }
1933c5e79ef5SDavid Hildenbrand 
1934001002e7SSumanth Korikkar /*
1935001002e7SSumanth Korikkar  * Must be called with mem_hotplug_lock in write mode.
1936001002e7SSumanth Korikkar  */
1937836809ecSDavid Hildenbrand int __ref offline_pages(unsigned long start_pfn, unsigned long nr_pages,
1938395f6081SDavid Hildenbrand 			struct zone *zone, struct memory_group *group)
19390c0e6195SKAMEZAWA Hiroyuki {
194073a11c96SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
19410a1a9a00SDavid Hildenbrand 	unsigned long pfn, system_ram_pages = 0;
1942395f6081SDavid Hildenbrand 	const int node = zone_to_nid(zone);
1943d702909fSCody P Schafer 	unsigned long flags;
19447b78d335SYasunori Goto 	struct memory_notify arg;
194579605093SMichal Hocko 	char *reason;
1946395f6081SDavid Hildenbrand 	int ret;
19470c0e6195SKAMEZAWA Hiroyuki 
1948dd8e2f23SOscar Salvador 	/*
1949dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1950041711ceSZhen Lei 	 * precisely to memory blocks from the user space POV).
1951dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1952dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1953dd8e2f23SOscar Salvador 	 * aligned.
1954dd8e2f23SOscar Salvador 	 */
1955ee0913c4SKefeng Wang 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
1956dd8e2f23SOscar Salvador 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
19574986fac1SDavid Hildenbrand 		return -EINVAL;
19584986fac1SDavid Hildenbrand 
1959c5e79ef5SDavid Hildenbrand 	/*
1960c5e79ef5SDavid Hildenbrand 	 * Don't allow to offline memory blocks that contain holes.
1961c5e79ef5SDavid Hildenbrand 	 * Consequently, memory blocks with holes can never get onlined
1962c5e79ef5SDavid Hildenbrand 	 * via the hotplug path - online_pages() - as hotplugged memory has
1963c5e79ef5SDavid Hildenbrand 	 * no holes. This way, we e.g., don't have to worry about marking
1964c5e79ef5SDavid Hildenbrand 	 * memory holes PG_reserved, don't need pfn_valid() checks, and can
1965c5e79ef5SDavid Hildenbrand 	 * avoid using walk_system_ram_range() later.
1966c5e79ef5SDavid Hildenbrand 	 */
196773a11c96SDavid Hildenbrand 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1968c5e79ef5SDavid Hildenbrand 			      count_system_ram_pages_cb);
196973a11c96SDavid Hildenbrand 	if (system_ram_pages != nr_pages) {
1970c5e79ef5SDavid Hildenbrand 		ret = -EINVAL;
1971c5e79ef5SDavid Hildenbrand 		reason = "memory holes";
1972c5e79ef5SDavid Hildenbrand 		goto failed_removal;
1973c5e79ef5SDavid Hildenbrand 	}
1974c5e79ef5SDavid Hildenbrand 
1975395f6081SDavid Hildenbrand 	/*
1976395f6081SDavid Hildenbrand 	 * We only support offlining of memory blocks managed by a single zone,
1977395f6081SDavid Hildenbrand 	 * checked by calling code. This is just a sanity check that we might
1978395f6081SDavid Hildenbrand 	 * want to remove in the future.
1979395f6081SDavid Hildenbrand 	 */
1980395f6081SDavid Hildenbrand 	if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
1981395f6081SDavid Hildenbrand 			 page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
198279605093SMichal Hocko 		ret = -EINVAL;
198379605093SMichal Hocko 		reason = "multizone range";
198479605093SMichal Hocko 		goto failed_removal;
1985381eab4aSDavid Hildenbrand 	}
19867b78d335SYasunori Goto 
1987ec6e8c7eSVlastimil Babka 	/*
1988ec6e8c7eSVlastimil Babka 	 * Disable pcplists so that page isolation cannot race with freeing
1989ec6e8c7eSVlastimil Babka 	 * in a way that pages from isolated pageblock are left on pcplists.
1990ec6e8c7eSVlastimil Babka 	 */
1991ec6e8c7eSVlastimil Babka 	zone_pcp_disable(zone);
1992d479960eSMinchan Kim 	lru_cache_disable();
1993ec6e8c7eSVlastimil Babka 
19940c0e6195SKAMEZAWA Hiroyuki 	/* set above range as isolated */
1995b023f468SWen Congyang 	ret = start_isolate_page_range(start_pfn, end_pfn,
1996d381c547SMichal Hocko 				       MIGRATE_MOVABLE,
1997b2c9e2fbSZi Yan 				       MEMORY_OFFLINE | REPORT_FAILURE,
1998b2c9e2fbSZi Yan 				       GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL);
19993fa0c7c7SDavid Hildenbrand 	if (ret) {
200079605093SMichal Hocko 		reason = "failure to isolate range";
2001ec6e8c7eSVlastimil Babka 		goto failed_removal_pcplists_disabled;
2002381eab4aSDavid Hildenbrand 	}
20037b78d335SYasunori Goto 
20047b78d335SYasunori Goto 	arg.start_pfn = start_pfn;
20057b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
2006d9713679SLai Jiangshan 	node_states_check_changes_offline(nr_pages, zone, &arg);
20077b78d335SYasunori Goto 
20087b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_OFFLINE, &arg);
20097b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
201079605093SMichal Hocko 	if (ret) {
201179605093SMichal Hocko 		reason = "notifier failure";
201279605093SMichal Hocko 		goto failed_removal_isolated;
201379605093SMichal Hocko 	}
20147b78d335SYasunori Goto 
2015bb8965bdSMichal Hocko 	do {
2016aa218795SDavid Hildenbrand 		pfn = start_pfn;
2017aa218795SDavid Hildenbrand 		do {
2018de7cb03dSDavid Hildenbrand 			/*
2019de7cb03dSDavid Hildenbrand 			 * Historically we always checked for any signal and
2020de7cb03dSDavid Hildenbrand 			 * can't limit it to fatal signals without eventually
2021de7cb03dSDavid Hildenbrand 			 * breaking user space.
2022de7cb03dSDavid Hildenbrand 			 */
202379605093SMichal Hocko 			if (signal_pending(current)) {
2024bb8965bdSMichal Hocko 				ret = -EINTR;
202579605093SMichal Hocko 				reason = "signal backoff";
202679605093SMichal Hocko 				goto failed_removal_isolated;
202779605093SMichal Hocko 			}
202872b39cfcSMichal Hocko 
20290c0e6195SKAMEZAWA Hiroyuki 			cond_resched();
20300c0e6195SKAMEZAWA Hiroyuki 
2031aa218795SDavid Hildenbrand 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
2032aa218795SDavid Hildenbrand 			if (!ret) {
2033bb8965bdSMichal Hocko 				/*
2034bb8965bdSMichal Hocko 				 * TODO: fatal migration failures should bail
2035bb8965bdSMichal Hocko 				 * out
2036bb8965bdSMichal Hocko 				 */
2037bb8965bdSMichal Hocko 				do_migrate_range(pfn, end_pfn);
2038bb8965bdSMichal Hocko 			}
2039aa218795SDavid Hildenbrand 		} while (!ret);
2040aa218795SDavid Hildenbrand 
2041aa218795SDavid Hildenbrand 		if (ret != -ENOENT) {
2042aa218795SDavid Hildenbrand 			reason = "unmovable page";
2043aa218795SDavid Hildenbrand 			goto failed_removal_isolated;
20440c0e6195SKAMEZAWA Hiroyuki 		}
204572b39cfcSMichal Hocko 
2046c8721bbbSNaoya Horiguchi 		/*
2047bb8965bdSMichal Hocko 		 * Dissolve free hugepages in the memory block before doing
2048bb8965bdSMichal Hocko 		 * offlining actually in order to make hugetlbfs's object
2049bb8965bdSMichal Hocko 		 * counting consistent.
2050c8721bbbSNaoya Horiguchi 		 */
2051082d5b6bSGerald Schaefer 		ret = dissolve_free_huge_pages(start_pfn, end_pfn);
205279605093SMichal Hocko 		if (ret) {
205379605093SMichal Hocko 			reason = "failure to dissolve huge pages";
205479605093SMichal Hocko 			goto failed_removal_isolated;
205579605093SMichal Hocko 		}
20560a1a9a00SDavid Hildenbrand 
20570a1a9a00SDavid Hildenbrand 		ret = test_pages_isolated(start_pfn, end_pfn, MEMORY_OFFLINE);
2058ec6e8c7eSVlastimil Babka 
20595557c766SMichal Hocko 	} while (ret);
2060bb8965bdSMichal Hocko 
20610a1a9a00SDavid Hildenbrand 	/* Mark all sections offline and remove free pages from the buddy. */
20620a1a9a00SDavid Hildenbrand 	__offline_isolated_pages(start_pfn, end_pfn);
20637c33023aSLaurent Dufour 	pr_debug("Offlined Pages %ld\n", nr_pages);
20640a1a9a00SDavid Hildenbrand 
20659b7ea46aSQian Cai 	/*
2066b30c5927SDavid Hildenbrand 	 * The memory sections are marked offline, and the pageblock flags
2067b30c5927SDavid Hildenbrand 	 * effectively stale; nobody should be touching them. Fixup the number
2068b30c5927SDavid Hildenbrand 	 * of isolated pageblocks, memory onlining will properly revert this.
20699b7ea46aSQian Cai 	 */
20709b7ea46aSQian Cai 	spin_lock_irqsave(&zone->lock, flags);
2071ea15153cSDavid Hildenbrand 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
20729b7ea46aSQian Cai 	spin_unlock_irqrestore(&zone->lock, flags);
20739b7ea46aSQian Cai 
2074d479960eSMinchan Kim 	lru_cache_enable();
2075ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
2076ec6e8c7eSVlastimil Babka 
20770c0e6195SKAMEZAWA Hiroyuki 	/* removal success */
20780a1a9a00SDavid Hildenbrand 	adjust_managed_page_count(pfn_to_page(start_pfn), -nr_pages);
2079836809ecSDavid Hildenbrand 	adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
20807b78d335SYasunori Goto 
2081b92ca18eSMel Gorman 	/* reinitialise watermarks and update pcp limits */
20821b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
20831b79acc9SKOSAKI Motohiro 
2084b7812c86SQi Zheng 	/*
2085b7812c86SQi Zheng 	 * Make sure to mark the node as memory-less before rebuilding the zone
2086b7812c86SQi Zheng 	 * list. Otherwise this node would still appear in the fallback lists.
2087b7812c86SQi Zheng 	 */
2088b7812c86SQi Zheng 	node_states_clear_node(node, &arg);
20891e8537baSXishi Qiu 	if (!populated_zone(zone)) {
2090340175b7SJiang Liu 		zone_pcp_reset(zone);
209172675e13SMichal Hocko 		build_all_zonelists(NULL);
2092b92ca18eSMel Gorman 	}
2093340175b7SJiang Liu 
2094698b1b30SVlastimil Babka 	if (arg.status_change_nid >= 0) {
2095698b1b30SVlastimil Babka 		kcompactd_stop(node);
2096b4a0215eSKefeng Wang 		kswapd_stop(node);
2097698b1b30SVlastimil Babka 	}
2098bce7394aSMinchan Kim 
20990c0e6195SKAMEZAWA Hiroyuki 	writeback_set_ratelimit();
21007b78d335SYasunori Goto 
21017b78d335SYasunori Goto 	memory_notify(MEM_OFFLINE, &arg);
2102feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
21030c0e6195SKAMEZAWA Hiroyuki 	return 0;
21040c0e6195SKAMEZAWA Hiroyuki 
210579605093SMichal Hocko failed_removal_isolated:
210636ba30bcSMiaohe Lin 	/* pushback to free area */
210779605093SMichal Hocko 	undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
2108c4efe484SQian Cai 	memory_notify(MEM_CANCEL_OFFLINE, &arg);
2109ec6e8c7eSVlastimil Babka failed_removal_pcplists_disabled:
2110946746d1SMiaohe Lin 	lru_cache_enable();
2111ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
21120c0e6195SKAMEZAWA Hiroyuki failed_removal:
211379605093SMichal Hocko 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
2114a62e2f4fSBjorn Helgaas 		 (unsigned long long) start_pfn << PAGE_SHIFT,
211579605093SMichal Hocko 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
211679605093SMichal Hocko 		 reason);
21170c0e6195SKAMEZAWA Hiroyuki 	return ret;
21180c0e6195SKAMEZAWA Hiroyuki }
211971088785SBadari Pulavarty 
2120d6de9d53SXishi Qiu static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
2121bbc76be6SWen Congyang {
2122e1c158e4SDavid Hildenbrand 	int *nid = arg;
2123bbc76be6SWen Congyang 
2124e1c158e4SDavid Hildenbrand 	*nid = mem->nid;
2125639118d1SKefeng Wang 	if (unlikely(mem->state != MEM_OFFLINE)) {
2126349daa0fSRandy Dunlap 		phys_addr_t beginpa, endpa;
2127349daa0fSRandy Dunlap 
2128349daa0fSRandy Dunlap 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
2129b6c88d3bSDavid Hildenbrand 		endpa = beginpa + memory_block_size_bytes() - 1;
2130756a025fSJoe Perches 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
2131349daa0fSRandy Dunlap 			&beginpa, &endpa);
2132bbc76be6SWen Congyang 
2133eca499abSPavel Tatashin 		return -EBUSY;
2134eca499abSPavel Tatashin 	}
2135eca499abSPavel Tatashin 	return 0;
2136bbc76be6SWen Congyang }
2137bbc76be6SWen Congyang 
21386b8f0798SVishal Verma static int count_memory_range_altmaps_cb(struct memory_block *mem, void *arg)
2139a08a2ae3SOscar Salvador {
21406b8f0798SVishal Verma 	u64 *num_altmaps = (u64 *)arg;
21416b8f0798SVishal Verma 
21426b8f0798SVishal Verma 	if (mem->altmap)
21436b8f0798SVishal Verma 		*num_altmaps += 1;
21446b8f0798SVishal Verma 
21451a8c64e1SAneesh Kumar K.V 	return 0;
2146a08a2ae3SOscar Salvador }
2147a08a2ae3SOscar Salvador 
2148b27340a5SMiaohe Lin static int check_cpu_on_node(int nid)
214960a5a19eSTang Chen {
215060a5a19eSTang Chen 	int cpu;
215160a5a19eSTang Chen 
215260a5a19eSTang Chen 	for_each_present_cpu(cpu) {
2153b27340a5SMiaohe Lin 		if (cpu_to_node(cpu) == nid)
215460a5a19eSTang Chen 			/*
215560a5a19eSTang Chen 			 * the cpu on this node isn't removed, and we can't
215660a5a19eSTang Chen 			 * offline this node.
215760a5a19eSTang Chen 			 */
215860a5a19eSTang Chen 			return -EBUSY;
215960a5a19eSTang Chen 	}
216060a5a19eSTang Chen 
216160a5a19eSTang Chen 	return 0;
216260a5a19eSTang Chen }
216360a5a19eSTang Chen 
21642c91f8fcSDavid Hildenbrand static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
21652c91f8fcSDavid Hildenbrand {
21662c91f8fcSDavid Hildenbrand 	int nid = *(int *)arg;
21672c91f8fcSDavid Hildenbrand 
21682c91f8fcSDavid Hildenbrand 	/*
21692c91f8fcSDavid Hildenbrand 	 * If a memory block belongs to multiple nodes, the stored nid is not
21702c91f8fcSDavid Hildenbrand 	 * reliable. However, such blocks are always online (e.g., cannot get
21712c91f8fcSDavid Hildenbrand 	 * offlined) and, therefore, are still spanned by the node.
21722c91f8fcSDavid Hildenbrand 	 */
21732c91f8fcSDavid Hildenbrand 	return mem->nid == nid ? -EEXIST : 0;
21742c91f8fcSDavid Hildenbrand }
21752c91f8fcSDavid Hildenbrand 
21760f1cfe9dSToshi Kani /**
21770f1cfe9dSToshi Kani  * try_offline_node
2178e8b098fcSMike Rapoport  * @nid: the node ID
21790f1cfe9dSToshi Kani  *
21800f1cfe9dSToshi Kani  * Offline a node if all memory sections and cpus of the node are removed.
21810f1cfe9dSToshi Kani  *
21820f1cfe9dSToshi Kani  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
21830f1cfe9dSToshi Kani  * and online/offline operations before this call.
21840f1cfe9dSToshi Kani  */
218590b30cdcSWen Congyang void try_offline_node(int nid)
218660a5a19eSTang Chen {
21872c91f8fcSDavid Hildenbrand 	int rc;
218860a5a19eSTang Chen 
218960a5a19eSTang Chen 	/*
21902c91f8fcSDavid Hildenbrand 	 * If the node still spans pages (especially ZONE_DEVICE), don't
21912c91f8fcSDavid Hildenbrand 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
21922c91f8fcSDavid Hildenbrand 	 * e.g., after the memory block was onlined.
219360a5a19eSTang Chen 	 */
2194b27340a5SMiaohe Lin 	if (node_spanned_pages(nid))
219560a5a19eSTang Chen 		return;
21962c91f8fcSDavid Hildenbrand 
21972c91f8fcSDavid Hildenbrand 	/*
21982c91f8fcSDavid Hildenbrand 	 * Especially offline memory blocks might not be spanned by the
21992c91f8fcSDavid Hildenbrand 	 * node. They will get spanned by the node once they get onlined.
22002c91f8fcSDavid Hildenbrand 	 * However, they link to the node in sysfs and can get onlined later.
22012c91f8fcSDavid Hildenbrand 	 */
22022c91f8fcSDavid Hildenbrand 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
22032c91f8fcSDavid Hildenbrand 	if (rc)
22042c91f8fcSDavid Hildenbrand 		return;
220560a5a19eSTang Chen 
2206b27340a5SMiaohe Lin 	if (check_cpu_on_node(nid))
220760a5a19eSTang Chen 		return;
220860a5a19eSTang Chen 
220960a5a19eSTang Chen 	/*
221060a5a19eSTang Chen 	 * all memory/cpu of this node are removed, we can offline this
221160a5a19eSTang Chen 	 * node now.
221260a5a19eSTang Chen 	 */
221360a5a19eSTang Chen 	node_set_offline(nid);
221460a5a19eSTang Chen 	unregister_one_node(nid);
221560a5a19eSTang Chen }
221690b30cdcSWen Congyang EXPORT_SYMBOL(try_offline_node);
221760a5a19eSTang Chen 
22186b8f0798SVishal Verma static int memory_blocks_have_altmaps(u64 start, u64 size)
22196b8f0798SVishal Verma {
22206b8f0798SVishal Verma 	u64 num_memblocks = size / memory_block_size_bytes();
22216b8f0798SVishal Verma 	u64 num_altmaps = 0;
22226b8f0798SVishal Verma 
22236b8f0798SVishal Verma 	if (!mhp_memmap_on_memory())
22246b8f0798SVishal Verma 		return 0;
22256b8f0798SVishal Verma 
22266b8f0798SVishal Verma 	walk_memory_blocks(start, size, &num_altmaps,
22276b8f0798SVishal Verma 			   count_memory_range_altmaps_cb);
22286b8f0798SVishal Verma 
22296b8f0798SVishal Verma 	if (num_altmaps == 0)
22306b8f0798SVishal Verma 		return 0;
22316b8f0798SVishal Verma 
22326b8f0798SVishal Verma 	if (WARN_ON_ONCE(num_memblocks != num_altmaps))
22336b8f0798SVishal Verma 		return -EINVAL;
22346b8f0798SVishal Verma 
22356b8f0798SVishal Verma 	return 1;
22366b8f0798SVishal Verma }
22376b8f0798SVishal Verma 
2238e1c158e4SDavid Hildenbrand static int __ref try_remove_memory(u64 start, u64 size)
2239bbc76be6SWen Congyang {
22406b8f0798SVishal Verma 	int rc, nid = NUMA_NO_NODE;
2241993c1aadSWen Congyang 
224227356f54SToshi Kani 	BUG_ON(check_hotplug_memory_range(start, size));
224327356f54SToshi Kani 
22446677e3eaSYasuaki Ishimatsu 	/*
2245242831ebSRafael J. Wysocki 	 * All memory blocks must be offlined before removing memory.  Check
2246eca499abSPavel Tatashin 	 * whether all memory blocks in question are offline and return error
2247242831ebSRafael J. Wysocki 	 * if this is not the case.
2248e1c158e4SDavid Hildenbrand 	 *
2249e1c158e4SDavid Hildenbrand 	 * While at it, determine the nid. Note that if we'd have mixed nodes,
2250e1c158e4SDavid Hildenbrand 	 * we'd only try to offline the last determined one -- which is good
2251e1c158e4SDavid Hildenbrand 	 * enough for the cases we care about.
22526677e3eaSYasuaki Ishimatsu 	 */
2253e1c158e4SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
2254eca499abSPavel Tatashin 	if (rc)
2255b4223a51SJia He 		return rc;
22566677e3eaSYasuaki Ishimatsu 
225746c66c4bSYasuaki Ishimatsu 	/* remove memmap entry */
225846c66c4bSYasuaki Ishimatsu 	firmware_map_remove(start, start + size, "System RAM");
225946c66c4bSYasuaki Ishimatsu 
22606b8f0798SVishal Verma 	mem_hotplug_begin();
22616b8f0798SVishal Verma 
22626b8f0798SVishal Verma 	rc = memory_blocks_have_altmaps(start, size);
22636b8f0798SVishal Verma 	if (rc < 0) {
22646b8f0798SVishal Verma 		mem_hotplug_done();
22656b8f0798SVishal Verma 		return rc;
22666b8f0798SVishal Verma 	} else if (!rc) {
2267f1037ec0SDan Williams 		/*
2268f1037ec0SDan Williams 		 * Memory block device removal under the device_hotplug_lock is
2269f1037ec0SDan Williams 		 * a barrier against racing online attempts.
22706b8f0798SVishal Verma 		 * No altmaps present, do the removal directly
2271f1037ec0SDan Williams 		 */
22724c4b7f9bSDavid Hildenbrand 		remove_memory_block_devices(start, size);
22736b8f0798SVishal Verma 		arch_remove_memory(start, size, NULL);
22746b8f0798SVishal Verma 	} else {
22756b8f0798SVishal Verma 		/* all memblocks in the range have altmaps */
22766b8f0798SVishal Verma 		remove_memory_blocks_and_altmaps(start, size);
22771a8c64e1SAneesh Kumar K.V 	}
22781a8c64e1SAneesh Kumar K.V 
227952219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
22803ecc6834SMike Rapoport 		memblock_phys_free(start, size);
228132d1fe8fSAnshuman Khandual 		memblock_remove(start, size);
228252219aeaSDavid Hildenbrand 	}
228352219aeaSDavid Hildenbrand 
2284cb8e3c8bSDavid Hildenbrand 	release_mem_region_adjustable(start, size);
228524d335caSWen Congyang 
2286e1c158e4SDavid Hildenbrand 	if (nid != NUMA_NO_NODE)
228760a5a19eSTang Chen 		try_offline_node(nid);
228860a5a19eSTang Chen 
2289bfc8c901SVladimir Davydov 	mem_hotplug_done();
2290b4223a51SJia He 	return 0;
229171088785SBadari Pulavarty }
2292d15e5926SDavid Hildenbrand 
2293eca499abSPavel Tatashin /**
22945640c9caSMel Gorman  * __remove_memory - Remove memory if every memory block is offline
2295eca499abSPavel Tatashin  * @start: physical address of the region to remove
2296eca499abSPavel Tatashin  * @size: size of the region to remove
2297eca499abSPavel Tatashin  *
2298eca499abSPavel Tatashin  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2299eca499abSPavel Tatashin  * and online/offline operations before this call, as required by
2300eca499abSPavel Tatashin  * try_offline_node().
2301eca499abSPavel Tatashin  */
2302e1c158e4SDavid Hildenbrand void __remove_memory(u64 start, u64 size)
2303d15e5926SDavid Hildenbrand {
2304eca499abSPavel Tatashin 
2305eca499abSPavel Tatashin 	/*
230629a90db9SSouptick Joarder 	 * trigger BUG() if some memory is not offlined prior to calling this
2307eca499abSPavel Tatashin 	 * function
2308eca499abSPavel Tatashin 	 */
2309e1c158e4SDavid Hildenbrand 	if (try_remove_memory(start, size))
2310eca499abSPavel Tatashin 		BUG();
2311eca499abSPavel Tatashin }
2312eca499abSPavel Tatashin 
2313eca499abSPavel Tatashin /*
2314eca499abSPavel Tatashin  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2315eca499abSPavel Tatashin  * some memory is not offline
2316eca499abSPavel Tatashin  */
2317e1c158e4SDavid Hildenbrand int remove_memory(u64 start, u64 size)
2318eca499abSPavel Tatashin {
2319eca499abSPavel Tatashin 	int rc;
2320eca499abSPavel Tatashin 
2321d15e5926SDavid Hildenbrand 	lock_device_hotplug();
2322e1c158e4SDavid Hildenbrand 	rc = try_remove_memory(start, size);
2323d15e5926SDavid Hildenbrand 	unlock_device_hotplug();
2324eca499abSPavel Tatashin 
2325eca499abSPavel Tatashin 	return rc;
2326d15e5926SDavid Hildenbrand }
232771088785SBadari Pulavarty EXPORT_SYMBOL_GPL(remove_memory);
232808b3acd7SDavid Hildenbrand 
23298dc4bb58SDavid Hildenbrand static int try_offline_memory_block(struct memory_block *mem, void *arg)
23308dc4bb58SDavid Hildenbrand {
23318dc4bb58SDavid Hildenbrand 	uint8_t online_type = MMOP_ONLINE_KERNEL;
23328dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
23338dc4bb58SDavid Hildenbrand 	struct page *page;
23348dc4bb58SDavid Hildenbrand 	int rc;
23358dc4bb58SDavid Hildenbrand 
233608b3acd7SDavid Hildenbrand 	/*
23378dc4bb58SDavid Hildenbrand 	 * Sense the online_type via the zone of the memory block. Offlining
23388dc4bb58SDavid Hildenbrand 	 * with multiple zones within one memory block will be rejected
23398dc4bb58SDavid Hildenbrand 	 * by offlining code ... so we don't care about that.
23408dc4bb58SDavid Hildenbrand 	 */
23418dc4bb58SDavid Hildenbrand 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
23428dc4bb58SDavid Hildenbrand 	if (page && zone_idx(page_zone(page)) == ZONE_MOVABLE)
23438dc4bb58SDavid Hildenbrand 		online_type = MMOP_ONLINE_MOVABLE;
23448dc4bb58SDavid Hildenbrand 
23458dc4bb58SDavid Hildenbrand 	rc = device_offline(&mem->dev);
23468dc4bb58SDavid Hildenbrand 	/*
23478dc4bb58SDavid Hildenbrand 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
23488dc4bb58SDavid Hildenbrand 	 * so try_reonline_memory_block() can do the right thing.
23498dc4bb58SDavid Hildenbrand 	 */
23508dc4bb58SDavid Hildenbrand 	if (!rc)
23518dc4bb58SDavid Hildenbrand 		**online_types = online_type;
23528dc4bb58SDavid Hildenbrand 
23538dc4bb58SDavid Hildenbrand 	(*online_types)++;
23548dc4bb58SDavid Hildenbrand 	/* Ignore if already offline. */
23558dc4bb58SDavid Hildenbrand 	return rc < 0 ? rc : 0;
23568dc4bb58SDavid Hildenbrand }
23578dc4bb58SDavid Hildenbrand 
23588dc4bb58SDavid Hildenbrand static int try_reonline_memory_block(struct memory_block *mem, void *arg)
23598dc4bb58SDavid Hildenbrand {
23608dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
23618dc4bb58SDavid Hildenbrand 	int rc;
23628dc4bb58SDavid Hildenbrand 
23638dc4bb58SDavid Hildenbrand 	if (**online_types != MMOP_OFFLINE) {
23648dc4bb58SDavid Hildenbrand 		mem->online_type = **online_types;
23658dc4bb58SDavid Hildenbrand 		rc = device_online(&mem->dev);
23668dc4bb58SDavid Hildenbrand 		if (rc < 0)
23678dc4bb58SDavid Hildenbrand 			pr_warn("%s: Failed to re-online memory: %d",
23688dc4bb58SDavid Hildenbrand 				__func__, rc);
23698dc4bb58SDavid Hildenbrand 	}
23708dc4bb58SDavid Hildenbrand 
23718dc4bb58SDavid Hildenbrand 	/* Continue processing all remaining memory blocks. */
23728dc4bb58SDavid Hildenbrand 	(*online_types)++;
23738dc4bb58SDavid Hildenbrand 	return 0;
23748dc4bb58SDavid Hildenbrand }
23758dc4bb58SDavid Hildenbrand 
23768dc4bb58SDavid Hildenbrand /*
23778dc4bb58SDavid Hildenbrand  * Try to offline and remove memory. Might take a long time to finish in case
23788dc4bb58SDavid Hildenbrand  * memory is still in use. Primarily useful for memory devices that logically
23798dc4bb58SDavid Hildenbrand  * unplugged all memory (so it's no longer in use) and want to offline + remove
23808dc4bb58SDavid Hildenbrand  * that memory.
238108b3acd7SDavid Hildenbrand  */
2382e1c158e4SDavid Hildenbrand int offline_and_remove_memory(u64 start, u64 size)
238308b3acd7SDavid Hildenbrand {
23848dc4bb58SDavid Hildenbrand 	const unsigned long mb_count = size / memory_block_size_bytes();
23858dc4bb58SDavid Hildenbrand 	uint8_t *online_types, *tmp;
23868dc4bb58SDavid Hildenbrand 	int rc;
238708b3acd7SDavid Hildenbrand 
238808b3acd7SDavid Hildenbrand 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
23898dc4bb58SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
23908dc4bb58SDavid Hildenbrand 		return -EINVAL;
239108b3acd7SDavid Hildenbrand 
239208b3acd7SDavid Hildenbrand 	/*
23938dc4bb58SDavid Hildenbrand 	 * We'll remember the old online type of each memory block, so we can
23948dc4bb58SDavid Hildenbrand 	 * try to revert whatever we did when offlining one memory block fails
23958dc4bb58SDavid Hildenbrand 	 * after offlining some others succeeded.
23968dc4bb58SDavid Hildenbrand 	 */
23978dc4bb58SDavid Hildenbrand 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
23988dc4bb58SDavid Hildenbrand 				     GFP_KERNEL);
23998dc4bb58SDavid Hildenbrand 	if (!online_types)
24008dc4bb58SDavid Hildenbrand 		return -ENOMEM;
24018dc4bb58SDavid Hildenbrand 	/*
24028dc4bb58SDavid Hildenbrand 	 * Initialize all states to MMOP_OFFLINE, so when we abort processing in
24038dc4bb58SDavid Hildenbrand 	 * try_offline_memory_block(), we'll skip all unprocessed blocks in
24048dc4bb58SDavid Hildenbrand 	 * try_reonline_memory_block().
24058dc4bb58SDavid Hildenbrand 	 */
24068dc4bb58SDavid Hildenbrand 	memset(online_types, MMOP_OFFLINE, mb_count);
24078dc4bb58SDavid Hildenbrand 
24088dc4bb58SDavid Hildenbrand 	lock_device_hotplug();
24098dc4bb58SDavid Hildenbrand 
24108dc4bb58SDavid Hildenbrand 	tmp = online_types;
24118dc4bb58SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
24128dc4bb58SDavid Hildenbrand 
24138dc4bb58SDavid Hildenbrand 	/*
24148dc4bb58SDavid Hildenbrand 	 * In case we succeeded to offline all memory, remove it.
241508b3acd7SDavid Hildenbrand 	 * This cannot fail as it cannot get onlined in the meantime.
241608b3acd7SDavid Hildenbrand 	 */
241708b3acd7SDavid Hildenbrand 	if (!rc) {
2418e1c158e4SDavid Hildenbrand 		rc = try_remove_memory(start, size);
24198dc4bb58SDavid Hildenbrand 		if (rc)
24208dc4bb58SDavid Hildenbrand 			pr_err("%s: Failed to remove memory: %d", __func__, rc);
24218dc4bb58SDavid Hildenbrand 	}
24228dc4bb58SDavid Hildenbrand 
24238dc4bb58SDavid Hildenbrand 	/*
24248dc4bb58SDavid Hildenbrand 	 * Rollback what we did. While memory onlining might theoretically fail
24258dc4bb58SDavid Hildenbrand 	 * (nacked by a notifier), it barely ever happens.
24268dc4bb58SDavid Hildenbrand 	 */
24278dc4bb58SDavid Hildenbrand 	if (rc) {
24288dc4bb58SDavid Hildenbrand 		tmp = online_types;
24298dc4bb58SDavid Hildenbrand 		walk_memory_blocks(start, size, &tmp,
24308dc4bb58SDavid Hildenbrand 				   try_reonline_memory_block);
243108b3acd7SDavid Hildenbrand 	}
243208b3acd7SDavid Hildenbrand 	unlock_device_hotplug();
243308b3acd7SDavid Hildenbrand 
24348dc4bb58SDavid Hildenbrand 	kfree(online_types);
243508b3acd7SDavid Hildenbrand 	return rc;
243608b3acd7SDavid Hildenbrand }
243708b3acd7SDavid Hildenbrand EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2438aba6efc4SRafael J. Wysocki #endif /* CONFIG_MEMORY_HOTREMOVE */
2439