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