xref: /openbmc/qemu/hw/core/numa.c (revision 9739b11a)
1 /*
2  * NUMA parameter parsing routines
3  *
4  * Copyright (c) 2014 Fujitsu Ltd.
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "sysemu/hostmem.h"
27 #include "sysemu/numa.h"
28 #include "sysemu/sysemu.h"
29 #include "exec/cpu-common.h"
30 #include "exec/ramlist.h"
31 #include "qemu/bitmap.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/opts-visitor.h"
35 #include "qapi/qapi-visit-machine.h"
36 #include "sysemu/qtest.h"
37 #include "hw/core/cpu.h"
38 #include "hw/mem/pc-dimm.h"
39 #include "migration/vmstate.h"
40 #include "hw/boards.h"
41 #include "hw/mem/memory-device.h"
42 #include "qemu/option.h"
43 #include "qemu/config-file.h"
44 #include "qemu/cutils.h"
45 
46 QemuOptsList qemu_numa_opts = {
47     .name = "numa",
48     .implied_opt_name = "type",
49     .head = QTAILQ_HEAD_INITIALIZER(qemu_numa_opts.head),
50     .desc = { { 0 } } /* validated with OptsVisitor */
51 };
52 
53 static int have_memdevs;
54 static int have_mem;
55 static int max_numa_nodeid; /* Highest specified NUMA node ID, plus one.
56                              * For all nodes, nodeid < max_numa_nodeid
57                              */
58 
59 static void parse_numa_node(MachineState *ms, NumaNodeOptions *node,
60                             Error **errp)
61 {
62     Error *err = NULL;
63     uint16_t nodenr;
64     uint16List *cpus = NULL;
65     MachineClass *mc = MACHINE_GET_CLASS(ms);
66     unsigned int max_cpus = ms->smp.max_cpus;
67     NodeInfo *numa_info = ms->numa_state->nodes;
68 
69     if (node->has_nodeid) {
70         nodenr = node->nodeid;
71     } else {
72         nodenr = ms->numa_state->num_nodes;
73     }
74 
75     if (nodenr >= MAX_NODES) {
76         error_setg(errp, "Max number of NUMA nodes reached: %"
77                    PRIu16 "", nodenr);
78         return;
79     }
80 
81     if (numa_info[nodenr].present) {
82         error_setg(errp, "Duplicate NUMA nodeid: %" PRIu16, nodenr);
83         return;
84     }
85 
86     if (!mc->cpu_index_to_instance_props || !mc->get_default_cpu_node_id) {
87         error_setg(errp, "NUMA is not supported by this machine-type");
88         return;
89     }
90     for (cpus = node->cpus; cpus; cpus = cpus->next) {
91         CpuInstanceProperties props;
92         if (cpus->value >= max_cpus) {
93             error_setg(errp,
94                        "CPU index (%" PRIu16 ")"
95                        " should be smaller than maxcpus (%d)",
96                        cpus->value, max_cpus);
97             return;
98         }
99         props = mc->cpu_index_to_instance_props(ms, cpus->value);
100         props.node_id = nodenr;
101         props.has_node_id = true;
102         machine_set_cpu_numa_node(ms, &props, &err);
103         if (err) {
104             error_propagate(errp, err);
105             return;
106         }
107     }
108 
109     have_memdevs = have_memdevs ? : node->has_memdev;
110     have_mem = have_mem ? : node->has_mem;
111     if ((node->has_mem && have_memdevs) || (node->has_memdev && have_mem)) {
112         error_setg(errp, "numa configuration should use either mem= or memdev=,"
113                    "mixing both is not allowed");
114         return;
115     }
116 
117     if (node->has_mem) {
118         numa_info[nodenr].node_mem = node->mem;
119         if (!qtest_enabled()) {
120             warn_report("Parameter -numa node,mem is deprecated,"
121                         " use -numa node,memdev instead");
122         }
123     }
124     if (node->has_memdev) {
125         Object *o;
126         o = object_resolve_path_type(node->memdev, TYPE_MEMORY_BACKEND, NULL);
127         if (!o) {
128             error_setg(errp, "memdev=%s is ambiguous", node->memdev);
129             return;
130         }
131 
132         object_ref(o);
133         numa_info[nodenr].node_mem = object_property_get_uint(o, "size", NULL);
134         numa_info[nodenr].node_memdev = MEMORY_BACKEND(o);
135     }
136     numa_info[nodenr].present = true;
137     max_numa_nodeid = MAX(max_numa_nodeid, nodenr + 1);
138     ms->numa_state->num_nodes++;
139 }
140 
141 static
142 void parse_numa_distance(MachineState *ms, NumaDistOptions *dist, Error **errp)
143 {
144     uint16_t src = dist->src;
145     uint16_t dst = dist->dst;
146     uint8_t val = dist->val;
147     NodeInfo *numa_info = ms->numa_state->nodes;
148 
149     if (src >= MAX_NODES || dst >= MAX_NODES) {
150         error_setg(errp, "Parameter '%s' expects an integer between 0 and %d",
151                    src >= MAX_NODES ? "src" : "dst", MAX_NODES - 1);
152         return;
153     }
154 
155     if (!numa_info[src].present || !numa_info[dst].present) {
156         error_setg(errp, "Source/Destination NUMA node is missing. "
157                    "Please use '-numa node' option to declare it first.");
158         return;
159     }
160 
161     if (val < NUMA_DISTANCE_MIN) {
162         error_setg(errp, "NUMA distance (%" PRIu8 ") is invalid, "
163                    "it shouldn't be less than %d.",
164                    val, NUMA_DISTANCE_MIN);
165         return;
166     }
167 
168     if (src == dst && val != NUMA_DISTANCE_MIN) {
169         error_setg(errp, "Local distance of node %d should be %d.",
170                    src, NUMA_DISTANCE_MIN);
171         return;
172     }
173 
174     numa_info[src].distance[dst] = val;
175     ms->numa_state->have_numa_distance = true;
176 }
177 
178 void set_numa_options(MachineState *ms, NumaOptions *object, Error **errp)
179 {
180     Error *err = NULL;
181     MachineClass *mc = MACHINE_GET_CLASS(ms);
182 
183     if (!mc->numa_mem_supported) {
184         error_setg(errp, "NUMA is not supported by this machine-type");
185         goto end;
186     }
187 
188     switch (object->type) {
189     case NUMA_OPTIONS_TYPE_NODE:
190         parse_numa_node(ms, &object->u.node, &err);
191         if (err) {
192             goto end;
193         }
194         break;
195     case NUMA_OPTIONS_TYPE_DIST:
196         parse_numa_distance(ms, &object->u.dist, &err);
197         if (err) {
198             goto end;
199         }
200         break;
201     case NUMA_OPTIONS_TYPE_CPU:
202         if (!object->u.cpu.has_node_id) {
203             error_setg(&err, "Missing mandatory node-id property");
204             goto end;
205         }
206         if (!ms->numa_state->nodes[object->u.cpu.node_id].present) {
207             error_setg(&err, "Invalid node-id=%" PRId64 ", NUMA node must be "
208                 "defined with -numa node,nodeid=ID before it's used with "
209                 "-numa cpu,node-id=ID", object->u.cpu.node_id);
210             goto end;
211         }
212 
213         machine_set_cpu_numa_node(ms, qapi_NumaCpuOptions_base(&object->u.cpu),
214                                   &err);
215         break;
216     default:
217         abort();
218     }
219 
220 end:
221     error_propagate(errp, err);
222 }
223 
224 static int parse_numa(void *opaque, QemuOpts *opts, Error **errp)
225 {
226     NumaOptions *object = NULL;
227     MachineState *ms = MACHINE(opaque);
228     Error *err = NULL;
229     Visitor *v = opts_visitor_new(opts);
230 
231     visit_type_NumaOptions(v, NULL, &object, &err);
232     visit_free(v);
233     if (err) {
234         goto end;
235     }
236 
237     /* Fix up legacy suffix-less format */
238     if ((object->type == NUMA_OPTIONS_TYPE_NODE) && object->u.node.has_mem) {
239         const char *mem_str = qemu_opt_get(opts, "mem");
240         qemu_strtosz_MiB(mem_str, NULL, &object->u.node.mem);
241     }
242 
243     set_numa_options(ms, object, &err);
244 
245 end:
246     qapi_free_NumaOptions(object);
247     if (err) {
248         error_propagate(errp, err);
249         return -1;
250     }
251 
252     return 0;
253 }
254 
255 /* If all node pair distances are symmetric, then only distances
256  * in one direction are enough. If there is even one asymmetric
257  * pair, though, then all distances must be provided. The
258  * distance from a node to itself is always NUMA_DISTANCE_MIN,
259  * so providing it is never necessary.
260  */
261 static void validate_numa_distance(MachineState *ms)
262 {
263     int src, dst;
264     bool is_asymmetrical = false;
265     int nb_numa_nodes = ms->numa_state->num_nodes;
266     NodeInfo *numa_info = ms->numa_state->nodes;
267 
268     for (src = 0; src < nb_numa_nodes; src++) {
269         for (dst = src; dst < nb_numa_nodes; dst++) {
270             if (numa_info[src].distance[dst] == 0 &&
271                 numa_info[dst].distance[src] == 0) {
272                 if (src != dst) {
273                     error_report("The distance between node %d and %d is "
274                                  "missing, at least one distance value "
275                                  "between each nodes should be provided.",
276                                  src, dst);
277                     exit(EXIT_FAILURE);
278                 }
279             }
280 
281             if (numa_info[src].distance[dst] != 0 &&
282                 numa_info[dst].distance[src] != 0 &&
283                 numa_info[src].distance[dst] !=
284                 numa_info[dst].distance[src]) {
285                 is_asymmetrical = true;
286             }
287         }
288     }
289 
290     if (is_asymmetrical) {
291         for (src = 0; src < nb_numa_nodes; src++) {
292             for (dst = 0; dst < nb_numa_nodes; dst++) {
293                 if (src != dst && numa_info[src].distance[dst] == 0) {
294                     error_report("At least one asymmetrical pair of "
295                             "distances is given, please provide distances "
296                             "for both directions of all node pairs.");
297                     exit(EXIT_FAILURE);
298                 }
299             }
300         }
301     }
302 }
303 
304 static void complete_init_numa_distance(MachineState *ms)
305 {
306     int src, dst;
307     NodeInfo *numa_info = ms->numa_state->nodes;
308 
309     /* Fixup NUMA distance by symmetric policy because if it is an
310      * asymmetric distance table, it should be a complete table and
311      * there would not be any missing distance except local node, which
312      * is verified by validate_numa_distance above.
313      */
314     for (src = 0; src < ms->numa_state->num_nodes; src++) {
315         for (dst = 0; dst < ms->numa_state->num_nodes; dst++) {
316             if (numa_info[src].distance[dst] == 0) {
317                 if (src == dst) {
318                     numa_info[src].distance[dst] = NUMA_DISTANCE_MIN;
319                 } else {
320                     numa_info[src].distance[dst] = numa_info[dst].distance[src];
321                 }
322             }
323         }
324     }
325 }
326 
327 void numa_legacy_auto_assign_ram(MachineClass *mc, NodeInfo *nodes,
328                                  int nb_nodes, ram_addr_t size)
329 {
330     int i;
331     uint64_t usedmem = 0;
332 
333     /* Align each node according to the alignment
334      * requirements of the machine class
335      */
336 
337     for (i = 0; i < nb_nodes - 1; i++) {
338         nodes[i].node_mem = (size / nb_nodes) &
339                             ~((1 << mc->numa_mem_align_shift) - 1);
340         usedmem += nodes[i].node_mem;
341     }
342     nodes[i].node_mem = size - usedmem;
343 }
344 
345 void numa_default_auto_assign_ram(MachineClass *mc, NodeInfo *nodes,
346                                   int nb_nodes, ram_addr_t size)
347 {
348     int i;
349     uint64_t usedmem = 0, node_mem;
350     uint64_t granularity = size / nb_nodes;
351     uint64_t propagate = 0;
352 
353     for (i = 0; i < nb_nodes - 1; i++) {
354         node_mem = (granularity + propagate) &
355                    ~((1 << mc->numa_mem_align_shift) - 1);
356         propagate = granularity + propagate - node_mem;
357         nodes[i].node_mem = node_mem;
358         usedmem += node_mem;
359     }
360     nodes[i].node_mem = size - usedmem;
361 }
362 
363 void numa_complete_configuration(MachineState *ms)
364 {
365     int i;
366     MachineClass *mc = MACHINE_GET_CLASS(ms);
367     NodeInfo *numa_info = ms->numa_state->nodes;
368 
369     /*
370      * If memory hotplug is enabled (slots > 0) but without '-numa'
371      * options explicitly on CLI, guestes will break.
372      *
373      *   Windows: won't enable memory hotplug without SRAT table at all
374      *
375      *   Linux: if QEMU is started with initial memory all below 4Gb
376      *   and no SRAT table present, guest kernel will use nommu DMA ops,
377      *   which breaks 32bit hw drivers when memory is hotplugged and
378      *   guest tries to use it with that drivers.
379      *
380      * Enable NUMA implicitly by adding a new NUMA node automatically.
381      */
382     if (ms->ram_slots > 0 && ms->numa_state->num_nodes == 0 &&
383         mc->auto_enable_numa_with_memhp) {
384             NumaNodeOptions node = { };
385             parse_numa_node(ms, &node, &error_abort);
386     }
387 
388     assert(max_numa_nodeid <= MAX_NODES);
389 
390     /* No support for sparse NUMA node IDs yet: */
391     for (i = max_numa_nodeid - 1; i >= 0; i--) {
392         /* Report large node IDs first, to make mistakes easier to spot */
393         if (!numa_info[i].present) {
394             error_report("numa: Node ID missing: %d", i);
395             exit(1);
396         }
397     }
398 
399     /* This must be always true if all nodes are present: */
400     assert(ms->numa_state->num_nodes == max_numa_nodeid);
401 
402     if (ms->numa_state->num_nodes > 0) {
403         uint64_t numa_total;
404 
405         if (ms->numa_state->num_nodes > MAX_NODES) {
406             ms->numa_state->num_nodes = MAX_NODES;
407         }
408 
409         /* If no memory size is given for any node, assume the default case
410          * and distribute the available memory equally across all nodes
411          */
412         for (i = 0; i < ms->numa_state->num_nodes; i++) {
413             if (numa_info[i].node_mem != 0) {
414                 break;
415             }
416         }
417         if (i == ms->numa_state->num_nodes) {
418             assert(mc->numa_auto_assign_ram);
419             mc->numa_auto_assign_ram(mc, numa_info,
420                                      ms->numa_state->num_nodes, ram_size);
421             if (!qtest_enabled()) {
422                 warn_report("Default splitting of RAM between nodes is deprecated,"
423                             " Use '-numa node,memdev' to explictly define RAM"
424                             " allocation per node");
425             }
426         }
427 
428         numa_total = 0;
429         for (i = 0; i < ms->numa_state->num_nodes; i++) {
430             numa_total += numa_info[i].node_mem;
431         }
432         if (numa_total != ram_size) {
433             error_report("total memory for NUMA nodes (0x%" PRIx64 ")"
434                          " should equal RAM size (0x" RAM_ADDR_FMT ")",
435                          numa_total, ram_size);
436             exit(1);
437         }
438 
439         /* QEMU needs at least all unique node pair distances to build
440          * the whole NUMA distance table. QEMU treats the distance table
441          * as symmetric by default, i.e. distance A->B == distance B->A.
442          * Thus, QEMU is able to complete the distance table
443          * initialization even though only distance A->B is provided and
444          * distance B->A is not. QEMU knows the distance of a node to
445          * itself is always 10, so A->A distances may be omitted. When
446          * the distances of two nodes of a pair differ, i.e. distance
447          * A->B != distance B->A, then that means the distance table is
448          * asymmetric. In this case, the distances for both directions
449          * of all node pairs are required.
450          */
451         if (ms->numa_state->have_numa_distance) {
452             /* Validate enough NUMA distance information was provided. */
453             validate_numa_distance(ms);
454 
455             /* Validation succeeded, now fill in any missing distances. */
456             complete_init_numa_distance(ms);
457         }
458     }
459 }
460 
461 void parse_numa_opts(MachineState *ms)
462 {
463     qemu_opts_foreach(qemu_find_opts("numa"), parse_numa, ms, &error_fatal);
464 }
465 
466 void numa_cpu_pre_plug(const CPUArchId *slot, DeviceState *dev, Error **errp)
467 {
468     int node_id = object_property_get_int(OBJECT(dev), "node-id", &error_abort);
469 
470     if (node_id == CPU_UNSET_NUMA_NODE_ID) {
471         /* due to bug in libvirt, it doesn't pass node-id from props on
472          * device_add as expected, so we have to fix it up here */
473         if (slot->props.has_node_id) {
474             object_property_set_int(OBJECT(dev), slot->props.node_id,
475                                     "node-id", errp);
476         }
477     } else if (node_id != slot->props.node_id) {
478         error_setg(errp, "invalid node-id, must be %"PRId64,
479                    slot->props.node_id);
480     }
481 }
482 
483 static void allocate_system_memory_nonnuma(MemoryRegion *mr, Object *owner,
484                                            const char *name,
485                                            uint64_t ram_size)
486 {
487     if (mem_path) {
488 #ifdef __linux__
489         Error *err = NULL;
490         memory_region_init_ram_from_file(mr, owner, name, ram_size, 0, 0,
491                                          mem_path, &err);
492         if (err) {
493             error_report_err(err);
494             if (mem_prealloc) {
495                 exit(1);
496             }
497             warn_report("falling back to regular RAM allocation");
498             error_printf("This is deprecated. Make sure that -mem-path "
499                          " specified path has sufficient resources to allocate"
500                          " -m specified RAM amount");
501             /* Legacy behavior: if allocation failed, fall back to
502              * regular RAM allocation.
503              */
504             mem_path = NULL;
505             memory_region_init_ram_nomigrate(mr, owner, name, ram_size, &error_fatal);
506         }
507 #else
508         fprintf(stderr, "-mem-path not supported on this host\n");
509         exit(1);
510 #endif
511     } else {
512         memory_region_init_ram_nomigrate(mr, owner, name, ram_size, &error_fatal);
513     }
514     vmstate_register_ram_global(mr);
515 }
516 
517 void memory_region_allocate_system_memory(MemoryRegion *mr, Object *owner,
518                                           const char *name,
519                                           uint64_t ram_size)
520 {
521     uint64_t addr = 0;
522     int i;
523     MachineState *ms = MACHINE(qdev_get_machine());
524 
525     if (ms->numa_state == NULL ||
526         ms->numa_state->num_nodes == 0 || !have_memdevs) {
527         allocate_system_memory_nonnuma(mr, owner, name, ram_size);
528         return;
529     }
530 
531     memory_region_init(mr, owner, name, ram_size);
532     for (i = 0; i < ms->numa_state->num_nodes; i++) {
533         uint64_t size = ms->numa_state->nodes[i].node_mem;
534         HostMemoryBackend *backend = ms->numa_state->nodes[i].node_memdev;
535         if (!backend) {
536             continue;
537         }
538         MemoryRegion *seg = host_memory_backend_get_memory(backend);
539 
540         if (memory_region_is_mapped(seg)) {
541             char *path = object_get_canonical_path_component(OBJECT(backend));
542             error_report("memory backend %s is used multiple times. Each "
543                          "-numa option must use a different memdev value.",
544                          path);
545             g_free(path);
546             exit(1);
547         }
548 
549         host_memory_backend_set_mapped(backend, true);
550         memory_region_add_subregion(mr, addr, seg);
551         vmstate_register_ram_global(seg);
552         addr += size;
553     }
554 }
555 
556 static void numa_stat_memory_devices(NumaNodeMem node_mem[])
557 {
558     MemoryDeviceInfoList *info_list = qmp_memory_device_list();
559     MemoryDeviceInfoList *info;
560     PCDIMMDeviceInfo     *pcdimm_info;
561     VirtioPMEMDeviceInfo *vpi;
562 
563     for (info = info_list; info; info = info->next) {
564         MemoryDeviceInfo *value = info->value;
565 
566         if (value) {
567             switch (value->type) {
568             case MEMORY_DEVICE_INFO_KIND_DIMM:
569             case MEMORY_DEVICE_INFO_KIND_NVDIMM:
570                 pcdimm_info = value->type == MEMORY_DEVICE_INFO_KIND_DIMM ?
571                               value->u.dimm.data : value->u.nvdimm.data;
572                 node_mem[pcdimm_info->node].node_mem += pcdimm_info->size;
573                 node_mem[pcdimm_info->node].node_plugged_mem +=
574                     pcdimm_info->size;
575                 break;
576             case MEMORY_DEVICE_INFO_KIND_VIRTIO_PMEM:
577                 vpi = value->u.virtio_pmem.data;
578                 /* TODO: once we support numa, assign to right node */
579                 node_mem[0].node_mem += vpi->size;
580                 node_mem[0].node_plugged_mem += vpi->size;
581                 break;
582             default:
583                 g_assert_not_reached();
584             }
585         }
586     }
587     qapi_free_MemoryDeviceInfoList(info_list);
588 }
589 
590 void query_numa_node_mem(NumaNodeMem node_mem[], MachineState *ms)
591 {
592     int i;
593 
594     if (ms->numa_state == NULL || ms->numa_state->num_nodes <= 0) {
595         return;
596     }
597 
598     numa_stat_memory_devices(node_mem);
599     for (i = 0; i < ms->numa_state->num_nodes; i++) {
600         node_mem[i].node_mem += ms->numa_state->nodes[i].node_mem;
601     }
602 }
603 
604 void ram_block_notifier_add(RAMBlockNotifier *n)
605 {
606     QLIST_INSERT_HEAD(&ram_list.ramblock_notifiers, n, next);
607 }
608 
609 void ram_block_notifier_remove(RAMBlockNotifier *n)
610 {
611     QLIST_REMOVE(n, next);
612 }
613 
614 void ram_block_notify_add(void *host, size_t size)
615 {
616     RAMBlockNotifier *notifier;
617 
618     QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
619         notifier->ram_block_added(notifier, host, size);
620     }
621 }
622 
623 void ram_block_notify_remove(void *host, size_t size)
624 {
625     RAMBlockNotifier *notifier;
626 
627     QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
628         notifier->ram_block_removed(notifier, host, size);
629     }
630 }
631