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