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