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