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