xref: /openbmc/qemu/hw/core/numa.c (revision 01c3ac68)
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 "qemu/units.h"
27 #include "sysemu/hostmem.h"
28 #include "sysemu/numa.h"
29 #include "exec/cpu-common.h"
30 #include "exec/ramlist.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 "hw/core/cpu.h"
37 #include "hw/mem/pc-dimm.h"
38 #include "hw/boards.h"
39 #include "hw/mem/memory-device.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qemu/cutils.h"
43 
44 QemuOptsList qemu_numa_opts = {
45     .name = "numa",
46     .implied_opt_name = "type",
47     .head = QTAILQ_HEAD_INITIALIZER(qemu_numa_opts.head),
48     .desc = { { 0 } } /* validated with OptsVisitor */
49 };
50 
51 static int have_memdevs;
52 bool numa_uses_legacy_mem(void)
53 {
54     return !have_memdevs;
55 }
56 
57 static int have_mem;
58 static int max_numa_nodeid; /* Highest specified NUMA node ID, plus one.
59                              * For all nodes, nodeid < max_numa_nodeid
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     NodeInfo *numa_info = ms->numa_state->nodes;
71 
72     if (node->has_nodeid) {
73         nodenr = node->nodeid;
74     } else {
75         nodenr = ms->numa_state->num_nodes;
76     }
77 
78     if (nodenr >= MAX_NODES) {
79         error_setg(errp, "Max number of NUMA nodes reached: %"
80                    PRIu16 "", nodenr);
81         return;
82     }
83 
84     if (numa_info[nodenr].present) {
85         error_setg(errp, "Duplicate NUMA nodeid: %" PRIu16, nodenr);
86         return;
87     }
88 
89     /*
90      * If not set the initiator, set it to MAX_NODES. And if
91      * HMAT is enabled and this node has no cpus, QEMU will raise error.
92      */
93     numa_info[nodenr].initiator = MAX_NODES;
94     if (node->has_initiator) {
95         if (!ms->numa_state->hmat_enabled) {
96             error_setg(errp, "ACPI Heterogeneous Memory Attribute Table "
97                        "(HMAT) is disabled, enable it with -machine hmat=on "
98                        "before using any of hmat specific options");
99             return;
100         }
101 
102         if (node->initiator >= MAX_NODES) {
103             error_report("The initiator id %" PRIu16 " expects an integer "
104                          "between 0 and %d", node->initiator,
105                          MAX_NODES - 1);
106             return;
107         }
108 
109         numa_info[nodenr].initiator = node->initiator;
110     }
111 
112     for (cpus = node->cpus; cpus; cpus = cpus->next) {
113         CpuInstanceProperties props;
114         if (cpus->value >= max_cpus) {
115             error_setg(errp,
116                        "CPU index (%" PRIu16 ")"
117                        " should be smaller than maxcpus (%d)",
118                        cpus->value, max_cpus);
119             return;
120         }
121         props = mc->cpu_index_to_instance_props(ms, cpus->value);
122         props.node_id = nodenr;
123         props.has_node_id = true;
124         machine_set_cpu_numa_node(ms, &props, &err);
125         if (err) {
126             error_propagate(errp, err);
127             return;
128         }
129     }
130 
131     have_memdevs = have_memdevs || node->memdev;
132     have_mem = have_mem || node->has_mem;
133     if ((node->has_mem && have_memdevs) || (node->memdev && have_mem)) {
134         error_setg(errp, "numa configuration should use either mem= or memdev=,"
135                    "mixing both is not allowed");
136         return;
137     }
138 
139     if (node->has_mem) {
140         if (!mc->numa_mem_supported) {
141             error_setg(errp, "Parameter -numa node,mem is not supported by this"
142                       " machine type");
143             error_append_hint(errp, "Use -numa node,memdev instead\n");
144             return;
145         }
146 
147         numa_info[nodenr].node_mem = node->mem;
148         if (!qtest_enabled()) {
149             warn_report("Parameter -numa node,mem is deprecated,"
150                         " use -numa node,memdev instead");
151         }
152     }
153     if (node->memdev) {
154         Object *o;
155         o = object_resolve_path_type(node->memdev, TYPE_MEMORY_BACKEND, NULL);
156         if (!o) {
157             error_setg(errp, "memdev=%s is ambiguous", node->memdev);
158             return;
159         }
160 
161         object_ref(o);
162         numa_info[nodenr].node_mem = object_property_get_uint(o, "size", NULL);
163         numa_info[nodenr].node_memdev = MEMORY_BACKEND(o);
164     }
165 
166     numa_info[nodenr].present = true;
167     max_numa_nodeid = MAX(max_numa_nodeid, nodenr + 1);
168     ms->numa_state->num_nodes++;
169 }
170 
171 static
172 void parse_numa_distance(MachineState *ms, NumaDistOptions *dist, Error **errp)
173 {
174     uint16_t src = dist->src;
175     uint16_t dst = dist->dst;
176     uint8_t val = dist->val;
177     NodeInfo *numa_info = ms->numa_state->nodes;
178 
179     if (src >= MAX_NODES || dst >= MAX_NODES) {
180         error_setg(errp, "Parameter '%s' expects an integer between 0 and %d",
181                    src >= MAX_NODES ? "src" : "dst", MAX_NODES - 1);
182         return;
183     }
184 
185     if (!numa_info[src].present || !numa_info[dst].present) {
186         error_setg(errp, "Source/Destination NUMA node is missing. "
187                    "Please use '-numa node' option to declare it first.");
188         return;
189     }
190 
191     if (val < NUMA_DISTANCE_MIN) {
192         error_setg(errp, "NUMA distance (%" PRIu8 ") is invalid, "
193                    "it shouldn't be less than %d.",
194                    val, NUMA_DISTANCE_MIN);
195         return;
196     }
197 
198     if (src == dst && val != NUMA_DISTANCE_MIN) {
199         error_setg(errp, "Local distance of node %d should be %d.",
200                    src, NUMA_DISTANCE_MIN);
201         return;
202     }
203 
204     numa_info[src].distance[dst] = val;
205     ms->numa_state->have_numa_distance = true;
206 }
207 
208 void parse_numa_hmat_lb(NumaState *numa_state, NumaHmatLBOptions *node,
209                         Error **errp)
210 {
211     int i, first_bit, last_bit;
212     uint64_t max_entry, temp_base, bitmap_copy;
213     NodeInfo *numa_info = numa_state->nodes;
214     HMAT_LB_Info *hmat_lb =
215         numa_state->hmat_lb[node->hierarchy][node->data_type];
216     HMAT_LB_Data lb_data = {};
217     HMAT_LB_Data *lb_temp;
218 
219     /* Error checking */
220     if (node->initiator > numa_state->num_nodes) {
221         error_setg(errp, "Invalid initiator=%d, it should be less than %d",
222                    node->initiator, numa_state->num_nodes);
223         return;
224     }
225     if (node->target > numa_state->num_nodes) {
226         error_setg(errp, "Invalid target=%d, it should be less than %d",
227                    node->target, numa_state->num_nodes);
228         return;
229     }
230     if (!numa_info[node->initiator].has_cpu &&
231         !numa_info[node->initiator].has_gi) {
232         error_setg(errp, "Invalid initiator=%d, it isn't an "
233                    "initiator proximity domain", node->initiator);
234         return;
235     }
236     if (!numa_info[node->target].present) {
237         error_setg(errp, "The target=%d should point to an existing node",
238                    node->target);
239         return;
240     }
241 
242     if (!hmat_lb) {
243         hmat_lb = g_malloc0(sizeof(*hmat_lb));
244         numa_state->hmat_lb[node->hierarchy][node->data_type] = hmat_lb;
245         hmat_lb->list = g_array_new(false, true, sizeof(HMAT_LB_Data));
246     }
247     hmat_lb->hierarchy = node->hierarchy;
248     hmat_lb->data_type = node->data_type;
249     lb_data.initiator = node->initiator;
250     lb_data.target = node->target;
251 
252     if (node->data_type <= HMATLB_DATA_TYPE_WRITE_LATENCY) {
253         /* Input latency data */
254 
255         if (!node->has_latency) {
256             error_setg(errp, "Missing 'latency' option");
257             return;
258         }
259         if (node->has_bandwidth) {
260             error_setg(errp, "Invalid option 'bandwidth' since "
261                        "the data type is latency");
262             return;
263         }
264 
265         /* Detect duplicate configuration */
266         for (i = 0; i < hmat_lb->list->len; i++) {
267             lb_temp = &g_array_index(hmat_lb->list, HMAT_LB_Data, i);
268 
269             if (node->initiator == lb_temp->initiator &&
270                 node->target == lb_temp->target) {
271                 error_setg(errp, "Duplicate configuration of the latency for "
272                     "initiator=%d and target=%d", node->initiator,
273                     node->target);
274                 return;
275             }
276         }
277 
278         hmat_lb->base = hmat_lb->base ? hmat_lb->base : UINT64_MAX;
279 
280         if (node->latency) {
281             /* Calculate the temporary base and compressed latency */
282             max_entry = node->latency;
283             temp_base = 1;
284             while (QEMU_IS_ALIGNED(max_entry, 10)) {
285                 max_entry /= 10;
286                 temp_base *= 10;
287             }
288 
289             /* Calculate the max compressed latency */
290             temp_base = MIN(hmat_lb->base, temp_base);
291             max_entry = node->latency / hmat_lb->base;
292             max_entry = MAX(hmat_lb->range_bitmap, max_entry);
293 
294             /*
295              * For latency hmat_lb->range_bitmap record the max compressed
296              * latency which should be less than 0xFFFF (UINT16_MAX)
297              */
298             if (max_entry >= UINT16_MAX) {
299                 error_setg(errp, "Latency %" PRIu64 " between initiator=%d and "
300                         "target=%d should not differ from previously entered "
301                         "min or max values on more than %d", node->latency,
302                         node->initiator, node->target, UINT16_MAX - 1);
303                 return;
304             } else {
305                 hmat_lb->base = temp_base;
306                 hmat_lb->range_bitmap = max_entry;
307             }
308 
309             /*
310              * Set lb_info_provided bit 0 as 1,
311              * latency information is provided
312              */
313             numa_info[node->target].lb_info_provided |= BIT(0);
314         }
315         lb_data.data = node->latency;
316     } else if (node->data_type >= HMATLB_DATA_TYPE_ACCESS_BANDWIDTH) {
317         /* Input bandwidth data */
318         if (!node->has_bandwidth) {
319             error_setg(errp, "Missing 'bandwidth' option");
320             return;
321         }
322         if (node->has_latency) {
323             error_setg(errp, "Invalid option 'latency' since "
324                        "the data type is bandwidth");
325             return;
326         }
327         if (!QEMU_IS_ALIGNED(node->bandwidth, MiB)) {
328             error_setg(errp, "Bandwidth %" PRIu64 " between initiator=%d and "
329                        "target=%d should be 1MB aligned", node->bandwidth,
330                        node->initiator, node->target);
331             return;
332         }
333 
334         /* Detect duplicate configuration */
335         for (i = 0; i < hmat_lb->list->len; i++) {
336             lb_temp = &g_array_index(hmat_lb->list, HMAT_LB_Data, i);
337 
338             if (node->initiator == lb_temp->initiator &&
339                 node->target == lb_temp->target) {
340                 error_setg(errp, "Duplicate configuration of the bandwidth for "
341                     "initiator=%d and target=%d", node->initiator,
342                     node->target);
343                 return;
344             }
345         }
346 
347         hmat_lb->base = hmat_lb->base ? hmat_lb->base : 1;
348 
349         if (node->bandwidth) {
350             /* Keep bitmap unchanged when bandwidth out of range */
351             bitmap_copy = hmat_lb->range_bitmap;
352             bitmap_copy |= node->bandwidth;
353             first_bit = ctz64(bitmap_copy);
354             temp_base = UINT64_C(1) << first_bit;
355             max_entry = node->bandwidth / temp_base;
356             last_bit = 64 - clz64(bitmap_copy);
357 
358             /*
359              * For bandwidth, first_bit record the base unit of bandwidth bits,
360              * last_bit record the last bit of the max bandwidth. The max
361              * compressed bandwidth should be less than 0xFFFF (UINT16_MAX)
362              */
363             if ((last_bit - first_bit) > UINT16_BITS ||
364                 max_entry >= UINT16_MAX) {
365                 error_setg(errp, "Bandwidth %" PRIu64 " between initiator=%d "
366                         "and target=%d should not differ from previously "
367                         "entered values on more than %d", node->bandwidth,
368                         node->initiator, node->target, UINT16_MAX - 1);
369                 return;
370             } else {
371                 hmat_lb->base = temp_base;
372                 hmat_lb->range_bitmap = bitmap_copy;
373             }
374 
375             /*
376              * Set lb_info_provided bit 1 as 1,
377              * bandwidth information is provided
378              */
379             numa_info[node->target].lb_info_provided |= BIT(1);
380         }
381         lb_data.data = node->bandwidth;
382     } else {
383         assert(0);
384     }
385 
386     g_array_append_val(hmat_lb->list, lb_data);
387 }
388 
389 void parse_numa_hmat_cache(MachineState *ms, NumaHmatCacheOptions *node,
390                            Error **errp)
391 {
392     int nb_numa_nodes = ms->numa_state->num_nodes;
393     NodeInfo *numa_info = ms->numa_state->nodes;
394     NumaHmatCacheOptions *hmat_cache = NULL;
395 
396     if (node->node_id >= nb_numa_nodes) {
397         error_setg(errp, "Invalid node-id=%" PRIu32 ", it should be less "
398                    "than %d", node->node_id, nb_numa_nodes);
399         return;
400     }
401 
402     if (numa_info[node->node_id].lb_info_provided != (BIT(0) | BIT(1))) {
403         error_setg(errp, "The latency and bandwidth information of "
404                    "node-id=%" PRIu32 " should be provided before memory side "
405                    "cache attributes", node->node_id);
406         return;
407     }
408 
409     if (node->level < 1 || node->level >= HMAT_LB_LEVELS) {
410         error_setg(errp, "Invalid level=%" PRIu8 ", it should be larger than 0 "
411                    "and less than or equal to %d", node->level,
412                    HMAT_LB_LEVELS - 1);
413         return;
414     }
415 
416     assert(node->associativity < HMAT_CACHE_ASSOCIATIVITY__MAX);
417     assert(node->policy < HMAT_CACHE_WRITE_POLICY__MAX);
418     if (ms->numa_state->hmat_cache[node->node_id][node->level]) {
419         error_setg(errp, "Duplicate configuration of the side cache for "
420                    "node-id=%" PRIu32 " and level=%" PRIu8,
421                    node->node_id, node->level);
422         return;
423     }
424 
425     if ((node->level > 1) &&
426         ms->numa_state->hmat_cache[node->node_id][node->level - 1] == NULL) {
427         error_setg(errp, "Cache level=%u shall be defined first",
428                    node->level - 1);
429         return;
430     }
431 
432     if ((node->level > 1) &&
433         (node->size <=
434             ms->numa_state->hmat_cache[node->node_id][node->level - 1]->size)) {
435         error_setg(errp, "Invalid size=%" PRIu64 ", the size of level=%" PRIu8
436                    " should be larger than the size(%" PRIu64 ") of "
437                    "level=%u", node->size, node->level,
438                    ms->numa_state->hmat_cache[node->node_id]
439                                              [node->level - 1]->size,
440                    node->level - 1);
441         return;
442     }
443 
444     if ((node->level < HMAT_LB_LEVELS - 1) &&
445         ms->numa_state->hmat_cache[node->node_id][node->level + 1] &&
446         (node->size >=
447             ms->numa_state->hmat_cache[node->node_id][node->level + 1]->size)) {
448         error_setg(errp, "Invalid size=%" PRIu64 ", the size of level=%" PRIu8
449                    " should be less than the size(%" PRIu64 ") of "
450                    "level=%u", node->size, node->level,
451                    ms->numa_state->hmat_cache[node->node_id]
452                                              [node->level + 1]->size,
453                    node->level + 1);
454         return;
455     }
456 
457     hmat_cache = g_malloc0(sizeof(*hmat_cache));
458     memcpy(hmat_cache, node, sizeof(*hmat_cache));
459     ms->numa_state->hmat_cache[node->node_id][node->level] = hmat_cache;
460 }
461 
462 void set_numa_options(MachineState *ms, NumaOptions *object, Error **errp)
463 {
464     if (!ms->numa_state) {
465         error_setg(errp, "NUMA is not supported by this machine-type");
466         return;
467     }
468 
469     switch (object->type) {
470     case NUMA_OPTIONS_TYPE_NODE:
471         parse_numa_node(ms, &object->u.node, errp);
472         break;
473     case NUMA_OPTIONS_TYPE_DIST:
474         parse_numa_distance(ms, &object->u.dist, errp);
475         break;
476     case NUMA_OPTIONS_TYPE_CPU:
477         if (!object->u.cpu.has_node_id) {
478             error_setg(errp, "Missing mandatory node-id property");
479             return;
480         }
481         if (!ms->numa_state->nodes[object->u.cpu.node_id].present) {
482             error_setg(errp, "Invalid node-id=%" PRId64 ", NUMA node must be "
483                        "defined with -numa node,nodeid=ID before it's used with "
484                        "-numa cpu,node-id=ID", object->u.cpu.node_id);
485             return;
486         }
487 
488         machine_set_cpu_numa_node(ms,
489                                   qapi_NumaCpuOptions_base(&object->u.cpu),
490                                   errp);
491         break;
492     case NUMA_OPTIONS_TYPE_HMAT_LB:
493         if (!ms->numa_state->hmat_enabled) {
494             error_setg(errp, "ACPI Heterogeneous Memory Attribute Table "
495                        "(HMAT) is disabled, enable it with -machine hmat=on "
496                        "before using any of hmat specific options");
497             return;
498         }
499 
500         parse_numa_hmat_lb(ms->numa_state, &object->u.hmat_lb, errp);
501         break;
502     case NUMA_OPTIONS_TYPE_HMAT_CACHE:
503         if (!ms->numa_state->hmat_enabled) {
504             error_setg(errp, "ACPI Heterogeneous Memory Attribute Table "
505                        "(HMAT) is disabled, enable it with -machine hmat=on "
506                        "before using any of hmat specific options");
507             return;
508         }
509 
510         parse_numa_hmat_cache(ms, &object->u.hmat_cache, errp);
511         break;
512     default:
513         abort();
514     }
515 }
516 
517 static int parse_numa(void *opaque, QemuOpts *opts, Error **errp)
518 {
519     NumaOptions *object = NULL;
520     MachineState *ms = MACHINE(opaque);
521     Error *err = NULL;
522     Visitor *v = opts_visitor_new(opts);
523 
524     visit_type_NumaOptions(v, NULL, &object, errp);
525     visit_free(v);
526     if (!object) {
527         return -1;
528     }
529 
530     /* Fix up legacy suffix-less format */
531     if ((object->type == NUMA_OPTIONS_TYPE_NODE) && object->u.node.has_mem) {
532         const char *mem_str = qemu_opt_get(opts, "mem");
533         int ret = qemu_strtosz_MiB(mem_str, NULL, &object->u.node.mem);
534 
535         if (ret < 0) {
536             error_setg_errno(&err, -ret, "could not parse memory size '%s'",
537                              mem_str);
538         }
539     }
540 
541     if (!err) {
542         set_numa_options(ms, object, &err);
543     }
544 
545     qapi_free_NumaOptions(object);
546     if (err) {
547         error_propagate(errp, err);
548         return -1;
549     }
550 
551     return 0;
552 }
553 
554 /* If all node pair distances are symmetric, then only distances
555  * in one direction are enough. If there is even one asymmetric
556  * pair, though, then all distances must be provided. The
557  * distance from a node to itself is always NUMA_DISTANCE_MIN,
558  * so providing it is never necessary.
559  */
560 static void validate_numa_distance(MachineState *ms)
561 {
562     int src, dst;
563     bool is_asymmetrical = false;
564     int nb_numa_nodes = ms->numa_state->num_nodes;
565     NodeInfo *numa_info = ms->numa_state->nodes;
566 
567     for (src = 0; src < nb_numa_nodes; src++) {
568         for (dst = src; dst < nb_numa_nodes; dst++) {
569             if (numa_info[src].distance[dst] == 0 &&
570                 numa_info[dst].distance[src] == 0) {
571                 if (src != dst) {
572                     error_report("The distance between node %d and %d is "
573                                  "missing, at least one distance value "
574                                  "between each nodes should be provided.",
575                                  src, dst);
576                     exit(EXIT_FAILURE);
577                 }
578             }
579 
580             if (numa_info[src].distance[dst] != 0 &&
581                 numa_info[dst].distance[src] != 0 &&
582                 numa_info[src].distance[dst] !=
583                 numa_info[dst].distance[src]) {
584                 is_asymmetrical = true;
585             }
586         }
587     }
588 
589     if (is_asymmetrical) {
590         for (src = 0; src < nb_numa_nodes; src++) {
591             for (dst = 0; dst < nb_numa_nodes; dst++) {
592                 if (src != dst && numa_info[src].distance[dst] == 0) {
593                     error_report("At least one asymmetrical pair of "
594                             "distances is given, please provide distances "
595                             "for both directions of all node pairs.");
596                     exit(EXIT_FAILURE);
597                 }
598             }
599         }
600     }
601 }
602 
603 static void complete_init_numa_distance(MachineState *ms)
604 {
605     int src, dst;
606     NodeInfo *numa_info = ms->numa_state->nodes;
607 
608     /* Fixup NUMA distance by symmetric policy because if it is an
609      * asymmetric distance table, it should be a complete table and
610      * there would not be any missing distance except local node, which
611      * is verified by validate_numa_distance above.
612      */
613     for (src = 0; src < ms->numa_state->num_nodes; src++) {
614         for (dst = 0; dst < ms->numa_state->num_nodes; dst++) {
615             if (numa_info[src].distance[dst] == 0) {
616                 if (src == dst) {
617                     numa_info[src].distance[dst] = NUMA_DISTANCE_MIN;
618                 } else {
619                     numa_info[src].distance[dst] = numa_info[dst].distance[src];
620                 }
621             }
622         }
623     }
624 }
625 
626 static void numa_init_memdev_container(MachineState *ms, MemoryRegion *ram)
627 {
628     int i;
629     uint64_t addr = 0;
630 
631     for (i = 0; i < ms->numa_state->num_nodes; i++) {
632         uint64_t size = ms->numa_state->nodes[i].node_mem;
633         HostMemoryBackend *backend = ms->numa_state->nodes[i].node_memdev;
634         if (!backend) {
635             continue;
636         }
637         MemoryRegion *seg = machine_consume_memdev(ms, backend);
638         memory_region_add_subregion(ram, addr, seg);
639         addr += size;
640     }
641 }
642 
643 void numa_complete_configuration(MachineState *ms)
644 {
645     int i;
646     MachineClass *mc = MACHINE_GET_CLASS(ms);
647     NodeInfo *numa_info = ms->numa_state->nodes;
648 
649     /*
650      * If memory hotplug is enabled (slot > 0) or memory devices are enabled
651      * (ms->maxram_size > ms->ram_size) but without '-numa' options explicitly on
652      * CLI, guests will break.
653      *
654      *   Windows: won't enable memory hotplug without SRAT table at all
655      *
656      *   Linux: if QEMU is started with initial memory all below 4Gb
657      *   and no SRAT table present, guest kernel will use nommu DMA ops,
658      *   which breaks 32bit hw drivers when memory is hotplugged and
659      *   guest tries to use it with that drivers.
660      *
661      * Enable NUMA implicitly by adding a new NUMA node automatically.
662      *
663      * Or if MachineClass::auto_enable_numa is true and no NUMA nodes,
664      * assume there is just one node with whole RAM.
665      */
666     if (ms->numa_state->num_nodes == 0 &&
667         ((ms->ram_slots && mc->auto_enable_numa_with_memhp) ||
668          (ms->maxram_size > ms->ram_size && mc->auto_enable_numa_with_memdev) ||
669          mc->auto_enable_numa)) {
670             NumaNodeOptions node = { };
671             parse_numa_node(ms, &node, &error_abort);
672             numa_info[0].node_mem = ms->ram_size;
673     }
674 
675     assert(max_numa_nodeid <= MAX_NODES);
676 
677     /* No support for sparse NUMA node IDs yet: */
678     for (i = max_numa_nodeid - 1; i >= 0; i--) {
679         /* Report large node IDs first, to make mistakes easier to spot */
680         if (!numa_info[i].present) {
681             error_report("numa: Node ID missing: %d", i);
682             exit(1);
683         }
684     }
685 
686     /* This must be always true if all nodes are present: */
687     assert(ms->numa_state->num_nodes == max_numa_nodeid);
688 
689     if (ms->numa_state->num_nodes > 0) {
690         uint64_t numa_total;
691 
692         numa_total = 0;
693         for (i = 0; i < ms->numa_state->num_nodes; i++) {
694             numa_total += numa_info[i].node_mem;
695         }
696         if (numa_total != ms->ram_size) {
697             error_report("total memory for NUMA nodes (0x%" PRIx64 ")"
698                          " should equal RAM size (0x" RAM_ADDR_FMT ")",
699                          numa_total, ms->ram_size);
700             exit(1);
701         }
702 
703         if (!numa_uses_legacy_mem() && mc->default_ram_id) {
704             if (ms->memdev) {
705                 error_report("'-machine memory-backend' and '-numa memdev'"
706                              " properties are mutually exclusive");
707                 exit(1);
708             }
709             ms->ram = g_new(MemoryRegion, 1);
710             memory_region_init(ms->ram, OBJECT(ms), mc->default_ram_id,
711                                ms->ram_size);
712             numa_init_memdev_container(ms, ms->ram);
713         }
714         /* QEMU needs at least all unique node pair distances to build
715          * the whole NUMA distance table. QEMU treats the distance table
716          * as symmetric by default, i.e. distance A->B == distance B->A.
717          * Thus, QEMU is able to complete the distance table
718          * initialization even though only distance A->B is provided and
719          * distance B->A is not. QEMU knows the distance of a node to
720          * itself is always 10, so A->A distances may be omitted. When
721          * the distances of two nodes of a pair differ, i.e. distance
722          * A->B != distance B->A, then that means the distance table is
723          * asymmetric. In this case, the distances for both directions
724          * of all node pairs are required.
725          */
726         if (ms->numa_state->have_numa_distance) {
727             /* Validate enough NUMA distance information was provided. */
728             validate_numa_distance(ms);
729 
730             /* Validation succeeded, now fill in any missing distances. */
731             complete_init_numa_distance(ms);
732         }
733     }
734 }
735 
736 void parse_numa_opts(MachineState *ms)
737 {
738     qemu_opts_foreach(qemu_find_opts("numa"), parse_numa, ms, &error_fatal);
739 }
740 
741 void numa_cpu_pre_plug(const CPUArchId *slot, DeviceState *dev, Error **errp)
742 {
743     int node_id = object_property_get_int(OBJECT(dev), "node-id", &error_abort);
744 
745     if (node_id == CPU_UNSET_NUMA_NODE_ID) {
746         /* due to bug in libvirt, it doesn't pass node-id from props on
747          * device_add as expected, so we have to fix it up here */
748         if (slot->props.has_node_id) {
749             object_property_set_int(OBJECT(dev), "node-id",
750                                     slot->props.node_id, errp);
751         }
752     } else if (node_id != slot->props.node_id) {
753         error_setg(errp, "invalid node-id, must be %"PRId64,
754                    slot->props.node_id);
755     }
756 }
757 
758 static void numa_stat_memory_devices(NumaNodeMem node_mem[])
759 {
760     MemoryDeviceInfoList *info_list = qmp_memory_device_list();
761     MemoryDeviceInfoList *info;
762     PCDIMMDeviceInfo     *pcdimm_info;
763     VirtioPMEMDeviceInfo *vpi;
764     VirtioMEMDeviceInfo *vmi;
765     SgxEPCDeviceInfo *se;
766 
767     for (info = info_list; info; info = info->next) {
768         MemoryDeviceInfo *value = info->value;
769 
770         if (value) {
771             switch (value->type) {
772             case MEMORY_DEVICE_INFO_KIND_DIMM:
773             case MEMORY_DEVICE_INFO_KIND_NVDIMM:
774                 pcdimm_info = value->type == MEMORY_DEVICE_INFO_KIND_DIMM ?
775                               value->u.dimm.data : value->u.nvdimm.data;
776                 node_mem[pcdimm_info->node].node_mem += pcdimm_info->size;
777                 node_mem[pcdimm_info->node].node_plugged_mem +=
778                     pcdimm_info->size;
779                 break;
780             case MEMORY_DEVICE_INFO_KIND_VIRTIO_PMEM:
781                 vpi = value->u.virtio_pmem.data;
782                 /* TODO: once we support numa, assign to right node */
783                 node_mem[0].node_mem += vpi->size;
784                 node_mem[0].node_plugged_mem += vpi->size;
785                 break;
786             case MEMORY_DEVICE_INFO_KIND_VIRTIO_MEM:
787                 vmi = value->u.virtio_mem.data;
788                 node_mem[vmi->node].node_mem += vmi->size;
789                 node_mem[vmi->node].node_plugged_mem += vmi->size;
790                 break;
791             case MEMORY_DEVICE_INFO_KIND_SGX_EPC:
792                 se = value->u.sgx_epc.data;
793                 node_mem[se->node].node_mem += se->size;
794                 node_mem[se->node].node_plugged_mem = 0;
795                 break;
796             default:
797                 g_assert_not_reached();
798             }
799         }
800     }
801     qapi_free_MemoryDeviceInfoList(info_list);
802 }
803 
804 void query_numa_node_mem(NumaNodeMem node_mem[], MachineState *ms)
805 {
806     int i;
807 
808     if (ms->numa_state == NULL || ms->numa_state->num_nodes <= 0) {
809         return;
810     }
811 
812     numa_stat_memory_devices(node_mem);
813     for (i = 0; i < ms->numa_state->num_nodes; i++) {
814         node_mem[i].node_mem += ms->numa_state->nodes[i].node_mem;
815     }
816 }
817 
818 static int ram_block_notify_add_single(RAMBlock *rb, void *opaque)
819 {
820     const ram_addr_t max_size = qemu_ram_get_max_length(rb);
821     const ram_addr_t size = qemu_ram_get_used_length(rb);
822     void *host = qemu_ram_get_host_addr(rb);
823     RAMBlockNotifier *notifier = opaque;
824 
825     if (host) {
826         notifier->ram_block_added(notifier, host, size, max_size);
827     }
828     return 0;
829 }
830 
831 static int ram_block_notify_remove_single(RAMBlock *rb, void *opaque)
832 {
833     const ram_addr_t max_size = qemu_ram_get_max_length(rb);
834     const ram_addr_t size = qemu_ram_get_used_length(rb);
835     void *host = qemu_ram_get_host_addr(rb);
836     RAMBlockNotifier *notifier = opaque;
837 
838     if (host) {
839         notifier->ram_block_removed(notifier, host, size, max_size);
840     }
841     return 0;
842 }
843 
844 void ram_block_notifier_add(RAMBlockNotifier *n)
845 {
846     QLIST_INSERT_HEAD(&ram_list.ramblock_notifiers, n, next);
847 
848     /* Notify about all existing ram blocks. */
849     if (n->ram_block_added) {
850         qemu_ram_foreach_block(ram_block_notify_add_single, n);
851     }
852 }
853 
854 void ram_block_notifier_remove(RAMBlockNotifier *n)
855 {
856     QLIST_REMOVE(n, next);
857 
858     if (n->ram_block_removed) {
859         qemu_ram_foreach_block(ram_block_notify_remove_single, n);
860     }
861 }
862 
863 void ram_block_notify_add(void *host, size_t size, size_t max_size)
864 {
865     RAMBlockNotifier *notifier;
866     RAMBlockNotifier *next;
867 
868     QLIST_FOREACH_SAFE(notifier, &ram_list.ramblock_notifiers, next, next) {
869         if (notifier->ram_block_added) {
870             notifier->ram_block_added(notifier, host, size, max_size);
871         }
872     }
873 }
874 
875 void ram_block_notify_remove(void *host, size_t size, size_t max_size)
876 {
877     RAMBlockNotifier *notifier;
878     RAMBlockNotifier *next;
879 
880     QLIST_FOREACH_SAFE(notifier, &ram_list.ramblock_notifiers, next, next) {
881         if (notifier->ram_block_removed) {
882             notifier->ram_block_removed(notifier, host, size, max_size);
883         }
884     }
885 }
886 
887 void ram_block_notify_resize(void *host, size_t old_size, size_t new_size)
888 {
889     RAMBlockNotifier *notifier;
890     RAMBlockNotifier *next;
891 
892     QLIST_FOREACH_SAFE(notifier, &ram_list.ramblock_notifiers, next, next) {
893         if (notifier->ram_block_resized) {
894             notifier->ram_block_resized(notifier, host, old_size, new_size);
895         }
896     }
897 }
898