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