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