xref: /linux/mm/memory_hotplug.c (revision 334fbe734e687404f346eba7d5d96ed2b44d35ab)
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 
memory_block_memmap_size(void)53 static inline unsigned long memory_block_memmap_size(void)
54 {
55 	return PHYS_PFN(memory_block_size_bytes()) * sizeof(struct page);
56 }
57 
memory_block_memmap_on_memory_pages(void)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  */
set_memmap_mode(const char * val,const struct kernel_param * kp)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 
get_memmap_mode(char * buffer,const struct kernel_param * kp)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 
mhp_memmap_on_memory(void)121 static inline bool mhp_memmap_on_memory(void)
122 {
123 	return memmap_mode != MEMMAP_ON_MEMORY_DISABLE;
124 }
125 #else
mhp_memmap_on_memory(void)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 
set_online_policy(const char * val,const struct kernel_param * kp)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 
get_online_policy(char * buffer,const struct kernel_param * kp)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 
get_online_mems(void)211 void get_online_mems(void)
212 {
213 	percpu_down_read(&mem_hotplug_lock);
214 }
215 
put_online_mems(void)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;
mhp_get_default_online_type(void)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 
mhp_set_default_online_type(enum mmop online_type)243 void mhp_set_default_online_type(enum mmop online_type)
244 {
245 	mhp_default_online_type = online_type;
246 }
247 
setup_memhp_default_state(char * str)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 
mem_hotplug_begin(void)259 void mem_hotplug_begin(void)
260 {
261 	cpus_read_lock();
262 	percpu_down_write(&mem_hotplug_lock);
263 }
264 
mem_hotplug_done(void)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 */
register_memory_resource(u64 start,u64 size,const char * resource_name)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 
release_memory_resource(struct resource * res)311 static void release_memory_resource(struct resource *res)
312 {
313 	if (!res)
314 		return;
315 	release_resource(res);
316 	kfree(res);
317 }
318 
check_pfn_span(unsigned long pfn,unsigned long nr_pages)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  */
pfn_to_online_page(unsigned long pfn)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 
__add_pages(int nid,unsigned long pfn,unsigned long nr_pages,struct mhp_params * params)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) */
find_smallest_section_pfn(int nid,struct zone * zone,unsigned long start_pfn,unsigned long 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). */
find_biggest_section_pfn(int nid,struct zone * zone,unsigned long start_pfn,unsigned long 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 
shrink_zone_span(struct zone * zone,unsigned long start_pfn,unsigned long end_pfn)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 
update_pgdat_span(struct pglist_data * pgdat)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 
remove_pfn_range_from_zone(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)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  *
580  * Generic helper function to remove section mappings and sysfs entries
581  * for the section of the memory we are removing. Caller needs to make
582  * sure that pages are marked reserved and zones are adjust properly by
583  * calling offline_pages().
584  */
__remove_pages(unsigned long pfn,unsigned long nr_pages,struct vmem_altmap * altmap)585 void __remove_pages(unsigned long pfn, unsigned long nr_pages,
586 		    struct vmem_altmap *altmap)
587 {
588 	const unsigned long end_pfn = pfn + nr_pages;
589 	unsigned long cur_nr_pages;
590 
591 	if (check_pfn_span(pfn, nr_pages)) {
592 		WARN(1, "Misaligned %s start: %#lx end: %#lx\n", __func__, pfn, pfn + nr_pages - 1);
593 		return;
594 	}
595 
596 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
597 		cond_resched();
598 		/* Select all remaining pages up to the next section boundary */
599 		cur_nr_pages = min(end_pfn - pfn,
600 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
601 		sparse_remove_section(pfn, cur_nr_pages, altmap);
602 	}
603 }
604 
set_online_page_callback(online_page_callback_t callback)605 int set_online_page_callback(online_page_callback_t callback)
606 {
607 	int rc = -EINVAL;
608 
609 	get_online_mems();
610 	mutex_lock(&online_page_callback_lock);
611 
612 	if (online_page_callback == generic_online_page) {
613 		online_page_callback = callback;
614 		rc = 0;
615 	}
616 
617 	mutex_unlock(&online_page_callback_lock);
618 	put_online_mems();
619 
620 	return rc;
621 }
622 EXPORT_SYMBOL_GPL(set_online_page_callback);
623 
restore_online_page_callback(online_page_callback_t callback)624 int restore_online_page_callback(online_page_callback_t callback)
625 {
626 	int rc = -EINVAL;
627 
628 	get_online_mems();
629 	mutex_lock(&online_page_callback_lock);
630 
631 	if (online_page_callback == callback) {
632 		online_page_callback = generic_online_page;
633 		rc = 0;
634 	}
635 
636 	mutex_unlock(&online_page_callback_lock);
637 	put_online_mems();
638 
639 	return rc;
640 }
641 EXPORT_SYMBOL_GPL(restore_online_page_callback);
642 
643 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
generic_online_page(struct page * page,unsigned int order)644 void generic_online_page(struct page *page, unsigned int order)
645 {
646 	__free_pages_core(page, order, MEMINIT_HOTPLUG);
647 }
648 EXPORT_SYMBOL_GPL(generic_online_page);
649 
online_pages_range(unsigned long start_pfn,unsigned long nr_pages)650 static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
651 {
652 	const unsigned long end_pfn = start_pfn + nr_pages;
653 	unsigned long pfn;
654 
655 	/*
656 	 * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
657 	 * decide to not expose all pages to the buddy (e.g., expose them
658 	 * later). We account all pages as being online and belonging to this
659 	 * zone ("present").
660 	 * When using memmap_on_memory, the range might not be aligned to
661 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
662 	 * this and the first chunk to online will be pageblock_nr_pages.
663 	 */
664 	for (pfn = start_pfn; pfn < end_pfn;) {
665 		struct page *page = pfn_to_page(pfn);
666 		int order;
667 
668 		/*
669 		 * Free to online pages in the largest chunks alignment allows.
670 		 *
671 		 * __ffs() behaviour is undefined for 0. start == 0 is
672 		 * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
673 		 * the case.
674 		 */
675 		if (pfn)
676 			order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
677 		else
678 			order = MAX_PAGE_ORDER;
679 
680 		/*
681 		 * Exposing the page to the buddy by freeing can cause
682 		 * issues with debug_pagealloc enabled: some archs don't
683 		 * like double-unmappings. So treat them like any pages that
684 		 * were allocated from the buddy.
685 		 */
686 		debug_pagealloc_map_pages(page, 1 << order);
687 		(*online_page_callback)(page, order);
688 		pfn += (1UL << order);
689 	}
690 
691 	/* mark all involved sections as online */
692 	online_mem_sections(start_pfn, end_pfn);
693 }
694 
resize_zone_range(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)695 static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
696 		unsigned long nr_pages)
697 {
698 	unsigned long old_end_pfn = zone_end_pfn(zone);
699 
700 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
701 		zone->zone_start_pfn = start_pfn;
702 
703 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
704 }
705 
resize_pgdat_range(struct pglist_data * pgdat,unsigned long start_pfn,unsigned long nr_pages)706 static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
707                                      unsigned long nr_pages)
708 {
709 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
710 
711 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
712 		pgdat->node_start_pfn = start_pfn;
713 
714 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
715 
716 }
717 
718 #ifdef CONFIG_ZONE_DEVICE
section_taint_zone_device(unsigned long pfn)719 static void section_taint_zone_device(unsigned long pfn)
720 {
721 	struct mem_section *ms = __pfn_to_section(pfn);
722 
723 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
724 }
725 #else
section_taint_zone_device(unsigned long pfn)726 static inline void section_taint_zone_device(unsigned long pfn)
727 {
728 }
729 #endif
730 
731 /*
732  * Associate the pfn range with the given zone, initializing the memmaps
733  * and resizing the pgdat/zone data to span the added pages. After this
734  * call, all affected pages are PageOffline().
735  *
736  * All aligned pageblocks are initialized to the specified migratetype
737  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
738  * zone stats (e.g., nr_isolate_pageblock) are touched.
739  */
move_pfn_range_to_zone(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages,struct vmem_altmap * altmap,int migratetype,bool isolate_pageblock)740 void move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
741 				  unsigned long nr_pages,
742 				  struct vmem_altmap *altmap, int migratetype,
743 				  bool isolate_pageblock)
744 {
745 	struct pglist_data *pgdat = zone->zone_pgdat;
746 	int nid = pgdat->node_id;
747 
748 	clear_zone_contiguous(zone);
749 
750 	if (zone_is_empty(zone))
751 		init_currently_empty_zone(zone, start_pfn, nr_pages);
752 	resize_zone_range(zone, start_pfn, nr_pages);
753 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
754 
755 	/*
756 	 * Subsection population requires care in pfn_to_online_page().
757 	 * Set the taint to enable the slow path detection of
758 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
759 	 * section.
760 	 */
761 	if (zone_is_zone_device(zone)) {
762 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
763 			section_taint_zone_device(start_pfn);
764 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
765 			section_taint_zone_device(start_pfn + nr_pages);
766 	}
767 
768 	/*
769 	 * TODO now we have a visible range of pages which are not associated
770 	 * with their zone properly. Not nice but set_pfnblock_migratetype()
771 	 * expects the zone spans the pfn range. All the pages in the range
772 	 * are reserved so nobody should be touching them so we should be safe
773 	 */
774 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
775 			 MEMINIT_HOTPLUG, altmap, migratetype,
776 			 isolate_pageblock);
777 
778 	set_zone_contiguous(zone);
779 }
780 
781 struct auto_movable_stats {
782 	unsigned long kernel_early_pages;
783 	unsigned long movable_pages;
784 };
785 
auto_movable_stats_account_zone(struct auto_movable_stats * stats,struct zone * zone)786 static void auto_movable_stats_account_zone(struct auto_movable_stats *stats,
787 					    struct zone *zone)
788 {
789 	if (zone_idx(zone) == ZONE_MOVABLE) {
790 		stats->movable_pages += zone->present_pages;
791 	} else {
792 		stats->kernel_early_pages += zone->present_early_pages;
793 #ifdef CONFIG_CMA
794 		/*
795 		 * CMA pages (never on hotplugged memory) behave like
796 		 * ZONE_MOVABLE.
797 		 */
798 		stats->movable_pages += zone->cma_pages;
799 		stats->kernel_early_pages -= zone->cma_pages;
800 #endif /* CONFIG_CMA */
801 	}
802 }
803 struct auto_movable_group_stats {
804 	unsigned long movable_pages;
805 	unsigned long req_kernel_early_pages;
806 };
807 
auto_movable_stats_account_group(struct memory_group * group,void * arg)808 static int auto_movable_stats_account_group(struct memory_group *group,
809 					   void *arg)
810 {
811 	const int ratio = READ_ONCE(auto_movable_ratio);
812 	struct auto_movable_group_stats *stats = arg;
813 	long pages;
814 
815 	/*
816 	 * We don't support modifying the config while the auto-movable online
817 	 * policy is already enabled. Just avoid the division by zero below.
818 	 */
819 	if (!ratio)
820 		return 0;
821 
822 	/*
823 	 * Calculate how many early kernel pages this group requires to
824 	 * satisfy the configured zone ratio.
825 	 */
826 	pages = group->present_movable_pages * 100 / ratio;
827 	pages -= group->present_kernel_pages;
828 
829 	if (pages > 0)
830 		stats->req_kernel_early_pages += pages;
831 	stats->movable_pages += group->present_movable_pages;
832 	return 0;
833 }
834 
auto_movable_can_online_movable(int nid,struct memory_group * group,unsigned long nr_pages)835 static bool auto_movable_can_online_movable(int nid, struct memory_group *group,
836 					    unsigned long nr_pages)
837 {
838 	unsigned long kernel_early_pages, movable_pages;
839 	struct auto_movable_group_stats group_stats = {};
840 	struct auto_movable_stats stats = {};
841 	struct zone *zone;
842 	int i;
843 
844 	/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */
845 	if (nid == NUMA_NO_NODE) {
846 		/* TODO: cache values */
847 		for_each_populated_zone(zone)
848 			auto_movable_stats_account_zone(&stats, zone);
849 	} else {
850 		for (i = 0; i < MAX_NR_ZONES; i++) {
851 			pg_data_t *pgdat = NODE_DATA(nid);
852 
853 			zone = pgdat->node_zones + i;
854 			if (populated_zone(zone))
855 				auto_movable_stats_account_zone(&stats, zone);
856 		}
857 	}
858 
859 	kernel_early_pages = stats.kernel_early_pages;
860 	movable_pages = stats.movable_pages;
861 
862 	/*
863 	 * Kernel memory inside dynamic memory group allows for more MOVABLE
864 	 * memory within the same group. Remove the effect of all but the
865 	 * current group from the stats.
866 	 */
867 	walk_dynamic_memory_groups(nid, auto_movable_stats_account_group,
868 				   group, &group_stats);
869 	if (kernel_early_pages <= group_stats.req_kernel_early_pages)
870 		return false;
871 	kernel_early_pages -= group_stats.req_kernel_early_pages;
872 	movable_pages -= group_stats.movable_pages;
873 
874 	if (group && group->is_dynamic)
875 		kernel_early_pages += group->present_kernel_pages;
876 
877 	/*
878 	 * Test if we could online the given number of pages to ZONE_MOVABLE
879 	 * and still stay in the configured ratio.
880 	 */
881 	movable_pages += nr_pages;
882 	return movable_pages <= (auto_movable_ratio * kernel_early_pages) / 100;
883 }
884 
885 /*
886  * Returns a default kernel memory zone for the given pfn range.
887  * If no kernel zone covers this pfn range it will automatically go
888  * to the ZONE_NORMAL.
889  */
default_kernel_zone_for_pfn(int nid,unsigned long start_pfn,unsigned long nr_pages)890 static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
891 		unsigned long nr_pages)
892 {
893 	struct pglist_data *pgdat = NODE_DATA(nid);
894 	int zid;
895 
896 	for (zid = 0; zid < ZONE_NORMAL; zid++) {
897 		struct zone *zone = &pgdat->node_zones[zid];
898 
899 		if (zone_intersects(zone, start_pfn, nr_pages))
900 			return zone;
901 	}
902 
903 	return &pgdat->node_zones[ZONE_NORMAL];
904 }
905 
906 /*
907  * Determine to which zone to online memory dynamically based on user
908  * configuration and system stats. We care about the following ratio:
909  *
910  *   MOVABLE : KERNEL
911  *
912  * Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in
913  * one of the kernel zones. CMA pages inside one of the kernel zones really
914  * behaves like ZONE_MOVABLE, so we treat them accordingly.
915  *
916  * We don't allow for hotplugged memory in a KERNEL zone to increase the
917  * amount of MOVABLE memory we can have, so we end up with:
918  *
919  *   MOVABLE : KERNEL_EARLY
920  *
921  * Whereby KERNEL_EARLY is memory in one of the kernel zones, available since
922  * boot. We base our calculation on KERNEL_EARLY internally, because:
923  *
924  * a) Hotplugged memory in one of the kernel zones can sometimes still get
925  *    hotunplugged, especially when hot(un)plugging individual memory blocks.
926  *    There is no coordination across memory devices, therefore "automatic"
927  *    hotunplugging, as implemented in hypervisors, could result in zone
928  *    imbalances.
929  * b) Early/boot memory in one of the kernel zones can usually not get
930  *    hotunplugged again (e.g., no firmware interface to unplug, fragmented
931  *    with unmovable allocations). While there are corner cases where it might
932  *    still work, it is barely relevant in practice.
933  *
934  * Exceptions are dynamic memory groups, which allow for more MOVABLE
935  * memory within the same memory group -- because in that case, there is
936  * coordination within the single memory device managed by a single driver.
937  *
938  * We rely on "present pages" instead of "managed pages", as the latter is
939  * highly unreliable and dynamic in virtualized environments, and does not
940  * consider boot time allocations. For example, memory ballooning adjusts the
941  * managed pages when inflating/deflating the balloon, and balloon page
942  * migration can even migrate inflated pages between zones.
943  *
944  * Using "present pages" is better but some things to keep in mind are:
945  *
946  * a) Some memblock allocations, such as for the crashkernel area, are
947  *    effectively unused by the kernel, yet they account to "present pages".
948  *    Fortunately, these allocations are comparatively small in relevant setups
949  *    (e.g., fraction of system memory).
950  * b) Some hotplugged memory blocks in virtualized environments, especially
951  *    hotplugged by virtio-mem, look like they are completely present, however,
952  *    only parts of the memory block are actually currently usable.
953  *    "present pages" is an upper limit that can get reached at runtime. As
954  *    we base our calculations on KERNEL_EARLY, this is not an issue.
955  */
auto_movable_zone_for_pfn(int nid,struct memory_group * group,unsigned long pfn,unsigned long nr_pages)956 static struct zone *auto_movable_zone_for_pfn(int nid,
957 					      struct memory_group *group,
958 					      unsigned long pfn,
959 					      unsigned long nr_pages)
960 {
961 	unsigned long online_pages = 0, max_pages, end_pfn;
962 	struct page *page;
963 
964 	if (!auto_movable_ratio)
965 		goto kernel_zone;
966 
967 	if (group && !group->is_dynamic) {
968 		max_pages = group->s.max_pages;
969 		online_pages = group->present_movable_pages;
970 
971 		/* If anything is !MOVABLE online the rest !MOVABLE. */
972 		if (group->present_kernel_pages)
973 			goto kernel_zone;
974 	} else if (!group || group->d.unit_pages == nr_pages) {
975 		max_pages = nr_pages;
976 	} else {
977 		max_pages = group->d.unit_pages;
978 		/*
979 		 * Take a look at all online sections in the current unit.
980 		 * We can safely assume that all pages within a section belong
981 		 * to the same zone, because dynamic memory groups only deal
982 		 * with hotplugged memory.
983 		 */
984 		pfn = ALIGN_DOWN(pfn, group->d.unit_pages);
985 		end_pfn = pfn + group->d.unit_pages;
986 		for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
987 			page = pfn_to_online_page(pfn);
988 			if (!page)
989 				continue;
990 			/* If anything is !MOVABLE online the rest !MOVABLE. */
991 			if (!is_zone_movable_page(page))
992 				goto kernel_zone;
993 			online_pages += PAGES_PER_SECTION;
994 		}
995 	}
996 
997 	/*
998 	 * Online MOVABLE if we could *currently* online all remaining parts
999 	 * MOVABLE. We expect to (add+) online them immediately next, so if
1000 	 * nobody interferes, all will be MOVABLE if possible.
1001 	 */
1002 	nr_pages = max_pages - online_pages;
1003 	if (!auto_movable_can_online_movable(NUMA_NO_NODE, group, nr_pages))
1004 		goto kernel_zone;
1005 
1006 #ifdef CONFIG_NUMA
1007 	if (auto_movable_numa_aware &&
1008 	    !auto_movable_can_online_movable(nid, group, nr_pages))
1009 		goto kernel_zone;
1010 #endif /* CONFIG_NUMA */
1011 
1012 	return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1013 kernel_zone:
1014 	return default_kernel_zone_for_pfn(nid, pfn, nr_pages);
1015 }
1016 
default_zone_for_pfn(int nid,unsigned long start_pfn,unsigned long nr_pages)1017 static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
1018 		unsigned long nr_pages)
1019 {
1020 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
1021 			nr_pages);
1022 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1023 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
1024 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
1025 
1026 	/*
1027 	 * We inherit the existing zone in a simple case where zones do not
1028 	 * overlap in the given range
1029 	 */
1030 	if (in_kernel ^ in_movable)
1031 		return (in_kernel) ? kernel_zone : movable_zone;
1032 
1033 	/*
1034 	 * If the range doesn't belong to any zone or two zones overlap in the
1035 	 * given range then we use movable zone only if movable_node is
1036 	 * enabled because we always online to a kernel zone by default.
1037 	 */
1038 	return movable_node_enabled ? movable_zone : kernel_zone;
1039 }
1040 
zone_for_pfn_range(enum mmop online_type,int nid,struct memory_group * group,unsigned long start_pfn,unsigned long nr_pages)1041 struct zone *zone_for_pfn_range(enum mmop online_type, int nid,
1042 		struct memory_group *group, unsigned long start_pfn,
1043 		unsigned long nr_pages)
1044 {
1045 	if (online_type == MMOP_ONLINE_KERNEL)
1046 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
1047 
1048 	if (online_type == MMOP_ONLINE_MOVABLE)
1049 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
1050 
1051 	if (online_policy == ONLINE_POLICY_AUTO_MOVABLE)
1052 		return auto_movable_zone_for_pfn(nid, group, start_pfn, nr_pages);
1053 
1054 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
1055 }
1056 
1057 /*
1058  * This function should only be called by memory_block_{online,offline},
1059  * and {online,offline}_pages.
1060  */
adjust_present_page_count(struct page * page,struct memory_group * group,long nr_pages)1061 void adjust_present_page_count(struct page *page, struct memory_group *group,
1062 			       long nr_pages)
1063 {
1064 	struct zone *zone = page_zone(page);
1065 	const bool movable = zone_idx(zone) == ZONE_MOVABLE;
1066 
1067 	/*
1068 	 * We only support onlining/offlining/adding/removing of complete
1069 	 * memory blocks; therefore, either all is either early or hotplugged.
1070 	 */
1071 	if (early_section(__pfn_to_section(page_to_pfn(page))))
1072 		zone->present_early_pages += nr_pages;
1073 	zone->present_pages += nr_pages;
1074 	zone->zone_pgdat->node_present_pages += nr_pages;
1075 
1076 	if (group && movable)
1077 		group->present_movable_pages += nr_pages;
1078 	else if (group && !movable)
1079 		group->present_kernel_pages += nr_pages;
1080 }
1081 
mhp_init_memmap_on_memory(unsigned long pfn,unsigned long nr_pages,struct zone * zone)1082 int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
1083 			      struct zone *zone)
1084 {
1085 	unsigned long end_pfn = pfn + nr_pages;
1086 	int ret, i;
1087 
1088 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1089 	if (ret)
1090 		return ret;
1091 
1092 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE,
1093 			       false);
1094 
1095 	for (i = 0; i < nr_pages; i++) {
1096 		struct page *page = pfn_to_page(pfn + i);
1097 
1098 		__ClearPageOffline(page);
1099 		SetPageVmemmapSelfHosted(page);
1100 	}
1101 
1102 	/*
1103 	 * It might be that the vmemmap_pages fully span sections. If that is
1104 	 * the case, mark those sections online here as otherwise they will be
1105 	 * left offline.
1106 	 */
1107 	if (nr_pages >= PAGES_PER_SECTION)
1108 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1109 
1110 	return ret;
1111 }
1112 
mhp_deinit_memmap_on_memory(unsigned long pfn,unsigned long nr_pages)1113 void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
1114 {
1115 	unsigned long end_pfn = pfn + nr_pages;
1116 
1117 	/*
1118 	 * It might be that the vmemmap_pages fully span sections. If that is
1119 	 * the case, mark those sections offline here as otherwise they will be
1120 	 * left online.
1121 	 */
1122 	if (nr_pages >= PAGES_PER_SECTION)
1123 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
1124 
1125         /*
1126 	 * The pages associated with this vmemmap have been offlined, so
1127 	 * we can reset its state here.
1128 	 */
1129 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
1130 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
1131 }
1132 
1133 /*
1134  * Must be called with mem_hotplug_lock in write mode.
1135  */
online_pages(unsigned long pfn,unsigned long nr_pages,struct zone * zone,struct memory_group * group)1136 int online_pages(unsigned long pfn, unsigned long nr_pages,
1137 		       struct zone *zone, struct memory_group *group)
1138 {
1139 	struct memory_notify mem_arg = {
1140 		.start_pfn = pfn,
1141 		.nr_pages = nr_pages,
1142 	};
1143 	struct node_notify node_arg = {
1144 		.nid = NUMA_NO_NODE,
1145 	};
1146 	const int nid = zone_to_nid(zone);
1147 	int need_zonelists_rebuild = 0;
1148 	unsigned long flags;
1149 	int ret;
1150 
1151 	/*
1152 	 * {on,off}lining is constrained to full memory sections (or more
1153 	 * precisely to memory blocks from the user space POV).
1154 	 * memmap_on_memory is an exception because it reserves initial part
1155 	 * of the physical memory space for vmemmaps. That space is pageblock
1156 	 * aligned.
1157 	 */
1158 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(pfn) ||
1159 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
1160 		return -EINVAL;
1161 
1162 
1163 	/* associate pfn range with the zone */
1164 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_MOVABLE,
1165 			       true);
1166 
1167 	if (!node_state(nid, N_MEMORY)) {
1168 		/* Adding memory to the node for the first time */
1169 		node_arg.nid = nid;
1170 		ret = node_notify(NODE_ADDING_FIRST_MEMORY, &node_arg);
1171 		ret = notifier_to_errno(ret);
1172 		if (ret)
1173 			goto failed_addition;
1174 	}
1175 
1176 	ret = memory_notify(MEM_GOING_ONLINE, &mem_arg);
1177 	ret = notifier_to_errno(ret);
1178 	if (ret)
1179 		goto failed_addition;
1180 
1181 	/*
1182 	 * Fixup the number of isolated pageblocks before marking the sections
1183 	 * onlining, such that undo_isolate_page_range() works correctly.
1184 	 */
1185 	spin_lock_irqsave(&zone->lock, flags);
1186 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
1187 	spin_unlock_irqrestore(&zone->lock, flags);
1188 
1189 	/*
1190 	 * If this zone is not populated, then it is not in zonelist.
1191 	 * This means the page allocator ignores this zone.
1192 	 * So, zonelist must be updated after online.
1193 	 */
1194 	if (!populated_zone(zone)) {
1195 		need_zonelists_rebuild = 1;
1196 		setup_zone_pageset(zone);
1197 	}
1198 
1199 	online_pages_range(pfn, nr_pages);
1200 	adjust_present_page_count(pfn_to_page(pfn), group, nr_pages);
1201 
1202 	if (node_arg.nid >= 0)
1203 		node_set_state(nid, N_MEMORY);
1204 	/*
1205 	 * Check whether we are adding normal memory to the node for the first
1206 	 * time.
1207 	 */
1208 	if (!node_state(nid, N_NORMAL_MEMORY) && zone_idx(zone) <= ZONE_NORMAL)
1209 		node_set_state(nid, N_NORMAL_MEMORY);
1210 
1211 	if (need_zonelists_rebuild)
1212 		build_all_zonelists(NULL);
1213 
1214 	/* Basic onlining is complete, allow allocation of onlined pages. */
1215 	undo_isolate_page_range(pfn, pfn + nr_pages);
1216 
1217 	/*
1218 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
1219 	 * the tail of the freelist when undoing isolation). Shuffle the whole
1220 	 * zone to make sure the just onlined pages are properly distributed
1221 	 * across the whole freelist - to create an initial shuffle.
1222 	 */
1223 	shuffle_zone(zone);
1224 
1225 	/* reinitialise watermarks and update pcp limits */
1226 	init_per_zone_wmark_min();
1227 
1228 	kswapd_run(nid);
1229 	kcompactd_run(nid);
1230 
1231 	if (node_arg.nid >= 0)
1232 		/* First memory added successfully. Notify consumers. */
1233 		node_notify(NODE_ADDED_FIRST_MEMORY, &node_arg);
1234 
1235 	writeback_set_ratelimit();
1236 
1237 	memory_notify(MEM_ONLINE, &mem_arg);
1238 	return 0;
1239 
1240 failed_addition:
1241 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1242 		 (unsigned long long) pfn << PAGE_SHIFT,
1243 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1244 	memory_notify(MEM_CANCEL_ONLINE, &mem_arg);
1245 	if (node_arg.nid != NUMA_NO_NODE)
1246 		node_notify(NODE_CANCEL_ADDING_FIRST_MEMORY, &node_arg);
1247 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
1248 	return ret;
1249 }
1250 
1251 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
hotadd_init_pgdat(int nid)1252 static pg_data_t *hotadd_init_pgdat(int nid)
1253 {
1254 	struct pglist_data *pgdat;
1255 
1256 	/*
1257 	 * NODE_DATA is preallocated (free_area_init) but its internal
1258 	 * state is not allocated completely. Add missing pieces.
1259 	 * Completely offline nodes stay around and they just need
1260 	 * reinitialization.
1261 	 */
1262 	pgdat = NODE_DATA(nid);
1263 
1264 	/* init node's zones as empty zones, we don't have any present pages.*/
1265 	free_area_init_core_hotplug(pgdat);
1266 
1267 	/*
1268 	 * The node we allocated has no zone fallback lists. For avoiding
1269 	 * to access not-initialized zonelist, build here.
1270 	 */
1271 	build_all_zonelists(pgdat);
1272 
1273 	return pgdat;
1274 }
1275 
1276 /*
1277  * __try_online_node - online a node if offlined
1278  * @nid: the node ID
1279  * @set_node_online: Whether we want to online the node
1280  * called by cpu_up() to online a node without onlined memory.
1281  *
1282  * Returns:
1283  * 1 -> a new node has been allocated
1284  * 0 -> the node is already online
1285  * -ENOMEM -> the node could not be allocated
1286  */
__try_online_node(int nid,bool set_node_online)1287 static int __try_online_node(int nid, bool set_node_online)
1288 {
1289 	pg_data_t *pgdat;
1290 	int ret = 1;
1291 
1292 	if (node_online(nid))
1293 		return 0;
1294 
1295 	pgdat = hotadd_init_pgdat(nid);
1296 	if (!pgdat) {
1297 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1298 		ret = -ENOMEM;
1299 		goto out;
1300 	}
1301 
1302 	if (set_node_online) {
1303 		node_set_online(nid);
1304 		ret = register_node(nid);
1305 		BUG_ON(ret);
1306 	}
1307 out:
1308 	return ret;
1309 }
1310 
1311 /*
1312  * Users of this function always want to online/register the node
1313  */
try_online_node(int nid)1314 int try_online_node(int nid)
1315 {
1316 	int ret;
1317 
1318 	mem_hotplug_begin();
1319 	ret =  __try_online_node(nid, true);
1320 	mem_hotplug_done();
1321 	return ret;
1322 }
1323 
check_hotplug_memory_range(u64 start,u64 size)1324 static int check_hotplug_memory_range(u64 start, u64 size)
1325 {
1326 	/* memory range must be block size aligned */
1327 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1328 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1329 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1330 		       memory_block_size_bytes(), start, size);
1331 		return -EINVAL;
1332 	}
1333 
1334 	return 0;
1335 }
1336 
online_memory_block(struct memory_block * mem,void * arg)1337 static int online_memory_block(struct memory_block *mem, void *arg)
1338 {
1339 	mem->online_type = mhp_get_default_online_type();
1340 	return device_online(&mem->dev);
1341 }
1342 
1343 #ifndef arch_supports_memmap_on_memory
arch_supports_memmap_on_memory(unsigned long vmemmap_size)1344 static inline bool arch_supports_memmap_on_memory(unsigned long vmemmap_size)
1345 {
1346 	/*
1347 	 * As default, we want the vmemmap to span a complete PMD such that we
1348 	 * can map the vmemmap using a single PMD if supported by the
1349 	 * architecture.
1350 	 */
1351 	return IS_ALIGNED(vmemmap_size, PMD_SIZE);
1352 }
1353 #endif
1354 
mhp_supports_memmap_on_memory(void)1355 bool mhp_supports_memmap_on_memory(void)
1356 {
1357 	unsigned long vmemmap_size = memory_block_memmap_size();
1358 	unsigned long memmap_pages = memory_block_memmap_on_memory_pages();
1359 
1360 	/*
1361 	 * Besides having arch support and the feature enabled at runtime, we
1362 	 * need a few more assumptions to hold true:
1363 	 *
1364 	 * a) The vmemmap pages span complete PMDs: We don't want vmemmap code
1365 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1366 	 *    other memory blocks)
1367 	 *
1368 	 * b) The vmemmap pages (and thereby the pages that will be exposed to
1369 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1370 	 *    code requires applicable ranges to be page-aligned, for example, to
1371 	 *    set the migratetypes properly.
1372 	 *
1373 	 * TODO: Although we have a check here to make sure that vmemmap pages
1374 	 *       fully populate a PMD, it is not the right place to check for
1375 	 *       this. A much better solution involves improving vmemmap code
1376 	 *       to fallback to base pages when trying to populate vmemmap using
1377 	 *       altmap as an alternative source of memory, and we do not exactly
1378 	 *       populate a single PMD.
1379 	 */
1380 	if (!mhp_memmap_on_memory())
1381 		return false;
1382 
1383 	/*
1384 	 * Make sure the vmemmap allocation is fully contained
1385 	 * so that we always allocate vmemmap memory from altmap area.
1386 	 */
1387 	if (!IS_ALIGNED(vmemmap_size, PAGE_SIZE))
1388 		return false;
1389 
1390 	/*
1391 	 * start pfn should be pageblock_nr_pages aligned for correctly
1392 	 * setting migrate types
1393 	 */
1394 	if (!pageblock_aligned(memmap_pages))
1395 		return false;
1396 
1397 	if (memmap_pages == PHYS_PFN(memory_block_size_bytes()))
1398 		/* No effective hotplugged memory doesn't make sense. */
1399 		return false;
1400 
1401 	return arch_supports_memmap_on_memory(vmemmap_size);
1402 }
1403 EXPORT_SYMBOL_GPL(mhp_supports_memmap_on_memory);
1404 
remove_memory_blocks_and_altmaps(u64 start,u64 size)1405 static void remove_memory_blocks_and_altmaps(u64 start, u64 size)
1406 {
1407 	unsigned long memblock_size = memory_block_size_bytes();
1408 	u64 cur_start;
1409 
1410 	/*
1411 	 * For memmap_on_memory, the altmaps were added on a per-memblock
1412 	 * basis; we have to process each individual memory block.
1413 	 */
1414 	for (cur_start = start; cur_start < start + size;
1415 	     cur_start += memblock_size) {
1416 		struct vmem_altmap *altmap = NULL;
1417 		struct memory_block *mem;
1418 
1419 		mem = find_memory_block(pfn_to_section_nr(PFN_DOWN(cur_start)));
1420 		if (WARN_ON_ONCE(!mem))
1421 			continue;
1422 
1423 		altmap = mem->altmap;
1424 		mem->altmap = NULL;
1425 
1426 		remove_memory_block_devices(cur_start, memblock_size);
1427 
1428 		arch_remove_memory(cur_start, memblock_size, altmap);
1429 
1430 		/* Verify that all vmemmap pages have actually been freed. */
1431 		WARN(altmap->alloc, "Altmap not fully unmapped");
1432 		kfree(altmap);
1433 	}
1434 }
1435 
create_altmaps_and_memory_blocks(int nid,struct memory_group * group,u64 start,u64 size)1436 static int create_altmaps_and_memory_blocks(int nid, struct memory_group *group,
1437 					    u64 start, u64 size)
1438 {
1439 	unsigned long memblock_size = memory_block_size_bytes();
1440 	u64 cur_start;
1441 	int ret;
1442 
1443 	for (cur_start = start; cur_start < start + size;
1444 	     cur_start += memblock_size) {
1445 		struct mhp_params params = { .pgprot =
1446 						     pgprot_mhp(PAGE_KERNEL) };
1447 		struct vmem_altmap mhp_altmap = {
1448 			.base_pfn = PHYS_PFN(cur_start),
1449 			.end_pfn = PHYS_PFN(cur_start + memblock_size - 1),
1450 		};
1451 
1452 		mhp_altmap.free = memory_block_memmap_on_memory_pages();
1453 		params.altmap = kmemdup(&mhp_altmap, sizeof(struct vmem_altmap),
1454 					GFP_KERNEL);
1455 		if (!params.altmap) {
1456 			ret = -ENOMEM;
1457 			goto out;
1458 		}
1459 
1460 		/* call arch's memory hotadd */
1461 		ret = arch_add_memory(nid, cur_start, memblock_size, &params);
1462 		if (ret < 0) {
1463 			kfree(params.altmap);
1464 			goto out;
1465 		}
1466 
1467 		/* create memory block devices after memory was added */
1468 		ret = create_memory_block_devices(cur_start, memblock_size, nid,
1469 						  params.altmap, group);
1470 		if (ret) {
1471 			arch_remove_memory(cur_start, memblock_size, NULL);
1472 			kfree(params.altmap);
1473 			goto out;
1474 		}
1475 	}
1476 
1477 	return 0;
1478 out:
1479 	if (ret && cur_start != start)
1480 		remove_memory_blocks_and_altmaps(start, cur_start - start);
1481 	return ret;
1482 }
1483 
1484 /*
1485  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1486  * and online/offline operations (triggered e.g. by sysfs).
1487  *
1488  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
1489  */
add_memory_resource(int nid,struct resource * res,mhp_t mhp_flags)1490 int add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1491 {
1492 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
1493 	enum memblock_flags memblock_flags = MEMBLOCK_NONE;
1494 	struct memory_group *group = NULL;
1495 	u64 start, size;
1496 	bool new_node = false;
1497 	int ret;
1498 
1499 	start = res->start;
1500 	size = resource_size(res);
1501 
1502 	ret = check_hotplug_memory_range(start, size);
1503 	if (ret)
1504 		return ret;
1505 
1506 	if (mhp_flags & MHP_NID_IS_MGID) {
1507 		group = memory_group_find_by_id(nid);
1508 		if (!group)
1509 			return -EINVAL;
1510 		nid = group->nid;
1511 	}
1512 
1513 	if (!node_possible(nid)) {
1514 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1515 		return -EINVAL;
1516 	}
1517 
1518 	mem_hotplug_begin();
1519 
1520 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
1521 		if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
1522 			memblock_flags = MEMBLOCK_DRIVER_MANAGED;
1523 		ret = memblock_add_node(start, size, nid, memblock_flags);
1524 		if (ret)
1525 			goto error_mem_hotplug_end;
1526 	}
1527 
1528 	ret = __try_online_node(nid, false);
1529 	if (ret < 0)
1530 		goto error_memblock_remove;
1531 	if (ret) {
1532 		node_set_online(nid);
1533 		ret = register_node(nid);
1534 		if (WARN_ON(ret)) {
1535 			node_set_offline(nid);
1536 			goto error_memblock_remove;
1537 		}
1538 		new_node = true;
1539 	}
1540 
1541 	/*
1542 	 * Self hosted memmap array
1543 	 */
1544 	if ((mhp_flags & MHP_MEMMAP_ON_MEMORY) &&
1545 	    mhp_supports_memmap_on_memory()) {
1546 		ret = create_altmaps_and_memory_blocks(nid, group, start, size);
1547 		if (ret)
1548 			goto error;
1549 	} else {
1550 		ret = arch_add_memory(nid, start, size, &params);
1551 		if (ret < 0)
1552 			goto error;
1553 
1554 		/* create memory block devices after memory was added */
1555 		ret = create_memory_block_devices(start, size, nid, NULL, group);
1556 		if (ret) {
1557 			arch_remove_memory(start, size, params.altmap);
1558 			goto error;
1559 		}
1560 	}
1561 
1562 	register_memory_blocks_under_node_hotplug(nid, PFN_DOWN(start),
1563 					  PFN_UP(start + size - 1));
1564 
1565 	/* create new memmap entry */
1566 	if (!strcmp(res->name, "System RAM"))
1567 		firmware_map_add_hotplug(start, start + size, "System RAM");
1568 
1569 	/* device_online() will take the lock when calling online_pages() */
1570 	mem_hotplug_done();
1571 
1572 	/*
1573 	 * In case we're allowed to merge the resource, flag it and trigger
1574 	 * merging now that adding succeeded.
1575 	 */
1576 	if (mhp_flags & MHP_MERGE_RESOURCE)
1577 		merge_system_ram_resource(res);
1578 
1579 	/* online pages if requested */
1580 	if (mhp_get_default_online_type() != MMOP_OFFLINE)
1581 		walk_memory_blocks(start, size, NULL, online_memory_block);
1582 
1583 	return ret;
1584 error:
1585 	if (new_node) {
1586 		node_set_offline(nid);
1587 		unregister_node(nid);
1588 	}
1589 error_memblock_remove:
1590 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
1591 		memblock_remove(start, size);
1592 error_mem_hotplug_end:
1593 	mem_hotplug_done();
1594 	return ret;
1595 }
1596 
1597 /* requires device_hotplug_lock, see add_memory_resource() */
__add_memory(int nid,u64 start,u64 size,mhp_t mhp_flags)1598 int __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
1599 {
1600 	struct resource *res;
1601 	int ret;
1602 
1603 	res = register_memory_resource(start, size, "System RAM");
1604 	if (IS_ERR(res))
1605 		return PTR_ERR(res);
1606 
1607 	ret = add_memory_resource(nid, res, mhp_flags);
1608 	if (ret < 0)
1609 		release_memory_resource(res);
1610 	return ret;
1611 }
1612 
add_memory(int nid,u64 start,u64 size,mhp_t mhp_flags)1613 int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
1614 {
1615 	int rc;
1616 
1617 	lock_device_hotplug();
1618 	rc = __add_memory(nid, start, size, mhp_flags);
1619 	unlock_device_hotplug();
1620 
1621 	return rc;
1622 }
1623 EXPORT_SYMBOL_GPL(add_memory);
1624 
1625 /*
1626  * Add special, driver-managed memory to the system as system RAM. Such
1627  * memory is not exposed via the raw firmware-provided memmap as system
1628  * RAM, instead, it is detected and added by a driver - during cold boot,
1629  * after a reboot, and after kexec.
1630  *
1631  * Reasons why this memory should not be used for the initial memmap of a
1632  * kexec kernel or for placing kexec images:
1633  * - The booting kernel is in charge of determining how this memory will be
1634  *   used (e.g., use persistent memory as system RAM)
1635  * - Coordination with a hypervisor is required before this memory
1636  *   can be used (e.g., inaccessible parts).
1637  *
1638  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
1639  * memory map") are created. Also, the created memory resource is flagged
1640  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
1641  * this memory as well (esp., not place kexec images onto it).
1642  *
1643  * The resource_name (visible via /proc/iomem) has to have the format
1644  * "System RAM ($DRIVER)".
1645  */
add_memory_driver_managed(int nid,u64 start,u64 size,const char * resource_name,mhp_t mhp_flags)1646 int add_memory_driver_managed(int nid, u64 start, u64 size,
1647 			      const char *resource_name, mhp_t mhp_flags)
1648 {
1649 	struct resource *res;
1650 	int rc;
1651 
1652 	if (!resource_name ||
1653 	    strstr(resource_name, "System RAM (") != resource_name ||
1654 	    resource_name[strlen(resource_name) - 1] != ')')
1655 		return -EINVAL;
1656 
1657 	lock_device_hotplug();
1658 
1659 	res = register_memory_resource(start, size, resource_name);
1660 	if (IS_ERR(res)) {
1661 		rc = PTR_ERR(res);
1662 		goto out_unlock;
1663 	}
1664 
1665 	rc = add_memory_resource(nid, res, mhp_flags);
1666 	if (rc < 0)
1667 		release_memory_resource(res);
1668 
1669 out_unlock:
1670 	unlock_device_hotplug();
1671 	return rc;
1672 }
1673 EXPORT_SYMBOL_GPL(add_memory_driver_managed);
1674 
1675 /*
1676  * Platforms should define arch_get_mappable_range() that provides
1677  * maximum possible addressable physical memory range for which the
1678  * linear mapping could be created. The platform returned address
1679  * range must adhere to these following semantics.
1680  *
1681  * - range.start <= range.end
1682  * - Range includes both end points [range.start..range.end]
1683  *
1684  * There is also a fallback definition provided here, allowing the
1685  * entire possible physical address range in case any platform does
1686  * not define arch_get_mappable_range().
1687  */
arch_get_mappable_range(void)1688 struct range __weak arch_get_mappable_range(void)
1689 {
1690 	struct range mhp_range = {
1691 		.start = 0UL,
1692 		.end = -1ULL,
1693 	};
1694 	return mhp_range;
1695 }
1696 
mhp_get_pluggable_range(bool need_mapping)1697 struct range mhp_get_pluggable_range(bool need_mapping)
1698 {
1699 	const u64 max_phys = DIRECT_MAP_PHYSMEM_END;
1700 	struct range mhp_range;
1701 
1702 	if (need_mapping) {
1703 		mhp_range = arch_get_mappable_range();
1704 		if (mhp_range.start > max_phys) {
1705 			mhp_range.start = 0;
1706 			mhp_range.end = 0;
1707 		}
1708 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1709 	} else {
1710 		mhp_range.start = 0;
1711 		mhp_range.end = max_phys;
1712 	}
1713 	return mhp_range;
1714 }
1715 EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1716 
mhp_range_allowed(u64 start,u64 size,bool need_mapping)1717 bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1718 {
1719 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1720 	u64 end = start + size;
1721 
1722 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1723 		return true;
1724 
1725 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1726 		start, end, mhp_range.start, mhp_range.end);
1727 	return false;
1728 }
1729 
1730 #ifdef CONFIG_MEMORY_HOTREMOVE
1731 /*
1732  * Scan pfn range [start,end) to find movable/migratable pages (LRU and
1733  * hugetlb folio, movable_ops pages). Will skip over most unmovable
1734  * pages (esp., pages that can be skipped when offlining), but bail out on
1735  * definitely unmovable pages.
1736  *
1737  * Returns:
1738  *	0 in case a movable page is found and movable_pfn was updated.
1739  *	-ENOENT in case no movable page was found.
1740  *	-EBUSY in case a definitely unmovable page was found.
1741  */
scan_movable_pages(unsigned long start,unsigned long end,unsigned long * movable_pfn)1742 static int scan_movable_pages(unsigned long start, unsigned long end,
1743 			      unsigned long *movable_pfn)
1744 {
1745 	unsigned long pfn;
1746 
1747 	for (pfn = start; pfn < end; pfn++) {
1748 		unsigned long nr_pages;
1749 		struct page *page;
1750 		struct folio *folio;
1751 
1752 		page = pfn_to_page(pfn);
1753 		if (PageLRU(page) || page_has_movable_ops(page))
1754 			goto found;
1755 
1756 		/*
1757 		 * PageOffline() pages that do not have movable_ops and
1758 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1759 		 * definitely unmovable. If their reference count would be 0,
1760 		 * they could at least be skipped when offlining memory.
1761 		 */
1762 		if (PageOffline(page) && page_count(page))
1763 			return -EBUSY;
1764 
1765 		folio = page_folio(page);
1766 		if (!folio_test_hugetlb(folio))
1767 			continue;
1768 		/*
1769 		 * This test is racy as we hold no reference or lock.  The
1770 		 * hugetlb page could have been free'ed and head is no longer
1771 		 * a hugetlb page before the following check.  In such unlikely
1772 		 * cases false positives and negatives are possible.  Calling
1773 		 * code must deal with these scenarios.
1774 		 */
1775 		if (folio_test_hugetlb_migratable(folio))
1776 			goto found;
1777 		nr_pages = folio_nr_pages(folio);
1778 		if (unlikely(nr_pages < 1 || nr_pages > MAX_FOLIO_NR_PAGES ||
1779 			     !is_power_of_2(nr_pages)))
1780 			continue;
1781 		pfn |= nr_pages - 1;
1782 	}
1783 	return -ENOENT;
1784 found:
1785 	*movable_pfn = pfn;
1786 	return 0;
1787 }
1788 
do_migrate_range(unsigned long start_pfn,unsigned long end_pfn)1789 static void do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
1790 {
1791 	struct folio *folio;
1792 	unsigned long pfn;
1793 	LIST_HEAD(source);
1794 	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
1795 				      DEFAULT_RATELIMIT_BURST);
1796 
1797 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1798 		struct page *page;
1799 
1800 		page = pfn_to_page(pfn);
1801 		folio = page_folio(page);
1802 
1803 		if (!folio_try_get(folio))
1804 			continue;
1805 
1806 		if (unlikely(page_folio(page) != folio))
1807 			goto put_folio;
1808 
1809 		if (folio_test_large(folio))
1810 			pfn = folio_pfn(folio) + folio_nr_pages(folio) - 1;
1811 
1812 		if (folio_contain_hwpoisoned_page(folio)) {
1813 			/*
1814 			 * unmap_poisoned_folio() cannot handle large folios
1815 			 * in all cases yet.
1816 			 */
1817 			if (folio_test_large(folio) && !folio_test_hugetlb(folio))
1818 				goto put_folio;
1819 			if (folio_test_lru(folio) && !folio_isolate_lru(folio))
1820 				goto put_folio;
1821 			if (folio_mapped(folio)) {
1822 				folio_lock(folio);
1823 				unmap_poisoned_folio(folio, pfn, false);
1824 				folio_unlock(folio);
1825 			}
1826 
1827 			goto put_folio;
1828 		}
1829 
1830 		if (!isolate_folio_to_list(folio, &source)) {
1831 			if (__ratelimit(&migrate_rs)) {
1832 				pr_warn("failed to isolate pfn %lx\n",
1833 					page_to_pfn(page));
1834 				dump_page(page, "isolation failed");
1835 			}
1836 		}
1837 put_folio:
1838 		folio_put(folio);
1839 	}
1840 	if (!list_empty(&source)) {
1841 		nodemask_t nmask = node_states[N_MEMORY];
1842 		struct migration_target_control mtc = {
1843 			.nmask = &nmask,
1844 			.gfp_mask = GFP_KERNEL | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1845 			.reason = MR_MEMORY_HOTPLUG,
1846 		};
1847 		int ret;
1848 
1849 		/*
1850 		 * We have checked that migration range is on a single zone so
1851 		 * we can use the nid of the first page to all the others.
1852 		 */
1853 		mtc.nid = folio_nid(list_first_entry(&source, struct folio, lru));
1854 
1855 		/*
1856 		 * try to allocate from a different node but reuse this node
1857 		 * if there are no other online nodes to be used (e.g. we are
1858 		 * offlining a part of the only existing node)
1859 		 */
1860 		node_clear(mtc.nid, nmask);
1861 		if (nodes_empty(nmask))
1862 			node_set(mtc.nid, nmask);
1863 		ret = migrate_pages(&source, alloc_migration_target, NULL,
1864 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG, NULL);
1865 		if (ret) {
1866 			list_for_each_entry(folio, &source, lru) {
1867 				if (__ratelimit(&migrate_rs)) {
1868 					pr_warn("migrating pfn %lx failed ret:%d\n",
1869 						folio_pfn(folio), ret);
1870 					dump_page(&folio->page,
1871 						  "migration failure");
1872 				}
1873 			}
1874 			putback_movable_pages(&source);
1875 		}
1876 	}
1877 }
1878 
cmdline_parse_movable_node(char * p)1879 static int __init cmdline_parse_movable_node(char *p)
1880 {
1881 	movable_node_enabled = true;
1882 	return 0;
1883 }
1884 early_param("movable_node", cmdline_parse_movable_node);
1885 
count_system_ram_pages_cb(unsigned long start_pfn,unsigned long nr_pages,void * data)1886 static int count_system_ram_pages_cb(unsigned long start_pfn,
1887 				     unsigned long nr_pages, void *data)
1888 {
1889 	unsigned long *nr_system_ram_pages = data;
1890 
1891 	*nr_system_ram_pages += nr_pages;
1892 	return 0;
1893 }
1894 
1895 /*
1896  * Must be called with mem_hotplug_lock in write mode.
1897  */
offline_pages(unsigned long start_pfn,unsigned long nr_pages,struct zone * zone,struct memory_group * group)1898 int offline_pages(unsigned long start_pfn, unsigned long nr_pages,
1899 			struct zone *zone, struct memory_group *group)
1900 {
1901 	unsigned long pfn, managed_pages, system_ram_pages = 0;
1902 	const unsigned long end_pfn = start_pfn + nr_pages;
1903 	struct pglist_data *pgdat = zone->zone_pgdat;
1904 	const int node = zone_to_nid(zone);
1905 	struct memory_notify mem_arg = {
1906 		.start_pfn = start_pfn,
1907 		.nr_pages = nr_pages,
1908 	};
1909 	struct node_notify node_arg = {
1910 		.nid = NUMA_NO_NODE,
1911 	};
1912 	unsigned long flags;
1913 	char *reason;
1914 	int ret;
1915 	unsigned long normal_pages = 0;
1916 	enum zone_type zt;
1917 
1918 	/*
1919 	 * {on,off}lining is constrained to full memory sections (or more
1920 	 * precisely to memory blocks from the user space POV).
1921 	 * memmap_on_memory is an exception because it reserves initial part
1922 	 * of the physical memory space for vmemmaps. That space is pageblock
1923 	 * aligned.
1924 	 */
1925 	if (WARN_ON_ONCE(!nr_pages || !pageblock_aligned(start_pfn) ||
1926 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
1927 		return -EINVAL;
1928 
1929 	/*
1930 	 * Don't allow to offline memory blocks that contain holes.
1931 	 * Consequently, memory blocks with holes can never get onlined
1932 	 * via the hotplug path - online_pages() - as hotplugged memory has
1933 	 * no holes. This way, we don't have to worry about memory holes,
1934 	 * don't need pfn_valid() checks, and can avoid using
1935 	 * walk_system_ram_range() later.
1936 	 */
1937 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1938 			      count_system_ram_pages_cb);
1939 	if (system_ram_pages != nr_pages) {
1940 		ret = -EINVAL;
1941 		reason = "memory holes";
1942 		goto failed_removal;
1943 	}
1944 
1945 	/*
1946 	 * We only support offlining of memory blocks managed by a single zone,
1947 	 * checked by calling code. This is just a sanity check that we might
1948 	 * want to remove in the future.
1949 	 */
1950 	if (WARN_ON_ONCE(page_zone(pfn_to_page(start_pfn)) != zone ||
1951 			 page_zone(pfn_to_page(end_pfn - 1)) != zone)) {
1952 		ret = -EINVAL;
1953 		reason = "multizone range";
1954 		goto failed_removal;
1955 	}
1956 
1957 	/*
1958 	 * Disable pcplists so that page isolation cannot race with freeing
1959 	 * in a way that pages from isolated pageblock are left on pcplists.
1960 	 */
1961 	zone_pcp_disable(zone);
1962 	lru_cache_disable();
1963 
1964 	/* set above range as isolated */
1965 	ret = start_isolate_page_range(start_pfn, end_pfn,
1966 				       PB_ISOLATE_MODE_MEM_OFFLINE);
1967 	if (ret) {
1968 		reason = "failure to isolate range";
1969 		goto failed_removal_pcplists_disabled;
1970 	}
1971 
1972 	/*
1973 	 * Check whether the node will have no present pages after we offline
1974 	 * 'nr_pages' more. If so, we know that the node will become empty, and
1975 	 * so we will clear N_MEMORY for it.
1976 	 */
1977 	if (nr_pages >= pgdat->node_present_pages) {
1978 		node_arg.nid = node;
1979 		ret = node_notify(NODE_REMOVING_LAST_MEMORY, &node_arg);
1980 		ret = notifier_to_errno(ret);
1981 		if (ret) {
1982 			reason = "node notifier failure";
1983 			goto failed_removal_isolated;
1984 		}
1985 	}
1986 
1987 	ret = memory_notify(MEM_GOING_OFFLINE, &mem_arg);
1988 	ret = notifier_to_errno(ret);
1989 	if (ret) {
1990 		reason = "notifier failure";
1991 		goto failed_removal_isolated;
1992 	}
1993 
1994 	do {
1995 		pfn = start_pfn;
1996 		do {
1997 			/*
1998 			 * Historically we always checked for any signal and
1999 			 * can't limit it to fatal signals without eventually
2000 			 * breaking user space.
2001 			 */
2002 			if (signal_pending(current)) {
2003 				ret = -EINTR;
2004 				reason = "signal backoff";
2005 				goto failed_removal_isolated;
2006 			}
2007 
2008 			cond_resched();
2009 
2010 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
2011 			if (!ret) {
2012 				/*
2013 				 * TODO: fatal migration failures should bail
2014 				 * out
2015 				 */
2016 				do_migrate_range(pfn, end_pfn);
2017 			}
2018 		} while (!ret);
2019 
2020 		if (ret != -ENOENT) {
2021 			reason = "unmovable page";
2022 			goto failed_removal_isolated;
2023 		}
2024 
2025 		/*
2026 		 * Dissolve free hugetlb folios in the memory block before doing
2027 		 * offlining actually in order to make hugetlbfs's object
2028 		 * counting consistent.
2029 		 */
2030 		ret = dissolve_free_hugetlb_folios(start_pfn, end_pfn);
2031 		if (ret) {
2032 			reason = "failure to dissolve huge pages";
2033 			goto failed_removal_isolated;
2034 		}
2035 
2036 		ret = test_pages_isolated(start_pfn, end_pfn,
2037 					  PB_ISOLATE_MODE_MEM_OFFLINE);
2038 
2039 	} while (ret);
2040 
2041 	/* Mark all sections offline and remove free pages from the buddy. */
2042 	managed_pages = __offline_isolated_pages(start_pfn, end_pfn);
2043 	pr_debug("Offlined Pages %ld\n", nr_pages);
2044 
2045 	/*
2046 	 * The memory sections are marked offline, and the pageblock flags
2047 	 * effectively stale; nobody should be touching them. Fixup the number
2048 	 * of isolated pageblocks, memory onlining will properly revert this.
2049 	 */
2050 	spin_lock_irqsave(&zone->lock, flags);
2051 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
2052 	spin_unlock_irqrestore(&zone->lock, flags);
2053 
2054 	lru_cache_enable();
2055 	zone_pcp_enable(zone);
2056 
2057 	/* removal success */
2058 	adjust_managed_page_count(pfn_to_page(start_pfn), -managed_pages);
2059 	adjust_present_page_count(pfn_to_page(start_pfn), group, -nr_pages);
2060 
2061 	/* reinitialise watermarks and update pcp limits */
2062 	init_per_zone_wmark_min();
2063 
2064 	/*
2065 	 * Check whether this operation removes the last normal memory from
2066 	 * the node. We do this before clearing N_MEMORY to avoid the possible
2067 	 * transient "!N_MEMORY && N_NORMAL_MEMORY" state.
2068 	 */
2069 	if (zone_idx(zone) <= ZONE_NORMAL) {
2070 		for (zt = 0; zt <= ZONE_NORMAL; zt++)
2071 			normal_pages += pgdat->node_zones[zt].present_pages;
2072 		if (!normal_pages)
2073 			node_clear_state(node, N_NORMAL_MEMORY);
2074 	}
2075 	/*
2076 	 * Make sure to mark the node as memory-less before rebuilding the zone
2077 	 * list. Otherwise this node would still appear in the fallback lists.
2078 	 */
2079 	if (node_arg.nid >= 0)
2080 		node_clear_state(node, N_MEMORY);
2081 	if (!populated_zone(zone)) {
2082 		zone_pcp_reset(zone);
2083 		build_all_zonelists(NULL);
2084 	}
2085 
2086 	if (node_arg.nid >= 0) {
2087 		kcompactd_stop(node);
2088 		kswapd_stop(node);
2089 		/* Node went memoryless. Notify consumers */
2090 		node_notify(NODE_REMOVED_LAST_MEMORY, &node_arg);
2091 	}
2092 
2093 	writeback_set_ratelimit();
2094 
2095 	memory_notify(MEM_OFFLINE, &mem_arg);
2096 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
2097 	return 0;
2098 
2099 failed_removal_isolated:
2100 	/* pushback to free area */
2101 	undo_isolate_page_range(start_pfn, end_pfn);
2102 	memory_notify(MEM_CANCEL_OFFLINE, &mem_arg);
2103 	if (node_arg.nid != NUMA_NO_NODE)
2104 		node_notify(NODE_CANCEL_REMOVING_LAST_MEMORY, &node_arg);
2105 failed_removal_pcplists_disabled:
2106 	lru_cache_enable();
2107 	zone_pcp_enable(zone);
2108 failed_removal:
2109 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
2110 		 (unsigned long long) start_pfn << PAGE_SHIFT,
2111 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
2112 		 reason);
2113 	return ret;
2114 }
2115 
check_memblock_offlined_cb(struct memory_block * mem,void * arg)2116 static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
2117 {
2118 	int *nid = arg;
2119 
2120 	*nid = mem->nid;
2121 	if (unlikely(mem->state != MEM_OFFLINE)) {
2122 		phys_addr_t beginpa, endpa;
2123 
2124 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
2125 		endpa = beginpa + memory_block_size_bytes() - 1;
2126 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
2127 			&beginpa, &endpa);
2128 
2129 		return -EBUSY;
2130 	}
2131 	return 0;
2132 }
2133 
count_memory_range_altmaps_cb(struct memory_block * mem,void * arg)2134 static int count_memory_range_altmaps_cb(struct memory_block *mem, void *arg)
2135 {
2136 	u64 *num_altmaps = (u64 *)arg;
2137 
2138 	if (mem->altmap)
2139 		*num_altmaps += 1;
2140 
2141 	return 0;
2142 }
2143 
check_cpu_on_node(int nid)2144 static int check_cpu_on_node(int nid)
2145 {
2146 	int cpu;
2147 
2148 	for_each_present_cpu(cpu) {
2149 		if (cpu_to_node(cpu) == nid)
2150 			/*
2151 			 * the cpu on this node isn't removed, and we can't
2152 			 * offline this node.
2153 			 */
2154 			return -EBUSY;
2155 	}
2156 
2157 	return 0;
2158 }
2159 
check_no_memblock_for_node_cb(struct memory_block * mem,void * arg)2160 static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
2161 {
2162 	int nid = *(int *)arg;
2163 
2164 	/*
2165 	 * If a memory block belongs to multiple nodes, the stored nid is not
2166 	 * reliable. However, such blocks are always online (e.g., cannot get
2167 	 * offlined) and, therefore, are still spanned by the node.
2168 	 */
2169 	return mem->nid == nid ? -EEXIST : 0;
2170 }
2171 
2172 /**
2173  * try_offline_node
2174  * @nid: the node ID
2175  *
2176  * Offline a node if all memory sections and cpus of the node are removed.
2177  *
2178  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2179  * and online/offline operations before this call.
2180  */
try_offline_node(int nid)2181 void try_offline_node(int nid)
2182 {
2183 	int rc;
2184 
2185 	/*
2186 	 * If the node still spans pages (especially ZONE_DEVICE), don't
2187 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
2188 	 * e.g., after the memory block was onlined.
2189 	 */
2190 	if (node_spanned_pages(nid))
2191 		return;
2192 
2193 	/*
2194 	 * Especially offline memory blocks might not be spanned by the
2195 	 * node. They will get spanned by the node once they get onlined.
2196 	 * However, they link to the node in sysfs and can get onlined later.
2197 	 */
2198 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
2199 	if (rc)
2200 		return;
2201 
2202 	if (check_cpu_on_node(nid))
2203 		return;
2204 
2205 	/*
2206 	 * all memory/cpu of this node are removed, we can offline this
2207 	 * node now.
2208 	 */
2209 	node_set_offline(nid);
2210 	unregister_node(nid);
2211 }
2212 EXPORT_SYMBOL(try_offline_node);
2213 
memory_blocks_have_altmaps(u64 start,u64 size)2214 static int memory_blocks_have_altmaps(u64 start, u64 size)
2215 {
2216 	u64 num_memblocks = size / memory_block_size_bytes();
2217 	u64 num_altmaps = 0;
2218 
2219 	if (!mhp_memmap_on_memory())
2220 		return 0;
2221 
2222 	walk_memory_blocks(start, size, &num_altmaps,
2223 			   count_memory_range_altmaps_cb);
2224 
2225 	if (num_altmaps == 0)
2226 		return 0;
2227 
2228 	if (WARN_ON_ONCE(num_memblocks != num_altmaps))
2229 		return -EINVAL;
2230 
2231 	return 1;
2232 }
2233 
try_remove_memory(u64 start,u64 size)2234 static int try_remove_memory(u64 start, u64 size)
2235 {
2236 	int rc, nid = NUMA_NO_NODE;
2237 
2238 	BUG_ON(check_hotplug_memory_range(start, size));
2239 
2240 	/*
2241 	 * All memory blocks must be offlined before removing memory.  Check
2242 	 * whether all memory blocks in question are offline and return error
2243 	 * if this is not the case.
2244 	 *
2245 	 * While at it, determine the nid. Note that if we'd have mixed nodes,
2246 	 * we'd only try to offline the last determined one -- which is good
2247 	 * enough for the cases we care about.
2248 	 */
2249 	rc = walk_memory_blocks(start, size, &nid, check_memblock_offlined_cb);
2250 	if (rc)
2251 		return rc;
2252 
2253 	/* remove memmap entry */
2254 	firmware_map_remove(start, start + size, "System RAM");
2255 
2256 	mem_hotplug_begin();
2257 
2258 	rc = memory_blocks_have_altmaps(start, size);
2259 	if (rc < 0) {
2260 		mem_hotplug_done();
2261 		return rc;
2262 	} else if (!rc) {
2263 		/*
2264 		 * Memory block device removal under the device_hotplug_lock is
2265 		 * a barrier against racing online attempts.
2266 		 * No altmaps present, do the removal directly
2267 		 */
2268 		remove_memory_block_devices(start, size);
2269 		arch_remove_memory(start, size, NULL);
2270 	} else {
2271 		/* all memblocks in the range have altmaps */
2272 		remove_memory_blocks_and_altmaps(start, size);
2273 	}
2274 
2275 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
2276 		memblock_remove(start, size);
2277 
2278 	release_mem_region_adjustable(start, size);
2279 
2280 	if (nid != NUMA_NO_NODE)
2281 		try_offline_node(nid);
2282 
2283 	mem_hotplug_done();
2284 	return 0;
2285 }
2286 
2287 /**
2288  * __remove_memory - Remove memory if every memory block is offline
2289  * @start: physical address of the region to remove
2290  * @size: size of the region to remove
2291  *
2292  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2293  * and online/offline operations before this call, as required by
2294  * try_offline_node().
2295  */
__remove_memory(u64 start,u64 size)2296 void __remove_memory(u64 start, u64 size)
2297 {
2298 
2299 	/*
2300 	 * trigger BUG() if some memory is not offlined prior to calling this
2301 	 * function
2302 	 */
2303 	if (try_remove_memory(start, size))
2304 		BUG();
2305 }
2306 
2307 /*
2308  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2309  * some memory is not offline
2310  */
remove_memory(u64 start,u64 size)2311 int remove_memory(u64 start, u64 size)
2312 {
2313 	int rc;
2314 
2315 	lock_device_hotplug();
2316 	rc = try_remove_memory(start, size);
2317 	unlock_device_hotplug();
2318 
2319 	return rc;
2320 }
2321 EXPORT_SYMBOL_GPL(remove_memory);
2322 
try_offline_memory_block(struct memory_block * mem,void * arg)2323 static int try_offline_memory_block(struct memory_block *mem, void *arg)
2324 {
2325 	enum mmop online_type = MMOP_ONLINE_KERNEL;
2326 	uint8_t **online_types = arg;
2327 	struct page *page;
2328 	int rc;
2329 
2330 	/*
2331 	 * Sense the online_type via the zone of the memory block. Offlining
2332 	 * with multiple zones within one memory block will be rejected
2333 	 * by offlining code ... so we don't care about that.
2334 	 */
2335 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
2336 	if (page && page_zonenum(page) == ZONE_MOVABLE)
2337 		online_type = MMOP_ONLINE_MOVABLE;
2338 
2339 	rc = device_offline(&mem->dev);
2340 	/*
2341 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
2342 	 * so try_reonline_memory_block() can do the right thing.
2343 	 */
2344 	if (!rc)
2345 		**online_types = online_type;
2346 
2347 	(*online_types)++;
2348 	/* Ignore if already offline. */
2349 	return rc < 0 ? rc : 0;
2350 }
2351 
try_reonline_memory_block(struct memory_block * mem,void * arg)2352 static int try_reonline_memory_block(struct memory_block *mem, void *arg)
2353 {
2354 	uint8_t **online_types = arg;
2355 	int rc;
2356 
2357 	if (**online_types != MMOP_OFFLINE) {
2358 		mem->online_type = (enum mmop)**online_types;
2359 		rc = device_online(&mem->dev);
2360 		if (rc < 0)
2361 			pr_warn("%s: Failed to re-online memory: %d",
2362 				__func__, rc);
2363 	}
2364 
2365 	/* Continue processing all remaining memory blocks. */
2366 	(*online_types)++;
2367 	return 0;
2368 }
2369 
2370 /*
2371  * Try to offline and remove memory. Might take a long time to finish in case
2372  * memory is still in use. Primarily useful for memory devices that logically
2373  * unplugged all memory (so it's no longer in use) and want to offline + remove
2374  * that memory.
2375  */
offline_and_remove_memory(u64 start,u64 size)2376 int offline_and_remove_memory(u64 start, u64 size)
2377 {
2378 	const unsigned long mb_count = size / memory_block_size_bytes();
2379 	uint8_t *online_types, *tmp;
2380 	int rc;
2381 
2382 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
2383 	    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
2384 		return -EINVAL;
2385 
2386 	/*
2387 	 * We'll remember the old online type of each memory block, so we can
2388 	 * try to revert whatever we did when offlining one memory block fails
2389 	 * after offlining some others succeeded.
2390 	 */
2391 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
2392 				     GFP_KERNEL);
2393 	if (!online_types)
2394 		return -ENOMEM;
2395 	/*
2396 	 * Initialize all states to MMOP_OFFLINE, so when we abort processing in
2397 	 * try_offline_memory_block(), we'll skip all unprocessed blocks in
2398 	 * try_reonline_memory_block().
2399 	 */
2400 	memset(online_types, MMOP_OFFLINE, mb_count);
2401 
2402 	lock_device_hotplug();
2403 
2404 	tmp = online_types;
2405 	rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
2406 
2407 	/*
2408 	 * In case we succeeded to offline all memory, remove it.
2409 	 * This cannot fail as it cannot get onlined in the meantime.
2410 	 */
2411 	if (!rc) {
2412 		rc = try_remove_memory(start, size);
2413 		if (rc)
2414 			pr_err("%s: Failed to remove memory: %d", __func__, rc);
2415 	}
2416 
2417 	/*
2418 	 * Rollback what we did. While memory onlining might theoretically fail
2419 	 * (nacked by a notifier), it barely ever happens.
2420 	 */
2421 	if (rc) {
2422 		tmp = online_types;
2423 		walk_memory_blocks(start, size, &tmp,
2424 				   try_reonline_memory_block);
2425 	}
2426 	unlock_device_hotplug();
2427 
2428 	kfree(online_types);
2429 	return rc;
2430 }
2431 EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2432 #endif /* CONFIG_MEMORY_HOTREMOVE */
2433