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