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