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