xref: /openbmc/qemu/hw/core/numa.c (revision 40f23e4e)
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     for (cpus = node->cpus; cpus; cpus = cpus->next) {
92         CpuInstanceProperties props;
93         if (cpus->value >= max_cpus) {
94             error_setg(errp,
95                        "CPU index (%" PRIu16 ")"
96                        " should be smaller than maxcpus (%d)",
97                        cpus->value, max_cpus);
98             return;
99         }
100         props = mc->cpu_index_to_instance_props(ms, cpus->value);
101         props.node_id = nodenr;
102         props.has_node_id = true;
103         machine_set_cpu_numa_node(ms, &props, &err);
104         if (err) {
105             error_propagate(errp, err);
106             return;
107         }
108     }
109 
110     have_memdevs = have_memdevs ? : node->has_memdev;
111     have_mem = have_mem ? : node->has_mem;
112     if ((node->has_mem && have_memdevs) || (node->has_memdev && have_mem)) {
113         error_setg(errp, "numa configuration should use either mem= or memdev=,"
114                    "mixing both is not allowed");
115         return;
116     }
117 
118     if (node->has_mem) {
119         if (!mc->numa_mem_supported) {
120             error_setg(errp, "Parameter -numa node,mem is not supported by this"
121                       " machine type");
122             error_append_hint(errp, "Use -numa node,memdev instead\n");
123             return;
124         }
125 
126         numa_info[nodenr].node_mem = node->mem;
127         if (!qtest_enabled()) {
128             warn_report("Parameter -numa node,mem is deprecated,"
129                         " use -numa node,memdev instead");
130         }
131     }
132     if (node->has_memdev) {
133         Object *o;
134         o = object_resolve_path_type(node->memdev, TYPE_MEMORY_BACKEND, NULL);
135         if (!o) {
136             error_setg(errp, "memdev=%s is ambiguous", node->memdev);
137             return;
138         }
139 
140         object_ref(o);
141         numa_info[nodenr].node_mem = object_property_get_uint(o, "size", NULL);
142         numa_info[nodenr].node_memdev = MEMORY_BACKEND(o);
143     }
144 
145     /*
146      * If not set the initiator, set it to MAX_NODES. And if
147      * HMAT is enabled and this node has no cpus, QEMU will raise error.
148      */
149     numa_info[nodenr].initiator = MAX_NODES;
150     if (node->has_initiator) {
151         if (!ms->numa_state->hmat_enabled) {
152             error_setg(errp, "ACPI Heterogeneous Memory Attribute Table "
153                        "(HMAT) is disabled, enable it with -machine hmat=on "
154                        "before using any of hmat specific options");
155             return;
156         }
157 
158         if (node->initiator >= MAX_NODES) {
159             error_report("The initiator id %" PRIu16 " expects an integer "
160                          "between 0 and %d", node->initiator,
161                          MAX_NODES - 1);
162             return;
163         }
164 
165         numa_info[nodenr].initiator = node->initiator;
166     }
167     numa_info[nodenr].present = true;
168     max_numa_nodeid = MAX(max_numa_nodeid, nodenr + 1);
169     ms->numa_state->num_nodes++;
170 }
171 
172 static
173 void parse_numa_distance(MachineState *ms, NumaDistOptions *dist, Error **errp)
174 {
175     uint16_t src = dist->src;
176     uint16_t dst = dist->dst;
177     uint8_t val = dist->val;
178     NodeInfo *numa_info = ms->numa_state->nodes;
179 
180     if (src >= MAX_NODES || dst >= MAX_NODES) {
181         error_setg(errp, "Parameter '%s' expects an integer between 0 and %d",
182                    src >= MAX_NODES ? "src" : "dst", MAX_NODES - 1);
183         return;
184     }
185 
186     if (!numa_info[src].present || !numa_info[dst].present) {
187         error_setg(errp, "Source/Destination NUMA node is missing. "
188                    "Please use '-numa node' option to declare it first.");
189         return;
190     }
191 
192     if (val < NUMA_DISTANCE_MIN) {
193         error_setg(errp, "NUMA distance (%" PRIu8 ") is invalid, "
194                    "it shouldn't be less than %d.",
195                    val, NUMA_DISTANCE_MIN);
196         return;
197     }
198 
199     if (src == dst && val != NUMA_DISTANCE_MIN) {
200         error_setg(errp, "Local distance of node %d should be %d.",
201                    src, NUMA_DISTANCE_MIN);
202         return;
203     }
204 
205     numa_info[src].distance[dst] = val;
206     ms->numa_state->have_numa_distance = true;
207 }
208 
209 void parse_numa_hmat_lb(NumaState *numa_state, NumaHmatLBOptions *node,
210                         Error **errp)
211 {
212     int i, first_bit, last_bit;
213     uint64_t max_entry, temp_base, bitmap_copy;
214     NodeInfo *numa_info = numa_state->nodes;
215     HMAT_LB_Info *hmat_lb =
216         numa_state->hmat_lb[node->hierarchy][node->data_type];
217     HMAT_LB_Data lb_data = {};
218     HMAT_LB_Data *lb_temp;
219 
220     /* Error checking */
221     if (node->initiator > numa_state->num_nodes) {
222         error_setg(errp, "Invalid initiator=%d, it should be less than %d",
223                    node->initiator, numa_state->num_nodes);
224         return;
225     }
226     if (node->target > numa_state->num_nodes) {
227         error_setg(errp, "Invalid target=%d, it should be less than %d",
228                    node->target, numa_state->num_nodes);
229         return;
230     }
231     if (!numa_info[node->initiator].has_cpu) {
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         qemu_strtosz_MiB(mem_str, NULL, &object->u.node.mem);
534     }
535 
536     set_numa_options(ms, object, &err);
537 
538     qapi_free_NumaOptions(object);
539     if (err) {
540         error_propagate(errp, err);
541         return -1;
542     }
543 
544     return 0;
545 }
546 
547 /* If all node pair distances are symmetric, then only distances
548  * in one direction are enough. If there is even one asymmetric
549  * pair, though, then all distances must be provided. The
550  * distance from a node to itself is always NUMA_DISTANCE_MIN,
551  * so providing it is never necessary.
552  */
553 static void validate_numa_distance(MachineState *ms)
554 {
555     int src, dst;
556     bool is_asymmetrical = false;
557     int nb_numa_nodes = ms->numa_state->num_nodes;
558     NodeInfo *numa_info = ms->numa_state->nodes;
559 
560     for (src = 0; src < nb_numa_nodes; src++) {
561         for (dst = src; dst < nb_numa_nodes; dst++) {
562             if (numa_info[src].distance[dst] == 0 &&
563                 numa_info[dst].distance[src] == 0) {
564                 if (src != dst) {
565                     error_report("The distance between node %d and %d is "
566                                  "missing, at least one distance value "
567                                  "between each nodes should be provided.",
568                                  src, dst);
569                     exit(EXIT_FAILURE);
570                 }
571             }
572 
573             if (numa_info[src].distance[dst] != 0 &&
574                 numa_info[dst].distance[src] != 0 &&
575                 numa_info[src].distance[dst] !=
576                 numa_info[dst].distance[src]) {
577                 is_asymmetrical = true;
578             }
579         }
580     }
581 
582     if (is_asymmetrical) {
583         for (src = 0; src < nb_numa_nodes; src++) {
584             for (dst = 0; dst < nb_numa_nodes; dst++) {
585                 if (src != dst && numa_info[src].distance[dst] == 0) {
586                     error_report("At least one asymmetrical pair of "
587                             "distances is given, please provide distances "
588                             "for both directions of all node pairs.");
589                     exit(EXIT_FAILURE);
590                 }
591             }
592         }
593     }
594 }
595 
596 static void complete_init_numa_distance(MachineState *ms)
597 {
598     int src, dst;
599     NodeInfo *numa_info = ms->numa_state->nodes;
600 
601     /* Fixup NUMA distance by symmetric policy because if it is an
602      * asymmetric distance table, it should be a complete table and
603      * there would not be any missing distance except local node, which
604      * is verified by validate_numa_distance above.
605      */
606     for (src = 0; src < ms->numa_state->num_nodes; src++) {
607         for (dst = 0; dst < ms->numa_state->num_nodes; dst++) {
608             if (numa_info[src].distance[dst] == 0) {
609                 if (src == dst) {
610                     numa_info[src].distance[dst] = NUMA_DISTANCE_MIN;
611                 } else {
612                     numa_info[src].distance[dst] = numa_info[dst].distance[src];
613                 }
614             }
615         }
616     }
617 }
618 
619 static void numa_init_memdev_container(MachineState *ms, MemoryRegion *ram)
620 {
621     int i;
622     uint64_t addr = 0;
623 
624     for (i = 0; i < ms->numa_state->num_nodes; i++) {
625         uint64_t size = ms->numa_state->nodes[i].node_mem;
626         HostMemoryBackend *backend = ms->numa_state->nodes[i].node_memdev;
627         if (!backend) {
628             continue;
629         }
630         MemoryRegion *seg = machine_consume_memdev(ms, backend);
631         memory_region_add_subregion(ram, addr, seg);
632         addr += size;
633     }
634 }
635 
636 void numa_complete_configuration(MachineState *ms)
637 {
638     int i;
639     MachineClass *mc = MACHINE_GET_CLASS(ms);
640     NodeInfo *numa_info = ms->numa_state->nodes;
641 
642     /*
643      * If memory hotplug is enabled (slot > 0) or memory devices are enabled
644      * (ms->maxram_size > ms->ram_size) but without '-numa' options explicitly on
645      * CLI, guests will break.
646      *
647      *   Windows: won't enable memory hotplug without SRAT table at all
648      *
649      *   Linux: if QEMU is started with initial memory all below 4Gb
650      *   and no SRAT table present, guest kernel will use nommu DMA ops,
651      *   which breaks 32bit hw drivers when memory is hotplugged and
652      *   guest tries to use it with that drivers.
653      *
654      * Enable NUMA implicitly by adding a new NUMA node automatically.
655      *
656      * Or if MachineClass::auto_enable_numa is true and no NUMA nodes,
657      * assume there is just one node with whole RAM.
658      */
659     if (ms->numa_state->num_nodes == 0 &&
660         ((ms->ram_slots && mc->auto_enable_numa_with_memhp) ||
661          (ms->maxram_size > ms->ram_size && mc->auto_enable_numa_with_memdev) ||
662          mc->auto_enable_numa)) {
663             NumaNodeOptions node = { };
664             parse_numa_node(ms, &node, &error_abort);
665             numa_info[0].node_mem = ms->ram_size;
666     }
667 
668     assert(max_numa_nodeid <= MAX_NODES);
669 
670     /* No support for sparse NUMA node IDs yet: */
671     for (i = max_numa_nodeid - 1; i >= 0; i--) {
672         /* Report large node IDs first, to make mistakes easier to spot */
673         if (!numa_info[i].present) {
674             error_report("numa: Node ID missing: %d", i);
675             exit(1);
676         }
677     }
678 
679     /* This must be always true if all nodes are present: */
680     assert(ms->numa_state->num_nodes == max_numa_nodeid);
681 
682     if (ms->numa_state->num_nodes > 0) {
683         uint64_t numa_total;
684 
685         numa_total = 0;
686         for (i = 0; i < ms->numa_state->num_nodes; i++) {
687             numa_total += numa_info[i].node_mem;
688         }
689         if (numa_total != ms->ram_size) {
690             error_report("total memory for NUMA nodes (0x%" PRIx64 ")"
691                          " should equal RAM size (0x" RAM_ADDR_FMT ")",
692                          numa_total, ms->ram_size);
693             exit(1);
694         }
695 
696         if (!numa_uses_legacy_mem() && mc->default_ram_id) {
697             if (ms->ram_memdev_id) {
698                 error_report("'-machine memory-backend' and '-numa memdev'"
699                              " properties are mutually exclusive");
700                 exit(1);
701             }
702             ms->ram = g_new(MemoryRegion, 1);
703             memory_region_init(ms->ram, OBJECT(ms), mc->default_ram_id,
704                                ms->ram_size);
705             numa_init_memdev_container(ms, ms->ram);
706         }
707         /* QEMU needs at least all unique node pair distances to build
708          * the whole NUMA distance table. QEMU treats the distance table
709          * as symmetric by default, i.e. distance A->B == distance B->A.
710          * Thus, QEMU is able to complete the distance table
711          * initialization even though only distance A->B is provided and
712          * distance B->A is not. QEMU knows the distance of a node to
713          * itself is always 10, so A->A distances may be omitted. When
714          * the distances of two nodes of a pair differ, i.e. distance
715          * A->B != distance B->A, then that means the distance table is
716          * asymmetric. In this case, the distances for both directions
717          * of all node pairs are required.
718          */
719         if (ms->numa_state->have_numa_distance) {
720             /* Validate enough NUMA distance information was provided. */
721             validate_numa_distance(ms);
722 
723             /* Validation succeeded, now fill in any missing distances. */
724             complete_init_numa_distance(ms);
725         }
726     }
727 }
728 
729 void parse_numa_opts(MachineState *ms)
730 {
731     qemu_opts_foreach(qemu_find_opts("numa"), parse_numa, ms, &error_fatal);
732 }
733 
734 void numa_cpu_pre_plug(const CPUArchId *slot, DeviceState *dev, Error **errp)
735 {
736     int node_id = object_property_get_int(OBJECT(dev), "node-id", &error_abort);
737 
738     if (node_id == CPU_UNSET_NUMA_NODE_ID) {
739         /* due to bug in libvirt, it doesn't pass node-id from props on
740          * device_add as expected, so we have to fix it up here */
741         if (slot->props.has_node_id) {
742             object_property_set_int(OBJECT(dev), "node-id",
743                                     slot->props.node_id, errp);
744         }
745     } else if (node_id != slot->props.node_id) {
746         error_setg(errp, "invalid node-id, must be %"PRId64,
747                    slot->props.node_id);
748     }
749 }
750 
751 static void numa_stat_memory_devices(NumaNodeMem node_mem[])
752 {
753     MemoryDeviceInfoList *info_list = qmp_memory_device_list();
754     MemoryDeviceInfoList *info;
755     PCDIMMDeviceInfo     *pcdimm_info;
756     VirtioPMEMDeviceInfo *vpi;
757     VirtioMEMDeviceInfo *vmi;
758 
759     for (info = info_list; info; info = info->next) {
760         MemoryDeviceInfo *value = info->value;
761 
762         if (value) {
763             switch (value->type) {
764             case MEMORY_DEVICE_INFO_KIND_DIMM:
765             case MEMORY_DEVICE_INFO_KIND_NVDIMM:
766                 pcdimm_info = value->type == MEMORY_DEVICE_INFO_KIND_DIMM ?
767                               value->u.dimm.data : value->u.nvdimm.data;
768                 node_mem[pcdimm_info->node].node_mem += pcdimm_info->size;
769                 node_mem[pcdimm_info->node].node_plugged_mem +=
770                     pcdimm_info->size;
771                 break;
772             case MEMORY_DEVICE_INFO_KIND_VIRTIO_PMEM:
773                 vpi = value->u.virtio_pmem.data;
774                 /* TODO: once we support numa, assign to right node */
775                 node_mem[0].node_mem += vpi->size;
776                 node_mem[0].node_plugged_mem += vpi->size;
777                 break;
778             case MEMORY_DEVICE_INFO_KIND_VIRTIO_MEM:
779                 vmi = value->u.virtio_mem.data;
780                 node_mem[vmi->node].node_mem += vmi->size;
781                 node_mem[vmi->node].node_plugged_mem += vmi->size;
782                 break;
783             default:
784                 g_assert_not_reached();
785             }
786         }
787     }
788     qapi_free_MemoryDeviceInfoList(info_list);
789 }
790 
791 void query_numa_node_mem(NumaNodeMem node_mem[], MachineState *ms)
792 {
793     int i;
794 
795     if (ms->numa_state == NULL || ms->numa_state->num_nodes <= 0) {
796         return;
797     }
798 
799     numa_stat_memory_devices(node_mem);
800     for (i = 0; i < ms->numa_state->num_nodes; i++) {
801         node_mem[i].node_mem += ms->numa_state->nodes[i].node_mem;
802     }
803 }
804 
805 static int ram_block_notify_add_single(RAMBlock *rb, void *opaque)
806 {
807     const ram_addr_t max_size = qemu_ram_get_max_length(rb);
808     const ram_addr_t size = qemu_ram_get_used_length(rb);
809     void *host = qemu_ram_get_host_addr(rb);
810     RAMBlockNotifier *notifier = opaque;
811 
812     if (host) {
813         notifier->ram_block_added(notifier, host, size, max_size);
814     }
815     return 0;
816 }
817 
818 void ram_block_notifier_add(RAMBlockNotifier *n)
819 {
820     QLIST_INSERT_HEAD(&ram_list.ramblock_notifiers, n, next);
821 
822     /* Notify about all existing ram blocks. */
823     if (n->ram_block_added) {
824         qemu_ram_foreach_block(ram_block_notify_add_single, n);
825     }
826 }
827 
828 void ram_block_notifier_remove(RAMBlockNotifier *n)
829 {
830     QLIST_REMOVE(n, next);
831 }
832 
833 void ram_block_notify_add(void *host, size_t size, size_t max_size)
834 {
835     RAMBlockNotifier *notifier;
836 
837     QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
838         if (notifier->ram_block_added) {
839             notifier->ram_block_added(notifier, host, size, max_size);
840         }
841     }
842 }
843 
844 void ram_block_notify_remove(void *host, size_t size, size_t max_size)
845 {
846     RAMBlockNotifier *notifier;
847 
848     QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
849         if (notifier->ram_block_removed) {
850             notifier->ram_block_removed(notifier, host, size, max_size);
851         }
852     }
853 }
854 
855 void ram_block_notify_resize(void *host, size_t old_size, size_t new_size)
856 {
857     RAMBlockNotifier *notifier;
858 
859     QLIST_FOREACH(notifier, &ram_list.ramblock_notifiers, next) {
860         if (notifier->ram_block_resized) {
861             notifier->ram_block_resized(notifier, host, old_size, new_size);
862         }
863     }
864 }
865