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