virt-arm: add node-id property to CPU
[qemu.git] / numa.c
blobbcdfca23094cae256c685b309c401e6f9d034f40
1 /*
2 * NUMA parameter parsing routines
4 * Copyright (c) 2014 Fujitsu Ltd.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "sysemu/numa.h"
27 #include "exec/cpu-common.h"
28 #include "exec/ramlist.h"
29 #include "qemu/bitmap.h"
30 #include "qom/cpu.h"
31 #include "qemu/error-report.h"
32 #include "include/exec/cpu-common.h" /* for RAM_ADDR_FMT */
33 #include "qapi-visit.h"
34 #include "qapi/opts-visitor.h"
35 #include "hw/boards.h"
36 #include "sysemu/hostmem.h"
37 #include "qmp-commands.h"
38 #include "hw/mem/pc-dimm.h"
39 #include "qemu/option.h"
40 #include "qemu/config-file.h"
42 QemuOptsList qemu_numa_opts = {
43 .name = "numa",
44 .implied_opt_name = "type",
45 .head = QTAILQ_HEAD_INITIALIZER(qemu_numa_opts.head),
46 .desc = { { 0 } } /* validated with OptsVisitor */
49 static int have_memdevs = -1;
50 static int max_numa_nodeid; /* Highest specified NUMA node ID, plus one.
51 * For all nodes, nodeid < max_numa_nodeid
53 int nb_numa_nodes;
54 bool have_numa_distance;
55 NodeInfo numa_info[MAX_NODES];
57 void numa_set_mem_node_id(ram_addr_t addr, uint64_t size, uint32_t node)
59 struct numa_addr_range *range;
62 * Memory-less nodes can come here with 0 size in which case,
63 * there is nothing to do.
65 if (!size) {
66 return;
69 range = g_malloc0(sizeof(*range));
70 range->mem_start = addr;
71 range->mem_end = addr + size - 1;
72 QLIST_INSERT_HEAD(&numa_info[node].addr, range, entry);
75 void numa_unset_mem_node_id(ram_addr_t addr, uint64_t size, uint32_t node)
77 struct numa_addr_range *range, *next;
79 QLIST_FOREACH_SAFE(range, &numa_info[node].addr, entry, next) {
80 if (addr == range->mem_start && (addr + size - 1) == range->mem_end) {
81 QLIST_REMOVE(range, entry);
82 g_free(range);
83 return;
88 static void numa_set_mem_ranges(void)
90 int i;
91 ram_addr_t mem_start = 0;
94 * Deduce start address of each node and use it to store
95 * the address range info in numa_info address range list
97 for (i = 0; i < nb_numa_nodes; i++) {
98 numa_set_mem_node_id(mem_start, numa_info[i].node_mem, i);
99 mem_start += numa_info[i].node_mem;
104 * Check if @addr falls under NUMA @node.
106 static bool numa_addr_belongs_to_node(ram_addr_t addr, uint32_t node)
108 struct numa_addr_range *range;
110 QLIST_FOREACH(range, &numa_info[node].addr, entry) {
111 if (addr >= range->mem_start && addr <= range->mem_end) {
112 return true;
115 return false;
119 * Given an address, return the index of the NUMA node to which the
120 * address belongs to.
122 uint32_t numa_get_node(ram_addr_t addr, Error **errp)
124 uint32_t i;
126 /* For non NUMA configurations, check if the addr falls under node 0 */
127 if (!nb_numa_nodes) {
128 if (numa_addr_belongs_to_node(addr, 0)) {
129 return 0;
133 for (i = 0; i < nb_numa_nodes; i++) {
134 if (numa_addr_belongs_to_node(addr, i)) {
135 return i;
139 error_setg(errp, "Address 0x" RAM_ADDR_FMT " doesn't belong to any "
140 "NUMA node", addr);
141 return -1;
144 static void parse_numa_node(NumaNodeOptions *node, QemuOpts *opts, Error **errp)
146 uint16_t nodenr;
147 uint16List *cpus = NULL;
149 if (node->has_nodeid) {
150 nodenr = node->nodeid;
151 } else {
152 nodenr = nb_numa_nodes;
155 if (nodenr >= MAX_NODES) {
156 error_setg(errp, "Max number of NUMA nodes reached: %"
157 PRIu16 "", nodenr);
158 return;
161 if (numa_info[nodenr].present) {
162 error_setg(errp, "Duplicate NUMA nodeid: %" PRIu16, nodenr);
163 return;
166 for (cpus = node->cpus; cpus; cpus = cpus->next) {
167 if (cpus->value >= max_cpus) {
168 error_setg(errp,
169 "CPU index (%" PRIu16 ")"
170 " should be smaller than maxcpus (%d)",
171 cpus->value, max_cpus);
172 return;
174 bitmap_set(numa_info[nodenr].node_cpu, cpus->value, 1);
177 if (node->has_mem && node->has_memdev) {
178 error_setg(errp, "qemu: cannot specify both mem= and memdev=");
179 return;
182 if (have_memdevs == -1) {
183 have_memdevs = node->has_memdev;
185 if (node->has_memdev != have_memdevs) {
186 error_setg(errp, "qemu: memdev option must be specified for either "
187 "all or no nodes");
188 return;
191 if (node->has_mem) {
192 uint64_t mem_size = node->mem;
193 const char *mem_str = qemu_opt_get(opts, "mem");
194 /* Fix up legacy suffix-less format */
195 if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
196 mem_size <<= 20;
198 numa_info[nodenr].node_mem = mem_size;
200 if (node->has_memdev) {
201 Object *o;
202 o = object_resolve_path_type(node->memdev, TYPE_MEMORY_BACKEND, NULL);
203 if (!o) {
204 error_setg(errp, "memdev=%s is ambiguous", node->memdev);
205 return;
208 object_ref(o);
209 numa_info[nodenr].node_mem = object_property_get_int(o, "size", NULL);
210 numa_info[nodenr].node_memdev = MEMORY_BACKEND(o);
212 numa_info[nodenr].present = true;
213 max_numa_nodeid = MAX(max_numa_nodeid, nodenr + 1);
216 static void parse_numa_distance(NumaDistOptions *dist, Error **errp)
218 uint16_t src = dist->src;
219 uint16_t dst = dist->dst;
220 uint8_t val = dist->val;
222 if (src >= MAX_NODES || dst >= MAX_NODES) {
223 error_setg(errp,
224 "Invalid node %" PRIu16
225 ", max possible could be %" PRIu16,
226 MAX(src, dst), MAX_NODES);
227 return;
230 if (!numa_info[src].present || !numa_info[dst].present) {
231 error_setg(errp, "Source/Destination NUMA node is missing. "
232 "Please use '-numa node' option to declare it first.");
233 return;
236 if (val < NUMA_DISTANCE_MIN) {
237 error_setg(errp, "NUMA distance (%" PRIu8 ") is invalid, "
238 "it shouldn't be less than %d.",
239 val, NUMA_DISTANCE_MIN);
240 return;
243 if (src == dst && val != NUMA_DISTANCE_MIN) {
244 error_setg(errp, "Local distance of node %d should be %d.",
245 src, NUMA_DISTANCE_MIN);
246 return;
249 numa_info[src].distance[dst] = val;
250 have_numa_distance = true;
253 static int parse_numa(void *opaque, QemuOpts *opts, Error **errp)
255 NumaOptions *object = NULL;
256 Error *err = NULL;
259 Visitor *v = opts_visitor_new(opts);
260 visit_type_NumaOptions(v, NULL, &object, &err);
261 visit_free(v);
264 if (err) {
265 goto end;
268 switch (object->type) {
269 case NUMA_OPTIONS_TYPE_NODE:
270 parse_numa_node(&object->u.node, opts, &err);
271 if (err) {
272 goto end;
274 nb_numa_nodes++;
275 break;
276 case NUMA_OPTIONS_TYPE_DIST:
277 parse_numa_distance(&object->u.dist, &err);
278 if (err) {
279 goto end;
281 break;
282 default:
283 abort();
286 end:
287 qapi_free_NumaOptions(object);
288 if (err) {
289 error_report_err(err);
290 return -1;
293 return 0;
296 static char *enumerate_cpus(unsigned long *cpus, int max_cpus)
298 int cpu;
299 bool first = true;
300 GString *s = g_string_new(NULL);
302 for (cpu = find_first_bit(cpus, max_cpus);
303 cpu < max_cpus;
304 cpu = find_next_bit(cpus, max_cpus, cpu + 1)) {
305 g_string_append_printf(s, "%s%d", first ? "" : " ", cpu);
306 first = false;
308 return g_string_free(s, FALSE);
311 static void validate_numa_cpus(void)
313 int i;
314 unsigned long *seen_cpus = bitmap_new(max_cpus);
316 for (i = 0; i < nb_numa_nodes; i++) {
317 if (bitmap_intersects(seen_cpus, numa_info[i].node_cpu, max_cpus)) {
318 bitmap_and(seen_cpus, seen_cpus,
319 numa_info[i].node_cpu, max_cpus);
320 error_report("CPU(s) present in multiple NUMA nodes: %s",
321 enumerate_cpus(seen_cpus, max_cpus));
322 g_free(seen_cpus);
323 exit(EXIT_FAILURE);
325 bitmap_or(seen_cpus, seen_cpus,
326 numa_info[i].node_cpu, max_cpus);
329 if (!bitmap_full(seen_cpus, max_cpus)) {
330 char *msg;
331 bitmap_complement(seen_cpus, seen_cpus, max_cpus);
332 msg = enumerate_cpus(seen_cpus, max_cpus);
333 error_report("warning: CPU(s) not present in any NUMA nodes: %s", msg);
334 error_report("warning: All CPU(s) up to maxcpus should be described "
335 "in NUMA config");
336 g_free(msg);
338 g_free(seen_cpus);
341 /* If all node pair distances are symmetric, then only distances
342 * in one direction are enough. If there is even one asymmetric
343 * pair, though, then all distances must be provided. The
344 * distance from a node to itself is always NUMA_DISTANCE_MIN,
345 * so providing it is never necessary.
347 static void validate_numa_distance(void)
349 int src, dst;
350 bool is_asymmetrical = false;
352 for (src = 0; src < nb_numa_nodes; src++) {
353 for (dst = src; dst < nb_numa_nodes; dst++) {
354 if (numa_info[src].distance[dst] == 0 &&
355 numa_info[dst].distance[src] == 0) {
356 if (src != dst) {
357 error_report("The distance between node %d and %d is "
358 "missing, at least one distance value "
359 "between each nodes should be provided.",
360 src, dst);
361 exit(EXIT_FAILURE);
365 if (numa_info[src].distance[dst] != 0 &&
366 numa_info[dst].distance[src] != 0 &&
367 numa_info[src].distance[dst] !=
368 numa_info[dst].distance[src]) {
369 is_asymmetrical = true;
374 if (is_asymmetrical) {
375 for (src = 0; src < nb_numa_nodes; src++) {
376 for (dst = 0; dst < nb_numa_nodes; dst++) {
377 if (src != dst && numa_info[src].distance[dst] == 0) {
378 error_report("At least one asymmetrical pair of "
379 "distances is given, please provide distances "
380 "for both directions of all node pairs.");
381 exit(EXIT_FAILURE);
388 static void complete_init_numa_distance(void)
390 int src, dst;
392 /* Fixup NUMA distance by symmetric policy because if it is an
393 * asymmetric distance table, it should be a complete table and
394 * there would not be any missing distance except local node, which
395 * is verified by validate_numa_distance above.
397 for (src = 0; src < nb_numa_nodes; src++) {
398 for (dst = 0; dst < nb_numa_nodes; dst++) {
399 if (numa_info[src].distance[dst] == 0) {
400 if (src == dst) {
401 numa_info[src].distance[dst] = NUMA_DISTANCE_MIN;
402 } else {
403 numa_info[src].distance[dst] = numa_info[dst].distance[src];
410 void numa_legacy_auto_assign_ram(MachineClass *mc, NodeInfo *nodes,
411 int nb_nodes, ram_addr_t size)
413 int i;
414 uint64_t usedmem = 0;
416 /* Align each node according to the alignment
417 * requirements of the machine class
420 for (i = 0; i < nb_nodes - 1; i++) {
421 nodes[i].node_mem = (size / nb_nodes) &
422 ~((1 << mc->numa_mem_align_shift) - 1);
423 usedmem += nodes[i].node_mem;
425 nodes[i].node_mem = size - usedmem;
428 void numa_default_auto_assign_ram(MachineClass *mc, NodeInfo *nodes,
429 int nb_nodes, ram_addr_t size)
431 int i;
432 uint64_t usedmem = 0, node_mem;
433 uint64_t granularity = size / nb_nodes;
434 uint64_t propagate = 0;
436 for (i = 0; i < nb_nodes - 1; i++) {
437 node_mem = (granularity + propagate) &
438 ~((1 << mc->numa_mem_align_shift) - 1);
439 propagate = granularity + propagate - node_mem;
440 nodes[i].node_mem = node_mem;
441 usedmem += node_mem;
443 nodes[i].node_mem = size - usedmem;
446 void parse_numa_opts(MachineState *ms)
448 int i;
449 MachineClass *mc = MACHINE_GET_CLASS(ms);
451 for (i = 0; i < MAX_NODES; i++) {
452 numa_info[i].node_cpu = bitmap_new(max_cpus);
455 if (qemu_opts_foreach(qemu_find_opts("numa"), parse_numa, NULL, NULL)) {
456 exit(1);
459 assert(max_numa_nodeid <= MAX_NODES);
461 /* No support for sparse NUMA node IDs yet: */
462 for (i = max_numa_nodeid - 1; i >= 0; i--) {
463 /* Report large node IDs first, to make mistakes easier to spot */
464 if (!numa_info[i].present) {
465 error_report("numa: Node ID missing: %d", i);
466 exit(1);
470 /* This must be always true if all nodes are present: */
471 assert(nb_numa_nodes == max_numa_nodeid);
473 if (nb_numa_nodes > 0) {
474 uint64_t numa_total;
476 if (nb_numa_nodes > MAX_NODES) {
477 nb_numa_nodes = MAX_NODES;
480 /* If no memory size is given for any node, assume the default case
481 * and distribute the available memory equally across all nodes
483 for (i = 0; i < nb_numa_nodes; i++) {
484 if (numa_info[i].node_mem != 0) {
485 break;
488 if (i == nb_numa_nodes) {
489 assert(mc->numa_auto_assign_ram);
490 mc->numa_auto_assign_ram(mc, numa_info, nb_numa_nodes, ram_size);
493 numa_total = 0;
494 for (i = 0; i < nb_numa_nodes; i++) {
495 numa_total += numa_info[i].node_mem;
497 if (numa_total != ram_size) {
498 error_report("total memory for NUMA nodes (0x%" PRIx64 ")"
499 " should equal RAM size (0x" RAM_ADDR_FMT ")",
500 numa_total, ram_size);
501 exit(1);
504 for (i = 0; i < nb_numa_nodes; i++) {
505 QLIST_INIT(&numa_info[i].addr);
508 numa_set_mem_ranges();
510 for (i = 0; i < nb_numa_nodes; i++) {
511 if (!bitmap_empty(numa_info[i].node_cpu, max_cpus)) {
512 break;
516 /* assign CPUs to nodes using board provided default mapping */
517 if (!mc->cpu_index_to_instance_props) {
518 error_report("default CPUs to NUMA node mapping isn't supported");
519 exit(1);
521 if (i == nb_numa_nodes) {
522 for (i = 0; i < max_cpus; i++) {
523 CpuInstanceProperties props;
524 props = mc->cpu_index_to_instance_props(ms, i);
526 set_bit(i, numa_info[props.node_id].node_cpu);
530 validate_numa_cpus();
532 /* QEMU needs at least all unique node pair distances to build
533 * the whole NUMA distance table. QEMU treats the distance table
534 * as symmetric by default, i.e. distance A->B == distance B->A.
535 * Thus, QEMU is able to complete the distance table
536 * initialization even though only distance A->B is provided and
537 * distance B->A is not. QEMU knows the distance of a node to
538 * itself is always 10, so A->A distances may be omitted. When
539 * the distances of two nodes of a pair differ, i.e. distance
540 * A->B != distance B->A, then that means the distance table is
541 * asymmetric. In this case, the distances for both directions
542 * of all node pairs are required.
544 if (have_numa_distance) {
545 /* Validate enough NUMA distance information was provided. */
546 validate_numa_distance();
548 /* Validation succeeded, now fill in any missing distances. */
549 complete_init_numa_distance();
551 } else {
552 numa_set_mem_node_id(0, ram_size, 0);
556 void numa_post_machine_init(void)
558 CPUState *cpu;
559 int i;
561 CPU_FOREACH(cpu) {
562 for (i = 0; i < nb_numa_nodes; i++) {
563 assert(cpu->cpu_index < max_cpus);
564 if (test_bit(cpu->cpu_index, numa_info[i].node_cpu)) {
565 cpu->numa_node = i;
571 static void allocate_system_memory_nonnuma(MemoryRegion *mr, Object *owner,
572 const char *name,
573 uint64_t ram_size)
575 if (mem_path) {
576 #ifdef __linux__
577 Error *err = NULL;
578 memory_region_init_ram_from_file(mr, owner, name, ram_size, false,
579 mem_path, &err);
580 if (err) {
581 error_report_err(err);
582 if (mem_prealloc) {
583 exit(1);
586 /* Legacy behavior: if allocation failed, fall back to
587 * regular RAM allocation.
589 memory_region_init_ram(mr, owner, name, ram_size, &error_fatal);
591 #else
592 fprintf(stderr, "-mem-path not supported on this host\n");
593 exit(1);
594 #endif
595 } else {
596 memory_region_init_ram(mr, owner, name, ram_size, &error_fatal);
598 vmstate_register_ram_global(mr);
601 void memory_region_allocate_system_memory(MemoryRegion *mr, Object *owner,
602 const char *name,
603 uint64_t ram_size)
605 uint64_t addr = 0;
606 int i;
608 if (nb_numa_nodes == 0 || !have_memdevs) {
609 allocate_system_memory_nonnuma(mr, owner, name, ram_size);
610 return;
613 memory_region_init(mr, owner, name, ram_size);
614 for (i = 0; i < MAX_NODES; i++) {
615 uint64_t size = numa_info[i].node_mem;
616 HostMemoryBackend *backend = numa_info[i].node_memdev;
617 if (!backend) {
618 continue;
620 MemoryRegion *seg = host_memory_backend_get_memory(backend,
621 &error_fatal);
623 if (memory_region_is_mapped(seg)) {
624 char *path = object_get_canonical_path_component(OBJECT(backend));
625 error_report("memory backend %s is used multiple times. Each "
626 "-numa option must use a different memdev value.",
627 path);
628 exit(1);
631 host_memory_backend_set_mapped(backend, true);
632 memory_region_add_subregion(mr, addr, seg);
633 vmstate_register_ram_global(seg);
634 addr += size;
638 static void numa_stat_memory_devices(uint64_t node_mem[])
640 MemoryDeviceInfoList *info_list = NULL;
641 MemoryDeviceInfoList **prev = &info_list;
642 MemoryDeviceInfoList *info;
644 qmp_pc_dimm_device_list(qdev_get_machine(), &prev);
645 for (info = info_list; info; info = info->next) {
646 MemoryDeviceInfo *value = info->value;
648 if (value) {
649 switch (value->type) {
650 case MEMORY_DEVICE_INFO_KIND_DIMM:
651 node_mem[value->u.dimm.data->node] += value->u.dimm.data->size;
652 break;
653 default:
654 break;
658 qapi_free_MemoryDeviceInfoList(info_list);
661 void query_numa_node_mem(uint64_t node_mem[])
663 int i;
665 if (nb_numa_nodes <= 0) {
666 return;
669 numa_stat_memory_devices(node_mem);
670 for (i = 0; i < nb_numa_nodes; i++) {
671 node_mem[i] += numa_info[i].node_mem;
675 static int query_memdev(Object *obj, void *opaque)
677 MemdevList **list = opaque;
678 MemdevList *m = NULL;
680 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
681 m = g_malloc0(sizeof(*m));
683 m->value = g_malloc0(sizeof(*m->value));
685 m->value->id = object_property_get_str(obj, "id", NULL);
686 m->value->has_id = !!m->value->id;
688 m->value->size = object_property_get_int(obj, "size",
689 &error_abort);
690 m->value->merge = object_property_get_bool(obj, "merge",
691 &error_abort);
692 m->value->dump = object_property_get_bool(obj, "dump",
693 &error_abort);
694 m->value->prealloc = object_property_get_bool(obj,
695 "prealloc",
696 &error_abort);
697 m->value->policy = object_property_get_enum(obj,
698 "policy",
699 "HostMemPolicy",
700 &error_abort);
701 object_property_get_uint16List(obj, "host-nodes",
702 &m->value->host_nodes,
703 &error_abort);
705 m->next = *list;
706 *list = m;
709 return 0;
712 MemdevList *qmp_query_memdev(Error **errp)
714 Object *obj = object_get_objects_root();
715 MemdevList *list = NULL;
717 object_child_foreach(obj, query_memdev, &list);
718 return list;
721 int numa_get_node_for_cpu(int idx)
723 int i;
725 assert(idx < max_cpus);
727 for (i = 0; i < nb_numa_nodes; i++) {
728 if (test_bit(idx, numa_info[i].node_cpu)) {
729 break;
732 return i;
735 void ram_block_notifier_add(RAMBlockNotifier *n)
737 QLIST_INSERT_HEAD(&ram_list.ramblock_notifiers, n, next);
740 void ram_block_notifier_remove(RAMBlockNotifier *n)
742 QLIST_REMOVE(n, next);
745 void ram_block_notify_add(void *host, size_t size)
747 RAMBlockNotifier *notifier;
749 QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
750 notifier->ram_block_added(notifier, host, size);
754 void ram_block_notify_remove(void *host, size_t size)
756 RAMBlockNotifier *notifier;
758 QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
759 notifier->ram_block_removed(notifier, host, size);