xref: /linux/mm/memory_hotplug.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/memory_hotplug.c
4  *
5  *  Copyright (C)
6  */
7 
8 #include <linux/stddef.h>
9 #include <linux/mm.h>
10 #include <linux/sched/signal.h>
11 #include <linux/swap.h>
12 #include <linux/interrupt.h>
13 #include <linux/pagemap.h>
14 #include <linux/compiler.h>
15 #include <linux/export.h>
16 #include <linux/writeback.h>
17 #include <linux/slab.h>
18 #include <linux/sysctl.h>
19 #include <linux/cpu.h>
20 #include <linux/memory.h>
21 #include <linux/memremap.h>
22 #include <linux/memory_hotplug.h>
23 #include <linux/vmalloc.h>
24 #include <linux/ioport.h>
25 #include <linux/delay.h>
26 #include <linux/migrate.h>
27 #include <linux/page-isolation.h>
28 #include <linux/pfn.h>
29 #include <linux/suspend.h>
30 #include <linux/mm_inline.h>
31 #include <linux/firmware-map.h>
32 #include <linux/stop_machine.h>
33 #include <linux/hugetlb.h>
34 #include <linux/memblock.h>
35 #include <linux/compaction.h>
36 #include <linux/rmap.h>
37 #include <linux/module.h>
38 #include <linux/node.h>
39 
40 #include <asm/tlbflush.h>
41 
42 #include "internal.h"
43 #include "mm_init.h"
44 #include "page_alloc.h"
45 #include "shuffle.h"
46 #include "sparse.h"
47 
48 enum {
49 	MEMMAP_ON_MEMORY_DISABLE = 0,
50 	MEMMAP_ON_MEMORY_ENABLE,
51 	MEMMAP_ON_MEMORY_FORCE,
52 };
53 
54 static int memmap_mode __read_mostly = MEMMAP_ON_MEMORY_DISABLE;
55 
56 static inline unsigned long memory_block_memmap_size(void)
57 {
58 	return PHYS_PFN(memory_block_size_bytes()) * sizeof(struct page);
59 }
60 
61 static inline unsigned long memory_block_memmap_on_memory_pages(void)
62 {
63 	unsigned long nr_pages = PFN_UP(memory_block_memmap_size());
64 
65 	/*
66 	 * In "forced" memmap_on_memory mode, we add extra pages to align the
67 	 * vmemmap size to cover full pageblocks. That way, we can add memory
68 	 * even if the vmemmap size is not properly aligned, however, we might waste
69 	 * memory.
70 	 */
71 	if (memmap_mode == MEMMAP_ON_MEMORY_FORCE)
72 		return pageblock_align(nr_pages);
73 	return nr_pages;
74 }
75 
76 #ifdef CONFIG_MHP_MEMMAP_ON_MEMORY
77 /*
78  * memory_hotplug.memmap_on_memory parameter
79  */
80 static int set_memmap_mode(const char *val, const struct kernel_param *kp)
81 {
82 	int ret, mode;
83 	bool enabled;
84 
85 	if (sysfs_streq(val, "force") ||  sysfs_streq(val, "FORCE")) {
86 		mode = MEMMAP_ON_MEMORY_FORCE;
87 	} else {
88 		ret = kstrtobool(val, &enabled);
89 		if (ret < 0)
90 			return ret;
91 		if (enabled)
92 			mode = MEMMAP_ON_MEMORY_ENABLE;
93 		else
94 			mode = MEMMAP_ON_MEMORY_DISABLE;
95 	}
96 	*((int *)kp->arg) = mode;
97 	if (mode == MEMMAP_ON_MEMORY_FORCE) {
98 		unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
99 
100 		pr_info_once("Memory hotplug will waste %ld pages in each memory block\n",
101 			     memmap_pages - PFN_UP(memory_block_memmap_size()));
102 	}
103 	return 0;
104 }
105 
106 static int get_memmap_mode(char *buffer, const struct kernel_param *kp)
107 {
108 	int mode = *((int *)kp->arg);
109 
110 	if (mode == MEMMAP_ON_MEMORY_FORCE)
111 		return sprintf(buffer, "force\n");
112 	return sprintf(buffer, "%c\n", mode ? 'Y' : 'N');
113 }
114 
115 static const struct kernel_param_ops memmap_mode_ops = {
116 	.set = set_memmap_mode,
117 	.get = get_memmap_mode,
118 };
119 module_param_cb(memmap_on_memory, &memmap_mode_ops, &memmap_mode, 0444);
120 MODULE_PARM_DESC(memmap_on_memory, "Enable memmap on memory for memory hotplug\n"
121 		 "With value \"force\" it could result in memory wastage due "
122 		 "to memmap size limitations (Y/N/force)");
123 
124 static inline bool mhp_memmap_on_memory(void)
125 {
126 	return memmap_mode != MEMMAP_ON_MEMORY_DISABLE;
127 }
128 #else
129 static inline bool mhp_memmap_on_memory(void)
130 {
131 	return false;
132 }
133 #endif
134 
135 enum {
136 	ONLINE_POLICY_CONTIG_ZONES = 0,
137 	ONLINE_POLICY_AUTO_MOVABLE,
138 };
139 
140 static const char * const online_policy_to_str[] = {
141 	[ONLINE_POLICY_CONTIG_ZONES] = "contig-zones",
142 	[ONLINE_POLICY_AUTO_MOVABLE] = "auto-movable",
143 };
144 
145 static int set_online_policy(const char *val, const struct kernel_param *kp)
146 {
147 	int ret = sysfs_match_string(online_policy_to_str, val);
148 
149 	if (ret < 0)
150 		return ret;
151 	*((int *)kp->arg) = ret;
152 	return 0;
153 }
154 
155 static int get_online_policy(char *buffer, const struct kernel_param *kp)
156 {
157 	return sprintf(buffer, "%s\n", online_policy_to_str[*((int *)kp->arg)]);
158 }
159 
160 /*
161  * memory_hotplug.online_policy: configure online behavior when onlining without
162  * specifying a zone (MMOP_ONLINE)
163  *
164  * "contig-zones": keep zone contiguous
165  * "auto-movable": online memory to ZONE_MOVABLE if the configuration
166  *                 (auto_movable_ratio, auto_movable_numa_aware) allows for it
167  */
168 static int online_policy __read_mostly = ONLINE_POLICY_CONTIG_ZONES;
169 static const struct kernel_param_ops online_policy_ops = {
170 	.set = set_online_policy,
171 	.get = get_online_policy,
172 };
173 module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
174 MODULE_PARM_DESC(online_policy,
175 		"Set the online policy (\"contig-zones\", \"auto-movable\") "
176 		"Default: \"contig-zones\"");
177 
178 /*
179  * memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio
180  *
181  * The ratio represent an upper limit and the kernel might decide to not
182  * online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory
183  * doesn't allow for more MOVABLE memory.
184  */
185 static unsigned int auto_movable_ratio __read_mostly = 301;
186 module_param(auto_movable_ratio, uint, 0644);
187 MODULE_PARM_DESC(auto_movable_ratio,
188 		"Set the maximum ratio of MOVABLE:KERNEL memory in the system "
189 		"in percent for \"auto-movable\" online policy. Default: 301");
190 
191 /*
192  * memory_hotplug.auto_movable_numa_aware: consider numa node stats
193  */
194 #ifdef CONFIG_NUMA
195 static bool auto_movable_numa_aware __read_mostly = true;
196 module_param(auto_movable_numa_aware, bool, 0644);
197 MODULE_PARM_DESC(auto_movable_numa_aware,
198 		"Consider numa node stats in addition to global stats in "
199 		"\"auto-movable\" online policy. Default: true");
200 #endif /* CONFIG_NUMA */
201 
202 /*
203  * online_page_callback contains pointer to current page onlining function.
204  * Initially it is generic_online_page(). If it is required it could be
205  * changed by calling set_online_page_callback() for callback registration
206  * and restore_online_page_callback() for generic callback restore.
207  */
208 
209 static online_page_callback_t online_page_callback = generic_online_page;
210 static DEFINE_MUTEX(online_page_callback_lock);
211 
212 DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
213 
214 void get_online_mems(void)
215 {
216 	percpu_down_read(&mem_hotplug_lock);
217 }
218 
219 void put_online_mems(void)
220 {
221 	percpu_up_read(&mem_hotplug_lock);
222 }
223 
224 bool movable_node_enabled = false;
225 
226 static int mhp_default_online_type = -1;
227 enum mmop mhp_get_default_online_type(void)
228 {
229 	if (mhp_default_online_type >= 0)
230 		return mhp_default_online_type;
231 
232 	if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_OFFLINE))
233 		mhp_default_online_type = MMOP_OFFLINE;
234 	else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_AUTO))
235 		mhp_default_online_type = MMOP_ONLINE;
236 	else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_KERNEL))
237 		mhp_default_online_type = MMOP_ONLINE_KERNEL;
238 	else if (IS_ENABLED(CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_MOVABLE))
239 		mhp_default_online_type = MMOP_ONLINE_MOVABLE;
240 	else
241 		mhp_default_online_type = MMOP_OFFLINE;
242 
243 	return mhp_default_online_type;
244 }
245 EXPORT_SYMBOL_GPL(mhp_get_default_online_type);
246 
247 void mhp_set_default_online_type(enum mmop online_type)
248 {
249 	mhp_default_online_type = online_type;
250 }
251 
252 static int __init setup_memhp_default_state(char *str)
253 {
254 	const int online_type = mhp_online_type_from_str(str);
255 
256 	if (online_type >= 0)
257 		mhp_default_online_type = online_type;
258 
259 	return 1;
260 }
261 __setup("memhp_default_state=", setup_memhp_default_state);
262 
263 void mem_hotplug_begin(void)
264 {
265 	cpus_read_lock();
266 	percpu_down_write(&mem_hotplug_lock);
267 }
268 
269 void mem_hotplug_done(void)
270 {
271 	percpu_up_write(&mem_hotplug_lock);
272 	cpus_read_unlock();
273 }
274 
275 u64 max_mem_size = U64_MAX;
276 
277 /* add this memory to iomem resource */
278 static struct resource *register_memory_resource(u64 start, u64 size,
279 						 const char *resource_name)
280 {
281 	struct resource *res;
282 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
283 
284 	if (strcmp(resource_name, "System RAM"))
285 		flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
286 
287 	if (!mhp_range_allowed(start, size, true))
288 		return ERR_PTR(-E2BIG);
289 
290 	/*
291 	 * Make sure value parsed from 'mem=' only restricts memory adding
292 	 * while booting, so that memory hotplug won't be impacted. Please
293 	 * refer to document of 'mem=' in kernel-parameters.txt for more
294 	 * details.
295 	 */
296 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
297 		return ERR_PTR(-E2BIG);
298 
299 	/*
300 	 * Request ownership of the new memory range.  This might be
301 	 * a child of an existing resource that was present but
302 	 * not marked as busy.
303 	 */
304 	res = __request_region(&iomem_resource, start, size,
305 			       resource_name, flags);
306 
307 	if (!res) {
308 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
309 				start, start + size);
310 		return ERR_PTR(-EEXIST);
311 	}
312 	return res;
313 }
314 
315 static void release_memory_resource(struct resource *res)
316 {
317 	if (!res)
318 		return;
319 	release_resource(res);
320 	kfree(res);
321 }
322 
323 static int check_pfn_span(unsigned long pfn, unsigned long nr_pages)
324 {
325 	/*
326 	 * Disallow all operations smaller than a sub-section.
327 	 * Note that check_hotplug_memory_range() enforces a larger
328 	 * memory_block_size_bytes() granularity for memory that will be marked
329 	 * online, so this check should only fire for direct
330 	 * arch_{add,remove}_memory() users outside of add_memory_resource().
331 	 */
332 	if (!IS_ALIGNED(pfn | nr_pages, PAGES_PER_SUBSECTION))
333 		return -EINVAL;
334 	return 0;
335 }
336 
337 /*
338  * Return page for the valid pfn only if the page is online. All pfn
339  * walkers which rely on the fully initialized page->flags and others
340  * should use this rather than pfn_valid && pfn_to_page
341  */
342 struct page *pfn_to_online_page(unsigned long pfn)
343 {
344 	unsigned long nr = pfn_to_section_nr(pfn);
345 	struct dev_pagemap *pgmap;
346 	struct mem_section *ms;
347 
348 	BUILD_BUG_ON(IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID));
349 
350 	if (nr >= NR_MEM_SECTIONS)
351 		return NULL;
352 
353 	ms = __nr_to_section(nr);
354 	if (!online_section(ms))
355 		return NULL;
356 
357 	if (!pfn_section_valid(ms, pfn))
358 		return NULL;
359 
360 	if (!online_device_section(ms))
361 		return pfn_to_page(pfn);
362 
363 	/*
364 	 * Slowpath: when ZONE_DEVICE collides with
365 	 * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
366 	 * the section may be 'offline' but 'valid'. Only
367 	 * get_dev_pagemap() can determine sub-section online status.
368 	 */
369 	pgmap = get_dev_pagemap(pfn);
370 	put_dev_pagemap(pgmap);
371 
372 	/* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
373 	if (pgmap)
374 		return NULL;
375 
376 	return pfn_to_page(pfn);
377 }
378 EXPORT_SYMBOL_GPL(pfn_to_online_page);
379 
380 int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
381 		struct mhp_params *params)
382 {
383 	const unsigned long start_pfn = pfn;
384 	const unsigned long end_pfn = pfn + nr_pages;
385 	unsigned long cur_nr_pages;
386 	int err;
387 	struct vmem_altmap *altmap = params->altmap;
388 
389 	if (WARN_ON_ONCE(!pgprot_val(params->pgprot)))
390 		return -EINVAL;
391 
392 	VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
393 
394 	if (altmap) {
395 		/*
396 		 * Validate altmap is within bounds of the total request
397 		 */
398 		if (altmap->base_pfn != pfn
399 				|| vmem_altmap_offset(altmap) > nr_pages) {
400 			pr_warn_once("memory add fail, invalid altmap\n");
401 			return -EINVAL;
402 		}
403 		altmap->alloc = 0;
404 	}
405 
406 	if (check_pfn_span(pfn, nr_pages)) {
407 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
408 		return -EINVAL;
409 	}
410 
411 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
412 		/* Select all remaining pages up to the next section boundary */
413 		cur_nr_pages = min(end_pfn - pfn,
414 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
415 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
416 					 params->pgmap);
417 		if (err) {
418 			__remove_pages(start_pfn, pfn - start_pfn, altmap,
419 				       params->pgmap);
420 			break;
421 		}
422 		cond_resched();
423 	}
424 	vmemmap_populate_print_last();
425 	return err;
426 }
427 
428 static bool subsection_overlaps_zone(unsigned long pfn, struct zone *zone)
429 {
430 	const unsigned long start_pfn = ALIGN_DOWN(pfn, PAGES_PER_SUBSECTION);
431 	const unsigned long end_pfn = start_pfn + PAGES_PER_SUBSECTION - 1;
432 
433 	/* All pages in a subsection are either online or offline. */
434 	if (unlikely(!pfn_to_online_page(start_pfn)))
435 		return false;
436 
437 	/* Checking start+end is sufficient. */
438 	return zone == page_zone(pfn_to_page(start_pfn)) ||
439 	       zone == page_zone(pfn_to_page(end_pfn));
440 }
441 
442 /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
443 static unsigned long find_smallest_section_pfn(struct zone *zone,
444 		unsigned long start_pfn, unsigned long end_pfn)
445 {
446 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
447 		if (subsection_overlaps_zone(start_pfn, zone))
448 			return start_pfn;
449 	}
450 	return 0;
451 }
452 
453 /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
454 static unsigned long find_biggest_section_pfn(struct zone *zone,
455 		unsigned long start_pfn, unsigned long end_pfn)
456 {
457 	for (; end_pfn > start_pfn; end_pfn -= PAGES_PER_SUBSECTION) {
458 		if (subsection_overlaps_zone(end_pfn - 1, zone))
459 			return end_pfn - 1;
460 	}
461 	return 0;
462 }
463 
464 /*
465  * The page allocator checks pages against the span of their zone while the
466  * zone is resized, see page_outside_zone_boundaries(). It must not see the
467  * new value of one field together with the old value of the other one.
468  */
469 static void zone_set_span(struct zone *zone, unsigned long start_pfn,
470 			  unsigned long spanned_pages)
471 {
472 	unsigned long flags;
473 
474 	write_seqlock_irqsave(&zone->span_seqlock, flags);
475 	zone->zone_start_pfn = start_pfn;
476 	zone->spanned_pages = spanned_pages;
477 	write_sequnlock_irqrestore(&zone->span_seqlock, flags);
478 }
479 
480 static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
481 			     unsigned long end_pfn)
482 {
483 	unsigned long pfn;
484 
485 	if (zone->zone_start_pfn == start_pfn) {
486 		/*
487 		 * If the section is smallest section in the zone, it need
488 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
489 		 * In this case, we find second smallest valid mem_section
490 		 * for shrinking zone.
491 		 */
492 		pfn = find_smallest_section_pfn(zone, end_pfn,
493 						zone_end_pfn(zone));
494 		if (pfn)
495 			zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn);
496 		else
497 			zone_set_span(zone, 0, 0);
498 	} else if (zone_end_pfn(zone) == end_pfn) {
499 		/*
500 		 * If the section is biggest section in the zone, it need
501 		 * shrink zone->spanned_pages.
502 		 * In this case, we find second biggest valid mem_section for
503 		 * shrinking zone.
504 		 */
505 		pfn = find_biggest_section_pfn(zone, zone->zone_start_pfn,
506 					       start_pfn);
507 		if (pfn)
508 			zone_set_span(zone, zone->zone_start_pfn,
509 				      pfn - zone->zone_start_pfn + 1);
510 		else
511 			zone_set_span(zone, 0, 0);
512 	}
513 }
514 
515 static void update_pgdat_span(struct pglist_data *pgdat)
516 {
517 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
518 	struct zone *zone;
519 
520 	for (zone = pgdat->node_zones;
521 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
522 		unsigned long end_pfn = zone_end_pfn(zone);
523 
524 		/* No need to lock the zones, they can't change. */
525 		if (!zone->spanned_pages)
526 			continue;
527 		if (!node_end_pfn) {
528 			node_start_pfn = zone->zone_start_pfn;
529 			node_end_pfn = end_pfn;
530 			continue;
531 		}
532 
533 		if (end_pfn > node_end_pfn)
534 			node_end_pfn = end_pfn;
535 		if (zone->zone_start_pfn < node_start_pfn)
536 			node_start_pfn = zone->zone_start_pfn;
537 	}
538 
539 	pgdat->node_start_pfn = node_start_pfn;
540 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
541 }
542 
543 void remove_pfn_range_from_zone(struct zone *zone,
544 				      unsigned long start_pfn,
545 				      unsigned long nr_pages)
546 {
547 	const unsigned long end_pfn = start_pfn + nr_pages;
548 	struct pglist_data *pgdat = zone->zone_pgdat;
549 	unsigned long pfn, cur_nr_pages;
550 
551 	/* Poison struct pages because they are now uninitialized again. */
552 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
553 		cond_resched();
554 
555 		/* Select all remaining pages up to the next section boundary */
556 		cur_nr_pages =
557 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
558 		if (!section_vmemmap_optimizable(__pfn_to_section(pfn)))
559 			page_init_poison(pfn_to_page(pfn),
560 					 sizeof(struct page) * cur_nr_pages);
561 	}
562 
563 	/*
564 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
565 	 * we will not try to shrink it.
566 	 */
567 	if (zone_is_zone_device(zone))
568 		return;
569 
570 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
571 	update_pgdat_span(pgdat);
572 }
573 
574 /**
575  * __remove_pages() - remove sections of pages
576  * @pfn: starting pageframe (must be aligned to start of a section)
577  * @nr_pages: number of pages to remove (must be multiple of section size)
578  * @altmap: alternative device page map or %NULL if default memmap is used
579  * @pgmap: device page map or %NULL if not ZONE_DEVICE
580  *
581  * Generic helper function to remove section mappings and sysfs entries
582  * for the section of the memory we are removing. Caller needs to make
583  * sure that pages are marked reserved and zones are adjust properly by
584  * calling offline_pages().
585  */
586 void __remove_pages(unsigned long pfn, unsigned long nr_pages,
587 		    struct vmem_altmap *altmap, struct dev_pagemap *pgmap)
588 {
589 	const unsigned long end_pfn = pfn + nr_pages;
590 	unsigned long cur_nr_pages;
591 
592 	if (check_pfn_span(pfn, nr_pages)) {
593 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
594 		return;
595 	}
596 
597 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
598 		cond_resched();
599 		/* Select all remaining pages up to the next section boundary */
600 		cur_nr_pages = min(end_pfn - pfn,
601 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
602 		sparse_remove_section(pfn, cur_nr_pages, altmap, pgmap);
603 	}
604 }
605 
606 int set_online_page_callback(online_page_callback_t callback)
607 {
608 	int rc = -EINVAL;
609 
610 	get_online_mems();
611 	mutex_lock(&online_page_callback_lock);
612 
613 	if (online_page_callback == generic_online_page) {
614 		online_page_callback = callback;
615 		rc = 0;
616 	}
617 
618 	mutex_unlock(&online_page_callback_lock);
619 	put_online_mems();
620 
621 	return rc;
622 }
623 EXPORT_SYMBOL_GPL(set_online_page_callback);
624 
625 int restore_online_page_callback(online_page_callback_t callback)
626 {
627 	int rc = -EINVAL;
628 
629 	get_online_mems();
630 	mutex_lock(&online_page_callback_lock);
631 
632 	if (online_page_callback == callback) {
633 		online_page_callback = generic_online_page;
634 		rc = 0;
635 	}
636 
637 	mutex_unlock(&online_page_callback_lock);
638 	put_online_mems();
639 
640 	return rc;
641 }
642 EXPORT_SYMBOL_GPL(restore_online_page_callback);
643 
644 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
645 void generic_online_page(struct page *page, unsigned int order)
646 {
647 	__free_pages_core(page, order, MEMINIT_HOTPLUG);
648 }
649 EXPORT_SYMBOL_GPL(generic_online_page);
650 
651 static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
652 {
653 	const unsigned long end_pfn = start_pfn + nr_pages;
654 	unsigned long pfn;
655 
656 	/*
657 	 * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
658 	 * decide to not expose all pages to the buddy (e.g., expose them
659 	 * later). We account all pages as being online and belonging to this
660 	 * zone ("present").
661 	 * When using memmap_on_memory, the range might not be aligned to
662 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
663 	 * this and the first chunk to online will be pageblock_nr_pages.
664 	 */
665 	for (pfn = start_pfn; pfn < end_pfn;) {
666 		struct page *page = pfn_to_page(pfn);
667 		int order;
668 
669 		/*
670 		 * Free to online pages in the largest chunks alignment allows.
671 		 *
672 		 * __ffs() behaviour is undefined for 0. start == 0 is
673 		 * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
674 		 * the case.
675 		 */
676 		if (pfn)
677 			order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
678 		else
679 			order = MAX_PAGE_ORDER;
680 
681 		/*
682 		 * Exposing the page to the buddy by freeing can cause
683 		 * issues with debug_pagealloc enabled: some archs don't
684 		 * like double-unmappings. So treat them like any pages that
685 		 * were allocated from the buddy.
686 		 */
687 		debug_pagealloc_map_pages(page, 1 << order);
688 		(*online_page_callback)(page, order);
689 		pfn += (1UL << order);
690 	}
691 
692 	/* mark all involved sections as online */
693 	online_mem_sections(start_pfn, end_pfn);
694 }
695 
696 static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
697 		unsigned long nr_pages)
698 {
699 	unsigned long end_pfn = max(start_pfn + nr_pages, zone_end_pfn(zone));
700 
701 	if (!zone_is_empty(zone) && start_pfn > zone->zone_start_pfn)
702 		start_pfn = zone->zone_start_pfn;
703 
704 	zone_set_span(zone, start_pfn, end_pfn - start_pfn);
705 }
706 
707 static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
708                                      unsigned long nr_pages)
709 {
710 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
711 
712 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
713 		pgdat->node_start_pfn = start_pfn;
714 
715 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
716 
717 }
718 
719 #ifdef CONFIG_ZONE_DEVICE
720 static void section_taint_zone_device(unsigned long pfn)
721 {
722 	struct mem_section *ms = __pfn_to_section(pfn);
723 
724 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
725 }
726 #else
727 static inline void section_taint_zone_device(unsigned long pfn)
728 {
729 }
730 #endif
731 
732 /*
733  * Associate the pfn range with the given zone, initializing the memmaps
734  * and resizing the pgdat/zone data to span the added pages. After this
735  * call, all affected pages are PageOffline().
736  *
737  * All aligned pageblocks are initialized to the specified migratetype
738  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
739  * zone stats (e.g., nr_isolate_pageblock) are touched.
740  */
741 void move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
742 				  unsigned long nr_pages,
743 				  struct vmem_altmap *altmap, int migratetype,
744 				  bool isolate_pageblock)
745 {
746 	struct pglist_data *pgdat = zone->zone_pgdat;
747 	int nid = pgdat->node_id;
748 
749 	if (zone_is_empty(zone))
750 		init_currently_empty_zone(zone, start_pfn, nr_pages);
751 	resize_zone_range(zone, start_pfn, nr_pages);
752 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
753 
754 	/*
755 	 * Subsection population requires care in pfn_to_online_page().
756 	 * Set the taint to enable the slow path detection of
757 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
758 	 * section.
759 	 */
760 	if (zone_is_zone_device(zone)) {
761 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
762 			section_taint_zone_device(start_pfn);
763 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
764 			section_taint_zone_device(start_pfn + nr_pages);
765 	}
766 
767 	/*
768 	 * TODO now we have a visible range of pages which are not associated
769 	 * with their zone properly. Not nice but set_pfnblock_migratetype()
770 	 * expects the zone spans the pfn range. All the pages in the range
771 	 * are reserved so nobody should be touching them so we should be safe
772 	 */
773 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
774 			 MEMINIT_HOTPLUG, altmap, migratetype,
775 			 isolate_pageblock);
776 }
777 
778 struct auto_movable_stats {
779 	unsigned long kernel_early_pages;
780 	unsigned long movable_pages;
781 };
782 
783 static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
784 					    struct zone *zone)
785 {
786 	if (zone_idx(zone) == ZONE_MOVABLE) {
787 		stats->movable_pages += zone->present_pages;
788 	} else {
789 		stats->kernel_early_pages += zone->present_early_pages;
790 #ifdef CONFIG_CMA
791 		/*
792 		 * CMA pages (never on hotplugged memory) behave like
793 		 * ZONE_MOVABLE.
794 		 */
795 		stats->movable_pages += zone->cma_pages;
796 		stats->kernel_early_pages -= zone->cma_pages;
797 #endif /* CONFIG_CMA */
798 	}
799 }
800 struct auto_movable_group_stats {
801 	unsigned long movable_pages;
802 	unsigned long req_kernel_early_pages;
803 };
804 
805 static int auto_movable_stats_account_group(struct memory_group *group,
806 					   void *arg)
807 {
808 	const int ratio = READ_ONCE(auto_movable_ratio);
809 	struct auto_movable_group_stats *stats = arg;
810 	long pages;
811 
812 	/*
813 	 * We don't support modifying the config while the auto-movable online
814 	 * policy is already enabled. Just avoid the division by zero below.
815 	 */
816 	if (!ratio)
817 		return 0;
818 
819 	/*
820 	 * Calculate how many early kernel pages this group requires to
821 	 * satisfy the configured zone ratio.
822 	 */
823 	pages = group->present_movable_pages * 100 / ratio;
824 	pages -= group->present_kernel_pages;
825 
826 	if (pages > 0)
827 		stats->req_kernel_early_pages += pages;
828 	stats->movable_pages += group->present_movable_pages;
829 	return 0;
830 }
831 
832 static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
833 					    unsigned long nr_pages)
834 {
835 	unsigned long kernel_early_pages, movable_pages;
836 	struct auto_movable_group_stats group_stats = {};
837 	struct auto_movable_stats stats = {};
838 	struct zone *zone;
839 	int i;
840 
841 	/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
842 	if (nid == NUMA_NO_NODE) {
843 		/* TODO: cache values */
844 		for_each_populated_zone(zone)
845 			auto_movable_stats_account_zone(&stats, zone);
846 	} else {
847 		for (i = 0; i < MAX_NR_ZONES; i++) {
848 			pg_data_t *pgdat = NODE_DATA(nid);
849 
850 			zone = pgdat->node_zones + i;
851 			if (populated_zone(zone))
852 				auto_movable_stats_account_zone(&stats, zone);
853 		}
854 	}
855 
856 	kernel_early_pages = stats.kernel_early_pages;
857 	movable_pages = stats.movable_pages;
858 
859 	/*
860 	 * Kernel memory inside dynamic memory group allows for more MOVABLE
861 	 * memory within the same group. Remove the effect of all but the
862 	 * current group from the stats.
863 	 */
864 	walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
865 				   group, &group_stats);
866 	if (kernel_early_pages <= group_stats.req_kernel_early_pages)
867 		return false;
868 	kernel_early_pages -= group_stats.req_kernel_early_pages;
869 	movable_pages -= group_stats.movable_pages;
870 
871 	if (group && group->is_dynamic)
872 		kernel_early_pages += group->present_kernel_pages;
873 
874 	/*
875 	 * Test if we could online the given number of pages to ZONE_MOVABLE
876 	 * and still stay in the configured ratio.
877 	 */
878 	movable_pages += nr_pages;
879 	return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
880 }
881 
882 /*
883  * Returns a default kernel memory zone for the given pfn range.
884  * If no kernel zone covers this pfn range it will automatically go
885  * to the ZONE_NORMAL.
886  */
887 static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
888 		unsigned long nr_pages)
889 {
890 	struct pglist_data *pgdat = NODE_DATA(nid);
891 	int zid;
892 
893 	for (zid = 0; zid < ZONE_NORMAL; zid++) {
894 		struct zone *zone = &pgdat->node_zones[zid];
895 
896 		if (zone_intersects(zone, start_pfn, nr_pages))
897 			return zone;
898 	}
899 
900 	return &pgdat->node_zones[ZONE_NORMAL];
901 }
902 
903 /*
904  * Determine to which zone to online memory dynamically based on user
905  * configuration and system stats. We care about the following ratio:
906  *
907  *   MOVABLE : KERNEL
908  *
909  * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
910  * one of the kernel zones. CMA pages inside one of the kernel zones really
911  * behaves like ZONE_MOVABLE, so we treat them accordingly.
912  *
913  * We don't allow for hotplugged memory in a KERNEL zone to increase the
914  * amount of MOVABLE memory we can have, so we end up with:
915  *
916  *   MOVABLE : KERNEL_EARLY
917  *
918  * Whereby KERNEL_EARLY is memory in one of the kernel zones, available since
919  * boot. We base our calculation on KERNEL_EARLY internally, because:
920  *
921  * a) Hotplugged memory in one of the kernel zones can sometimes still get
922  *    hotunplugged, especially when hot(un)plugging individual memory blocks.
923  *    There is no coordination across memory devices, therefore "automatic"
924  *    hotunplugging, as implemented in hypervisors, could result in zone
925  *    imbalances.
926  * b) Early/boot memory in one of the kernel zones can usually not get
927  *    hotunplugged again (e.g., no firmware interface to unplug, fragmented
928  *    with unmovable allocations). While there are corner cases where it might
929  *    still work, it is barely relevant in practice.
930  *
931  * Exceptions are dynamic memory groups, which allow for more MOVABLE
932  * memory within the same memory group -- because in that case, there is
933  * coordination within the single memory device managed by a single driver.
934  *
935  * We rely on "present pages" instead of "managed pages", as the latter is
936  * highly unreliable and dynamic in virtualized environments, and does not
937  * consider boot time allocations. For example, memory ballooning adjusts the
938  * managed pages when inflating/deflating the balloon, and balloon page
939  * migration can even migrate inflated pages between zones.
940  *
941  * Using "present pages" is better but some things to keep in mind are:
942  *
943  * a) Some memblock allocations, such as for the crashkernel area, are
944  *    effectively unused by the kernel, yet they account to "present pages".
945  *    Fortunately, these allocations are comparatively small in relevant setups
946  *    (e.g., fraction of system memory).
947  * b) Some hotplugged memory blocks in virtualized environments, especially
948  *    hotplugged by virtio-mem, look like they are completely present, however,
949  *    only parts of the memory block are actually currently usable.
950  *    "present pages" is an upper limit that can get reached at runtime. As
951  *    we base our calculations on KERNEL_EARLY, this is not an issue.
952  */
953 static struct zone *auto_movable_zone_for_pfn(int nid,
954 					      struct memory_group *group,
955 					      unsigned long pfn,
956 					      unsigned long nr_pages)
957 {
958 	unsigned long online_pages = 0, max_pages, end_pfn;
959 	struct page *page;
960 
961 	if (!auto_movable_ratio)
962 		goto kernel_zone;
963 
964 	if (group && !group->is_dynamic) {
965 		max_pages = group->s.max_pages;
966 		online_pages = group->present_movable_pages;
967 
968 		/* If anything is !MOVABLE online the rest !MOVABLE. */
969 		if (group->present_kernel_pages)
970 			goto kernel_zone;
971 	} else if (!group || group->d.unit_pages == nr_pages) {
972 		max_pages = nr_pages;
973 	} else {
974 		max_pages = group->d.unit_pages;
975 		/*
976 		 * Take a look at all online sections in the current unit.
977 		 * We can safely assume that all pages within a section belong
978 		 * to the same zone, because dynamic memory groups only deal
979 		 * with hotplugged memory.
980 		 */
981 		pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
982 		end_pfn = pfn + group->d.unit_pages;
983 		for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
984 			page = pfn_to_online_page(pfn);
985 			if (!page)
986 				continue;
987 			/* If anything is !MOVABLE online the rest !MOVABLE. */
988 			if (!is_zone_movable_page(page))
989 				goto kernel_zone;
990 			online_pages += PAGES_PER_SECTION;
991 		}
992 	}
993 
994 	/*
995 	 * Online MOVABLE if we could *currently* online all remaining parts
996 	 * MOVABLE. We expect to (add+) online them immediately next, so if
997 	 * nobody interferes, all will be MOVABLE if possible.
998 	 */
999 	nr_pages = max_pages - online_pages;
1000 	if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
1001 		goto kernel_zone;
1002 
1003 #ifdef CONFIG_NUMA
1004 	if (auto_movable_numa_aware &&
1005 	    !auto_movable_can_online_movable(nid, group, nr_pages))
1006 		goto kernel_zone;
1007 #endif /* CONFIG_NUMA */
1008 
1009 	return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1010 kernel_zone:
1011 	return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
1012 }
1013 
1014 static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
1015 		unsigned long nr_pages)
1016 {
1017 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
1018 			nr_pages);
1019 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1020 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
1021 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
1022 
1023 	/*
1024 	 * We inherit the existing zone in a simple case where zones do not
1025 	 * overlap in the given range
1026 	 */
1027 	if (in_kernel ^ in_movable)
1028 		return (in_kernel) ? kernel_zone : movable_zone;
1029 
1030 	/*
1031 	 * If the range doesn't belong to any zone or two zones overlap in the
1032 	 * given range then we use movable zone only if movable_node is
1033 	 * enabled because we always online to a kernel zone by default.
1034 	 */
1035 	return movable_node_enabled ? movable_zone : kernel_zone;
1036 }
1037 
1038 struct zone *zone_for_pfn_range(enum mmop online_type, int nid,
1039 		struct memory_group *group, unsigned long start_pfn,
1040 		unsigned long nr_pages)
1041 {
1042 	if (online_type == MMOP_ONLINE_KERNEL)
1043 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
1044 
1045 	if (online_type == MMOP_ONLINE_MOVABLE)
1046 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1047 
1048 	if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
1049 		return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
1050 
1051 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
1052 }
1053 
1054 /*
1055  * This function should only be called by memory_block_{online,offline},
1056  * and {online,offline}_pages.
1057  */
1058 void adjust_present_page_count(struct page *page, struct memory_group *group,
1059 			       long nr_pages)
1060 {
1061 	struct zone *zone = page_zone(page);
1062 	const bool movable = zone_idx(zone) == ZONE_MOVABLE;
1063 
1064 	/*
1065 	 * We only support onlining/offlining/adding/removing of complete
1066 	 * memory blocks; therefore, either all is either early or hotplugged.
1067 	 */
1068 	if (early_section(__pfn_to_section(page_to_pfn(page))))
1069 		zone->present_early_pages += nr_pages;
1070 	zone->present_pages += nr_pages;
1071 	zone->pages_with_online_memmap += nr_pages;
1072 	zone->zone_pgdat->node_present_pages += nr_pages;
1073 
1074 	if (group && movable)
1075 		group->present_movable_pages += nr_pages;
1076 	else if (group && !movable)
1077 		group->present_kernel_pages += nr_pages;
1078 }
1079 
1080 int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
1081 			      struct zone *zone)
1082 {
1083 	unsigned long end_pfn = pfn + nr_pages;
1084 	int ret, i;
1085 
1086 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1087 	if (ret)
1088 		return ret;
1089 
1090 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE,
1091 			       false);
1092 
1093 	for (i = 0; i < nr_pages; i++) {
1094 		struct page *page = pfn_to_page(pfn + i);
1095 
1096 		__ClearPageOffline(page);
1097 		SetPageVmemmapSelfHosted(page);
1098 	}
1099 
1100 	/*
1101 	 * It might be that the vmemmap_pages fully span sections. If that is
1102 	 * the case, mark those sections online here as otherwise they will be
1103 	 * left offline.
1104 	 */
1105 	if (nr_pages >= PAGES_PER_SECTION)
1106 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1107 
1108 	return ret;
1109 }
1110 
1111 void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
1112 {
1113 	unsigned long end_pfn = pfn + nr_pages;
1114 
1115 	/*
1116 	 * It might be that the vmemmap_pages fully span sections. If that is
1117 	 * the case, mark those sections offline here as otherwise they will be
1118 	 * left online.
1119 	 */
1120 	if (nr_pages >= PAGES_PER_SECTION)
1121 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1122 
1123         /*
1124 	 * The pages associated with this vmemmap have been offlined, so
1125 	 * we can reset its state here.
1126 	 */
1127 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
1128 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1129 }
1130 
1131 /*
1132  * Must be called with mem_hotplug_lock in write mode.
1133  */
1134 int online_pages(unsigned long pfn, unsigned long nr_pages,
1135 		       struct zone *zone, struct memory_group *group)
1136 {
1137 	struct memory_notify mem_arg = {
1138 		.start_pfn = pfn,
1139 		.nr_pages = nr_pages,
1140 	};
1141 	struct node_notify node_arg = {
1142 		.nid = NUMA_NO_NODE,
1143 	};
1144 	const int nid = zone_to_nid(zone);
1145 	int need_zonelists_rebuild = 0;
1146 	unsigned long flags;
1147 	int ret;
1148 
1149 	/*
1150 	 * {on,off}lining is constrained to full memory sections (or more
1151 	 * precisely to memory blocks from the user space POV).
1152 	 * memmap_on_memory is an exception because it reserves initial part
1153 	 * of the physical memory space for vmemmaps. That space is pageblock
1154 	 * aligned.
1155 	 */
1156 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
1157 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
1158 		return -EINVAL;
1159 
1160 
1161 	/* associate pfn range with the zone */
1162 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_MOVABLE,
1163 			       true);
1164 
1165 	if (!node_state(nid, N_MEMORY)) {
1166 		/* Adding memory to the node for the first time */
1167 		node_arg.nid = nid;
1168 		ret = node_notify(NODE_ADDING_FIRST_MEMORY, &node_arg);
1169 		ret = notifier_to_errno(ret);
1170 		if (ret)
1171 			goto failed_addition;
1172 	}
1173 
1174 	ret = memory_notify(MEM_GOING_ONLINE, &mem_arg);
1175 	ret = notifier_to_errno(ret);
1176 	if (ret)
1177 		goto failed_addition;
1178 
1179 	/*
1180 	 * Fixup the number of isolated pageblocks before marking the sections
1181 	 * onlining, such that undo_isolate_page_range() works correctly.
1182 	 */
1183 	spin_lock_irqsave(&zone->lock, flags);
1184 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
1185 	spin_unlock_irqrestore(&zone->lock, flags);
1186 
1187 	/*
1188 	 * If this zone is not populated, then it is not in zonelist.
1189 	 * This means the page allocator ignores this zone.
1190 	 * So, zonelist must be updated after online.
1191 	 */
1192 	if (!populated_zone(zone)) {
1193 		need_zonelists_rebuild = 1;
1194 		setup_zone_pageset(zone);
1195 	}
1196 
1197 	online_pages_range(pfn, nr_pages);
1198 	adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
1199 
1200 	if (node_arg.nid >= 0)
1201 		node_set_state(nid, N_MEMORY);
1202 	/*
1203 	 * Check whether we are adding normal memory to the node for the first
1204 	 * time.
1205 	 */
1206 	if (!node_state(nid, N_NORMAL_MEMORY) && zone_idx(zone) <= ZONE_NORMAL)
1207 		node_set_state(nid, N_NORMAL_MEMORY);
1208 
1209 	if (need_zonelists_rebuild)
1210 		build_all_zonelists(NULL);
1211 
1212 	/* Basic onlining is complete, allow allocation of onlined pages. */
1213 	undo_isolate_page_range(pfn, pfn + nr_pages);
1214 
1215 	/*
1216 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
1217 	 * the tail of the freelist when undoing isolation). Shuffle the whole
1218 	 * zone to make sure the just onlined pages are properly distributed
1219 	 * across the whole freelist - to create an initial shuffle.
1220 	 */
1221 	shuffle_zone(zone);
1222 
1223 	/* reinitialise watermarks and update pcp limits */
1224 	init_per_zone_wmark_min();
1225 
1226 	kswapd_run(nid);
1227 	kcompactd_run(nid);
1228 
1229 	if (node_arg.nid >= 0)
1230 		/* First memory added successfully. Notify consumers. */
1231 		node_notify(NODE_ADDED_FIRST_MEMORY, &node_arg);
1232 
1233 	writeback_set_ratelimit();
1234 
1235 	memory_notify(MEM_ONLINE, &mem_arg);
1236 	return 0;
1237 
1238 failed_addition:
1239 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1240 		 (unsigned long long) pfn << PAGE_SHIFT,
1241 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1242 	memory_notify(MEM_CANCEL_ONLINE, &mem_arg);
1243 	if (node_arg.nid != NUMA_NO_NODE)
1244 		node_notify(NODE_CANCEL_ADDING_FIRST_MEMORY, &node_arg);
1245 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
1246 	return ret;
1247 }
1248 
1249 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
1250 static pg_data_t *hotadd_init_pgdat(int nid)
1251 {
1252 	struct pglist_data *pgdat;
1253 
1254 	/*
1255 	 * NODE_DATA is preallocated (free_area_init) but its internal
1256 	 * state is not allocated completely. Add missing pieces.
1257 	 * Completely offline nodes stay around and they just need
1258 	 * reinitialization.
1259 	 */
1260 	pgdat = NODE_DATA(nid);
1261 
1262 	/* init node's zones as empty zones, we don't have any present pages.*/
1263 	if (free_area_init_core_hotplug(pgdat))
1264 		return NULL;
1265 
1266 	/*
1267 	 * The node we allocated has no zone fallback lists. For avoiding
1268 	 * to access not-initialized zonelist, build here.
1269 	 */
1270 	build_all_zonelists(pgdat);
1271 
1272 	return pgdat;
1273 }
1274 
1275 /*
1276  * __try_online_node - online a node if offlined
1277  * @nid: the node ID
1278  * @set_node_online: Whether we want to online the node
1279  * called by cpu_up() to online a node without onlined memory.
1280  *
1281  * Returns:
1282  * 1 -> a new node has been allocated
1283  * 0 -> the node is already online
1284  * -ENOMEM -> the node could not be allocated
1285  */
1286 static int __try_online_node(int nid, bool set_node_online)
1287 {
1288 	pg_data_t *pgdat;
1289 	int ret = 1;
1290 
1291 	if (node_online(nid))
1292 		return 0;
1293 
1294 	pgdat = hotadd_init_pgdat(nid);
1295 	if (!pgdat) {
1296 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1297 		ret = -ENOMEM;
1298 		goto out;
1299 	}
1300 
1301 	if (set_node_online) {
1302 		node_set_online(nid);
1303 		ret = register_node(nid);
1304 		BUG_ON(ret);
1305 	}
1306 out:
1307 	return ret;
1308 }
1309 
1310 /*
1311  * Users of this function always want to online/register the node
1312  */
1313 int try_online_node(int nid)
1314 {
1315 	int ret;
1316 
1317 	mem_hotplug_begin();
1318 	ret =  __try_online_node(nid, true);
1319 	mem_hotplug_done();
1320 	return ret;
1321 }
1322 
1323 static int check_hotplug_memory_range(u64 start, u64 size)
1324 {
1325 	/* memory range must be block size aligned */
1326 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1327 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1328 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1329 		       memory_block_size_bytes(), start, size);
1330 		return -EINVAL;
1331 	}
1332 
1333 	return 0;
1334 }
1335 
1336 static int online_memory_block(struct memory_block *mem, void *arg)
1337 {
1338 	enum mmop *online_type = arg;
1339 
1340 	mem->online_type = *online_type;
1341 	return device_online(&mem->dev);
1342 }
1343 
1344 #ifndef arch_supports_memmap_on_memory
1345 static inline bool arch_supports_memmap_on_memory(unsigned long vmemmap_size)
1346 {
1347 	/*
1348 	 * As default, we want the vmemmap to span a complete PMD such that we
1349 	 * can map the vmemmap using a single PMD if supported by the
1350 	 * architecture.
1351 	 */
1352 	return IS_ALIGNED(vmemmap_size, PMD_SIZE);
1353 }
1354 #endif
1355 
1356 bool mhp_supports_memmap_on_memory(void)
1357 {
1358 	unsigned long vmemmap_size = memory_block_memmap_size();
1359 	unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
1360 
1361 	/*
1362 	 * Besides having arch support and the feature enabled at runtime, we
1363 	 * need a few more assumptions to hold true:
1364 	 *
1365 	 * a) The vmemmap pages span complete PMDs: We don't want vmemmap code
1366 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1367 	 *    other memory blocks)
1368 	 *
1369 	 * b) The vmemmap pages (and thereby the pages that will be exposed to
1370 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1371 	 *    code requires applicable ranges to be page-aligned, for example, to
1372 	 *    set the migratetypes properly.
1373 	 *
1374 	 * TODO: Although we have a check here to make sure that vmemmap pages
1375 	 *       fully populate a PMD, it is not the right place to check for
1376 	 *       this. A much better solution involves improving vmemmap code
1377 	 *       to fallback to base pages when trying to populate vmemmap using
1378 	 *       altmap as an alternative source of memory, and we do not exactly
1379 	 *       populate a single PMD.
1380 	 */
1381 	if (!mhp_memmap_on_memory())
1382 		return false;
1383 
1384 	/*
1385 	 * Make sure the vmemmap allocation is fully contained
1386 	 * so that we always allocate vmemmap memory from altmap area.
1387 	 */
1388 	if (!IS_ALIGNED(vmemmap_size, PAGE_SIZE))
1389 		return false;
1390 
1391 	/*
1392 	 * start pfn should be pageblock_nr_pages aligned for correctly
1393 	 * setting migrate types
1394 	 */
1395 	if (!pageblock_aligned(memmap_pages))
1396 		return false;
1397 
1398 	if (memmap_pages == PHYS_PFN(memory_block_size_bytes()))
1399 		/* No effective hotplugged memory doesn't make sense. */
1400 		return false;
1401 
1402 	return arch_supports_memmap_on_memory(vmemmap_size);
1403 }
1404 EXPORT_SYMBOL_GPL(mhp_supports_memmap_on_memory);
1405 
1406 static void altmap_free(struct vmem_altmap *altmap)
1407 {
1408 	WARN_ONCE(altmap->alloc, "Altmap not fully unmapped");
1409 	kfree(altmap);
1410 }
1411 
1412 static void remove_memory_blocks_and_altmaps(u64 start, u64 size)
1413 {
1414 	unsigned long memblock_size = memory_block_size_bytes();
1415 	u64 cur_start;
1416 
1417 	/*
1418 	 * For memmap_on_memory, the altmaps were added on a per-memblock
1419 	 * basis; we have to process each individual memory block.
1420 	 */
1421 	for (cur_start = start; cur_start < start + size;
1422 	     cur_start += memblock_size) {
1423 		struct vmem_altmap *altmap = NULL;
1424 		struct memory_block *mem;
1425 
1426 		mem = memory_block_get(phys_to_block_id(cur_start));
1427 		if (WARN_ON_ONCE(!mem))
1428 			continue;
1429 
1430 		altmap = mem->altmap;
1431 		mem->altmap = NULL;
1432 		memory_block_put(mem);
1433 
1434 		remove_memory_block_devices(cur_start, memblock_size);
1435 		arch_remove_memory(cur_start, memblock_size, altmap, NULL);
1436 		altmap_free(altmap);
1437 	}
1438 }
1439 
1440 static int create_altmaps_and_memory_blocks(int nid, struct memory_group *group,
1441 					    u64 start, u64 size)
1442 {
1443 	unsigned long memblock_size = memory_block_size_bytes();
1444 	u64 cur_start;
1445 	int ret;
1446 
1447 	for (cur_start = start; cur_start < start + size;
1448 	     cur_start += memblock_size) {
1449 		struct mhp_params params = { .pgprot =
1450 						     pgprot_mhp(PAGE_KERNEL) };
1451 		struct vmem_altmap mhp_altmap = {
1452 			.base_pfn = PHYS_PFN(cur_start),
1453 			.end_pfn = PHYS_PFN(cur_start + memblock_size - 1),
1454 		};
1455 
1456 		mhp_altmap.free = memory_block_memmap_on_memory_pages();
1457 		params.altmap = kmemdup(&mhp_altmap, sizeof(struct vmem_altmap),
1458 					GFP_KERNEL);
1459 		if (!params.altmap) {
1460 			ret = -ENOMEM;
1461 			goto out;
1462 		}
1463 
1464 		/* call arch's memory hotadd */
1465 		ret = arch_add_memory(nid, cur_start, memblock_size, &params);
1466 		if (ret < 0) {
1467 			altmap_free(params.altmap);
1468 			goto out;
1469 		}
1470 
1471 		/* create memory block devices after memory was added */
1472 		ret = create_memory_block_devices(cur_start, memblock_size, nid,
1473 						  params.altmap, group);
1474 		if (ret) {
1475 			arch_remove_memory(cur_start, memblock_size, params.altmap, NULL);
1476 			altmap_free(params.altmap);
1477 			goto out;
1478 		}
1479 	}
1480 
1481 	return 0;
1482 out:
1483 	if (ret && cur_start != start)
1484 		remove_memory_blocks_and_altmaps(start, cur_start - start);
1485 	return ret;
1486 }
1487 
1488 /*
1489  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1490  * and online/offline operations (triggered e.g. by sysfs).
1491  *
1492  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
1493  */
1494 static int __add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags,
1495 				 enum mmop online_type)
1496 {
1497 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
1498 	enum memblock_flags memblock_flags = MEMBLOCK_NONE;
1499 	struct memory_group *group = NULL;
1500 	u64 start, size;
1501 	bool new_node = false;
1502 	int ret;
1503 
1504 	start = res->start;
1505 	size = resource_size(res);
1506 
1507 	ret = check_hotplug_memory_range(start, size);
1508 	if (ret)
1509 		return ret;
1510 
1511 	if (mhp_flags & MHP_NID_IS_MGID) {
1512 		group = memory_group_find_by_id(nid);
1513 		if (!group)
1514 			return -EINVAL;
1515 		nid = group->nid;
1516 	}
1517 
1518 	if (!node_possible(nid)) {
1519 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1520 		return -EINVAL;
1521 	}
1522 
1523 	mem_hotplug_begin();
1524 
1525 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
1526 		if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
1527 			memblock_flags = MEMBLOCK_DRIVER_MANAGED;
1528 		ret = memblock_add_node(start, size, nid, memblock_flags);
1529 		if (ret)
1530 			goto error_mem_hotplug_end;
1531 	}
1532 
1533 	ret = __try_online_node(nid, false);
1534 	if (ret < 0)
1535 		goto error_memblock_remove;
1536 	if (ret) {
1537 		node_set_online(nid);
1538 		ret = register_node(nid);
1539 		if (WARN_ON(ret)) {
1540 			node_set_offline(nid);
1541 			goto error_memblock_remove;
1542 		}
1543 		new_node = true;
1544 	}
1545 
1546 	/*
1547 	 * Self hosted memmap array
1548 	 */
1549 	if ((mhp_flags & MHP_MEMMAP_ON_MEMORY) &&
1550 	    mhp_supports_memmap_on_memory()) {
1551 		ret = create_altmaps_and_memory_blocks(nid, group, start, size);
1552 		if (ret)
1553 			goto error;
1554 	} else {
1555 		ret = arch_add_memory(nid, start, size, &params);
1556 		if (ret < 0)
1557 			goto error;
1558 
1559 		/* create memory block devices after memory was added */
1560 		ret = create_memory_block_devices(start, size, nid, NULL, group);
1561 		if (ret) {
1562 			arch_remove_memory(start, size, params.altmap, NULL);
1563 			goto error;
1564 		}
1565 	}
1566 
1567 	register_memory_blocks_under_node_hotplug(nid, PFN_DOWN(start),
1568 					  PFN_UP(start + size - 1));
1569 
1570 	/* create new memmap entry */
1571 	if (!strcmp(res->name, "System RAM"))
1572 		firmware_map_add_hotplug(start, start + size, "System RAM");
1573 
1574 	/* device_online() will take the lock when calling online_pages() */
1575 	mem_hotplug_done();
1576 
1577 	/*
1578 	 * In case we're allowed to merge the resource, flag it and trigger
1579 	 * merging now that adding succeeded.
1580 	 */
1581 	if (mhp_flags & MHP_MERGE_RESOURCE)
1582 		merge_system_ram_resource(res);
1583 
1584 	/* online pages if requested */
1585 	if (online_type != MMOP_OFFLINE)
1586 		walk_memory_blocks(start, size, &online_type,
1587 				   online_memory_block);
1588 
1589 	return ret;
1590 error:
1591 	if (new_node) {
1592 		node_set_offline(nid);
1593 		unregister_node(nid);
1594 	}
1595 error_memblock_remove:
1596 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
1597 		memblock_remove(start, size);
1598 error_mem_hotplug_end:
1599 	mem_hotplug_done();
1600 	return ret;
1601 }
1602 
1603 int add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1604 {
1605 	return __add_memory_resource(nid, res, mhp_flags,
1606 				     mhp_get_default_online_type());
1607 }
1608 
1609 /* requires device_hotplug_lock, see __add_memory_resource() */
1610 int __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
1611 {
1612 	struct resource *res;
1613 	int ret;
1614 
1615 	res = register_memory_resource(start, size, "System RAM");
1616 	if (IS_ERR(res))
1617 		return PTR_ERR(res);
1618 
1619 	ret = add_memory_resource(nid, res, mhp_flags);
1620 	if (ret < 0)
1621 		release_memory_resource(res);
1622 	return ret;
1623 }
1624 
1625 int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
1626 {
1627 	int rc;
1628 
1629 	lock_device_hotplug();
1630 	rc = __add_memory(nid, start, size, mhp_flags);
1631 	unlock_device_hotplug();
1632 
1633 	return rc;
1634 }
1635 EXPORT_SYMBOL_GPL(add_memory);
1636 
1637 /**
1638  * __add_memory_driver_managed - add driver-managed memory with explicit online_type
1639  * @nid: NUMA node ID where the memory will be added
1640  * @start: Start physical address of the memory range
1641  * @size: Size of the memory range in bytes
1642  * @resource_name: Resource name in format "System RAM ($DRIVER)"
1643  * @mhp_flags: Memory hotplug flags
1644  * @online_type: Auto-Online behavior (offline, online, kernel, movable)
1645  *
1646  * Add special, driver-managed memory to the system as system RAM. Such
1647  * memory is not exposed via the raw firmware-provided memmap as system
1648  * RAM, instead, it is detected and added by a driver - during cold boot,
1649  * after a reboot, and after kexec.
1650  *
1651  * Reasons why this memory should not be used for the initial memmap of a
1652  * kexec kernel or for placing kexec images:
1653  *
1654  * - The booting kernel is in charge of determining how this memory will be
1655  *   used (e.g., use persistent memory as system RAM)
1656  * - Coordination with a hypervisor is required before this memory
1657  *   can be used (e.g., inaccessible parts).
1658  *
1659  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
1660  * memory map") are created. Also, the created memory resource is flagged
1661  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
1662  * this memory as well (esp., not place kexec images onto it).
1663  *
1664  * The resource_name (visible via /proc/iomem) has to have the format
1665  * "System RAM ($DRIVER)".
1666  *
1667  * Return: 0 on success, negative error code on failure.
1668  */
1669 int __add_memory_driver_managed(int nid, u64 start, u64 size,
1670 		const char *resource_name, mhp_t mhp_flags,
1671 		enum mmop online_type)
1672 {
1673 	struct resource *res;
1674 	int rc;
1675 
1676 	if (!resource_name ||
1677 	    strstr(resource_name, "System RAM (") != resource_name ||
1678 	    resource_name[strlen(resource_name) - 1] != ')')
1679 		return -EINVAL;
1680 
1681 	if (online_type < MMOP_OFFLINE || online_type > MMOP_ONLINE_MOVABLE)
1682 		return -EINVAL;
1683 
1684 	lock_device_hotplug();
1685 
1686 	res = register_memory_resource(start, size, resource_name);
1687 	if (IS_ERR(res)) {
1688 		rc = PTR_ERR(res);
1689 		goto out_unlock;
1690 	}
1691 
1692 	rc = __add_memory_resource(nid, res, mhp_flags, online_type);
1693 	if (rc < 0)
1694 		release_memory_resource(res);
1695 
1696 out_unlock:
1697 	unlock_device_hotplug();
1698 	return rc;
1699 }
1700 EXPORT_SYMBOL_FOR_MODULES(__add_memory_driver_managed, "kmem");
1701 
1702 /**
1703  * add_memory_driver_managed - add driver-managed memory
1704  * @nid: NUMA node ID where the memory will be added
1705  * @start: Start physical address of the memory range
1706  * @size: Size of the memory range in bytes
1707  * @resource_name: Resource name in format "System RAM ($DRIVER)"
1708  * @mhp_flags: Memory hotplug flags
1709  *
1710  * Add driver-managed memory with the system default online type set by
1711  * build config or kernel boot parameter.
1712  *
1713  * See __add_memory_driver_managed for more details.
1714  *
1715  * Return: 0 on success, negative error code on failure.
1716  */
1717 int add_memory_driver_managed(int nid, u64 start, u64 size,
1718 			      const char *resource_name, mhp_t mhp_flags)
1719 {
1720 	return __add_memory_driver_managed(nid, start, size, resource_name,
1721 			mhp_flags,
1722 			mhp_get_default_online_type());
1723 }
1724 EXPORT_SYMBOL_GPL(add_memory_driver_managed);
1725 
1726 /*
1727  * Platforms should define arch_get_mappable_range() that provides
1728  * maximum possible addressable physical memory range for which the
1729  * linear mapping could be created. The platform returned address
1730  * range must adhere to these following semantics.
1731  *
1732  * - range.start <= range.end
1733  * - Range includes both end points [range.start..range.end]
1734  *
1735  * There is also a fallback definition provided here, allowing the
1736  * entire possible physical address range in case any platform does
1737  * not define arch_get_mappable_range().
1738  */
1739 struct range __weak arch_get_mappable_range(void)
1740 {
1741 	struct range mhp_range = {
1742 		.start = 0UL,
1743 		.end = -1ULL,
1744 	};
1745 	return mhp_range;
1746 }
1747 
1748 struct range mhp_get_pluggable_range(bool need_mapping)
1749 {
1750 	const u64 max_phys = DIRECT_MAP_PHYSMEM_END;
1751 	struct range mhp_range;
1752 
1753 	if (need_mapping) {
1754 		mhp_range = arch_get_mappable_range();
1755 		if (mhp_range.start > max_phys) {
1756 			mhp_range.start = 0;
1757 			mhp_range.end = 0;
1758 		}
1759 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1760 	} else {
1761 		mhp_range.start = 0;
1762 		mhp_range.end = max_phys;
1763 	}
1764 	return mhp_range;
1765 }
1766 EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1767 
1768 bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1769 {
1770 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1771 	u64 end = start + size;
1772 
1773 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1774 		return true;
1775 
1776 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1777 		start, end, mhp_range.start, mhp_range.end);
1778 	return false;
1779 }
1780 
1781 #ifdef CONFIG_MEMORY_HOTREMOVE
1782 
1783 static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
1784 {
1785 	int nid = *(int *)arg;
1786 
1787 	/*
1788 	 * If a memory block belongs to multiple nodes, the stored nid is not
1789 	 * reliable. However, such blocks are always online (e.g., cannot get
1790 	 * offlined) and, therefore, are still spanned by the node.
1791 	 */
1792 	return mem->nid == nid ? -EEXIST : 0;
1793 }
1794 
1795 /* Caller must hold the memory hotplug lock for this check. */
1796 static bool node_is_memoryless(int nid)
1797 {
1798 	/*
1799 	 * A node still spanning pages (especially ZONE_DEVICE) is not
1800 	 * memoryless.  A node spans memory after move_pfn_range_to_zone(),
1801 	 * e.g. once a memory block has been onlined.
1802 	 */
1803 	if (node_spanned_pages(nid))
1804 		return false;
1805 	/*
1806 	 * Offline memory blocks may not be spanned by the node yet, but they
1807 	 * link to it in sysfs and can be onlined later, so the node is not
1808 	 * memoryless while any remain.
1809 	 */
1810 	return !for_each_memory_block(&nid, check_no_memblock_for_node_cb);
1811 }
1812 
1813 /*
1814  * Scan pfn range [start,end) to find movable/migratable pages (LRU and
1815  * hugetlb folio, movable_ops pages). Will skip over most unmovable
1816  * pages (esp., pages that can be skipped when offlining), but bail out on
1817  * definitely unmovable pages.
1818  *
1819  * Returns:
1820  *	0 in case a movable page is found and movable_pfn was updated.
1821  *	-ENOENT in case no movable page was found.
1822  *	-EBUSY in case a definitely unmovable page was found.
1823  */
1824 static int scan_movable_pages(unsigned long start, unsigned long end,
1825 			      unsigned long *movable_pfn)
1826 {
1827 	unsigned long pfn;
1828 
1829 	for (pfn = start; pfn < end; pfn++) {
1830 		unsigned long nr_pages;
1831 		struct page *page;
1832 		struct folio *folio;
1833 
1834 		page = pfn_to_page(pfn);
1835 		if (PageLRU(page) || page_has_movable_ops(page))
1836 			goto found;
1837 
1838 		/*
1839 		 * PageOffline() pages that do not have movable_ops and
1840 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1841 		 * definitely unmovable. If their reference count would be 0,
1842 		 * they could at least be skipped when offlining memory.
1843 		 */
1844 		if (PageOffline(page) && page_count(page))
1845 			return -EBUSY;
1846 
1847 		/*
1848 		 * A page that was allocated, but was not a slab page yet, when
1849 		 * its pageblock was isolated.
1850 		 */
1851 		if (PageSlab(page))
1852 			return -EBUSY;
1853 
1854 		folio = page_folio(page);
1855 		if (!folio_test_hugetlb(folio))
1856 			continue;
1857 		/*
1858 		 * This test is racy as we hold no reference or lock.  The
1859 		 * hugetlb page could have been free'ed and head is no longer
1860 		 * a hugetlb page before the following check.  In such unlikely
1861 		 * cases false positives and negatives are possible.  Calling
1862 		 * code must deal with these scenarios.
1863 		 */
1864 		if (folio_test_hugetlb_migratable(folio))
1865 			goto found;
1866 		nr_pages = folio_nr_pages(folio);
1867 		if (unlikely(nr_pages < 1 || nr_pages > MAX_FOLIO_NR_PAGES ||
1868 			     !is_power_of_2(nr_pages)))
1869 			continue;
1870 		pfn |= nr_pages - 1;
1871 	}
1872 	return -ENOENT;
1873 found:
1874 	*movable_pfn = pfn;
1875 	return 0;
1876 }
1877 
1878 static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
1879 {
1880 	struct folio *folio;
1881 	unsigned long pfn;
1882 	LIST_HEAD(source);
1883 	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
1884 				      DEFAULT_RATELIMIT_BURST);
1885 
1886 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1887 		struct page *page;
1888 
1889 		page = pfn_to_page(pfn);
1890 		folio = page_folio(page);
1891 
1892 		if (!folio_try_get(folio))
1893 			continue;
1894 
1895 		if (unlikely(page_folio(page) != folio))
1896 			goto put_folio;
1897 
1898 		if (folio_test_large(folio))
1899 			pfn = folio_pfn(folio) + folio_nr_pages(folio) - 1;
1900 
1901 		if (folio_contain_hwpoisoned_page(folio)) {
1902 			/*
1903 			 * unmap_poisoned_folio() cannot handle large folios
1904 			 * in all cases yet.
1905 			 */
1906 			if (folio_test_large(folio) && !folio_test_hugetlb(folio))
1907 				goto put_folio;
1908 			if (folio_test_lru(folio) && !folio_isolate_lru(folio))
1909 				goto put_folio;
1910 			if (folio_mapped(folio)) {
1911 				folio_lock(folio);
1912 				unmap_poisoned_folio(folio, pfn, false);
1913 				folio_unlock(folio);
1914 			}
1915 
1916 			goto put_folio;
1917 		}
1918 
1919 		if (!isolate_folio_to_list(folio, &source)) {
1920 			if (__ratelimit(&migrate_rs)) {
1921 				pr_warn("failed to isolate pfn %lx\n",
1922 					page_to_pfn(page));
1923 				dump_page(page, "isolation failed");
1924 			}
1925 		}
1926 put_folio:
1927 		folio_put(folio);
1928 	}
1929 	if (!list_empty(&source)) {
1930 		nodemask_t nmask = node_states[N_MEMORY];
1931 		struct migration_target_control mtc = {
1932 			.nmask = &nmask,
1933 			.gfp_mask = GFP_KERNEL | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1934 			.reason = MR_MEMORY_HOTPLUG,
1935 		};
1936 		int ret;
1937 
1938 		/*
1939 		 * We have checked that migration range is on a single zone so
1940 		 * we can use the nid of the first page to all the others.
1941 		 */
1942 		mtc.nid = folio_nid(list_first_entry(&source, struct folio, lru));
1943 
1944 		/*
1945 		 * try to allocate from a different node but reuse this node
1946 		 * if there are no other online nodes to be used (e.g. we are
1947 		 * offlining a part of the only existing node)
1948 		 */
1949 		node_clear(mtc.nid, nmask);
1950 		if (nodes_empty(nmask))
1951 			node_set(mtc.nid, nmask);
1952 		ret = migrate_pages(&source, alloc_migration_target, NULL,
1953 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
1954 		if (ret) {
1955 			list_for_each_entry(folio, &source, lru) {
1956 				if (__ratelimit(&migrate_rs)) {
1957 					pr_warn("migrating pfn %lx failed ret:%d\n",
1958 						folio_pfn(folio), ret);
1959 					dump_page(&folio->page,
1960 						  "migration failure");
1961 				}
1962 			}
1963 			putback_movable_pages(&source);
1964 		}
1965 	}
1966 }
1967 
1968 static int __init cmdline_parse_movable_node(char *p)
1969 {
1970 	movable_node_enabled = true;
1971 	return 0;
1972 }
1973 early_param("movable_node", cmdline_parse_movable_node);
1974 
1975 static int count_system_ram_pages_cb(unsigned long start_pfn,
1976 				     unsigned long nr_pages, void *data)
1977 {
1978 	unsigned long *nr_system_ram_pages = data;
1979 
1980 	*nr_system_ram_pages += nr_pages;
1981 	return 0;
1982 }
1983 
1984 /*
1985  * Must be called with mem_hotplug_lock in write mode.
1986  */
1987 int offline_pages(unsigned long start_pfn, unsigned long nr_pages,
1988 			struct zone *zone, struct memory_group *group)
1989 {
1990 	unsigned long pfn, managed_pages, system_ram_pages = 0;
1991 	const unsigned long end_pfn = start_pfn + nr_pages;
1992 	struct pglist_data *pgdat = zone->zone_pgdat;
1993 	const int node = zone_to_nid(zone);
1994 	struct memory_notify mem_arg = {
1995 		.start_pfn = start_pfn,
1996 		.nr_pages = nr_pages,
1997 	};
1998 	struct node_notify node_arg = {
1999 		.nid = NUMA_NO_NODE,
2000 	};
2001 	unsigned long flags;
2002 	char *reason;
2003 	int ret;
2004 	unsigned long normal_pages = 0;
2005 	enum zone_type zt;
2006 
2007 	/*
2008 	 * {on,off}lining is constrained to full memory sections (or more
2009 	 * precisely to memory blocks from the user space POV).
2010 	 * memmap_on_memory is an exception because it reserves initial part
2011 	 * of the physical memory space for vmemmaps. That space is pageblock
2012 	 * aligned.
2013 	 */
2014 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
2015 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
2016 		return -EINVAL;
2017 
2018 	/*
2019 	 * Don't allow to offline memory blocks that contain holes.
2020 	 * Consequently, memory blocks with holes can never get onlined
2021 	 * via the hotplug path - online_pages() - as hotplugged memory has
2022 	 * no holes. This way, we don't have to worry about memory holes,
2023 	 * don't need pfn_valid() checks, and can avoid using
2024 	 * walk_system_ram_range() later.
2025 	 */
2026 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
2027 			      count_system_ram_pages_cb);
2028 	if (system_ram_pages != nr_pages) {
2029 		ret = -EINVAL;
2030 		reason = "memory holes";
2031 		goto failed_removal;
2032 	}
2033 
2034 	/*
2035 	 * We only support offlining of memory blocks managed by a single zone,
2036 	 * checked by calling code. This is just a sanity check that we might
2037 	 * want to remove in the future.
2038 	 */
2039 	if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
2040 			 page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
2041 		ret = -EINVAL;
2042 		reason = "multizone range";
2043 		goto failed_removal;
2044 	}
2045 
2046 	/*
2047 	 * Disable pcplists so that page isolation cannot race with freeing
2048 	 * in a way that pages from isolated pageblock are left on pcplists.
2049 	 */
2050 	zone_pcp_disable(zone);
2051 	lru_cache_disable();
2052 
2053 	/* set above range as isolated */
2054 	ret = start_isolate_page_range(start_pfn, end_pfn,
2055 				       PB_ISOLATE_MODE_MEM_OFFLINE);
2056 	if (ret) {
2057 		reason = "failure to isolate range";
2058 		goto failed_removal_pcplists_disabled;
2059 	}
2060 
2061 	/*
2062 	 * Check whether the node will have no present pages after we offline
2063 	 * 'nr_pages' more. If so, we know that the node will become empty, and
2064 	 * so we will clear N_MEMORY for it.
2065 	 */
2066 	if (nr_pages >= pgdat->node_present_pages) {
2067 		node_arg.nid = node;
2068 		ret = node_notify(NODE_REMOVING_LAST_MEMORY, &node_arg);
2069 		ret = notifier_to_errno(ret);
2070 		if (ret) {
2071 			reason = "node notifier failure";
2072 			goto failed_removal_isolated;
2073 		}
2074 	}
2075 
2076 	ret = memory_notify(MEM_GOING_OFFLINE, &mem_arg);
2077 	ret = notifier_to_errno(ret);
2078 	if (ret) {
2079 		reason = "notifier failure";
2080 		goto failed_removal_isolated;
2081 	}
2082 
2083 	do {
2084 		pfn = start_pfn;
2085 		do {
2086 			/*
2087 			 * Historically we always checked for any signal and
2088 			 * can't limit it to fatal signals without eventually
2089 			 * breaking user space.
2090 			 */
2091 			if (signal_pending(current)) {
2092 				ret = -EINTR;
2093 				reason = "signal backoff";
2094 				goto failed_removal_isolated;
2095 			}
2096 
2097 			cond_resched();
2098 
2099 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
2100 			if (!ret) {
2101 				/*
2102 				 * TODO: fatal migration failures should bail
2103 				 * out
2104 				 */
2105 				do_migrate_range(pfn, end_pfn);
2106 			}
2107 		} while (!ret);
2108 
2109 		if (ret != -ENOENT) {
2110 			reason = "unmovable page";
2111 			goto failed_removal_isolated;
2112 		}
2113 
2114 		/*
2115 		 * Dissolve free hugetlb folios in the memory block before doing
2116 		 * offlining actually in order to make hugetlbfs's object
2117 		 * counting consistent.
2118 		 */
2119 		ret = dissolve_free_hugetlb_folios(start_pfn, end_pfn);
2120 		if (ret) {
2121 			reason = "failure to dissolve huge pages";
2122 			goto failed_removal_isolated;
2123 		}
2124 
2125 		ret = test_pages_isolated(start_pfn, end_pfn,
2126 					  PB_ISOLATE_MODE_MEM_OFFLINE);
2127 
2128 	} while (ret);
2129 
2130 	/* Mark all sections offline and remove free pages from the buddy. */
2131 	managed_pages = __offline_isolated_pages(start_pfn, end_pfn);
2132 	pr_debug("Offlined Pages %ld\n", nr_pages);
2133 
2134 	/*
2135 	 * The memory sections are marked offline, and the pageblock flags
2136 	 * effectively stale; nobody should be touching them. Fixup the number
2137 	 * of isolated pageblocks, memory onlining will properly revert this.
2138 	 */
2139 	spin_lock_irqsave(&zone->lock, flags);
2140 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
2141 	spin_unlock_irqrestore(&zone->lock, flags);
2142 
2143 	lru_cache_enable();
2144 	zone_pcp_enable(zone);
2145 
2146 	/* removal success */
2147 	adjust_managed_page_count(pfn_to_page(start_pfn), -managed_pages);
2148 	adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
2149 
2150 	/* reinitialise watermarks and update pcp limits */
2151 	init_per_zone_wmark_min();
2152 
2153 	/*
2154 	 * Check whether this operation removes the last normal memory from
2155 	 * the node. We do this before clearing N_MEMORY to avoid the possible
2156 	 * transient "!N_MEMORY && N_NORMAL_MEMORY" state.
2157 	 */
2158 	if (zone_idx(zone) <= ZONE_NORMAL) {
2159 		for (zt = 0; zt <= ZONE_NORMAL; zt++)
2160 			normal_pages += pgdat->node_zones[zt].present_pages;
2161 		if (!normal_pages)
2162 			node_clear_state(node, N_NORMAL_MEMORY);
2163 	}
2164 	/*
2165 	 * Make sure to mark the node as memory-less before rebuilding the zone
2166 	 * list. Otherwise this node would still appear in the fallback lists.
2167 	 */
2168 	if (node_arg.nid >= 0)
2169 		node_clear_state(node, N_MEMORY);
2170 	if (!populated_zone(zone)) {
2171 		zone_pcp_reset(zone);
2172 		build_all_zonelists(NULL);
2173 	}
2174 
2175 	if (node_arg.nid >= 0) {
2176 		kcompactd_stop(node);
2177 		kswapd_stop(node);
2178 		/* Node went memoryless. Notify consumers */
2179 		node_notify(NODE_REMOVED_LAST_MEMORY, &node_arg);
2180 	}
2181 
2182 	writeback_set_ratelimit();
2183 
2184 	memory_notify(MEM_OFFLINE, &mem_arg);
2185 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
2186 	return 0;
2187 
2188 failed_removal_isolated:
2189 	/* pushback to free area */
2190 	undo_isolate_page_range(start_pfn, end_pfn);
2191 	memory_notify(MEM_CANCEL_OFFLINE, &mem_arg);
2192 	if (node_arg.nid != NUMA_NO_NODE)
2193 		node_notify(NODE_CANCEL_REMOVING_LAST_MEMORY, &node_arg);
2194 failed_removal_pcplists_disabled:
2195 	lru_cache_enable();
2196 	zone_pcp_enable(zone);
2197 failed_removal:
2198 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
2199 		 (unsigned long long) start_pfn << PAGE_SHIFT,
2200 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
2201 		 reason);
2202 	return ret;
2203 }
2204 
2205 static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
2206 {
2207 	int *nid = arg;
2208 
2209 	*nid = mem->nid;
2210 	if (unlikely(mem->state != MEM_OFFLINE)) {
2211 		phys_addr_t beginpa, endpa;
2212 
2213 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
2214 		endpa = beginpa + memory_block_size_bytes() - 1;
2215 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
2216 			&beginpa, &endpa);
2217 
2218 		return -EBUSY;
2219 	}
2220 	return 0;
2221 }
2222 
2223 static int count_memory_range_altmaps_cb(struct memory_block *mem, void *arg)
2224 {
2225 	u64 *num_altmaps = (u64 *)arg;
2226 
2227 	if (mem->altmap)
2228 		*num_altmaps += 1;
2229 
2230 	return 0;
2231 }
2232 
2233 static int check_cpu_on_node(int nid)
2234 {
2235 	int cpu;
2236 
2237 	for_each_present_cpu(cpu) {
2238 		if (cpu_to_node(cpu) == nid)
2239 			/*
2240 			 * the cpu on this node isn't removed, and we can't
2241 			 * offline this node.
2242 			 */
2243 			return -EBUSY;
2244 	}
2245 
2246 	return 0;
2247 }
2248 
2249 /**
2250  * try_offline_node
2251  * @nid: the node ID
2252  *
2253  * Offline a node if all memory sections and cpus of the node are removed.
2254  *
2255  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2256  * and online/offline operations before this call.
2257  */
2258 void try_offline_node(int nid)
2259 {
2260 	if (!node_is_memoryless(nid))
2261 		return;
2262 
2263 	if (check_cpu_on_node(nid))
2264 		return;
2265 
2266 	/*
2267 	 * all memory/cpu of this node are removed, we can offline this
2268 	 * node now.
2269 	 */
2270 	node_set_offline(nid);
2271 	unregister_node(nid);
2272 }
2273 EXPORT_SYMBOL(try_offline_node);
2274 
2275 static int memory_blocks_have_altmaps(u64 start, u64 size)
2276 {
2277 	u64 num_memblocks = size / memory_block_size_bytes();
2278 	u64 num_altmaps = 0;
2279 
2280 	if (!mhp_memmap_on_memory())
2281 		return 0;
2282 
2283 	walk_memory_blocks(start, size, &num_altmaps,
2284 			   count_memory_range_altmaps_cb);
2285 
2286 	if (num_altmaps == 0)
2287 		return 0;
2288 
2289 	if (WARN_ON_ONCE(num_memblocks != num_altmaps))
2290 		return -EINVAL;
2291 
2292 	return 1;
2293 }
2294 
2295 static int try_remove_memory(u64 start, u64 size)
2296 {
2297 	int rc, nid = NUMA_NO_NODE;
2298 
2299 	BUG_ON(check_hotplug_memory_range(start, size));
2300 
2301 	/*
2302 	 * All memory blocks must be offlined before removing memory.  Check
2303 	 * whether all memory blocks in question are offline and return error
2304 	 * if this is not the case.
2305 	 *
2306 	 * While at it, determine the nid. Note that if we'd have mixed nodes,
2307 	 * we'd only try to offline the last determined one -- which is good
2308 	 * enough for the cases we care about.
2309 	 */
2310 	rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
2311 	if (rc)
2312 		return rc;
2313 
2314 	/* remove memmap entry */
2315 	firmware_map_remove(start, start + size, "System RAM");
2316 
2317 	mem_hotplug_begin();
2318 
2319 	rc = memory_blocks_have_altmaps(start, size);
2320 	if (rc < 0) {
2321 		mem_hotplug_done();
2322 		return rc;
2323 	} else if (!rc) {
2324 		/*
2325 		 * Memory block device removal under the device_hotplug_lock is
2326 		 * a barrier against racing online attempts.
2327 		 * No altmaps present, do the removal directly
2328 		 */
2329 		remove_memory_block_devices(start, size);
2330 		arch_remove_memory(start, size, NULL, NULL);
2331 	} else {
2332 		/* all memblocks in the range have altmaps */
2333 		remove_memory_blocks_and_altmaps(start, size);
2334 	}
2335 
2336 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
2337 		memblock_remove(start, size);
2338 
2339 	release_mem_region_adjustable(start, size);
2340 
2341 	if (nid != NUMA_NO_NODE)
2342 		try_offline_node(nid);
2343 
2344 	mem_hotplug_done();
2345 	return 0;
2346 }
2347 
2348 /**
2349  * __remove_memory - Remove memory if every memory block is offline
2350  * @start: physical address of the region to remove
2351  * @size: size of the region to remove
2352  *
2353  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2354  * and online/offline operations before this call, as required by
2355  * try_offline_node().
2356  */
2357 void __remove_memory(u64 start, u64 size)
2358 {
2359 
2360 	/*
2361 	 * trigger BUG() if some memory is not offlined prior to calling this
2362 	 * function
2363 	 */
2364 	if (try_remove_memory(start, size))
2365 		BUG();
2366 }
2367 
2368 /*
2369  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2370  * some memory is not offline
2371  */
2372 int remove_memory(u64 start, u64 size)
2373 {
2374 	int rc;
2375 
2376 	lock_device_hotplug();
2377 	rc = try_remove_memory(start, size);
2378 	unlock_device_hotplug();
2379 
2380 	return rc;
2381 }
2382 EXPORT_SYMBOL_GPL(remove_memory);
2383 
2384 static int try_offline_memory_block(struct memory_block *mem, void *arg)
2385 {
2386 	enum mmop online_type = MMOP_ONLINE_KERNEL;
2387 	uint8_t **online_types = arg;
2388 	struct page *page;
2389 	int rc;
2390 
2391 	/*
2392 	 * Sense the online_type via the zone of the memory block. Offlining
2393 	 * with multiple zones within one memory block will be rejected
2394 	 * by offlining code ... so we don't care about that.
2395 	 */
2396 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
2397 	if (page && page_zonenum(page) == ZONE_MOVABLE)
2398 		online_type = MMOP_ONLINE_MOVABLE;
2399 
2400 	rc = device_offline(&mem->dev);
2401 	/*
2402 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
2403 	 * so try_reonline_memory_block() can do the right thing.
2404 	 */
2405 	if (!rc)
2406 		**online_types = online_type;
2407 
2408 	(*online_types)++;
2409 	/* Ignore if already offline. */
2410 	return rc < 0 ? rc : 0;
2411 }
2412 
2413 static int try_reonline_memory_block(struct memory_block *mem, void *arg)
2414 {
2415 	uint8_t **online_types = arg;
2416 	int rc;
2417 
2418 	if (**online_types != MMOP_OFFLINE) {
2419 		mem->online_type = (enum mmop)**online_types;
2420 		rc = device_online(&mem->dev);
2421 		if (rc < 0)
2422 			pr_warn("%s: Failed to re-online memory: %d",
2423 				__func__, rc);
2424 	}
2425 
2426 	/* Continue processing all remaining memory blocks. */
2427 	(*online_types)++;
2428 	return 0;
2429 }
2430 
2431 /*
2432  * Try to offline and remove memory. Might take a long time to finish in case
2433  * memory is still in use. Primarily useful for memory devices that logically
2434  * unplugged all memory (so it's no longer in use) and want to offline + remove
2435  * that memory.
2436  */
2437 int offline_and_remove_memory(u64 start, u64 size)
2438 {
2439 	struct range range = {
2440 		.start = start,
2441 		.end = start + size - 1,
2442 	};
2443 
2444 	return offline_and_remove_memory_ranges(&range, 1);
2445 }
2446 EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2447 
2448 /**
2449  * offline_and_remove_memory_ranges - offline and remove multiple memory ranges
2450  * @ranges: array of physical address ranges to offline and remove
2451  * @nr_ranges: number of entries in @ranges
2452  *
2453  * Offline and remove several memory ranges as one operation, serialized
2454  * against other hotplug operations by a single lock_device_hotplug().
2455  *
2456  * This offlines all ranges before removing any of them.  If offlining any
2457  * range fails, the entire process is reverted and nothing is removed.
2458  * This provides a fully atomic semantic for unplugging an entire device.
2459  *
2460  * Each range must be memory-block aligned in start and size.
2461  *
2462  * Return: 0 on success, negative errno on failure (never positive).  On
2463  * failure no range has been removed.
2464  */
2465 int offline_and_remove_memory_ranges(const struct range *ranges,
2466 		unsigned int nr_ranges)
2467 {
2468 	unsigned long mb_count = 0;
2469 	uint8_t *online_types, *tmp;
2470 	unsigned int i;
2471 	int rc = 0;
2472 
2473 	if (!ranges || !nr_ranges)
2474 		return -EINVAL;
2475 
2476 	for (i = 0; i < nr_ranges; i++) {
2477 		const u64 start = ranges[i].start;
2478 		const u64 size = range_len(&ranges[i]);
2479 
2480 		if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
2481 		    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
2482 			return -EINVAL;
2483 		mb_count += size / memory_block_size_bytes();
2484 	}
2485 
2486 	/*
2487 	 * Remember the old online type of every memory block across all ranges,
2488 	 * so we can revert if offlining a later block fails.  All entries start
2489 	 * as MMOP_OFFLINE so blocks we never touched are skipped on rollback.
2490 	 */
2491 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
2492 				     GFP_KERNEL);
2493 	if (!online_types)
2494 		return -ENOMEM;
2495 	memset(online_types, MMOP_OFFLINE, mb_count);
2496 
2497 	lock_device_hotplug();
2498 
2499 	/*
2500 	 * Phase 1: offline every block in every range.  An already-offline
2501 	 * block folds to success, so out-of-band offlining never blocks unplug.
2502 	 */
2503 	tmp = online_types;
2504 	for (i = 0; i < nr_ranges; i++) {
2505 		rc = walk_memory_blocks(ranges[i].start, range_len(&ranges[i]),
2506 					&tmp, try_offline_memory_block);
2507 		if (rc)
2508 			break;
2509 	}
2510 
2511 	/* If any failure occurred at all, rollback any changes and bail */
2512 	if (rc) {
2513 		tmp = online_types;
2514 		for (i = 0; i < nr_ranges; i++)
2515 			walk_memory_blocks(ranges[i].start,
2516 					   range_len(&ranges[i]), &tmp,
2517 					   try_reonline_memory_block);
2518 		goto out_unlock;
2519 	}
2520 
2521 	/* Phase 2: Remove. This should never fail holding the hotplug lock */
2522 	for (i = 0; i < nr_ranges; i++)
2523 		WARN_ON_ONCE(try_remove_memory(ranges[i].start,
2524 					       range_len(&ranges[i])));
2525 
2526 out_unlock:
2527 	unlock_device_hotplug();
2528 
2529 	kfree(online_types);
2530 	return rc;
2531 }
2532 EXPORT_SYMBOL_GPL(offline_and_remove_memory_ranges);
2533 #endif /* CONFIG_MEMORY_HOTREMOVE */
2534