xref: /linux/mm/numa_memblks.c (revision 38fda1d9d2f5df55bd1c095aec07de3699091316)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/array_size.h>
4 #include <linux/sort.h>
5 #include <linux/printk.h>
6 #include <linux/memblock.h>
7 #include <linux/numa.h>
8 #include <linux/numa_memblks.h>
9 
10 #include <asm/numa.h>
11 
12 int numa_distance_cnt;
13 static u8 *numa_distance;
14 
15 nodemask_t numa_nodes_parsed __initdata;
16 
17 static struct numa_meminfo numa_meminfo __initdata_or_meminfo;
18 static struct numa_meminfo numa_reserved_meminfo __initdata_or_meminfo;
19 
20 /**
21  * numa_reset_distance - Reset NUMA distance table
22  *
23  * The current table is freed.  The next numa_set_distance() call will
24  * create a new one.
25  */
26 void __init numa_reset_distance(void)
27 {
28 	size_t size = numa_distance_cnt * numa_distance_cnt * sizeof(numa_distance[0]);
29 
30 	/* numa_distance could be 1LU marking allocation failure, test cnt */
31 	if (numa_distance_cnt)
32 		memblock_free(numa_distance, size);
33 	numa_distance_cnt = 0;
34 	numa_distance = NULL;	/* enable table creation */
35 }
36 
37 static int __init numa_alloc_distance(void)
38 {
39 	nodemask_t nodes_parsed;
40 	size_t size;
41 	int i, j, cnt = 0;
42 
43 	/* size the new table and allocate it */
44 	nodes_parsed = numa_nodes_parsed;
45 
46 	for_each_node_mask(i, nodes_parsed)
47 		cnt = i;
48 	cnt++;
49 	size = cnt * cnt * sizeof(numa_distance[0]);
50 
51 	numa_distance = memblock_alloc(size, PAGE_SIZE);
52 	if (!numa_distance) {
53 		pr_warn("Warning: can't allocate distance table!\n");
54 		/* don't retry until explicitly reset */
55 		numa_distance = (void *)1LU;
56 		return -ENOMEM;
57 	}
58 
59 	numa_distance_cnt = cnt;
60 
61 	/* fill with the default distances */
62 	for (i = 0; i < cnt; i++)
63 		for (j = 0; j < cnt; j++)
64 			numa_distance[i * cnt + j] = i == j ?
65 				LOCAL_DISTANCE : REMOTE_DISTANCE;
66 	pr_debug("NUMA: Initialized distance table, cnt=%d\n", cnt);
67 
68 	return 0;
69 }
70 
71 /**
72  * numa_set_distance - Set NUMA distance from one NUMA to another
73  * @from: the 'from' node to set distance
74  * @to: the 'to'  node to set distance
75  * @distance: NUMA distance
76  *
77  * Set the distance from node @from to @to to @distance.  If distance table
78  * doesn't exist, one which is large enough to accommodate all the currently
79  * known nodes will be created.
80  *
81  * If such table cannot be allocated, a warning is printed and further
82  * calls are ignored until the distance table is reset with
83  * numa_reset_distance().
84  *
85  * If @from or @to is higher than the highest known node or lower than zero
86  * at the time of table creation or @distance doesn't make sense, the call
87  * is ignored.
88  * This is to allow simplification of specific NUMA config implementations.
89  */
90 void __init numa_set_distance(int from, int to, int distance)
91 {
92 	if (!numa_distance && numa_alloc_distance() < 0)
93 		return;
94 
95 	if (from >= numa_distance_cnt || to >= numa_distance_cnt ||
96 			from < 0 || to < 0) {
97 		pr_warn_once("Warning: node ids are out of bound, from=%d to=%d distance=%d\n",
98 			     from, to, distance);
99 		return;
100 	}
101 
102 	if ((u8)distance != distance ||
103 	    (from == to && distance != LOCAL_DISTANCE)) {
104 		pr_warn_once("Warning: invalid distance parameter, from=%d to=%d distance=%d\n",
105 			     from, to, distance);
106 		return;
107 	}
108 
109 	numa_distance[from * numa_distance_cnt + to] = distance;
110 }
111 
112 int __node_distance(int from, int to)
113 {
114 	if (from >= numa_distance_cnt || to >= numa_distance_cnt)
115 		return from == to ? LOCAL_DISTANCE : REMOTE_DISTANCE;
116 	return numa_distance[from * numa_distance_cnt + to];
117 }
118 EXPORT_SYMBOL(__node_distance);
119 
120 static int __init numa_add_memblk_to(int nid, u64 start, u64 end,
121 				     struct numa_meminfo *mi)
122 {
123 	/* whine about and ignore invalid nid */
124 	if (nid < 0 || nid >= MAX_NUMNODES) {
125 		pr_warn("Warning: invalid memblk node id %d [mem %#010Lx-%#010Lx]\n",
126 			nid, start, end - 1);
127 		return -EINVAL;
128 	}
129 
130 	/* ignore zero length blks */
131 	if (start == end)
132 		return 0;
133 
134 	/* whine about and ignore invalid ranges */
135 	if (start > end) {
136 		pr_warn("Warning: invalid memblk range for node %d [mem %#010Lx-%#010Lx]\n",
137 			nid, start, end - 1);
138 		return 0;
139 	}
140 
141 	if (mi->nr_blks >= NR_NODE_MEMBLKS) {
142 		pr_err("too many memblk ranges\n");
143 		return -EINVAL;
144 	}
145 
146 	mi->blk[mi->nr_blks].start = start;
147 	mi->blk[mi->nr_blks].end = end;
148 	mi->blk[mi->nr_blks].nid = nid;
149 	mi->nr_blks++;
150 	return 0;
151 }
152 
153 /**
154  * numa_remove_memblk_from - Remove one numa_memblk from a numa_meminfo
155  * @idx: Index of memblk to remove
156  * @mi: numa_meminfo to remove memblk from
157  *
158  * Remove @idx'th numa_memblk from @mi by shifting @mi->blk[] and
159  * decrementing @mi->nr_blks.
160  */
161 void __init numa_remove_memblk_from(int idx, struct numa_meminfo *mi)
162 {
163 	mi->nr_blks--;
164 	memmove(&mi->blk[idx], &mi->blk[idx + 1],
165 		(mi->nr_blks - idx) * sizeof(mi->blk[0]));
166 }
167 
168 /**
169  * numa_move_tail_memblk - Move a numa_memblk from one numa_meminfo to another
170  * @dst: numa_meminfo to append block to
171  * @idx: Index of memblk to remove
172  * @src: numa_meminfo to remove memblk from
173  */
174 static void __init numa_move_tail_memblk(struct numa_meminfo *dst, int idx,
175 					 struct numa_meminfo *src)
176 {
177 	dst->blk[dst->nr_blks++] = src->blk[idx];
178 	numa_remove_memblk_from(idx, src);
179 }
180 
181 /**
182  * numa_add_memblk - Add one numa_memblk to numa_meminfo
183  * @nid: NUMA node ID of the new memblk
184  * @start: Start address of the new memblk
185  * @end: End address of the new memblk
186  *
187  * Add a new memblk to the default numa_meminfo.
188  * On success @nid is also set in numa_nodes_parsed.
189  *
190  * RETURNS:
191  * 0 on success, -errno on failure.
192  */
193 int __init numa_add_memblk(int nid, u64 start, u64 end)
194 {
195 	int ret;
196 
197 	ret = numa_add_memblk_to(nid, start, end, &numa_meminfo);
198 	if (!ret)
199 		node_set(nid, numa_nodes_parsed);
200 
201 	return ret;
202 }
203 
204 /**
205  * numa_add_reserved_memblk - Add one numa_memblk to numa_reserved_meminfo
206  * @nid: NUMA node ID of the new memblk
207  * @start: Start address of the new memblk
208  * @end: End address of the new memblk
209  *
210  * Add a new memblk to the numa_reserved_meminfo.
211  *
212  * Usage Case: numa_cleanup_meminfo() reconciles all numa_memblk instances
213  * against memblock_type information and moves any that intersect reserved
214  * ranges to numa_reserved_meminfo. However, when that information is known
215  * ahead of time, we use numa_add_reserved_memblk() to add the numa_memblk
216  * to numa_reserved_meminfo directly.
217  *
218  * RETURNS:
219  * 0 on success, -errno on failure.
220  */
221 int __init numa_add_reserved_memblk(int nid, u64 start, u64 end)
222 {
223 	return numa_add_memblk_to(nid, start, end, &numa_reserved_meminfo);
224 }
225 
226 /**
227  * numa_cleanup_meminfo - Cleanup a numa_meminfo
228  * @mi: numa_meminfo to clean up
229  *
230  * Sanitize @mi by merging and removing unnecessary memblks.  Also check for
231  * conflicts and clear unused memblks.
232  *
233  * RETURNS:
234  * 0 on success, -errno on failure.
235  */
236 int __init numa_cleanup_meminfo(struct numa_meminfo *mi)
237 {
238 	const u64 low = memblock_start_of_DRAM();
239 	const u64 high = memblock_end_of_DRAM();
240 	int i, j, k;
241 
242 	/* first, trim all entries */
243 	for (i = 0; i < mi->nr_blks; i++) {
244 		struct numa_memblk *bi = &mi->blk[i];
245 
246 		/* move / save reserved memory ranges */
247 		if (!memblock_overlaps_region(&memblock.memory,
248 					bi->start, bi->end - bi->start)) {
249 			numa_move_tail_memblk(&numa_reserved_meminfo, i--, mi);
250 			continue;
251 		}
252 
253 		/* make sure all non-reserved blocks are inside the limits */
254 		bi->start = max(bi->start, low);
255 
256 		/* preserve info for non-RAM areas above 'max_pfn': */
257 		if (bi->end > high) {
258 			numa_add_reserved_memblk(bi->nid, high, bi->end);
259 			bi->end = high;
260 		}
261 
262 		/* and there's no empty block */
263 		if (bi->start >= bi->end)
264 			numa_remove_memblk_from(i--, mi);
265 	}
266 
267 	/* merge neighboring / overlapping entries */
268 	for (i = 0; i < mi->nr_blks; i++) {
269 		struct numa_memblk *bi = &mi->blk[i];
270 
271 		for (j = i + 1; j < mi->nr_blks; j++) {
272 			struct numa_memblk *bj = &mi->blk[j];
273 			u64 start, end;
274 
275 			/*
276 			 * See whether there are overlapping blocks.  Whine
277 			 * about but allow overlaps of the same nid.  They
278 			 * will be merged below.
279 			 */
280 			if (bi->end > bj->start && bi->start < bj->end) {
281 				if (bi->nid != bj->nid) {
282 					pr_err("node %d [mem %#010Lx-%#010Lx] overlaps with node %d [mem %#010Lx-%#010Lx]\n",
283 					       bi->nid, bi->start, bi->end - 1,
284 					       bj->nid, bj->start, bj->end - 1);
285 					return -EINVAL;
286 				}
287 				pr_warn("Warning: node %d [mem %#010Lx-%#010Lx] overlaps with itself [mem %#010Lx-%#010Lx]\n",
288 					bi->nid, bi->start, bi->end - 1,
289 					bj->start, bj->end - 1);
290 			}
291 
292 			/*
293 			 * Join together blocks on the same node, holes
294 			 * between which don't overlap with memory on other
295 			 * nodes.
296 			 */
297 			if (bi->nid != bj->nid)
298 				continue;
299 			start = min(bi->start, bj->start);
300 			end = max(bi->end, bj->end);
301 			for (k = 0; k < mi->nr_blks; k++) {
302 				struct numa_memblk *bk = &mi->blk[k];
303 
304 				if (bi->nid == bk->nid)
305 					continue;
306 				if (start < bk->end && end > bk->start)
307 					break;
308 			}
309 			if (k < mi->nr_blks)
310 				continue;
311 			pr_info("NUMA: Node %d [mem %#010Lx-%#010Lx] + [mem %#010Lx-%#010Lx] -> [mem %#010Lx-%#010Lx]\n",
312 			       bi->nid, bi->start, bi->end - 1, bj->start,
313 			       bj->end - 1, start, end - 1);
314 			bi->start = start;
315 			bi->end = end;
316 			numa_remove_memblk_from(j--, mi);
317 		}
318 	}
319 
320 	/* clear unused ones */
321 	for (i = mi->nr_blks; i < ARRAY_SIZE(mi->blk); i++) {
322 		mi->blk[i].start = mi->blk[i].end = 0;
323 		mi->blk[i].nid = NUMA_NO_NODE;
324 	}
325 
326 	return 0;
327 }
328 
329 /*
330  * Mark all currently memblock-reserved physical memory (which covers the
331  * kernel's own memory ranges) as hot-unswappable.
332  */
333 static void __init numa_clear_kernel_node_hotplug(void)
334 {
335 	nodemask_t reserved_nodemask = NODE_MASK_NONE;
336 	struct memblock_region *mb_region;
337 	int i;
338 
339 	/*
340 	 * We have to do some preprocessing of memblock regions, to
341 	 * make them suitable for reservation.
342 	 *
343 	 * At this time, all memory regions reserved by memblock are
344 	 * used by the kernel, but those regions are not split up
345 	 * along node boundaries yet, and don't necessarily have their
346 	 * node ID set yet either.
347 	 *
348 	 * So iterate over all parsed memory blocks and use those ranges to
349 	 * set the nid in memblock.reserved.  This will split up the
350 	 * memblock regions along node boundaries and will set the node IDs
351 	 * as well.
352 	 */
353 	for (i = 0; i < numa_meminfo.nr_blks; i++) {
354 		struct numa_memblk *mb = numa_meminfo.blk + i;
355 		int ret;
356 
357 		ret = memblock_set_node(mb->start, mb->end - mb->start,
358 					&memblock.reserved, mb->nid);
359 		WARN_ON_ONCE(ret);
360 	}
361 
362 	/*
363 	 * Now go over all reserved memblock regions, to construct a
364 	 * node mask of all kernel reserved memory areas.
365 	 *
366 	 * [ Note, when booting with mem=nn[kMG] or in a kdump kernel,
367 	 *   numa_meminfo might not include all memblock.reserved
368 	 *   memory ranges, because quirks such as trim_snb_memory()
369 	 *   reserve specific pages for Sandy Bridge graphics. ]
370 	 */
371 	for_each_reserved_mem_region(mb_region) {
372 		int nid = memblock_get_region_node(mb_region);
373 
374 		if (numa_valid_node(nid))
375 			node_set(nid, reserved_nodemask);
376 	}
377 
378 	/*
379 	 * Finally, clear the MEMBLOCK_HOTPLUG flag for all memory
380 	 * belonging to the reserved node mask.
381 	 *
382 	 * Note that this will include memory regions that reside
383 	 * on nodes that contain kernel memory - entire nodes
384 	 * become hot-unpluggable:
385 	 */
386 	for (i = 0; i < numa_meminfo.nr_blks; i++) {
387 		struct numa_memblk *mb = numa_meminfo.blk + i;
388 
389 		if (!node_isset(mb->nid, reserved_nodemask))
390 			continue;
391 
392 		memblock_clear_hotplug(mb->start, mb->end - mb->start);
393 	}
394 }
395 
396 static int __init numa_register_meminfo(struct numa_meminfo *mi)
397 {
398 	int i;
399 
400 	/* Account for nodes with cpus and no memory */
401 	node_possible_map = numa_nodes_parsed;
402 	if (WARN_ON(nodes_empty(node_possible_map)))
403 		return -EINVAL;
404 
405 	for (i = 0; i < mi->nr_blks; i++) {
406 		struct numa_memblk *mb = &mi->blk[i];
407 
408 		memblock_set_node(mb->start, mb->end - mb->start,
409 				  &memblock.memory, mb->nid);
410 	}
411 
412 	/*
413 	 * At very early time, the kernel have to use some memory such as
414 	 * loading the kernel image. We cannot prevent this anyway. So any
415 	 * node the kernel resides in should be un-hotpluggable.
416 	 *
417 	 * And when we come here, alloc node data won't fail.
418 	 */
419 	numa_clear_kernel_node_hotplug();
420 
421 	/*
422 	 * If sections array is gonna be used for pfn -> nid mapping, check
423 	 * whether its granularity is fine enough.
424 	 */
425 	if (IS_ENABLED(NODE_NOT_IN_PAGE_FLAGS)) {
426 		unsigned long pfn_align = node_map_pfn_alignment();
427 
428 		if (pfn_align && pfn_align < PAGES_PER_SECTION) {
429 			unsigned long node_align_mb = PFN_PHYS(pfn_align) / SZ_1M;
430 
431 			unsigned long sect_align_mb = PFN_PHYS(PAGES_PER_SECTION) / SZ_1M;
432 
433 			pr_warn("Node alignment %luMB < min %luMB, rejecting NUMA config\n",
434 				node_align_mb, sect_align_mb);
435 			return -EINVAL;
436 		}
437 	}
438 
439 	return 0;
440 }
441 
442 int __init numa_memblks_init(int (*init_func)(void),
443 			     bool memblock_force_top_down)
444 {
445 	phys_addr_t max_addr = (phys_addr_t)ULLONG_MAX;
446 	int ret;
447 
448 	nodes_clear(numa_nodes_parsed);
449 	nodes_clear(node_possible_map);
450 	nodes_clear(node_online_map);
451 	memset(&numa_meminfo, 0, sizeof(numa_meminfo));
452 	WARN_ON(memblock_set_node(0, max_addr, &memblock.memory, NUMA_NO_NODE));
453 	WARN_ON(memblock_set_node(0, max_addr, &memblock.reserved,
454 				  NUMA_NO_NODE));
455 	/* In case that parsing SRAT failed. */
456 	WARN_ON(memblock_clear_hotplug(0, max_addr));
457 	numa_reset_distance();
458 
459 	ret = init_func();
460 	if (ret < 0)
461 		return ret;
462 
463 	/*
464 	 * We reset memblock back to the top-down direction
465 	 * here because if we configured ACPI_NUMA, we have
466 	 * parsed SRAT in init_func(). It is ok to have the
467 	 * reset here even if we didn't configure ACPI_NUMA
468 	 * or acpi numa init fails and fallbacks to dummy
469 	 * numa init.
470 	 */
471 	if (memblock_force_top_down)
472 		memblock_set_bottom_up(false);
473 
474 	ret = numa_cleanup_meminfo(&numa_meminfo);
475 	if (ret < 0)
476 		return ret;
477 
478 	numa_emulation(&numa_meminfo, numa_distance_cnt);
479 
480 	return numa_register_meminfo(&numa_meminfo);
481 }
482 
483 static int __init cmp_memblk(const void *a, const void *b)
484 {
485 	const struct numa_memblk *ma = *(const struct numa_memblk **)a;
486 	const struct numa_memblk *mb = *(const struct numa_memblk **)b;
487 
488 	return (ma->start > mb->start) - (ma->start < mb->start);
489 }
490 
491 static struct numa_memblk *numa_memblk_list[NR_NODE_MEMBLKS] __initdata;
492 
493 /**
494  * numa_fill_memblks - Fill gaps in numa_meminfo memblks
495  * @start: address to begin fill
496  * @end: address to end fill
497  *
498  * Find and extend numa_meminfo memblks to cover the physical
499  * address range @start-@end
500  *
501  * RETURNS:
502  * 0		  : Success
503  * NUMA_NO_MEMBLK : No memblks exist in address range @start-@end
504  */
505 
506 int __init numa_fill_memblks(u64 start, u64 end)
507 {
508 	struct numa_memblk **blk = &numa_memblk_list[0];
509 	struct numa_meminfo *mi = &numa_meminfo;
510 	int count = 0;
511 	u64 prev_end;
512 
513 	/*
514 	 * Create a list of pointers to numa_meminfo memblks that
515 	 * overlap start, end. The list is used to make in-place
516 	 * changes that fill out the numa_meminfo memblks.
517 	 */
518 	for (int i = 0; i < mi->nr_blks; i++) {
519 		struct numa_memblk *bi = &mi->blk[i];
520 
521 		if (memblock_addrs_overlap(start, end - start, bi->start,
522 					   bi->end - bi->start)) {
523 			blk[count] = &mi->blk[i];
524 			count++;
525 		}
526 	}
527 	if (!count)
528 		return NUMA_NO_MEMBLK;
529 
530 	/* Sort the list of pointers in memblk->start order */
531 	sort(&blk[0], count, sizeof(blk[0]), cmp_memblk, NULL);
532 
533 	/* Make sure the first/last memblks include start/end */
534 	blk[0]->start = min(blk[0]->start, start);
535 	blk[count - 1]->end = max(blk[count - 1]->end, end);
536 
537 	/*
538 	 * Fill any gaps by tracking the previous memblks
539 	 * end address and backfilling to it if needed.
540 	 */
541 	prev_end = blk[0]->end;
542 	for (int i = 1; i < count; i++) {
543 		struct numa_memblk *curr = blk[i];
544 
545 		if (prev_end >= curr->start) {
546 			if (prev_end < curr->end)
547 				prev_end = curr->end;
548 		} else {
549 			curr->start = prev_end;
550 			prev_end = curr->end;
551 		}
552 	}
553 	return 0;
554 }
555 
556 #ifdef CONFIG_NUMA_KEEP_MEMINFO
557 static int meminfo_to_nid(struct numa_meminfo *mi, u64 start)
558 {
559 	int i;
560 
561 	for (i = 0; i < mi->nr_blks; i++)
562 		if (mi->blk[i].start <= start && mi->blk[i].end > start)
563 			return mi->blk[i].nid;
564 	return NUMA_NO_NODE;
565 }
566 
567 int phys_to_target_node(u64 start)
568 {
569 	int nid = meminfo_to_nid(&numa_meminfo, start);
570 	int reserved_nid = meminfo_to_nid(&numa_reserved_meminfo, start);
571 
572 	/*
573 	 * Prefer online nodes unless the address is also described
574 	 * by reserved ranges, in which case use the reserved nid.
575 	 */
576 	if (nid != NUMA_NO_NODE && reserved_nid == NUMA_NO_NODE)
577 		return nid;
578 
579 	return reserved_nid;
580 }
581 EXPORT_SYMBOL_GPL(phys_to_target_node);
582 
583 int memory_add_physaddr_to_nid(u64 start)
584 {
585 	int nid = meminfo_to_nid(&numa_meminfo, start);
586 
587 	if (nid == NUMA_NO_NODE)
588 		nid = numa_meminfo.blk[0].nid;
589 	return nid;
590 }
591 EXPORT_SYMBOL_GPL(memory_add_physaddr_to_nid);
592 
593 #endif /* CONFIG_NUMA_KEEP_MEMINFO */
594