xref: /linux/drivers/base/memory.c (revision a552c81ff4a16738ca5a44a177d552eb38d552ce)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Memory subsystem support
4  *
5  * Written by Matt Tolentino <matthew.e.tolentino@intel.com>
6  *            Dave Hansen <haveblue@us.ibm.com>
7  *
8  * This file provides the necessary infrastructure to represent
9  * a SPARSEMEM-memory-model system's physical memory in /sysfs.
10  * All arch-independent code that assumes MEMORY_HOTPLUG requires
11  * SPARSEMEM should be contained here, or in mm/memory_hotplug.c.
12  */
13 
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/topology.h>
17 #include <linux/capability.h>
18 #include <linux/device.h>
19 #include <linux/memory.h>
20 #include <linux/memory_hotplug.h>
21 #include <linux/mm.h>
22 #include <linux/stat.h>
23 #include <linux/slab.h>
24 #include <linux/xarray.h>
25 #include <linux/export.h>
26 
27 #include <linux/atomic.h>
28 #include <linux/uaccess.h>
29 
30 #define MEMORY_CLASS_NAME	"memory"
31 
32 static const char *const online_type_to_str[] = {
33 	[MMOP_OFFLINE] = "offline",
34 	[MMOP_ONLINE] = "online",
35 	[MMOP_ONLINE_KERNEL] = "online_kernel",
36 	[MMOP_ONLINE_MOVABLE] = "online_movable",
37 };
38 
39 int mhp_online_type_from_str(const char *str)
40 {
41 	int i;
42 
43 	for (i = 0; i < ARRAY_SIZE(online_type_to_str); i++) {
44 		if (sysfs_streq(str, online_type_to_str[i]))
45 			return i;
46 	}
47 	return -EINVAL;
48 }
49 
50 #define to_memory_block(dev) container_of(dev, struct memory_block, dev)
51 
52 int sections_per_block;
53 EXPORT_SYMBOL(sections_per_block);
54 
55 static int memory_subsys_online(struct device *dev);
56 static int memory_subsys_offline(struct device *dev);
57 
58 static const struct bus_type memory_subsys = {
59 	.name = MEMORY_CLASS_NAME,
60 	.dev_name = MEMORY_CLASS_NAME,
61 	.online = memory_subsys_online,
62 	.offline = memory_subsys_offline,
63 };
64 
65 /*
66  * Memory blocks are cached in a local radix tree to avoid
67  * a costly linear search for the corresponding device on
68  * the subsystem bus.
69  */
70 static DEFINE_XARRAY(memory_blocks);
71 
72 /*
73  * Memory groups, indexed by memory group id (mgid).
74  */
75 static DEFINE_XARRAY_FLAGS(memory_groups, XA_FLAGS_ALLOC);
76 #define MEMORY_GROUP_MARK_DYNAMIC	XA_MARK_1
77 
78 static BLOCKING_NOTIFIER_HEAD(memory_chain);
79 
80 int register_memory_notifier(struct notifier_block *nb)
81 {
82 	return blocking_notifier_chain_register(&memory_chain, nb);
83 }
84 EXPORT_SYMBOL(register_memory_notifier);
85 
86 void unregister_memory_notifier(struct notifier_block *nb)
87 {
88 	blocking_notifier_chain_unregister(&memory_chain, nb);
89 }
90 EXPORT_SYMBOL(unregister_memory_notifier);
91 
92 static void memory_block_release(struct device *dev)
93 {
94 	struct memory_block *mem = to_memory_block(dev);
95 	/* Verify that the altmap is freed */
96 	WARN_ON(mem->altmap);
97 	kfree(mem);
98 }
99 
100 
101 /* Max block size to be set by memory_block_advise_max_size */
102 static unsigned long memory_block_advised_size;
103 static bool memory_block_advised_size_queried;
104 
105 /**
106  * memory_block_advise_max_size() - advise memory hotplug on the max suggested
107  *				    block size, usually for alignment.
108  * @size: suggestion for maximum block size. must be aligned on power of 2.
109  *
110  * Early boot software (pre-allocator init) may advise archs on the max block
111  * size. This value can only decrease after initialization, as the intent is
112  * to identify the largest supported alignment for all sources.
113  *
114  * Use of this value is arch-defined, as is min/max block size.
115  *
116  * Return: 0 on success
117  *	   -EINVAL if size is 0 or not pow2 aligned
118  *	   -EBUSY if value has already been probed
119  */
120 int __init memory_block_advise_max_size(unsigned long size)
121 {
122 	if (!size || !is_power_of_2(size))
123 		return -EINVAL;
124 
125 	if (memory_block_advised_size_queried)
126 		return -EBUSY;
127 
128 	if (memory_block_advised_size)
129 		memory_block_advised_size = min(memory_block_advised_size, size);
130 	else
131 		memory_block_advised_size = size;
132 
133 	return 0;
134 }
135 
136 /**
137  * memory_block_advised_max_size() - query advised max hotplug block size.
138  *
139  * After the first call, the value can never change. Callers looking for the
140  * actual block size should use memory_block_size_bytes. This interface is
141  * intended for use by arch-init when initializing the hotplug block size.
142  *
143  * Return: advised size in bytes, or 0 if never set.
144  */
145 unsigned long memory_block_advised_max_size(void)
146 {
147 	memory_block_advised_size_queried = true;
148 	return memory_block_advised_size;
149 }
150 
151 unsigned long __weak memory_block_size_bytes(void)
152 {
153 	return MIN_MEMORY_BLOCK_SIZE;
154 }
155 EXPORT_SYMBOL_GPL(memory_block_size_bytes);
156 
157 /* Show the memory block ID, relative to the memory block size */
158 static ssize_t phys_index_show(struct device *dev,
159 			       struct device_attribute *attr, char *buf)
160 {
161 	struct memory_block *mem = to_memory_block(dev);
162 
163 	return sysfs_emit(buf, "%08lx\n", memory_block_id(mem->start_section_nr));
164 }
165 
166 /*
167  * Legacy interface that we cannot remove. Always indicate "removable"
168  * with CONFIG_MEMORY_HOTREMOVE - bad heuristic.
169  */
170 static ssize_t removable_show(struct device *dev, struct device_attribute *attr,
171 			      char *buf)
172 {
173 	return sysfs_emit(buf, "%d\n", (int)IS_ENABLED(CONFIG_MEMORY_HOTREMOVE));
174 }
175 
176 /*
177  * online, offline, going offline, etc.
178  */
179 static ssize_t state_show(struct device *dev, struct device_attribute *attr,
180 			  char *buf)
181 {
182 	struct memory_block *mem = to_memory_block(dev);
183 	const char *output;
184 
185 	/*
186 	 * We can probably put these states in a nice little array
187 	 * so that they're not open-coded
188 	 */
189 	switch (mem->state) {
190 	case MEM_ONLINE:
191 		output = "online";
192 		break;
193 	case MEM_OFFLINE:
194 		output = "offline";
195 		break;
196 	case MEM_GOING_OFFLINE:
197 		output = "going-offline";
198 		break;
199 	default:
200 		WARN_ON(1);
201 		return sysfs_emit(buf, "ERROR-UNKNOWN-%d\n", mem->state);
202 	}
203 
204 	return sysfs_emit(buf, "%s\n", output);
205 }
206 
207 int memory_notify(enum memory_block_state state, void *v)
208 {
209 	return blocking_notifier_call_chain(&memory_chain, state, v);
210 }
211 
212 #if defined(CONFIG_MEMORY_FAILURE) && defined(CONFIG_MEMORY_HOTPLUG)
213 static unsigned long memblk_nr_poison(struct memory_block *mem);
214 #else
215 static inline unsigned long memblk_nr_poison(struct memory_block *mem)
216 {
217 	return 0;
218 }
219 #endif
220 
221 /*
222  * Must acquire mem_hotplug_lock in write mode.
223  */
224 static int memory_block_online(struct memory_block *mem)
225 {
226 	unsigned long start_pfn = section_nr_to_pfn(mem->start_section_nr);
227 	unsigned long nr_pages = PAGES_PER_SECTION * sections_per_block;
228 	unsigned long nr_vmemmap_pages = 0;
229 	struct zone *zone;
230 	int ret;
231 
232 	if (memblk_nr_poison(mem))
233 		return -EHWPOISON;
234 
235 	zone = zone_for_pfn_range(mem->online_type, mem->nid, mem->group,
236 				  start_pfn, nr_pages);
237 
238 	/*
239 	 * Although vmemmap pages have a different lifecycle than the pages
240 	 * they describe (they remain until the memory is unplugged), doing
241 	 * their initialization and accounting at memory onlining/offlining
242 	 * stage helps to keep accounting easier to follow - e.g vmemmaps
243 	 * belong to the same zone as the memory they backed.
244 	 */
245 	if (mem->altmap)
246 		nr_vmemmap_pages = mem->altmap->free;
247 
248 	mem_hotplug_begin();
249 	if (nr_vmemmap_pages) {
250 		ret = mhp_init_memmap_on_memory(start_pfn, nr_vmemmap_pages, zone);
251 		if (ret)
252 			goto out;
253 	}
254 
255 	ret = online_pages(start_pfn + nr_vmemmap_pages,
256 			   nr_pages - nr_vmemmap_pages, zone, mem->group);
257 	if (ret) {
258 		if (nr_vmemmap_pages)
259 			mhp_deinit_memmap_on_memory(start_pfn, nr_vmemmap_pages);
260 		goto out;
261 	}
262 
263 	/*
264 	 * Account once onlining succeeded. If the zone was unpopulated, it is
265 	 * now already properly populated.
266 	 */
267 	if (nr_vmemmap_pages)
268 		adjust_present_page_count(pfn_to_page(start_pfn), mem->group,
269 					  nr_vmemmap_pages);
270 
271 	mem->zone = zone;
272 out:
273 	mem_hotplug_done();
274 	return ret;
275 }
276 
277 /*
278  * Must acquire mem_hotplug_lock in write mode.
279  */
280 static int memory_block_offline(struct memory_block *mem)
281 {
282 	unsigned long start_pfn = section_nr_to_pfn(mem->start_section_nr);
283 	unsigned long nr_pages = PAGES_PER_SECTION * sections_per_block;
284 	unsigned long nr_vmemmap_pages = 0;
285 	int ret;
286 
287 	if (!mem->zone)
288 		return -EINVAL;
289 
290 	/*
291 	 * Unaccount before offlining, such that unpopulated zone and kthreads
292 	 * can properly be torn down in offline_pages().
293 	 */
294 	if (mem->altmap)
295 		nr_vmemmap_pages = mem->altmap->free;
296 
297 	mem_hotplug_begin();
298 	if (nr_vmemmap_pages)
299 		adjust_present_page_count(pfn_to_page(start_pfn), mem->group,
300 					  -nr_vmemmap_pages);
301 
302 	ret = offline_pages(start_pfn + nr_vmemmap_pages,
303 			    nr_pages - nr_vmemmap_pages, mem->zone, mem->group);
304 	if (ret) {
305 		/* offline_pages() failed. Account back. */
306 		if (nr_vmemmap_pages)
307 			adjust_present_page_count(pfn_to_page(start_pfn),
308 						  mem->group, nr_vmemmap_pages);
309 		goto out;
310 	}
311 
312 	if (nr_vmemmap_pages)
313 		mhp_deinit_memmap_on_memory(start_pfn, nr_vmemmap_pages);
314 
315 	mem->zone = NULL;
316 out:
317 	mem_hotplug_done();
318 	return ret;
319 }
320 
321 /*
322  * MEMORY_HOTPLUG depends on SPARSEMEM in mm/Kconfig, so it is
323  * OK to have direct references to sparsemem variables in here.
324  */
325 static int
326 memory_block_action(struct memory_block *mem, unsigned long action)
327 {
328 	int ret;
329 
330 	switch (action) {
331 	case MEM_ONLINE:
332 		ret = memory_block_online(mem);
333 		break;
334 	case MEM_OFFLINE:
335 		ret = memory_block_offline(mem);
336 		break;
337 	default:
338 		WARN(1, KERN_WARNING "%s(%ld, %ld) unknown action: "
339 		     "%ld\n", __func__, mem->start_section_nr, action, action);
340 		ret = -EINVAL;
341 	}
342 
343 	return ret;
344 }
345 
346 static int memory_block_change_state(struct memory_block *mem,
347 		unsigned long to_state, unsigned long from_state_req)
348 {
349 	int ret = 0;
350 
351 	if (mem->state != from_state_req)
352 		return -EINVAL;
353 
354 	if (to_state == MEM_OFFLINE)
355 		mem->state = MEM_GOING_OFFLINE;
356 
357 	ret = memory_block_action(mem, to_state);
358 	mem->state = ret ? from_state_req : to_state;
359 
360 	return ret;
361 }
362 
363 /* The device lock serializes operations on memory_subsys_[online|offline] */
364 static int memory_subsys_online(struct device *dev)
365 {
366 	struct memory_block *mem = to_memory_block(dev);
367 	int ret;
368 
369 	if (mem->state == MEM_ONLINE)
370 		return 0;
371 
372 	/*
373 	 * When called via device_online() without configuring the online_type,
374 	 * we want to default to MMOP_ONLINE.
375 	 */
376 	if (mem->online_type == MMOP_OFFLINE)
377 		mem->online_type = MMOP_ONLINE;
378 
379 	ret = memory_block_change_state(mem, MEM_ONLINE, MEM_OFFLINE);
380 	mem->online_type = MMOP_OFFLINE;
381 
382 	return ret;
383 }
384 
385 static int memory_subsys_offline(struct device *dev)
386 {
387 	struct memory_block *mem = to_memory_block(dev);
388 
389 	if (mem->state == MEM_OFFLINE)
390 		return 0;
391 
392 	return memory_block_change_state(mem, MEM_OFFLINE, MEM_ONLINE);
393 }
394 
395 static ssize_t state_store(struct device *dev, struct device_attribute *attr,
396 			   const char *buf, size_t count)
397 {
398 	const int online_type = mhp_online_type_from_str(buf);
399 	struct memory_block *mem = to_memory_block(dev);
400 	int ret;
401 
402 	if (online_type < 0)
403 		return -EINVAL;
404 
405 	ret = lock_device_hotplug_sysfs();
406 	if (ret)
407 		return ret;
408 
409 	switch (online_type) {
410 	case MMOP_ONLINE_KERNEL:
411 	case MMOP_ONLINE_MOVABLE:
412 	case MMOP_ONLINE:
413 		/* mem->online_type is protected by device_hotplug_lock */
414 		mem->online_type = online_type;
415 		ret = device_online(&mem->dev);
416 		break;
417 	case MMOP_OFFLINE:
418 		ret = device_offline(&mem->dev);
419 		break;
420 	default:
421 		ret = -EINVAL; /* should never happen */
422 	}
423 
424 	unlock_device_hotplug();
425 
426 	if (ret < 0)
427 		return ret;
428 	if (ret)
429 		return -EINVAL;
430 
431 	return count;
432 }
433 
434 /*
435  * Legacy interface that we cannot remove: s390x exposes the storage increment
436  * covered by a memory block, allowing for identifying which memory blocks
437  * comprise a storage increment. Since a memory block spans complete
438  * storage increments nowadays, this interface is basically unused. Other
439  * archs never exposed != 0.
440  */
441 static ssize_t phys_device_show(struct device *dev,
442 				struct device_attribute *attr, char *buf)
443 {
444 	struct memory_block *mem = to_memory_block(dev);
445 	unsigned long start_pfn = section_nr_to_pfn(mem->start_section_nr);
446 
447 	return sysfs_emit(buf, "%d\n",
448 			  arch_get_memory_phys_device(start_pfn));
449 }
450 
451 #ifdef CONFIG_MEMORY_HOTREMOVE
452 static int print_allowed_zone(char *buf, int len, int nid,
453 			      struct memory_group *group,
454 			      unsigned long start_pfn, unsigned long nr_pages,
455 			      enum mmop online_type, struct zone *default_zone)
456 {
457 	struct zone *zone;
458 
459 	zone = zone_for_pfn_range(online_type, nid, group, start_pfn, nr_pages);
460 	if (zone == default_zone)
461 		return 0;
462 
463 	return sysfs_emit_at(buf, len, " %s", zone->name);
464 }
465 
466 static ssize_t valid_zones_show(struct device *dev,
467 				struct device_attribute *attr, char *buf)
468 {
469 	struct memory_block *mem = to_memory_block(dev);
470 	unsigned long start_pfn = section_nr_to_pfn(mem->start_section_nr);
471 	unsigned long nr_pages = PAGES_PER_SECTION * sections_per_block;
472 	struct memory_group *group = mem->group;
473 	struct zone *default_zone;
474 	int nid = mem->nid;
475 	int len;
476 
477 	/*
478 	 * Check the existing zone. Make sure that we do that only on the
479 	 * online nodes otherwise the page_zone is not reliable
480 	 */
481 	if (mem->state == MEM_ONLINE) {
482 		/*
483 		 * If !mem->zone, the memory block spans multiple zones and
484 		 * cannot get offlined.
485 		 */
486 		return sysfs_emit(buf, "%s\n",
487 				  mem->zone ? mem->zone->name : "none");
488 	}
489 
490 	default_zone = zone_for_pfn_range(MMOP_ONLINE, nid, group,
491 					  start_pfn, nr_pages);
492 
493 	len = sysfs_emit(buf, "%s", default_zone->name);
494 	len += print_allowed_zone(buf, len, nid, group, start_pfn, nr_pages,
495 				  MMOP_ONLINE_KERNEL, default_zone);
496 	len += print_allowed_zone(buf, len, nid, group, start_pfn, nr_pages,
497 				  MMOP_ONLINE_MOVABLE, default_zone);
498 	len += sysfs_emit_at(buf, len, "\n");
499 	return len;
500 }
501 static DEVICE_ATTR_RO(valid_zones);
502 #endif
503 
504 static DEVICE_ATTR_RO(phys_index);
505 static DEVICE_ATTR_RW(state);
506 static DEVICE_ATTR_RO(phys_device);
507 static DEVICE_ATTR_RO(removable);
508 
509 /*
510  * Show the memory block size (shared by all memory blocks).
511  */
512 static ssize_t block_size_bytes_show(struct device *dev,
513 				     struct device_attribute *attr, char *buf)
514 {
515 	return sysfs_emit(buf, "%lx\n", memory_block_size_bytes());
516 }
517 
518 static DEVICE_ATTR_RO(block_size_bytes);
519 
520 /*
521  * Memory auto online policy.
522  */
523 
524 static ssize_t auto_online_blocks_show(struct device *dev,
525 				       struct device_attribute *attr, char *buf)
526 {
527 	return sysfs_emit(buf, "%s\n",
528 			  online_type_to_str[mhp_get_default_online_type()]);
529 }
530 
531 static ssize_t auto_online_blocks_store(struct device *dev,
532 					struct device_attribute *attr,
533 					const char *buf, size_t count)
534 {
535 	const int online_type = mhp_online_type_from_str(buf);
536 
537 	if (online_type < 0)
538 		return -EINVAL;
539 
540 	mhp_set_default_online_type(online_type);
541 	return count;
542 }
543 
544 static DEVICE_ATTR_RW(auto_online_blocks);
545 
546 #ifdef CONFIG_CRASH_HOTPLUG
547 #include <linux/kexec.h>
548 static ssize_t crash_hotplug_show(struct device *dev,
549 				       struct device_attribute *attr, char *buf)
550 {
551 	return sysfs_emit(buf, "%d\n", crash_check_hotplug_support());
552 }
553 static DEVICE_ATTR_RO(crash_hotplug);
554 #endif
555 
556 /*
557  * Some architectures will have custom drivers to do this, and
558  * will not need to do it from userspace.  The fake hot-add code
559  * as well as ppc64 will do all of their discovery in userspace
560  * and will require this interface.
561  */
562 #ifdef CONFIG_ARCH_MEMORY_PROBE
563 static ssize_t probe_store(struct device *dev, struct device_attribute *attr,
564 			   const char *buf, size_t count)
565 {
566 	u64 phys_addr;
567 	int nid, ret;
568 	unsigned long pages_per_block = PAGES_PER_SECTION * sections_per_block;
569 
570 	ret = kstrtoull(buf, 0, &phys_addr);
571 	if (ret)
572 		return ret;
573 
574 	if (phys_addr & ((pages_per_block << PAGE_SHIFT) - 1))
575 		return -EINVAL;
576 
577 	ret = lock_device_hotplug_sysfs();
578 	if (ret)
579 		return ret;
580 
581 	nid = memory_add_physaddr_to_nid(phys_addr);
582 	ret = __add_memory(nid, phys_addr,
583 			   MIN_MEMORY_BLOCK_SIZE * sections_per_block,
584 			   MHP_NONE);
585 
586 	if (ret)
587 		goto out;
588 
589 	ret = count;
590 out:
591 	unlock_device_hotplug();
592 	return ret;
593 }
594 
595 static DEVICE_ATTR_WO(probe);
596 #endif
597 
598 #ifdef CONFIG_MEMORY_FAILURE
599 /*
600  * Support for offlining pages of memory
601  */
602 
603 /* Soft offline a page */
604 static ssize_t soft_offline_page_store(struct device *dev,
605 				       struct device_attribute *attr,
606 				       const char *buf, size_t count)
607 {
608 	int ret;
609 	u64 pfn;
610 	if (!capable(CAP_SYS_ADMIN))
611 		return -EPERM;
612 	if (kstrtoull(buf, 0, &pfn) < 0)
613 		return -EINVAL;
614 	pfn >>= PAGE_SHIFT;
615 	ret = soft_offline_page(pfn, 0);
616 	return ret == 0 ? count : ret;
617 }
618 
619 /* Forcibly offline a page, including killing processes. */
620 static ssize_t hard_offline_page_store(struct device *dev,
621 				       struct device_attribute *attr,
622 				       const char *buf, size_t count)
623 {
624 	int ret;
625 	u64 pfn;
626 	if (!capable(CAP_SYS_ADMIN))
627 		return -EPERM;
628 	if (kstrtoull(buf, 0, &pfn) < 0)
629 		return -EINVAL;
630 	pfn >>= PAGE_SHIFT;
631 	ret = memory_failure(pfn, MF_SW_SIMULATED);
632 	if (ret == -EOPNOTSUPP)
633 		ret = 0;
634 	return ret ? ret : count;
635 }
636 
637 static DEVICE_ATTR_WO(soft_offline_page);
638 static DEVICE_ATTR_WO(hard_offline_page);
639 #endif
640 
641 /* See phys_device_show(). */
642 int __weak arch_get_memory_phys_device(unsigned long start_pfn)
643 {
644 	return 0;
645 }
646 
647 /*
648  * A reference for the returned memory block device is acquired.
649  *
650  * Called under device_hotplug_lock.
651  */
652 struct memory_block *memory_block_get(unsigned long block_id)
653 {
654 	struct memory_block *mem;
655 
656 	mem = xa_load(&memory_blocks, block_id);
657 	if (mem)
658 		get_device(&mem->dev);
659 	return mem;
660 }
661 
662 static struct attribute *memory_memblk_attrs[] = {
663 	&dev_attr_phys_index.attr,
664 	&dev_attr_state.attr,
665 	&dev_attr_phys_device.attr,
666 	&dev_attr_removable.attr,
667 #ifdef CONFIG_MEMORY_HOTREMOVE
668 	&dev_attr_valid_zones.attr,
669 #endif
670 	NULL
671 };
672 
673 static const struct attribute_group memory_memblk_attr_group = {
674 	.attrs = memory_memblk_attrs,
675 };
676 
677 static const struct attribute_group *memory_memblk_attr_groups[] = {
678 	&memory_memblk_attr_group,
679 	NULL,
680 };
681 
682 static int __add_memory_block(struct memory_block *memory)
683 {
684 	int ret;
685 
686 	memory->dev.bus = &memory_subsys;
687 	memory->dev.id = memory->start_section_nr / sections_per_block;
688 	memory->dev.release = memory_block_release;
689 	memory->dev.groups = memory_memblk_attr_groups;
690 	dev_assign_offline(&memory->dev, memory->state == MEM_OFFLINE);
691 
692 	ret = device_register(&memory->dev);
693 	if (ret) {
694 		memory_block_put(memory);
695 		return ret;
696 	}
697 	ret = xa_err(xa_store(&memory_blocks, memory->dev.id, memory,
698 			      GFP_KERNEL));
699 	if (ret)
700 		device_unregister(&memory->dev);
701 
702 	return ret;
703 }
704 
705 static struct zone *early_node_zone_for_memory_block(struct memory_block *mem,
706 						     int nid)
707 {
708 	const unsigned long start_pfn = section_nr_to_pfn(mem->start_section_nr);
709 	const unsigned long nr_pages = PAGES_PER_SECTION * sections_per_block;
710 	struct zone *zone, *matching_zone = NULL;
711 	pg_data_t *pgdat = NODE_DATA(nid);
712 	int i;
713 
714 	/*
715 	 * This logic only works for early memory, when the applicable zones
716 	 * already span the memory block. We don't expect overlapping zones on
717 	 * a single node for early memory. So if we're told that some PFNs
718 	 * of a node fall into this memory block, we can assume that all node
719 	 * zones that intersect with the memory block are actually applicable.
720 	 * No need to look at the memmap.
721 	 */
722 	for (i = 0; i < MAX_NR_ZONES; i++) {
723 		zone = pgdat->node_zones + i;
724 		if (!populated_zone(zone))
725 			continue;
726 		if (!zone_intersects(zone, start_pfn, nr_pages))
727 			continue;
728 		if (!matching_zone) {
729 			matching_zone = zone;
730 			continue;
731 		}
732 		/* Spans multiple zones ... */
733 		matching_zone = NULL;
734 		break;
735 	}
736 	return matching_zone;
737 }
738 
739 #ifdef CONFIG_NUMA
740 /**
741  * memory_block_add_nid_early() - Indicate that early system RAM falling into
742  *				  this memory block device (partially) belongs
743  *				  to the given node.
744  * @mem: The memory block device.
745  * @nid: The node id.
746  *
747  * Indicate that early system RAM falling into this memory block (partially)
748  * belongs to the given node. This will also properly set/adjust mem->zone based
749  * on the zone ranges of the given node.
750  *
751  * Memory hotplug handles this on memory block creation, where we can only have
752  * a single nid span a memory block.
753  */
754 void memory_block_add_nid_early(struct memory_block *mem, int nid)
755 {
756 	if (mem->nid != nid) {
757 		/*
758 		 * For early memory we have to determine the zone when setting
759 		 * the node id and handle multiple nodes spanning a single
760 		 * memory block by indicate via zone == NULL that we're not
761 		 * dealing with a single zone. So if we're setting the node id
762 		 * the first time, determine if there is a single zone. If we're
763 		 * setting the node id a second time to a different node,
764 		 * invalidate the single detected zone.
765 		 */
766 		if (mem->nid == NUMA_NO_NODE)
767 			mem->zone = early_node_zone_for_memory_block(mem, nid);
768 		else
769 			mem->zone = NULL;
770 		/*
771 		 * If this memory block spans multiple nodes, we only indicate
772 		 * the last processed node. If we span multiple nodes (not applicable
773 		 * to hotplugged memory), zone == NULL will prohibit memory offlining
774 		 * and consequently unplug.
775 		 */
776 		mem->nid = nid;
777 	}
778 }
779 #endif
780 
781 static int add_memory_block(unsigned long block_id, int nid, unsigned long state,
782 			    struct vmem_altmap *altmap,
783 			    struct memory_group *group)
784 {
785 	struct memory_block *mem;
786 	int ret = 0;
787 
788 	mem = memory_block_get(block_id);
789 	if (mem) {
790 		memory_block_put(mem);
791 		return -EEXIST;
792 	}
793 	mem = kzalloc_obj(*mem);
794 	if (!mem)
795 		return -ENOMEM;
796 
797 	mem->start_section_nr = block_id * sections_per_block;
798 	mem->state = state;
799 	mem->nid = nid;
800 	INIT_LIST_HEAD(&mem->group_next);
801 
802 #ifndef CONFIG_NUMA
803 	if (state == MEM_ONLINE)
804 		/*
805 		 * MEM_ONLINE at this point implies early memory. With NUMA,
806 		 * we'll determine the zone when setting the node id via
807 		 * memory_block_add_nid_early(). Memory hotplug updated the zone
808 		 * manually when memory onlining/offlining succeeds.
809 		 */
810 		mem->zone = early_node_zone_for_memory_block(mem, NUMA_NO_NODE);
811 #endif /* CONFIG_NUMA */
812 
813 	ret = __add_memory_block(mem);
814 	if (ret)
815 		return ret;
816 
817 	mem->altmap = altmap;
818 
819 	if (group) {
820 		mem->group = group;
821 		list_add(&mem->group_next, &group->memory_blocks);
822 	}
823 
824 	return 0;
825 }
826 
827 static void remove_memory_block(struct memory_block *memory)
828 {
829 	if (WARN_ON_ONCE(memory->dev.bus != &memory_subsys))
830 		return;
831 
832 	WARN_ON(xa_erase(&memory_blocks, memory->dev.id) == NULL);
833 
834 	if (memory->group) {
835 		list_del(&memory->group_next);
836 		memory->group = NULL;
837 	}
838 
839 	/* drop the ref. we got via memory_block_get() */
840 	memory_block_put(memory);
841 	device_unregister(&memory->dev);
842 }
843 
844 /*
845  * Create memory block devices for the given memory area. Start and size
846  * have to be aligned to memory block granularity. Memory block devices
847  * will be initialized as offline.
848  *
849  * Called under device_hotplug_lock.
850  */
851 int create_memory_block_devices(unsigned long start, unsigned long size,
852 				int nid, struct vmem_altmap *altmap,
853 				struct memory_group *group)
854 {
855 	const unsigned long start_block_id = pfn_to_block_id(PFN_DOWN(start));
856 	unsigned long end_block_id = pfn_to_block_id(PFN_DOWN(start + size));
857 	struct memory_block *mem;
858 	unsigned long block_id;
859 	int ret = 0;
860 
861 	if (WARN_ON_ONCE(!IS_ALIGNED(start, memory_block_size_bytes()) ||
862 			 !IS_ALIGNED(size, memory_block_size_bytes())))
863 		return -EINVAL;
864 
865 	for (block_id = start_block_id; block_id != end_block_id; block_id++) {
866 		ret = add_memory_block(block_id, nid, MEM_OFFLINE, altmap, group);
867 		if (ret)
868 			break;
869 	}
870 	if (ret) {
871 		end_block_id = block_id;
872 		for (block_id = start_block_id; block_id != end_block_id;
873 		     block_id++) {
874 			mem = memory_block_get(block_id);
875 			if (WARN_ON_ONCE(!mem))
876 				continue;
877 			remove_memory_block(mem);
878 		}
879 	}
880 	return ret;
881 }
882 
883 /*
884  * Remove memory block devices for the given memory area. Start and size
885  * have to be aligned to memory block granularity. Memory block devices
886  * have to be offline.
887  *
888  * Called under device_hotplug_lock.
889  */
890 void remove_memory_block_devices(unsigned long start, unsigned long size)
891 {
892 	const unsigned long start_block_id = pfn_to_block_id(PFN_DOWN(start));
893 	const unsigned long end_block_id = pfn_to_block_id(PFN_DOWN(start + size));
894 	struct memory_block *mem;
895 	unsigned long block_id;
896 
897 	if (WARN_ON_ONCE(!IS_ALIGNED(start, memory_block_size_bytes()) ||
898 			 !IS_ALIGNED(size, memory_block_size_bytes())))
899 		return;
900 
901 	for (block_id = start_block_id; block_id != end_block_id; block_id++) {
902 		mem = memory_block_get(block_id);
903 		if (WARN_ON_ONCE(!mem))
904 			continue;
905 		num_poisoned_pages_sub(-1UL, memblk_nr_poison(mem));
906 		unregister_memory_block_under_nodes(mem);
907 		remove_memory_block(mem);
908 	}
909 }
910 
911 static struct attribute *memory_root_attrs[] = {
912 #ifdef CONFIG_ARCH_MEMORY_PROBE
913 	&dev_attr_probe.attr,
914 #endif
915 
916 #ifdef CONFIG_MEMORY_FAILURE
917 	&dev_attr_soft_offline_page.attr,
918 	&dev_attr_hard_offline_page.attr,
919 #endif
920 
921 	&dev_attr_block_size_bytes.attr,
922 	&dev_attr_auto_online_blocks.attr,
923 #ifdef CONFIG_CRASH_HOTPLUG
924 	&dev_attr_crash_hotplug.attr,
925 #endif
926 	NULL
927 };
928 
929 static const struct attribute_group memory_root_attr_group = {
930 	.attrs = memory_root_attrs,
931 };
932 
933 static const struct attribute_group *memory_root_attr_groups[] = {
934 	&memory_root_attr_group,
935 	NULL,
936 };
937 
938 /*
939  * Initialize the sysfs support for memory devices. At the time this function
940  * is called, we cannot have concurrent creation/deletion of memory block
941  * devices, the device_hotplug_lock is not needed.
942  */
943 void __init memory_dev_init(void)
944 {
945 	int ret;
946 	unsigned long block_sz, block_id, nr;
947 
948 	/* Validate the configured memory block size */
949 	block_sz = memory_block_size_bytes();
950 	if (!is_power_of_2(block_sz) || block_sz < MIN_MEMORY_BLOCK_SIZE)
951 		panic("Memory block size not suitable: 0x%lx\n", block_sz);
952 	sections_per_block = block_sz / MIN_MEMORY_BLOCK_SIZE;
953 
954 	ret = subsys_system_register(&memory_subsys, memory_root_attr_groups);
955 	if (ret)
956 		panic("%s() failed to register subsystem: %d\n", __func__, ret);
957 
958 	/*
959 	 * Create entries for memory sections that were found during boot
960 	 * and have been initialized. Use @block_id to track the last
961 	 * handled block and initialize it to an invalid value (ULONG_MAX)
962 	 * to bypass the block ID matching check for the first present
963 	 * block so that it can be covered.
964 	 */
965 	block_id = ULONG_MAX;
966 	for_each_present_section_nr(0, nr) {
967 		if (block_id != ULONG_MAX && memory_block_id(nr) == block_id)
968 			continue;
969 
970 		block_id = memory_block_id(nr);
971 		ret = add_memory_block(block_id, NUMA_NO_NODE, MEM_ONLINE, NULL, NULL);
972 		if (ret) {
973 			panic("%s() failed to add memory block: %d\n",
974 			      __func__, ret);
975 		}
976 	}
977 }
978 
979 /**
980  * walk_memory_blocks - walk through all present memory blocks overlapped
981  *			by the range [start, start + size)
982  *
983  * @start: start address of the memory range
984  * @size: size of the memory range
985  * @arg: argument passed to func
986  * @func: callback for each memory section walked
987  *
988  * This function walks through all present memory blocks overlapped by the
989  * range [start, start + size), calling func on each memory block.
990  *
991  * In case func() returns an error, walking is aborted and the error is
992  * returned.
993  *
994  * Called under device_hotplug_lock.
995  */
996 int walk_memory_blocks(unsigned long start, unsigned long size,
997 		       void *arg, walk_memory_blocks_func_t func)
998 {
999 	const unsigned long start_block_id = phys_to_block_id(start);
1000 	const unsigned long end_block_id = phys_to_block_id(start + size - 1);
1001 	struct memory_block *mem;
1002 	unsigned long block_id;
1003 	int ret = 0;
1004 
1005 	if (!size)
1006 		return 0;
1007 
1008 	for (block_id = start_block_id; block_id <= end_block_id; block_id++) {
1009 		mem = memory_block_get(block_id);
1010 		if (!mem)
1011 			continue;
1012 
1013 		ret = func(mem, arg);
1014 		memory_block_put(mem);
1015 		if (ret)
1016 			break;
1017 	}
1018 	return ret;
1019 }
1020 
1021 struct for_each_memory_block_cb_data {
1022 	walk_memory_blocks_func_t func;
1023 	void *arg;
1024 };
1025 
1026 static int for_each_memory_block_cb(struct device *dev, void *data)
1027 {
1028 	struct memory_block *mem = to_memory_block(dev);
1029 	struct for_each_memory_block_cb_data *cb_data = data;
1030 
1031 	return cb_data->func(mem, cb_data->arg);
1032 }
1033 
1034 /**
1035  * for_each_memory_block - walk through all present memory blocks
1036  *
1037  * @arg: argument passed to func
1038  * @func: callback for each memory block walked
1039  *
1040  * This function walks through all present memory blocks, calling func on
1041  * each memory block.
1042  *
1043  * In case func() returns an error, walking is aborted and the error is
1044  * returned.
1045  */
1046 int for_each_memory_block(void *arg, walk_memory_blocks_func_t func)
1047 {
1048 	struct for_each_memory_block_cb_data cb_data = {
1049 		.func = func,
1050 		.arg = arg,
1051 	};
1052 
1053 	return bus_for_each_dev(&memory_subsys, NULL, &cb_data,
1054 				for_each_memory_block_cb);
1055 }
1056 
1057 /*
1058  * This is an internal helper to unify allocation and initialization of
1059  * memory groups. Note that the passed memory group will be copied to a
1060  * dynamically allocated memory group. After this call, the passed
1061  * memory group should no longer be used.
1062  */
1063 static int memory_group_register(struct memory_group group)
1064 {
1065 	struct memory_group *new_group;
1066 	uint32_t mgid;
1067 	int ret;
1068 
1069 	if (!node_possible(group.nid))
1070 		return -EINVAL;
1071 
1072 	new_group = kzalloc_obj(group);
1073 	if (!new_group)
1074 		return -ENOMEM;
1075 	*new_group = group;
1076 	INIT_LIST_HEAD(&new_group->memory_blocks);
1077 
1078 	ret = xa_alloc(&memory_groups, &mgid, new_group, xa_limit_31b,
1079 		       GFP_KERNEL);
1080 	if (ret) {
1081 		kfree(new_group);
1082 		return ret;
1083 	} else if (group.is_dynamic) {
1084 		xa_set_mark(&memory_groups, mgid, MEMORY_GROUP_MARK_DYNAMIC);
1085 	}
1086 	return mgid;
1087 }
1088 
1089 /**
1090  * memory_group_register_static() - Register a static memory group.
1091  * @nid: The node id.
1092  * @max_pages: The maximum number of pages we'll have in this static memory
1093  *	       group.
1094  *
1095  * Register a new static memory group and return the memory group id.
1096  * All memory in the group belongs to a single unit, such as a DIMM. All
1097  * memory belonging to a static memory group is added in one go to be removed
1098  * in one go -- it's static.
1099  *
1100  * Returns an error if out of memory, if the node id is invalid, if no new
1101  * memory groups can be registered, or if max_pages is invalid (0). Otherwise,
1102  * returns the new memory group id.
1103  */
1104 int memory_group_register_static(int nid, unsigned long max_pages)
1105 {
1106 	struct memory_group group = {
1107 		.nid = nid,
1108 		.s = {
1109 			.max_pages = max_pages,
1110 		},
1111 	};
1112 
1113 	if (!max_pages)
1114 		return -EINVAL;
1115 	return memory_group_register(group);
1116 }
1117 EXPORT_SYMBOL_GPL(memory_group_register_static);
1118 
1119 /**
1120  * memory_group_register_dynamic() - Register a dynamic memory group.
1121  * @nid: The node id.
1122  * @unit_pages: Unit in pages in which is memory added/removed in this dynamic
1123  *		memory group.
1124  *
1125  * Register a new dynamic memory group and return the memory group id.
1126  * Memory within a dynamic memory group is added/removed dynamically
1127  * in unit_pages.
1128  *
1129  * Returns an error if out of memory, if the node id is invalid, if no new
1130  * memory groups can be registered, or if unit_pages is invalid (0, not a
1131  * power of two, smaller than a single memory block). Otherwise, returns the
1132  * new memory group id.
1133  */
1134 int memory_group_register_dynamic(int nid, unsigned long unit_pages)
1135 {
1136 	struct memory_group group = {
1137 		.nid = nid,
1138 		.is_dynamic = true,
1139 		.d = {
1140 			.unit_pages = unit_pages,
1141 		},
1142 	};
1143 
1144 	if (!unit_pages || !is_power_of_2(unit_pages) ||
1145 	    unit_pages < PHYS_PFN(memory_block_size_bytes()))
1146 		return -EINVAL;
1147 	return memory_group_register(group);
1148 }
1149 EXPORT_SYMBOL_GPL(memory_group_register_dynamic);
1150 
1151 /**
1152  * memory_group_unregister() - Unregister a memory group.
1153  * @mgid: the memory group id
1154  *
1155  * Unregister a memory group. If any memory block still belongs to this
1156  * memory group, unregistering will fail.
1157  *
1158  * Returns -EINVAL if the memory group id is invalid, returns -EBUSY if some
1159  * memory blocks still belong to this memory group and returns 0 if
1160  * unregistering succeeded.
1161  */
1162 int memory_group_unregister(int mgid)
1163 {
1164 	struct memory_group *group;
1165 
1166 	if (mgid < 0)
1167 		return -EINVAL;
1168 
1169 	group = xa_load(&memory_groups, mgid);
1170 	if (!group)
1171 		return -EINVAL;
1172 	if (!list_empty(&group->memory_blocks))
1173 		return -EBUSY;
1174 	xa_erase(&memory_groups, mgid);
1175 	kfree(group);
1176 	return 0;
1177 }
1178 EXPORT_SYMBOL_GPL(memory_group_unregister);
1179 
1180 /*
1181  * This is an internal helper only to be used in core memory hotplug code to
1182  * lookup a memory group. We don't care about locking, as we don't expect a
1183  * memory group to get unregistered while adding memory to it -- because
1184  * the group and the memory is managed by the same driver.
1185  */
1186 struct memory_group *memory_group_find_by_id(int mgid)
1187 {
1188 	return xa_load(&memory_groups, mgid);
1189 }
1190 
1191 /*
1192  * This is an internal helper only to be used in core memory hotplug code to
1193  * walk all dynamic memory groups excluding a given memory group, either
1194  * belonging to a specific node, or belonging to any node.
1195  */
1196 int walk_dynamic_memory_groups(int nid, walk_memory_groups_func_t func,
1197 			       struct memory_group *excluded, void *arg)
1198 {
1199 	struct memory_group *group;
1200 	unsigned long index;
1201 	int ret = 0;
1202 
1203 	xa_for_each_marked(&memory_groups, index, group,
1204 			   MEMORY_GROUP_MARK_DYNAMIC) {
1205 		if (group == excluded)
1206 			continue;
1207 #ifdef CONFIG_NUMA
1208 		if (nid != NUMA_NO_NODE && group->nid != nid)
1209 			continue;
1210 #endif /* CONFIG_NUMA */
1211 		ret = func(group, arg);
1212 		if (ret)
1213 			break;
1214 	}
1215 	return ret;
1216 }
1217 
1218 #if defined(CONFIG_MEMORY_FAILURE) && defined(CONFIG_MEMORY_HOTPLUG)
1219 void memblk_nr_poison_inc(unsigned long pfn)
1220 {
1221 	const unsigned long block_id = pfn_to_block_id(pfn);
1222 	struct memory_block *mem = memory_block_get(block_id);
1223 
1224 	if (mem) {
1225 		atomic_long_inc(&mem->nr_hwpoison);
1226 		memory_block_put(mem);
1227 	}
1228 }
1229 
1230 void memblk_nr_poison_sub(unsigned long pfn, long i)
1231 {
1232 	const unsigned long block_id = pfn_to_block_id(pfn);
1233 	struct memory_block *mem = memory_block_get(block_id);
1234 
1235 	if (mem) {
1236 		atomic_long_sub(i, &mem->nr_hwpoison);
1237 		memory_block_put(mem);
1238 	}
1239 }
1240 
1241 static unsigned long memblk_nr_poison(struct memory_block *mem)
1242 {
1243 	return atomic_long_read(&mem->nr_hwpoison);
1244 }
1245 #endif
1246