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