xref: /openbmc/qemu/hw/ppc/spapr.c (revision 9ac703ac5f9e830ab96d38dc77061bd4be76cf60)
1 /*
2  * QEMU PowerPC pSeries Logical Partition (aka sPAPR) hardware System Emulator
3  *
4  * Copyright (c) 2004-2007 Fabrice Bellard
5  * Copyright (c) 2007 Jocelyn Mayer
6  * Copyright (c) 2010 David Gibson, IBM Corporation.
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  */
26 
27 #include "qemu/osdep.h"
28 #include "qemu-common.h"
29 #include "qapi/error.h"
30 #include "qapi/visitor.h"
31 #include "sysemu/sysemu.h"
32 #include "sysemu/hostmem.h"
33 #include "sysemu/numa.h"
34 #include "sysemu/qtest.h"
35 #include "sysemu/reset.h"
36 #include "sysemu/runstate.h"
37 #include "qemu/log.h"
38 #include "hw/fw-path-provider.h"
39 #include "elf.h"
40 #include "net/net.h"
41 #include "sysemu/device_tree.h"
42 #include "sysemu/cpus.h"
43 #include "sysemu/hw_accel.h"
44 #include "kvm_ppc.h"
45 #include "migration/misc.h"
46 #include "migration/qemu-file-types.h"
47 #include "migration/global_state.h"
48 #include "migration/register.h"
49 #include "mmu-hash64.h"
50 #include "mmu-book3s-v3.h"
51 #include "cpu-models.h"
52 #include "hw/core/cpu.h"
53 
54 #include "hw/boards.h"
55 #include "hw/ppc/ppc.h"
56 #include "hw/loader.h"
57 
58 #include "hw/ppc/fdt.h"
59 #include "hw/ppc/spapr.h"
60 #include "hw/ppc/spapr_vio.h"
61 #include "hw/qdev-properties.h"
62 #include "hw/pci-host/spapr.h"
63 #include "hw/pci/msi.h"
64 
65 #include "hw/pci/pci.h"
66 #include "hw/scsi/scsi.h"
67 #include "hw/virtio/virtio-scsi.h"
68 #include "hw/virtio/vhost-scsi-common.h"
69 
70 #include "exec/address-spaces.h"
71 #include "exec/ram_addr.h"
72 #include "hw/usb.h"
73 #include "qemu/config-file.h"
74 #include "qemu/error-report.h"
75 #include "trace.h"
76 #include "hw/nmi.h"
77 #include "hw/intc/intc.h"
78 
79 #include "hw/ppc/spapr_cpu_core.h"
80 #include "hw/mem/memory-device.h"
81 #include "hw/ppc/spapr_tpm_proxy.h"
82 
83 #include "monitor/monitor.h"
84 
85 #include <libfdt.h>
86 
87 /* SLOF memory layout:
88  *
89  * SLOF raw image loaded at 0, copies its romfs right below the flat
90  * device-tree, then position SLOF itself 31M below that
91  *
92  * So we set FW_OVERHEAD to 40MB which should account for all of that
93  * and more
94  *
95  * We load our kernel at 4M, leaving space for SLOF initial image
96  */
97 #define FDT_MAX_SIZE            0x100000
98 #define RTAS_MAX_ADDR           0x80000000 /* RTAS must stay below that */
99 #define FW_MAX_SIZE             0x400000
100 #define FW_FILE_NAME            "slof.bin"
101 #define FW_OVERHEAD             0x2800000
102 #define KERNEL_LOAD_ADDR        FW_MAX_SIZE
103 
104 #define MIN_RMA_SLOF            128UL
105 
106 #define PHANDLE_INTC            0x00001111
107 
108 /* These two functions implement the VCPU id numbering: one to compute them
109  * all and one to identify thread 0 of a VCORE. Any change to the first one
110  * is likely to have an impact on the second one, so let's keep them close.
111  */
112 static int spapr_vcpu_id(SpaprMachineState *spapr, int cpu_index)
113 {
114     MachineState *ms = MACHINE(spapr);
115     unsigned int smp_threads = ms->smp.threads;
116 
117     assert(spapr->vsmt);
118     return
119         (cpu_index / smp_threads) * spapr->vsmt + cpu_index % smp_threads;
120 }
121 static bool spapr_is_thread0_in_vcore(SpaprMachineState *spapr,
122                                       PowerPCCPU *cpu)
123 {
124     assert(spapr->vsmt);
125     return spapr_get_vcpu_id(cpu) % spapr->vsmt == 0;
126 }
127 
128 static bool pre_2_10_vmstate_dummy_icp_needed(void *opaque)
129 {
130     /* Dummy entries correspond to unused ICPState objects in older QEMUs,
131      * and newer QEMUs don't even have them. In both cases, we don't want
132      * to send anything on the wire.
133      */
134     return false;
135 }
136 
137 static const VMStateDescription pre_2_10_vmstate_dummy_icp = {
138     .name = "icp/server",
139     .version_id = 1,
140     .minimum_version_id = 1,
141     .needed = pre_2_10_vmstate_dummy_icp_needed,
142     .fields = (VMStateField[]) {
143         VMSTATE_UNUSED(4), /* uint32_t xirr */
144         VMSTATE_UNUSED(1), /* uint8_t pending_priority */
145         VMSTATE_UNUSED(1), /* uint8_t mfrr */
146         VMSTATE_END_OF_LIST()
147     },
148 };
149 
150 static void pre_2_10_vmstate_register_dummy_icp(int i)
151 {
152     vmstate_register(NULL, i, &pre_2_10_vmstate_dummy_icp,
153                      (void *)(uintptr_t) i);
154 }
155 
156 static void pre_2_10_vmstate_unregister_dummy_icp(int i)
157 {
158     vmstate_unregister(NULL, &pre_2_10_vmstate_dummy_icp,
159                        (void *)(uintptr_t) i);
160 }
161 
162 int spapr_max_server_number(SpaprMachineState *spapr)
163 {
164     MachineState *ms = MACHINE(spapr);
165 
166     assert(spapr->vsmt);
167     return DIV_ROUND_UP(ms->smp.max_cpus * spapr->vsmt, ms->smp.threads);
168 }
169 
170 static int spapr_fixup_cpu_smt_dt(void *fdt, int offset, PowerPCCPU *cpu,
171                                   int smt_threads)
172 {
173     int i, ret = 0;
174     uint32_t servers_prop[smt_threads];
175     uint32_t gservers_prop[smt_threads * 2];
176     int index = spapr_get_vcpu_id(cpu);
177 
178     if (cpu->compat_pvr) {
179         ret = fdt_setprop_cell(fdt, offset, "cpu-version", cpu->compat_pvr);
180         if (ret < 0) {
181             return ret;
182         }
183     }
184 
185     /* Build interrupt servers and gservers properties */
186     for (i = 0; i < smt_threads; i++) {
187         servers_prop[i] = cpu_to_be32(index + i);
188         /* Hack, direct the group queues back to cpu 0 */
189         gservers_prop[i*2] = cpu_to_be32(index + i);
190         gservers_prop[i*2 + 1] = 0;
191     }
192     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-server#s",
193                       servers_prop, sizeof(servers_prop));
194     if (ret < 0) {
195         return ret;
196     }
197     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-gserver#s",
198                       gservers_prop, sizeof(gservers_prop));
199 
200     return ret;
201 }
202 
203 static int spapr_fixup_cpu_numa_dt(void *fdt, int offset, PowerPCCPU *cpu)
204 {
205     int index = spapr_get_vcpu_id(cpu);
206     uint32_t associativity[] = {cpu_to_be32(0x5),
207                                 cpu_to_be32(0x0),
208                                 cpu_to_be32(0x0),
209                                 cpu_to_be32(0x0),
210                                 cpu_to_be32(cpu->node_id),
211                                 cpu_to_be32(index)};
212 
213     /* Advertise NUMA via ibm,associativity */
214     return fdt_setprop(fdt, offset, "ibm,associativity", associativity,
215                           sizeof(associativity));
216 }
217 
218 /* Populate the "ibm,pa-features" property */
219 static void spapr_populate_pa_features(SpaprMachineState *spapr,
220                                        PowerPCCPU *cpu,
221                                        void *fdt, int offset)
222 {
223     uint8_t pa_features_206[] = { 6, 0,
224         0xf6, 0x1f, 0xc7, 0x00, 0x80, 0xc0 };
225     uint8_t pa_features_207[] = { 24, 0,
226         0xf6, 0x1f, 0xc7, 0xc0, 0x80, 0xf0,
227         0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
228         0x00, 0x00, 0x00, 0x00, 0x80, 0x00,
229         0x80, 0x00, 0x80, 0x00, 0x00, 0x00 };
230     uint8_t pa_features_300[] = { 66, 0,
231         /* 0: MMU|FPU|SLB|RUN|DABR|NX, 1: fri[nzpm]|DABRX|SPRG3|SLB0|PP110 */
232         /* 2: VPM|DS205|PPR|DS202|DS206, 3: LSD|URG, SSO, 5: LE|CFAR|EB|LSQ */
233         0xf6, 0x1f, 0xc7, 0xc0, 0x80, 0xf0, /* 0 - 5 */
234         /* 6: DS207 */
235         0x80, 0x00, 0x00, 0x00, 0x00, 0x00, /* 6 - 11 */
236         /* 16: Vector */
237         0x00, 0x00, 0x00, 0x00, 0x80, 0x00, /* 12 - 17 */
238         /* 18: Vec. Scalar, 20: Vec. XOR, 22: HTM */
239         0x80, 0x00, 0x80, 0x00, 0x00, 0x00, /* 18 - 23 */
240         /* 24: Ext. Dec, 26: 64 bit ftrs, 28: PM ftrs */
241         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 24 - 29 */
242         /* 30: MMR, 32: LE atomic, 34: EBB + ext EBB */
243         0x80, 0x00, 0x80, 0x00, 0xC0, 0x00, /* 30 - 35 */
244         /* 36: SPR SO, 38: Copy/Paste, 40: Radix MMU */
245         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 36 - 41 */
246         /* 42: PM, 44: PC RA, 46: SC vec'd */
247         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 42 - 47 */
248         /* 48: SIMD, 50: QP BFP, 52: String */
249         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 48 - 53 */
250         /* 54: DecFP, 56: DecI, 58: SHA */
251         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 54 - 59 */
252         /* 60: NM atomic, 62: RNG */
253         0x80, 0x00, 0x80, 0x00, 0x00, 0x00, /* 60 - 65 */
254     };
255     uint8_t *pa_features = NULL;
256     size_t pa_size;
257 
258     if (ppc_check_compat(cpu, CPU_POWERPC_LOGICAL_2_06, 0, cpu->compat_pvr)) {
259         pa_features = pa_features_206;
260         pa_size = sizeof(pa_features_206);
261     }
262     if (ppc_check_compat(cpu, CPU_POWERPC_LOGICAL_2_07, 0, cpu->compat_pvr)) {
263         pa_features = pa_features_207;
264         pa_size = sizeof(pa_features_207);
265     }
266     if (ppc_check_compat(cpu, CPU_POWERPC_LOGICAL_3_00, 0, cpu->compat_pvr)) {
267         pa_features = pa_features_300;
268         pa_size = sizeof(pa_features_300);
269     }
270     if (!pa_features) {
271         return;
272     }
273 
274     if (ppc_hash64_has(cpu, PPC_HASH64_CI_LARGEPAGE)) {
275         /*
276          * Note: we keep CI large pages off by default because a 64K capable
277          * guest provisioned with large pages might otherwise try to map a qemu
278          * framebuffer (or other kind of memory mapped PCI BAR) using 64K pages
279          * even if that qemu runs on a 4k host.
280          * We dd this bit back here if we are confident this is not an issue
281          */
282         pa_features[3] |= 0x20;
283     }
284     if ((spapr_get_cap(spapr, SPAPR_CAP_HTM) != 0) && pa_size > 24) {
285         pa_features[24] |= 0x80;    /* Transactional memory support */
286     }
287     if (spapr->cas_pre_isa3_guest && pa_size > 40) {
288         /* Workaround for broken kernels that attempt (guest) radix
289          * mode when they can't handle it, if they see the radix bit set
290          * in pa-features. So hide it from them. */
291         pa_features[40 + 2] &= ~0x80; /* Radix MMU */
292     }
293 
294     _FDT((fdt_setprop(fdt, offset, "ibm,pa-features", pa_features, pa_size)));
295 }
296 
297 static hwaddr spapr_node0_size(MachineState *machine)
298 {
299     if (machine->numa_state->num_nodes) {
300         int i;
301         for (i = 0; i < machine->numa_state->num_nodes; ++i) {
302             if (machine->numa_state->nodes[i].node_mem) {
303                 return MIN(pow2floor(machine->numa_state->nodes[i].node_mem),
304                            machine->ram_size);
305             }
306         }
307     }
308     return machine->ram_size;
309 }
310 
311 static void add_str(GString *s, const gchar *s1)
312 {
313     g_string_append_len(s, s1, strlen(s1) + 1);
314 }
315 
316 static int spapr_populate_memory_node(void *fdt, int nodeid, hwaddr start,
317                                        hwaddr size)
318 {
319     uint32_t associativity[] = {
320         cpu_to_be32(0x4), /* length */
321         cpu_to_be32(0x0), cpu_to_be32(0x0),
322         cpu_to_be32(0x0), cpu_to_be32(nodeid)
323     };
324     char mem_name[32];
325     uint64_t mem_reg_property[2];
326     int off;
327 
328     mem_reg_property[0] = cpu_to_be64(start);
329     mem_reg_property[1] = cpu_to_be64(size);
330 
331     sprintf(mem_name, "memory@%" HWADDR_PRIx, start);
332     off = fdt_add_subnode(fdt, 0, mem_name);
333     _FDT(off);
334     _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
335     _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property,
336                       sizeof(mem_reg_property))));
337     _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity,
338                       sizeof(associativity))));
339     return off;
340 }
341 
342 static int spapr_populate_memory(SpaprMachineState *spapr, void *fdt)
343 {
344     MachineState *machine = MACHINE(spapr);
345     hwaddr mem_start, node_size;
346     int i, nb_nodes = machine->numa_state->num_nodes;
347     NodeInfo *nodes = machine->numa_state->nodes;
348 
349     for (i = 0, mem_start = 0; i < nb_nodes; ++i) {
350         if (!nodes[i].node_mem) {
351             continue;
352         }
353         if (mem_start >= machine->ram_size) {
354             node_size = 0;
355         } else {
356             node_size = nodes[i].node_mem;
357             if (node_size > machine->ram_size - mem_start) {
358                 node_size = machine->ram_size - mem_start;
359             }
360         }
361         if (!mem_start) {
362             /* spapr_machine_init() checks for rma_size <= node0_size
363              * already */
364             spapr_populate_memory_node(fdt, i, 0, spapr->rma_size);
365             mem_start += spapr->rma_size;
366             node_size -= spapr->rma_size;
367         }
368         for ( ; node_size; ) {
369             hwaddr sizetmp = pow2floor(node_size);
370 
371             /* mem_start != 0 here */
372             if (ctzl(mem_start) < ctzl(sizetmp)) {
373                 sizetmp = 1ULL << ctzl(mem_start);
374             }
375 
376             spapr_populate_memory_node(fdt, i, mem_start, sizetmp);
377             node_size -= sizetmp;
378             mem_start += sizetmp;
379         }
380     }
381 
382     return 0;
383 }
384 
385 static void spapr_populate_cpu_dt(CPUState *cs, void *fdt, int offset,
386                                   SpaprMachineState *spapr)
387 {
388     MachineState *ms = MACHINE(spapr);
389     PowerPCCPU *cpu = POWERPC_CPU(cs);
390     CPUPPCState *env = &cpu->env;
391     PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
392     int index = spapr_get_vcpu_id(cpu);
393     uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
394                        0xffffffff, 0xffffffff};
395     uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq()
396         : SPAPR_TIMEBASE_FREQ;
397     uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
398     uint32_t page_sizes_prop[64];
399     size_t page_sizes_prop_size;
400     unsigned int smp_threads = ms->smp.threads;
401     uint32_t vcpus_per_socket = smp_threads * ms->smp.cores;
402     uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};
403     int compat_smt = MIN(smp_threads, ppc_compat_max_vthreads(cpu));
404     SpaprDrc *drc;
405     int drc_index;
406     uint32_t radix_AP_encodings[PPC_PAGE_SIZES_MAX_SZ];
407     int i;
408 
409     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index);
410     if (drc) {
411         drc_index = spapr_drc_index(drc);
412         _FDT((fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index)));
413     }
414 
415     _FDT((fdt_setprop_cell(fdt, offset, "reg", index)));
416     _FDT((fdt_setprop_string(fdt, offset, "device_type", "cpu")));
417 
418     _FDT((fdt_setprop_cell(fdt, offset, "cpu-version", env->spr[SPR_PVR])));
419     _FDT((fdt_setprop_cell(fdt, offset, "d-cache-block-size",
420                            env->dcache_line_size)));
421     _FDT((fdt_setprop_cell(fdt, offset, "d-cache-line-size",
422                            env->dcache_line_size)));
423     _FDT((fdt_setprop_cell(fdt, offset, "i-cache-block-size",
424                            env->icache_line_size)));
425     _FDT((fdt_setprop_cell(fdt, offset, "i-cache-line-size",
426                            env->icache_line_size)));
427 
428     if (pcc->l1_dcache_size) {
429         _FDT((fdt_setprop_cell(fdt, offset, "d-cache-size",
430                                pcc->l1_dcache_size)));
431     } else {
432         warn_report("Unknown L1 dcache size for cpu");
433     }
434     if (pcc->l1_icache_size) {
435         _FDT((fdt_setprop_cell(fdt, offset, "i-cache-size",
436                                pcc->l1_icache_size)));
437     } else {
438         warn_report("Unknown L1 icache size for cpu");
439     }
440 
441     _FDT((fdt_setprop_cell(fdt, offset, "timebase-frequency", tbfreq)));
442     _FDT((fdt_setprop_cell(fdt, offset, "clock-frequency", cpufreq)));
443     _FDT((fdt_setprop_cell(fdt, offset, "slb-size", cpu->hash64_opts->slb_size)));
444     _FDT((fdt_setprop_cell(fdt, offset, "ibm,slb-size", cpu->hash64_opts->slb_size)));
445     _FDT((fdt_setprop_string(fdt, offset, "status", "okay")));
446     _FDT((fdt_setprop(fdt, offset, "64-bit", NULL, 0)));
447 
448     if (env->spr_cb[SPR_PURR].oea_read) {
449         _FDT((fdt_setprop_cell(fdt, offset, "ibm,purr", 1)));
450     }
451     if (env->spr_cb[SPR_SPURR].oea_read) {
452         _FDT((fdt_setprop_cell(fdt, offset, "ibm,spurr", 1)));
453     }
454 
455     if (ppc_hash64_has(cpu, PPC_HASH64_1TSEG)) {
456         _FDT((fdt_setprop(fdt, offset, "ibm,processor-segment-sizes",
457                           segs, sizeof(segs))));
458     }
459 
460     /* Advertise VSX (vector extensions) if available
461      *   1               == VMX / Altivec available
462      *   2               == VSX available
463      *
464      * Only CPUs for which we create core types in spapr_cpu_core.c
465      * are possible, and all of those have VMX */
466     if (spapr_get_cap(spapr, SPAPR_CAP_VSX) != 0) {
467         _FDT((fdt_setprop_cell(fdt, offset, "ibm,vmx", 2)));
468     } else {
469         _FDT((fdt_setprop_cell(fdt, offset, "ibm,vmx", 1)));
470     }
471 
472     /* Advertise DFP (Decimal Floating Point) if available
473      *   0 / no property == no DFP
474      *   1               == DFP available */
475     if (spapr_get_cap(spapr, SPAPR_CAP_DFP) != 0) {
476         _FDT((fdt_setprop_cell(fdt, offset, "ibm,dfp", 1)));
477     }
478 
479     page_sizes_prop_size = ppc_create_page_sizes_prop(cpu, page_sizes_prop,
480                                                       sizeof(page_sizes_prop));
481     if (page_sizes_prop_size) {
482         _FDT((fdt_setprop(fdt, offset, "ibm,segment-page-sizes",
483                           page_sizes_prop, page_sizes_prop_size)));
484     }
485 
486     spapr_populate_pa_features(spapr, cpu, fdt, offset);
487 
488     _FDT((fdt_setprop_cell(fdt, offset, "ibm,chip-id",
489                            cs->cpu_index / vcpus_per_socket)));
490 
491     _FDT((fdt_setprop(fdt, offset, "ibm,pft-size",
492                       pft_size_prop, sizeof(pft_size_prop))));
493 
494     if (ms->numa_state->num_nodes > 1) {
495         _FDT(spapr_fixup_cpu_numa_dt(fdt, offset, cpu));
496     }
497 
498     _FDT(spapr_fixup_cpu_smt_dt(fdt, offset, cpu, compat_smt));
499 
500     if (pcc->radix_page_info) {
501         for (i = 0; i < pcc->radix_page_info->count; i++) {
502             radix_AP_encodings[i] =
503                 cpu_to_be32(pcc->radix_page_info->entries[i]);
504         }
505         _FDT((fdt_setprop(fdt, offset, "ibm,processor-radix-AP-encodings",
506                           radix_AP_encodings,
507                           pcc->radix_page_info->count *
508                           sizeof(radix_AP_encodings[0]))));
509     }
510 
511     /*
512      * We set this property to let the guest know that it can use the large
513      * decrementer and its width in bits.
514      */
515     if (spapr_get_cap(spapr, SPAPR_CAP_LARGE_DECREMENTER) != SPAPR_CAP_OFF)
516         _FDT((fdt_setprop_u32(fdt, offset, "ibm,dec-bits",
517                               pcc->lrg_decr_bits)));
518 }
519 
520 static void spapr_populate_cpus_dt_node(void *fdt, SpaprMachineState *spapr)
521 {
522     CPUState **rev;
523     CPUState *cs;
524     int n_cpus;
525     int cpus_offset;
526     char *nodename;
527     int i;
528 
529     cpus_offset = fdt_add_subnode(fdt, 0, "cpus");
530     _FDT(cpus_offset);
531     _FDT((fdt_setprop_cell(fdt, cpus_offset, "#address-cells", 0x1)));
532     _FDT((fdt_setprop_cell(fdt, cpus_offset, "#size-cells", 0x0)));
533 
534     /*
535      * We walk the CPUs in reverse order to ensure that CPU DT nodes
536      * created by fdt_add_subnode() end up in the right order in FDT
537      * for the guest kernel the enumerate the CPUs correctly.
538      *
539      * The CPU list cannot be traversed in reverse order, so we need
540      * to do extra work.
541      */
542     n_cpus = 0;
543     rev = NULL;
544     CPU_FOREACH(cs) {
545         rev = g_renew(CPUState *, rev, n_cpus + 1);
546         rev[n_cpus++] = cs;
547     }
548 
549     for (i = n_cpus - 1; i >= 0; i--) {
550         CPUState *cs = rev[i];
551         PowerPCCPU *cpu = POWERPC_CPU(cs);
552         int index = spapr_get_vcpu_id(cpu);
553         DeviceClass *dc = DEVICE_GET_CLASS(cs);
554         int offset;
555 
556         if (!spapr_is_thread0_in_vcore(spapr, cpu)) {
557             continue;
558         }
559 
560         nodename = g_strdup_printf("%s@%x", dc->fw_name, index);
561         offset = fdt_add_subnode(fdt, cpus_offset, nodename);
562         g_free(nodename);
563         _FDT(offset);
564         spapr_populate_cpu_dt(cs, fdt, offset, spapr);
565     }
566 
567     g_free(rev);
568 }
569 
570 static int spapr_rng_populate_dt(void *fdt)
571 {
572     int node;
573     int ret;
574 
575     node = qemu_fdt_add_subnode(fdt, "/ibm,platform-facilities");
576     if (node <= 0) {
577         return -1;
578     }
579     ret = fdt_setprop_string(fdt, node, "device_type",
580                              "ibm,platform-facilities");
581     ret |= fdt_setprop_cell(fdt, node, "#address-cells", 0x1);
582     ret |= fdt_setprop_cell(fdt, node, "#size-cells", 0x0);
583 
584     node = fdt_add_subnode(fdt, node, "ibm,random-v1");
585     if (node <= 0) {
586         return -1;
587     }
588     ret |= fdt_setprop_string(fdt, node, "compatible", "ibm,random");
589 
590     return ret ? -1 : 0;
591 }
592 
593 static uint32_t spapr_pc_dimm_node(MemoryDeviceInfoList *list, ram_addr_t addr)
594 {
595     MemoryDeviceInfoList *info;
596 
597     for (info = list; info; info = info->next) {
598         MemoryDeviceInfo *value = info->value;
599 
600         if (value && value->type == MEMORY_DEVICE_INFO_KIND_DIMM) {
601             PCDIMMDeviceInfo *pcdimm_info = value->u.dimm.data;
602 
603             if (addr >= pcdimm_info->addr &&
604                 addr < (pcdimm_info->addr + pcdimm_info->size)) {
605                 return pcdimm_info->node;
606             }
607         }
608     }
609 
610     return -1;
611 }
612 
613 struct sPAPRDrconfCellV2 {
614      uint32_t seq_lmbs;
615      uint64_t base_addr;
616      uint32_t drc_index;
617      uint32_t aa_index;
618      uint32_t flags;
619 } QEMU_PACKED;
620 
621 typedef struct DrconfCellQueue {
622     struct sPAPRDrconfCellV2 cell;
623     QSIMPLEQ_ENTRY(DrconfCellQueue) entry;
624 } DrconfCellQueue;
625 
626 static DrconfCellQueue *
627 spapr_get_drconf_cell(uint32_t seq_lmbs, uint64_t base_addr,
628                       uint32_t drc_index, uint32_t aa_index,
629                       uint32_t flags)
630 {
631     DrconfCellQueue *elem;
632 
633     elem = g_malloc0(sizeof(*elem));
634     elem->cell.seq_lmbs = cpu_to_be32(seq_lmbs);
635     elem->cell.base_addr = cpu_to_be64(base_addr);
636     elem->cell.drc_index = cpu_to_be32(drc_index);
637     elem->cell.aa_index = cpu_to_be32(aa_index);
638     elem->cell.flags = cpu_to_be32(flags);
639 
640     return elem;
641 }
642 
643 /* ibm,dynamic-memory-v2 */
644 static int spapr_populate_drmem_v2(SpaprMachineState *spapr, void *fdt,
645                                    int offset, MemoryDeviceInfoList *dimms)
646 {
647     MachineState *machine = MACHINE(spapr);
648     uint8_t *int_buf, *cur_index;
649     int ret;
650     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
651     uint64_t addr, cur_addr, size;
652     uint32_t nr_boot_lmbs = (machine->device_memory->base / lmb_size);
653     uint64_t mem_end = machine->device_memory->base +
654                        memory_region_size(&machine->device_memory->mr);
655     uint32_t node, buf_len, nr_entries = 0;
656     SpaprDrc *drc;
657     DrconfCellQueue *elem, *next;
658     MemoryDeviceInfoList *info;
659     QSIMPLEQ_HEAD(, DrconfCellQueue) drconf_queue
660         = QSIMPLEQ_HEAD_INITIALIZER(drconf_queue);
661 
662     /* Entry to cover RAM and the gap area */
663     elem = spapr_get_drconf_cell(nr_boot_lmbs, 0, 0, -1,
664                                  SPAPR_LMB_FLAGS_RESERVED |
665                                  SPAPR_LMB_FLAGS_DRC_INVALID);
666     QSIMPLEQ_INSERT_TAIL(&drconf_queue, elem, entry);
667     nr_entries++;
668 
669     cur_addr = machine->device_memory->base;
670     for (info = dimms; info; info = info->next) {
671         PCDIMMDeviceInfo *di = info->value->u.dimm.data;
672 
673         addr = di->addr;
674         size = di->size;
675         node = di->node;
676 
677         /* Entry for hot-pluggable area */
678         if (cur_addr < addr) {
679             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB, cur_addr / lmb_size);
680             g_assert(drc);
681             elem = spapr_get_drconf_cell((addr - cur_addr) / lmb_size,
682                                          cur_addr, spapr_drc_index(drc), -1, 0);
683             QSIMPLEQ_INSERT_TAIL(&drconf_queue, elem, entry);
684             nr_entries++;
685         }
686 
687         /* Entry for DIMM */
688         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB, addr / lmb_size);
689         g_assert(drc);
690         elem = spapr_get_drconf_cell(size / lmb_size, addr,
691                                      spapr_drc_index(drc), node,
692                                      SPAPR_LMB_FLAGS_ASSIGNED);
693         QSIMPLEQ_INSERT_TAIL(&drconf_queue, elem, entry);
694         nr_entries++;
695         cur_addr = addr + size;
696     }
697 
698     /* Entry for remaining hotpluggable area */
699     if (cur_addr < mem_end) {
700         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB, cur_addr / lmb_size);
701         g_assert(drc);
702         elem = spapr_get_drconf_cell((mem_end - cur_addr) / lmb_size,
703                                      cur_addr, spapr_drc_index(drc), -1, 0);
704         QSIMPLEQ_INSERT_TAIL(&drconf_queue, elem, entry);
705         nr_entries++;
706     }
707 
708     buf_len = nr_entries * sizeof(struct sPAPRDrconfCellV2) + sizeof(uint32_t);
709     int_buf = cur_index = g_malloc0(buf_len);
710     *(uint32_t *)int_buf = cpu_to_be32(nr_entries);
711     cur_index += sizeof(nr_entries);
712 
713     QSIMPLEQ_FOREACH_SAFE(elem, &drconf_queue, entry, next) {
714         memcpy(cur_index, &elem->cell, sizeof(elem->cell));
715         cur_index += sizeof(elem->cell);
716         QSIMPLEQ_REMOVE(&drconf_queue, elem, DrconfCellQueue, entry);
717         g_free(elem);
718     }
719 
720     ret = fdt_setprop(fdt, offset, "ibm,dynamic-memory-v2", int_buf, buf_len);
721     g_free(int_buf);
722     if (ret < 0) {
723         return -1;
724     }
725     return 0;
726 }
727 
728 /* ibm,dynamic-memory */
729 static int spapr_populate_drmem_v1(SpaprMachineState *spapr, void *fdt,
730                                    int offset, MemoryDeviceInfoList *dimms)
731 {
732     MachineState *machine = MACHINE(spapr);
733     int i, ret;
734     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
735     uint32_t device_lmb_start = machine->device_memory->base / lmb_size;
736     uint32_t nr_lmbs = (machine->device_memory->base +
737                        memory_region_size(&machine->device_memory->mr)) /
738                        lmb_size;
739     uint32_t *int_buf, *cur_index, buf_len;
740 
741     /*
742      * Allocate enough buffer size to fit in ibm,dynamic-memory
743      */
744     buf_len = (nr_lmbs * SPAPR_DR_LMB_LIST_ENTRY_SIZE + 1) * sizeof(uint32_t);
745     cur_index = int_buf = g_malloc0(buf_len);
746     int_buf[0] = cpu_to_be32(nr_lmbs);
747     cur_index++;
748     for (i = 0; i < nr_lmbs; i++) {
749         uint64_t addr = i * lmb_size;
750         uint32_t *dynamic_memory = cur_index;
751 
752         if (i >= device_lmb_start) {
753             SpaprDrc *drc;
754 
755             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB, i);
756             g_assert(drc);
757 
758             dynamic_memory[0] = cpu_to_be32(addr >> 32);
759             dynamic_memory[1] = cpu_to_be32(addr & 0xffffffff);
760             dynamic_memory[2] = cpu_to_be32(spapr_drc_index(drc));
761             dynamic_memory[3] = cpu_to_be32(0); /* reserved */
762             dynamic_memory[4] = cpu_to_be32(spapr_pc_dimm_node(dimms, addr));
763             if (memory_region_present(get_system_memory(), addr)) {
764                 dynamic_memory[5] = cpu_to_be32(SPAPR_LMB_FLAGS_ASSIGNED);
765             } else {
766                 dynamic_memory[5] = cpu_to_be32(0);
767             }
768         } else {
769             /*
770              * LMB information for RMA, boot time RAM and gap b/n RAM and
771              * device memory region -- all these are marked as reserved
772              * and as having no valid DRC.
773              */
774             dynamic_memory[0] = cpu_to_be32(addr >> 32);
775             dynamic_memory[1] = cpu_to_be32(addr & 0xffffffff);
776             dynamic_memory[2] = cpu_to_be32(0);
777             dynamic_memory[3] = cpu_to_be32(0); /* reserved */
778             dynamic_memory[4] = cpu_to_be32(-1);
779             dynamic_memory[5] = cpu_to_be32(SPAPR_LMB_FLAGS_RESERVED |
780                                             SPAPR_LMB_FLAGS_DRC_INVALID);
781         }
782 
783         cur_index += SPAPR_DR_LMB_LIST_ENTRY_SIZE;
784     }
785     ret = fdt_setprop(fdt, offset, "ibm,dynamic-memory", int_buf, buf_len);
786     g_free(int_buf);
787     if (ret < 0) {
788         return -1;
789     }
790     return 0;
791 }
792 
793 /*
794  * Adds ibm,dynamic-reconfiguration-memory node.
795  * Refer to docs/specs/ppc-spapr-hotplug.txt for the documentation
796  * of this device tree node.
797  */
798 static int spapr_populate_drconf_memory(SpaprMachineState *spapr, void *fdt)
799 {
800     MachineState *machine = MACHINE(spapr);
801     int nb_numa_nodes = machine->numa_state->num_nodes;
802     int ret, i, offset;
803     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
804     uint32_t prop_lmb_size[] = {0, cpu_to_be32(lmb_size)};
805     uint32_t *int_buf, *cur_index, buf_len;
806     int nr_nodes = nb_numa_nodes ? nb_numa_nodes : 1;
807     MemoryDeviceInfoList *dimms = NULL;
808 
809     /*
810      * Don't create the node if there is no device memory
811      */
812     if (machine->ram_size == machine->maxram_size) {
813         return 0;
814     }
815 
816     offset = fdt_add_subnode(fdt, 0, "ibm,dynamic-reconfiguration-memory");
817 
818     ret = fdt_setprop(fdt, offset, "ibm,lmb-size", prop_lmb_size,
819                     sizeof(prop_lmb_size));
820     if (ret < 0) {
821         return ret;
822     }
823 
824     ret = fdt_setprop_cell(fdt, offset, "ibm,memory-flags-mask", 0xff);
825     if (ret < 0) {
826         return ret;
827     }
828 
829     ret = fdt_setprop_cell(fdt, offset, "ibm,memory-preservation-time", 0x0);
830     if (ret < 0) {
831         return ret;
832     }
833 
834     /* ibm,dynamic-memory or ibm,dynamic-memory-v2 */
835     dimms = qmp_memory_device_list();
836     if (spapr_ovec_test(spapr->ov5_cas, OV5_DRMEM_V2)) {
837         ret = spapr_populate_drmem_v2(spapr, fdt, offset, dimms);
838     } else {
839         ret = spapr_populate_drmem_v1(spapr, fdt, offset, dimms);
840     }
841     qapi_free_MemoryDeviceInfoList(dimms);
842 
843     if (ret < 0) {
844         return ret;
845     }
846 
847     /* ibm,associativity-lookup-arrays */
848     buf_len = (nr_nodes * 4 + 2) * sizeof(uint32_t);
849     cur_index = int_buf = g_malloc0(buf_len);
850     int_buf[0] = cpu_to_be32(nr_nodes);
851     int_buf[1] = cpu_to_be32(4); /* Number of entries per associativity list */
852     cur_index += 2;
853     for (i = 0; i < nr_nodes; i++) {
854         uint32_t associativity[] = {
855             cpu_to_be32(0x0),
856             cpu_to_be32(0x0),
857             cpu_to_be32(0x0),
858             cpu_to_be32(i)
859         };
860         memcpy(cur_index, associativity, sizeof(associativity));
861         cur_index += 4;
862     }
863     ret = fdt_setprop(fdt, offset, "ibm,associativity-lookup-arrays", int_buf,
864             (cur_index - int_buf) * sizeof(uint32_t));
865     g_free(int_buf);
866 
867     return ret;
868 }
869 
870 static int spapr_dt_cas_updates(SpaprMachineState *spapr, void *fdt,
871                                 SpaprOptionVector *ov5_updates)
872 {
873     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
874     int ret = 0, offset;
875 
876     /* Generate ibm,dynamic-reconfiguration-memory node if required */
877     if (spapr_ovec_test(ov5_updates, OV5_DRCONF_MEMORY)) {
878         g_assert(smc->dr_lmb_enabled);
879         ret = spapr_populate_drconf_memory(spapr, fdt);
880         if (ret) {
881             return ret;
882         }
883     }
884 
885     offset = fdt_path_offset(fdt, "/chosen");
886     if (offset < 0) {
887         offset = fdt_add_subnode(fdt, 0, "chosen");
888         if (offset < 0) {
889             return offset;
890         }
891     }
892     return spapr_ovec_populate_dt(fdt, offset, spapr->ov5_cas,
893                                   "ibm,architecture-vec-5");
894 }
895 
896 static void spapr_dt_rtas(SpaprMachineState *spapr, void *fdt)
897 {
898     MachineState *ms = MACHINE(spapr);
899     int rtas;
900     GString *hypertas = g_string_sized_new(256);
901     GString *qemu_hypertas = g_string_sized_new(256);
902     uint32_t refpoints[] = { cpu_to_be32(0x4), cpu_to_be32(0x4) };
903     uint64_t max_device_addr = MACHINE(spapr)->device_memory->base +
904         memory_region_size(&MACHINE(spapr)->device_memory->mr);
905     uint32_t lrdr_capacity[] = {
906         cpu_to_be32(max_device_addr >> 32),
907         cpu_to_be32(max_device_addr & 0xffffffff),
908         0, cpu_to_be32(SPAPR_MEMORY_BLOCK_SIZE),
909         cpu_to_be32(ms->smp.max_cpus / ms->smp.threads),
910     };
911     uint32_t maxdomain = cpu_to_be32(spapr->gpu_numa_id > 1 ? 1 : 0);
912     uint32_t maxdomains[] = {
913         cpu_to_be32(4),
914         maxdomain,
915         maxdomain,
916         maxdomain,
917         cpu_to_be32(spapr->gpu_numa_id),
918     };
919 
920     _FDT(rtas = fdt_add_subnode(fdt, 0, "rtas"));
921 
922     /* hypertas */
923     add_str(hypertas, "hcall-pft");
924     add_str(hypertas, "hcall-term");
925     add_str(hypertas, "hcall-dabr");
926     add_str(hypertas, "hcall-interrupt");
927     add_str(hypertas, "hcall-tce");
928     add_str(hypertas, "hcall-vio");
929     add_str(hypertas, "hcall-splpar");
930     add_str(hypertas, "hcall-join");
931     add_str(hypertas, "hcall-bulk");
932     add_str(hypertas, "hcall-set-mode");
933     add_str(hypertas, "hcall-sprg0");
934     add_str(hypertas, "hcall-copy");
935     add_str(hypertas, "hcall-debug");
936     add_str(hypertas, "hcall-vphn");
937     add_str(qemu_hypertas, "hcall-memop1");
938 
939     if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {
940         add_str(hypertas, "hcall-multi-tce");
941     }
942 
943     if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {
944         add_str(hypertas, "hcall-hpt-resize");
945     }
946 
947     _FDT(fdt_setprop(fdt, rtas, "ibm,hypertas-functions",
948                      hypertas->str, hypertas->len));
949     g_string_free(hypertas, TRUE);
950     _FDT(fdt_setprop(fdt, rtas, "qemu,hypertas-functions",
951                      qemu_hypertas->str, qemu_hypertas->len));
952     g_string_free(qemu_hypertas, TRUE);
953 
954     _FDT(fdt_setprop(fdt, rtas, "ibm,associativity-reference-points",
955                      refpoints, sizeof(refpoints)));
956 
957     _FDT(fdt_setprop(fdt, rtas, "ibm,max-associativity-domains",
958                      maxdomains, sizeof(maxdomains)));
959 
960     _FDT(fdt_setprop_cell(fdt, rtas, "rtas-error-log-max",
961                           RTAS_ERROR_LOG_MAX));
962     _FDT(fdt_setprop_cell(fdt, rtas, "rtas-event-scan-rate",
963                           RTAS_EVENT_SCAN_RATE));
964 
965     g_assert(msi_nonbroken);
966     _FDT(fdt_setprop(fdt, rtas, "ibm,change-msix-capable", NULL, 0));
967 
968     /*
969      * According to PAPR, rtas ibm,os-term does not guarantee a return
970      * back to the guest cpu.
971      *
972      * While an additional ibm,extended-os-term property indicates
973      * that rtas call return will always occur. Set this property.
974      */
975     _FDT(fdt_setprop(fdt, rtas, "ibm,extended-os-term", NULL, 0));
976 
977     _FDT(fdt_setprop(fdt, rtas, "ibm,lrdr-capacity",
978                      lrdr_capacity, sizeof(lrdr_capacity)));
979 
980     spapr_dt_rtas_tokens(fdt, rtas);
981 }
982 
983 /*
984  * Prepare ibm,arch-vec-5-platform-support, which indicates the MMU
985  * and the XIVE features that the guest may request and thus the valid
986  * values for bytes 23..26 of option vector 5:
987  */
988 static void spapr_dt_ov5_platform_support(SpaprMachineState *spapr, void *fdt,
989                                           int chosen)
990 {
991     PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu);
992 
993     char val[2 * 4] = {
994         23, 0x00, /* XICS / XIVE mode */
995         24, 0x00, /* Hash/Radix, filled in below. */
996         25, 0x00, /* Hash options: Segment Tables == no, GTSE == no. */
997         26, 0x40, /* Radix options: GTSE == yes. */
998     };
999 
1000     if (spapr->irq->xics && spapr->irq->xive) {
1001         val[1] = SPAPR_OV5_XIVE_BOTH;
1002     } else if (spapr->irq->xive) {
1003         val[1] = SPAPR_OV5_XIVE_EXPLOIT;
1004     } else {
1005         assert(spapr->irq->xics);
1006         val[1] = SPAPR_OV5_XIVE_LEGACY;
1007     }
1008 
1009     if (!ppc_check_compat(first_ppc_cpu, CPU_POWERPC_LOGICAL_3_00, 0,
1010                           first_ppc_cpu->compat_pvr)) {
1011         /*
1012          * If we're in a pre POWER9 compat mode then the guest should
1013          * do hash and use the legacy interrupt mode
1014          */
1015         val[1] = SPAPR_OV5_XIVE_LEGACY; /* XICS */
1016         val[3] = 0x00; /* Hash */
1017     } else if (kvm_enabled()) {
1018         if (kvmppc_has_cap_mmu_radix() && kvmppc_has_cap_mmu_hash_v3()) {
1019             val[3] = 0x80; /* OV5_MMU_BOTH */
1020         } else if (kvmppc_has_cap_mmu_radix()) {
1021             val[3] = 0x40; /* OV5_MMU_RADIX_300 */
1022         } else {
1023             val[3] = 0x00; /* Hash */
1024         }
1025     } else {
1026         /* V3 MMU supports both hash and radix in tcg (with dynamic switching) */
1027         val[3] = 0xC0;
1028     }
1029     _FDT(fdt_setprop(fdt, chosen, "ibm,arch-vec-5-platform-support",
1030                      val, sizeof(val)));
1031 }
1032 
1033 static void spapr_dt_chosen(SpaprMachineState *spapr, void *fdt)
1034 {
1035     MachineState *machine = MACHINE(spapr);
1036     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
1037     int chosen;
1038     const char *boot_device = machine->boot_order;
1039     char *stdout_path = spapr_vio_stdout_path(spapr->vio_bus);
1040     size_t cb = 0;
1041     char *bootlist = get_boot_devices_list(&cb);
1042 
1043     _FDT(chosen = fdt_add_subnode(fdt, 0, "chosen"));
1044 
1045     if (machine->kernel_cmdline && machine->kernel_cmdline[0]) {
1046         _FDT(fdt_setprop_string(fdt, chosen, "bootargs",
1047                                 machine->kernel_cmdline));
1048     }
1049     if (spapr->initrd_size) {
1050         _FDT(fdt_setprop_cell(fdt, chosen, "linux,initrd-start",
1051                               spapr->initrd_base));
1052         _FDT(fdt_setprop_cell(fdt, chosen, "linux,initrd-end",
1053                               spapr->initrd_base + spapr->initrd_size));
1054     }
1055 
1056     if (spapr->kernel_size) {
1057         uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
1058                               cpu_to_be64(spapr->kernel_size) };
1059 
1060         _FDT(fdt_setprop(fdt, chosen, "qemu,boot-kernel",
1061                          &kprop, sizeof(kprop)));
1062         if (spapr->kernel_le) {
1063             _FDT(fdt_setprop(fdt, chosen, "qemu,boot-kernel-le", NULL, 0));
1064         }
1065     }
1066     if (boot_menu) {
1067         _FDT((fdt_setprop_cell(fdt, chosen, "qemu,boot-menu", boot_menu)));
1068     }
1069     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-width", graphic_width));
1070     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-height", graphic_height));
1071     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-depth", graphic_depth));
1072 
1073     if (cb && bootlist) {
1074         int i;
1075 
1076         for (i = 0; i < cb; i++) {
1077             if (bootlist[i] == '\n') {
1078                 bootlist[i] = ' ';
1079             }
1080         }
1081         _FDT(fdt_setprop_string(fdt, chosen, "qemu,boot-list", bootlist));
1082     }
1083 
1084     if (boot_device && strlen(boot_device)) {
1085         _FDT(fdt_setprop_string(fdt, chosen, "qemu,boot-device", boot_device));
1086     }
1087 
1088     if (!spapr->has_graphics && stdout_path) {
1089         /*
1090          * "linux,stdout-path" and "stdout" properties are deprecated by linux
1091          * kernel. New platforms should only use the "stdout-path" property. Set
1092          * the new property and continue using older property to remain
1093          * compatible with the existing firmware.
1094          */
1095         _FDT(fdt_setprop_string(fdt, chosen, "linux,stdout-path", stdout_path));
1096         _FDT(fdt_setprop_string(fdt, chosen, "stdout-path", stdout_path));
1097     }
1098 
1099     /* We can deal with BAR reallocation just fine, advertise it to the guest */
1100     if (smc->linux_pci_probe) {
1101         _FDT(fdt_setprop_cell(fdt, chosen, "linux,pci-probe-only", 0));
1102     }
1103 
1104     spapr_dt_ov5_platform_support(spapr, fdt, chosen);
1105 
1106     g_free(stdout_path);
1107     g_free(bootlist);
1108 }
1109 
1110 static void spapr_dt_hypervisor(SpaprMachineState *spapr, void *fdt)
1111 {
1112     /* The /hypervisor node isn't in PAPR - this is a hack to allow PR
1113      * KVM to work under pHyp with some guest co-operation */
1114     int hypervisor;
1115     uint8_t hypercall[16];
1116 
1117     _FDT(hypervisor = fdt_add_subnode(fdt, 0, "hypervisor"));
1118     /* indicate KVM hypercall interface */
1119     _FDT(fdt_setprop_string(fdt, hypervisor, "compatible", "linux,kvm"));
1120     if (kvmppc_has_cap_fixup_hcalls()) {
1121         /*
1122          * Older KVM versions with older guest kernels were broken
1123          * with the magic page, don't allow the guest to map it.
1124          */
1125         if (!kvmppc_get_hypercall(first_cpu->env_ptr, hypercall,
1126                                   sizeof(hypercall))) {
1127             _FDT(fdt_setprop(fdt, hypervisor, "hcall-instructions",
1128                              hypercall, sizeof(hypercall)));
1129         }
1130     }
1131 }
1132 
1133 void *spapr_build_fdt(SpaprMachineState *spapr, bool reset, size_t space)
1134 {
1135     MachineState *machine = MACHINE(spapr);
1136     MachineClass *mc = MACHINE_GET_CLASS(machine);
1137     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
1138     int ret;
1139     void *fdt;
1140     SpaprPhbState *phb;
1141     char *buf;
1142 
1143     fdt = g_malloc0(space);
1144     _FDT((fdt_create_empty_tree(fdt, space)));
1145 
1146     /* Root node */
1147     _FDT(fdt_setprop_string(fdt, 0, "device_type", "chrp"));
1148     _FDT(fdt_setprop_string(fdt, 0, "model", "IBM pSeries (emulated by qemu)"));
1149     _FDT(fdt_setprop_string(fdt, 0, "compatible", "qemu,pseries"));
1150 
1151     /* Guest UUID & Name*/
1152     buf = qemu_uuid_unparse_strdup(&qemu_uuid);
1153     _FDT(fdt_setprop_string(fdt, 0, "vm,uuid", buf));
1154     if (qemu_uuid_set) {
1155         _FDT(fdt_setprop_string(fdt, 0, "system-id", buf));
1156     }
1157     g_free(buf);
1158 
1159     if (qemu_get_vm_name()) {
1160         _FDT(fdt_setprop_string(fdt, 0, "ibm,partition-name",
1161                                 qemu_get_vm_name()));
1162     }
1163 
1164     /* Host Model & Serial Number */
1165     if (spapr->host_model) {
1166         _FDT(fdt_setprop_string(fdt, 0, "host-model", spapr->host_model));
1167     } else if (smc->broken_host_serial_model && kvmppc_get_host_model(&buf)) {
1168         _FDT(fdt_setprop_string(fdt, 0, "host-model", buf));
1169         g_free(buf);
1170     }
1171 
1172     if (spapr->host_serial) {
1173         _FDT(fdt_setprop_string(fdt, 0, "host-serial", spapr->host_serial));
1174     } else if (smc->broken_host_serial_model && kvmppc_get_host_serial(&buf)) {
1175         _FDT(fdt_setprop_string(fdt, 0, "host-serial", buf));
1176         g_free(buf);
1177     }
1178 
1179     _FDT(fdt_setprop_cell(fdt, 0, "#address-cells", 2));
1180     _FDT(fdt_setprop_cell(fdt, 0, "#size-cells", 2));
1181 
1182     /* /interrupt controller */
1183     spapr_irq_dt(spapr, spapr_max_server_number(spapr), fdt, PHANDLE_INTC);
1184 
1185     ret = spapr_populate_memory(spapr, fdt);
1186     if (ret < 0) {
1187         error_report("couldn't setup memory nodes in fdt");
1188         exit(1);
1189     }
1190 
1191     /* /vdevice */
1192     spapr_dt_vdevice(spapr->vio_bus, fdt);
1193 
1194     if (object_resolve_path_type("", TYPE_SPAPR_RNG, NULL)) {
1195         ret = spapr_rng_populate_dt(fdt);
1196         if (ret < 0) {
1197             error_report("could not set up rng device in the fdt");
1198             exit(1);
1199         }
1200     }
1201 
1202     QLIST_FOREACH(phb, &spapr->phbs, list) {
1203         ret = spapr_dt_phb(spapr, phb, PHANDLE_INTC, fdt, NULL);
1204         if (ret < 0) {
1205             error_report("couldn't setup PCI devices in fdt");
1206             exit(1);
1207         }
1208     }
1209 
1210     /* cpus */
1211     spapr_populate_cpus_dt_node(fdt, spapr);
1212 
1213     if (smc->dr_lmb_enabled) {
1214         _FDT(spapr_dt_drc(fdt, 0, NULL, SPAPR_DR_CONNECTOR_TYPE_LMB));
1215     }
1216 
1217     if (mc->has_hotpluggable_cpus) {
1218         int offset = fdt_path_offset(fdt, "/cpus");
1219         ret = spapr_dt_drc(fdt, offset, NULL, SPAPR_DR_CONNECTOR_TYPE_CPU);
1220         if (ret < 0) {
1221             error_report("Couldn't set up CPU DR device tree properties");
1222             exit(1);
1223         }
1224     }
1225 
1226     /* /event-sources */
1227     spapr_dt_events(spapr, fdt);
1228 
1229     /* /rtas */
1230     spapr_dt_rtas(spapr, fdt);
1231 
1232     /* /chosen */
1233     if (reset) {
1234         spapr_dt_chosen(spapr, fdt);
1235     }
1236 
1237     /* /hypervisor */
1238     if (kvm_enabled()) {
1239         spapr_dt_hypervisor(spapr, fdt);
1240     }
1241 
1242     /* Build memory reserve map */
1243     if (reset) {
1244         if (spapr->kernel_size) {
1245             _FDT((fdt_add_mem_rsv(fdt, KERNEL_LOAD_ADDR, spapr->kernel_size)));
1246         }
1247         if (spapr->initrd_size) {
1248             _FDT((fdt_add_mem_rsv(fdt, spapr->initrd_base,
1249                                   spapr->initrd_size)));
1250         }
1251     }
1252 
1253     /* ibm,client-architecture-support updates */
1254     ret = spapr_dt_cas_updates(spapr, fdt, spapr->ov5_cas);
1255     if (ret < 0) {
1256         error_report("couldn't setup CAS properties fdt");
1257         exit(1);
1258     }
1259 
1260     if (smc->dr_phb_enabled) {
1261         ret = spapr_dt_drc(fdt, 0, NULL, SPAPR_DR_CONNECTOR_TYPE_PHB);
1262         if (ret < 0) {
1263             error_report("Couldn't set up PHB DR device tree properties");
1264             exit(1);
1265         }
1266     }
1267 
1268     return fdt;
1269 }
1270 
1271 static uint64_t translate_kernel_address(void *opaque, uint64_t addr)
1272 {
1273     return (addr & 0x0fffffff) + KERNEL_LOAD_ADDR;
1274 }
1275 
1276 static void emulate_spapr_hypercall(PPCVirtualHypervisor *vhyp,
1277                                     PowerPCCPU *cpu)
1278 {
1279     CPUPPCState *env = &cpu->env;
1280 
1281     /* The TCG path should also be holding the BQL at this point */
1282     g_assert(qemu_mutex_iothread_locked());
1283 
1284     if (msr_pr) {
1285         hcall_dprintf("Hypercall made with MSR[PR]=1\n");
1286         env->gpr[3] = H_PRIVILEGE;
1287     } else {
1288         env->gpr[3] = spapr_hypercall(cpu, env->gpr[3], &env->gpr[4]);
1289     }
1290 }
1291 
1292 struct LPCRSyncState {
1293     target_ulong value;
1294     target_ulong mask;
1295 };
1296 
1297 static void do_lpcr_sync(CPUState *cs, run_on_cpu_data arg)
1298 {
1299     struct LPCRSyncState *s = arg.host_ptr;
1300     PowerPCCPU *cpu = POWERPC_CPU(cs);
1301     CPUPPCState *env = &cpu->env;
1302     target_ulong lpcr;
1303 
1304     cpu_synchronize_state(cs);
1305     lpcr = env->spr[SPR_LPCR];
1306     lpcr &= ~s->mask;
1307     lpcr |= s->value;
1308     ppc_store_lpcr(cpu, lpcr);
1309 }
1310 
1311 void spapr_set_all_lpcrs(target_ulong value, target_ulong mask)
1312 {
1313     CPUState *cs;
1314     struct LPCRSyncState s = {
1315         .value = value,
1316         .mask = mask
1317     };
1318     CPU_FOREACH(cs) {
1319         run_on_cpu(cs, do_lpcr_sync, RUN_ON_CPU_HOST_PTR(&s));
1320     }
1321 }
1322 
1323 static void spapr_get_pate(PPCVirtualHypervisor *vhyp, ppc_v3_pate_t *entry)
1324 {
1325     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1326 
1327     /* Copy PATE1:GR into PATE0:HR */
1328     entry->dw0 = spapr->patb_entry & PATE0_HR;
1329     entry->dw1 = spapr->patb_entry;
1330 }
1331 
1332 #define HPTE(_table, _i)   (void *)(((uint64_t *)(_table)) + ((_i) * 2))
1333 #define HPTE_VALID(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_VALID)
1334 #define HPTE_DIRTY(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_HPTE_DIRTY)
1335 #define CLEAN_HPTE(_hpte)  ((*(uint64_t *)(_hpte)) &= tswap64(~HPTE64_V_HPTE_DIRTY))
1336 #define DIRTY_HPTE(_hpte)  ((*(uint64_t *)(_hpte)) |= tswap64(HPTE64_V_HPTE_DIRTY))
1337 
1338 /*
1339  * Get the fd to access the kernel htab, re-opening it if necessary
1340  */
1341 static int get_htab_fd(SpaprMachineState *spapr)
1342 {
1343     Error *local_err = NULL;
1344 
1345     if (spapr->htab_fd >= 0) {
1346         return spapr->htab_fd;
1347     }
1348 
1349     spapr->htab_fd = kvmppc_get_htab_fd(false, 0, &local_err);
1350     if (spapr->htab_fd < 0) {
1351         error_report_err(local_err);
1352     }
1353 
1354     return spapr->htab_fd;
1355 }
1356 
1357 void close_htab_fd(SpaprMachineState *spapr)
1358 {
1359     if (spapr->htab_fd >= 0) {
1360         close(spapr->htab_fd);
1361     }
1362     spapr->htab_fd = -1;
1363 }
1364 
1365 static hwaddr spapr_hpt_mask(PPCVirtualHypervisor *vhyp)
1366 {
1367     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1368 
1369     return HTAB_SIZE(spapr) / HASH_PTEG_SIZE_64 - 1;
1370 }
1371 
1372 static target_ulong spapr_encode_hpt_for_kvm_pr(PPCVirtualHypervisor *vhyp)
1373 {
1374     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1375 
1376     assert(kvm_enabled());
1377 
1378     if (!spapr->htab) {
1379         return 0;
1380     }
1381 
1382     return (target_ulong)(uintptr_t)spapr->htab | (spapr->htab_shift - 18);
1383 }
1384 
1385 static const ppc_hash_pte64_t *spapr_map_hptes(PPCVirtualHypervisor *vhyp,
1386                                                 hwaddr ptex, int n)
1387 {
1388     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1389     hwaddr pte_offset = ptex * HASH_PTE_SIZE_64;
1390 
1391     if (!spapr->htab) {
1392         /*
1393          * HTAB is controlled by KVM. Fetch into temporary buffer
1394          */
1395         ppc_hash_pte64_t *hptes = g_malloc(n * HASH_PTE_SIZE_64);
1396         kvmppc_read_hptes(hptes, ptex, n);
1397         return hptes;
1398     }
1399 
1400     /*
1401      * HTAB is controlled by QEMU. Just point to the internally
1402      * accessible PTEG.
1403      */
1404     return (const ppc_hash_pte64_t *)(spapr->htab + pte_offset);
1405 }
1406 
1407 static void spapr_unmap_hptes(PPCVirtualHypervisor *vhyp,
1408                               const ppc_hash_pte64_t *hptes,
1409                               hwaddr ptex, int n)
1410 {
1411     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1412 
1413     if (!spapr->htab) {
1414         g_free((void *)hptes);
1415     }
1416 
1417     /* Nothing to do for qemu managed HPT */
1418 }
1419 
1420 void spapr_store_hpte(PowerPCCPU *cpu, hwaddr ptex,
1421                       uint64_t pte0, uint64_t pte1)
1422 {
1423     SpaprMachineState *spapr = SPAPR_MACHINE(cpu->vhyp);
1424     hwaddr offset = ptex * HASH_PTE_SIZE_64;
1425 
1426     if (!spapr->htab) {
1427         kvmppc_write_hpte(ptex, pte0, pte1);
1428     } else {
1429         if (pte0 & HPTE64_V_VALID) {
1430             stq_p(spapr->htab + offset + HASH_PTE_SIZE_64 / 2, pte1);
1431             /*
1432              * When setting valid, we write PTE1 first. This ensures
1433              * proper synchronization with the reading code in
1434              * ppc_hash64_pteg_search()
1435              */
1436             smp_wmb();
1437             stq_p(spapr->htab + offset, pte0);
1438         } else {
1439             stq_p(spapr->htab + offset, pte0);
1440             /*
1441              * When clearing it we set PTE0 first. This ensures proper
1442              * synchronization with the reading code in
1443              * ppc_hash64_pteg_search()
1444              */
1445             smp_wmb();
1446             stq_p(spapr->htab + offset + HASH_PTE_SIZE_64 / 2, pte1);
1447         }
1448     }
1449 }
1450 
1451 static void spapr_hpte_set_c(PPCVirtualHypervisor *vhyp, hwaddr ptex,
1452                              uint64_t pte1)
1453 {
1454     hwaddr offset = ptex * HASH_PTE_SIZE_64 + 15;
1455     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1456 
1457     if (!spapr->htab) {
1458         /* There should always be a hash table when this is called */
1459         error_report("spapr_hpte_set_c called with no hash table !");
1460         return;
1461     }
1462 
1463     /* The HW performs a non-atomic byte update */
1464     stb_p(spapr->htab + offset, (pte1 & 0xff) | 0x80);
1465 }
1466 
1467 static void spapr_hpte_set_r(PPCVirtualHypervisor *vhyp, hwaddr ptex,
1468                              uint64_t pte1)
1469 {
1470     hwaddr offset = ptex * HASH_PTE_SIZE_64 + 14;
1471     SpaprMachineState *spapr = SPAPR_MACHINE(vhyp);
1472 
1473     if (!spapr->htab) {
1474         /* There should always be a hash table when this is called */
1475         error_report("spapr_hpte_set_r called with no hash table !");
1476         return;
1477     }
1478 
1479     /* The HW performs a non-atomic byte update */
1480     stb_p(spapr->htab + offset, ((pte1 >> 8) & 0xff) | 0x01);
1481 }
1482 
1483 int spapr_hpt_shift_for_ramsize(uint64_t ramsize)
1484 {
1485     int shift;
1486 
1487     /* We aim for a hash table of size 1/128 the size of RAM (rounded
1488      * up).  The PAPR recommendation is actually 1/64 of RAM size, but
1489      * that's much more than is needed for Linux guests */
1490     shift = ctz64(pow2ceil(ramsize)) - 7;
1491     shift = MAX(shift, 18); /* Minimum architected size */
1492     shift = MIN(shift, 46); /* Maximum architected size */
1493     return shift;
1494 }
1495 
1496 void spapr_free_hpt(SpaprMachineState *spapr)
1497 {
1498     g_free(spapr->htab);
1499     spapr->htab = NULL;
1500     spapr->htab_shift = 0;
1501     close_htab_fd(spapr);
1502 }
1503 
1504 void spapr_reallocate_hpt(SpaprMachineState *spapr, int shift,
1505                           Error **errp)
1506 {
1507     long rc;
1508 
1509     /* Clean up any HPT info from a previous boot */
1510     spapr_free_hpt(spapr);
1511 
1512     rc = kvmppc_reset_htab(shift);
1513     if (rc < 0) {
1514         /* kernel-side HPT needed, but couldn't allocate one */
1515         error_setg_errno(errp, errno,
1516                          "Failed to allocate KVM HPT of order %d (try smaller maxmem?)",
1517                          shift);
1518         /* This is almost certainly fatal, but if the caller really
1519          * wants to carry on with shift == 0, it's welcome to try */
1520     } else if (rc > 0) {
1521         /* kernel-side HPT allocated */
1522         if (rc != shift) {
1523             error_setg(errp,
1524                        "Requested order %d HPT, but kernel allocated order %ld (try smaller maxmem?)",
1525                        shift, rc);
1526         }
1527 
1528         spapr->htab_shift = shift;
1529         spapr->htab = NULL;
1530     } else {
1531         /* kernel-side HPT not needed, allocate in userspace instead */
1532         size_t size = 1ULL << shift;
1533         int i;
1534 
1535         spapr->htab = qemu_memalign(size, size);
1536         if (!spapr->htab) {
1537             error_setg_errno(errp, errno,
1538                              "Could not allocate HPT of order %d", shift);
1539             return;
1540         }
1541 
1542         memset(spapr->htab, 0, size);
1543         spapr->htab_shift = shift;
1544 
1545         for (i = 0; i < size / HASH_PTE_SIZE_64; i++) {
1546             DIRTY_HPTE(HPTE(spapr->htab, i));
1547         }
1548     }
1549     /* We're setting up a hash table, so that means we're not radix */
1550     spapr->patb_entry = 0;
1551     spapr_set_all_lpcrs(0, LPCR_HR | LPCR_UPRT);
1552 }
1553 
1554 void spapr_setup_hpt_and_vrma(SpaprMachineState *spapr)
1555 {
1556     int hpt_shift;
1557 
1558     if ((spapr->resize_hpt == SPAPR_RESIZE_HPT_DISABLED)
1559         || (spapr->cas_reboot
1560             && !spapr_ovec_test(spapr->ov5_cas, OV5_HPT_RESIZE))) {
1561         hpt_shift = spapr_hpt_shift_for_ramsize(MACHINE(spapr)->maxram_size);
1562     } else {
1563         uint64_t current_ram_size;
1564 
1565         current_ram_size = MACHINE(spapr)->ram_size + get_plugged_memory_size();
1566         hpt_shift = spapr_hpt_shift_for_ramsize(current_ram_size);
1567     }
1568     spapr_reallocate_hpt(spapr, hpt_shift, &error_fatal);
1569 
1570     if (spapr->vrma_adjust) {
1571         spapr->rma_size = kvmppc_rma_size(spapr_node0_size(MACHINE(spapr)),
1572                                           spapr->htab_shift);
1573     }
1574 }
1575 
1576 static int spapr_reset_drcs(Object *child, void *opaque)
1577 {
1578     SpaprDrc *drc =
1579         (SpaprDrc *) object_dynamic_cast(child,
1580                                                  TYPE_SPAPR_DR_CONNECTOR);
1581 
1582     if (drc) {
1583         spapr_drc_reset(drc);
1584     }
1585 
1586     return 0;
1587 }
1588 
1589 static void spapr_machine_reset(MachineState *machine)
1590 {
1591     SpaprMachineState *spapr = SPAPR_MACHINE(machine);
1592     PowerPCCPU *first_ppc_cpu;
1593     hwaddr fdt_addr;
1594     void *fdt;
1595     int rc;
1596 
1597     kvmppc_svm_off(&error_fatal);
1598     spapr_caps_apply(spapr);
1599 
1600     first_ppc_cpu = POWERPC_CPU(first_cpu);
1601     if (kvm_enabled() && kvmppc_has_cap_mmu_radix() &&
1602         ppc_type_check_compat(machine->cpu_type, CPU_POWERPC_LOGICAL_3_00, 0,
1603                               spapr->max_compat_pvr)) {
1604         /*
1605          * If using KVM with radix mode available, VCPUs can be started
1606          * without a HPT because KVM will start them in radix mode.
1607          * Set the GR bit in PATE so that we know there is no HPT.
1608          */
1609         spapr->patb_entry = PATE1_GR;
1610         spapr_set_all_lpcrs(LPCR_HR | LPCR_UPRT, LPCR_HR | LPCR_UPRT);
1611     } else {
1612         spapr_setup_hpt_and_vrma(spapr);
1613     }
1614 
1615     qemu_devices_reset();
1616 
1617     /*
1618      * If this reset wasn't generated by CAS, we should reset our
1619      * negotiated options and start from scratch
1620      */
1621     if (!spapr->cas_reboot) {
1622         spapr_ovec_cleanup(spapr->ov5_cas);
1623         spapr->ov5_cas = spapr_ovec_new();
1624 
1625         ppc_set_compat_all(spapr->max_compat_pvr, &error_fatal);
1626     }
1627 
1628     /*
1629      * This is fixing some of the default configuration of the XIVE
1630      * devices. To be called after the reset of the machine devices.
1631      */
1632     spapr_irq_reset(spapr, &error_fatal);
1633 
1634     /*
1635      * There is no CAS under qtest. Simulate one to please the code that
1636      * depends on spapr->ov5_cas. This is especially needed to test device
1637      * unplug, so we do that before resetting the DRCs.
1638      */
1639     if (qtest_enabled()) {
1640         spapr_ovec_cleanup(spapr->ov5_cas);
1641         spapr->ov5_cas = spapr_ovec_clone(spapr->ov5);
1642     }
1643 
1644     /* DRC reset may cause a device to be unplugged. This will cause troubles
1645      * if this device is used by another device (eg, a running vhost backend
1646      * will crash QEMU if the DIMM holding the vring goes away). To avoid such
1647      * situations, we reset DRCs after all devices have been reset.
1648      */
1649     object_child_foreach_recursive(object_get_root(), spapr_reset_drcs, NULL);
1650 
1651     spapr_clear_pending_events(spapr);
1652 
1653     /*
1654      * We place the device tree and RTAS just below either the top of the RMA,
1655      * or just below 2GB, whichever is lower, so that it can be
1656      * processed with 32-bit real mode code if necessary
1657      */
1658     fdt_addr = MIN(spapr->rma_size, RTAS_MAX_ADDR) - FDT_MAX_SIZE;
1659 
1660     fdt = spapr_build_fdt(spapr, true, FDT_MAX_SIZE);
1661 
1662     rc = fdt_pack(fdt);
1663 
1664     /* Should only fail if we've built a corrupted tree */
1665     assert(rc == 0);
1666 
1667     /* Load the fdt */
1668     qemu_fdt_dumpdtb(fdt, fdt_totalsize(fdt));
1669     cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt));
1670     g_free(spapr->fdt_blob);
1671     spapr->fdt_size = fdt_totalsize(fdt);
1672     spapr->fdt_initial_size = spapr->fdt_size;
1673     spapr->fdt_blob = fdt;
1674 
1675     /* Set up the entry state */
1676     spapr_cpu_set_entry_state(first_ppc_cpu, SPAPR_ENTRY_POINT, fdt_addr);
1677     first_ppc_cpu->env.gpr[5] = 0;
1678 
1679     spapr->cas_reboot = false;
1680 
1681     spapr->mc_status = -1;
1682     spapr->guest_machine_check_addr = -1;
1683 
1684     /* Signal all vCPUs waiting on this condition */
1685     qemu_cond_broadcast(&spapr->mc_delivery_cond);
1686 }
1687 
1688 static void spapr_create_nvram(SpaprMachineState *spapr)
1689 {
1690     DeviceState *dev = qdev_create(&spapr->vio_bus->bus, "spapr-nvram");
1691     DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);
1692 
1693     if (dinfo) {
1694         qdev_prop_set_drive(dev, "drive", blk_by_legacy_dinfo(dinfo),
1695                             &error_fatal);
1696     }
1697 
1698     qdev_init_nofail(dev);
1699 
1700     spapr->nvram = (struct SpaprNvram *)dev;
1701 }
1702 
1703 static void spapr_rtc_create(SpaprMachineState *spapr)
1704 {
1705     object_initialize_child(OBJECT(spapr), "rtc",
1706                             &spapr->rtc, sizeof(spapr->rtc), TYPE_SPAPR_RTC,
1707                             &error_fatal, NULL);
1708     object_property_set_bool(OBJECT(&spapr->rtc), true, "realized",
1709                               &error_fatal);
1710     object_property_add_alias(OBJECT(spapr), "rtc-time", OBJECT(&spapr->rtc),
1711                               "date", &error_fatal);
1712 }
1713 
1714 /* Returns whether we want to use VGA or not */
1715 static bool spapr_vga_init(PCIBus *pci_bus, Error **errp)
1716 {
1717     switch (vga_interface_type) {
1718     case VGA_NONE:
1719         return false;
1720     case VGA_DEVICE:
1721         return true;
1722     case VGA_STD:
1723     case VGA_VIRTIO:
1724     case VGA_CIRRUS:
1725         return pci_vga_init(pci_bus) != NULL;
1726     default:
1727         error_setg(errp,
1728                    "Unsupported VGA mode, only -vga std or -vga virtio is supported");
1729         return false;
1730     }
1731 }
1732 
1733 static int spapr_pre_load(void *opaque)
1734 {
1735     int rc;
1736 
1737     rc = spapr_caps_pre_load(opaque);
1738     if (rc) {
1739         return rc;
1740     }
1741 
1742     return 0;
1743 }
1744 
1745 static int spapr_post_load(void *opaque, int version_id)
1746 {
1747     SpaprMachineState *spapr = (SpaprMachineState *)opaque;
1748     int err = 0;
1749 
1750     err = spapr_caps_post_migration(spapr);
1751     if (err) {
1752         return err;
1753     }
1754 
1755     /*
1756      * In earlier versions, there was no separate qdev for the PAPR
1757      * RTC, so the RTC offset was stored directly in sPAPREnvironment.
1758      * So when migrating from those versions, poke the incoming offset
1759      * value into the RTC device
1760      */
1761     if (version_id < 3) {
1762         err = spapr_rtc_import_offset(&spapr->rtc, spapr->rtc_offset);
1763         if (err) {
1764             return err;
1765         }
1766     }
1767 
1768     if (kvm_enabled() && spapr->patb_entry) {
1769         PowerPCCPU *cpu = POWERPC_CPU(first_cpu);
1770         bool radix = !!(spapr->patb_entry & PATE1_GR);
1771         bool gtse = !!(cpu->env.spr[SPR_LPCR] & LPCR_GTSE);
1772 
1773         /*
1774          * Update LPCR:HR and UPRT as they may not be set properly in
1775          * the stream
1776          */
1777         spapr_set_all_lpcrs(radix ? (LPCR_HR | LPCR_UPRT) : 0,
1778                             LPCR_HR | LPCR_UPRT);
1779 
1780         err = kvmppc_configure_v3_mmu(cpu, radix, gtse, spapr->patb_entry);
1781         if (err) {
1782             error_report("Process table config unsupported by the host");
1783             return -EINVAL;
1784         }
1785     }
1786 
1787     err = spapr_irq_post_load(spapr, version_id);
1788     if (err) {
1789         return err;
1790     }
1791 
1792     return err;
1793 }
1794 
1795 static int spapr_pre_save(void *opaque)
1796 {
1797     int rc;
1798 
1799     rc = spapr_caps_pre_save(opaque);
1800     if (rc) {
1801         return rc;
1802     }
1803 
1804     return 0;
1805 }
1806 
1807 static bool version_before_3(void *opaque, int version_id)
1808 {
1809     return version_id < 3;
1810 }
1811 
1812 static bool spapr_pending_events_needed(void *opaque)
1813 {
1814     SpaprMachineState *spapr = (SpaprMachineState *)opaque;
1815     return !QTAILQ_EMPTY(&spapr->pending_events);
1816 }
1817 
1818 static const VMStateDescription vmstate_spapr_event_entry = {
1819     .name = "spapr_event_log_entry",
1820     .version_id = 1,
1821     .minimum_version_id = 1,
1822     .fields = (VMStateField[]) {
1823         VMSTATE_UINT32(summary, SpaprEventLogEntry),
1824         VMSTATE_UINT32(extended_length, SpaprEventLogEntry),
1825         VMSTATE_VBUFFER_ALLOC_UINT32(extended_log, SpaprEventLogEntry, 0,
1826                                      NULL, extended_length),
1827         VMSTATE_END_OF_LIST()
1828     },
1829 };
1830 
1831 static const VMStateDescription vmstate_spapr_pending_events = {
1832     .name = "spapr_pending_events",
1833     .version_id = 1,
1834     .minimum_version_id = 1,
1835     .needed = spapr_pending_events_needed,
1836     .fields = (VMStateField[]) {
1837         VMSTATE_QTAILQ_V(pending_events, SpaprMachineState, 1,
1838                          vmstate_spapr_event_entry, SpaprEventLogEntry, next),
1839         VMSTATE_END_OF_LIST()
1840     },
1841 };
1842 
1843 static bool spapr_ov5_cas_needed(void *opaque)
1844 {
1845     SpaprMachineState *spapr = opaque;
1846     SpaprOptionVector *ov5_mask = spapr_ovec_new();
1847     bool cas_needed;
1848 
1849     /* Prior to the introduction of SpaprOptionVector, we had two option
1850      * vectors we dealt with: OV5_FORM1_AFFINITY, and OV5_DRCONF_MEMORY.
1851      * Both of these options encode machine topology into the device-tree
1852      * in such a way that the now-booted OS should still be able to interact
1853      * appropriately with QEMU regardless of what options were actually
1854      * negotiatied on the source side.
1855      *
1856      * As such, we can avoid migrating the CAS-negotiated options if these
1857      * are the only options available on the current machine/platform.
1858      * Since these are the only options available for pseries-2.7 and
1859      * earlier, this allows us to maintain old->new/new->old migration
1860      * compatibility.
1861      *
1862      * For QEMU 2.8+, there are additional CAS-negotiatable options available
1863      * via default pseries-2.8 machines and explicit command-line parameters.
1864      * Some of these options, like OV5_HP_EVT, *do* require QEMU to be aware
1865      * of the actual CAS-negotiated values to continue working properly. For
1866      * example, availability of memory unplug depends on knowing whether
1867      * OV5_HP_EVT was negotiated via CAS.
1868      *
1869      * Thus, for any cases where the set of available CAS-negotiatable
1870      * options extends beyond OV5_FORM1_AFFINITY and OV5_DRCONF_MEMORY, we
1871      * include the CAS-negotiated options in the migration stream, unless
1872      * if they affect boot time behaviour only.
1873      */
1874     spapr_ovec_set(ov5_mask, OV5_FORM1_AFFINITY);
1875     spapr_ovec_set(ov5_mask, OV5_DRCONF_MEMORY);
1876     spapr_ovec_set(ov5_mask, OV5_DRMEM_V2);
1877 
1878     /* We need extra information if we have any bits outside the mask
1879      * defined above */
1880     cas_needed = !spapr_ovec_subset(spapr->ov5, ov5_mask);
1881 
1882     spapr_ovec_cleanup(ov5_mask);
1883 
1884     return cas_needed;
1885 }
1886 
1887 static const VMStateDescription vmstate_spapr_ov5_cas = {
1888     .name = "spapr_option_vector_ov5_cas",
1889     .version_id = 1,
1890     .minimum_version_id = 1,
1891     .needed = spapr_ov5_cas_needed,
1892     .fields = (VMStateField[]) {
1893         VMSTATE_STRUCT_POINTER_V(ov5_cas, SpaprMachineState, 1,
1894                                  vmstate_spapr_ovec, SpaprOptionVector),
1895         VMSTATE_END_OF_LIST()
1896     },
1897 };
1898 
1899 static bool spapr_patb_entry_needed(void *opaque)
1900 {
1901     SpaprMachineState *spapr = opaque;
1902 
1903     return !!spapr->patb_entry;
1904 }
1905 
1906 static const VMStateDescription vmstate_spapr_patb_entry = {
1907     .name = "spapr_patb_entry",
1908     .version_id = 1,
1909     .minimum_version_id = 1,
1910     .needed = spapr_patb_entry_needed,
1911     .fields = (VMStateField[]) {
1912         VMSTATE_UINT64(patb_entry, SpaprMachineState),
1913         VMSTATE_END_OF_LIST()
1914     },
1915 };
1916 
1917 static bool spapr_irq_map_needed(void *opaque)
1918 {
1919     SpaprMachineState *spapr = opaque;
1920 
1921     return spapr->irq_map && !bitmap_empty(spapr->irq_map, spapr->irq_map_nr);
1922 }
1923 
1924 static const VMStateDescription vmstate_spapr_irq_map = {
1925     .name = "spapr_irq_map",
1926     .version_id = 1,
1927     .minimum_version_id = 1,
1928     .needed = spapr_irq_map_needed,
1929     .fields = (VMStateField[]) {
1930         VMSTATE_BITMAP(irq_map, SpaprMachineState, 0, irq_map_nr),
1931         VMSTATE_END_OF_LIST()
1932     },
1933 };
1934 
1935 static bool spapr_dtb_needed(void *opaque)
1936 {
1937     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(opaque);
1938 
1939     return smc->update_dt_enabled;
1940 }
1941 
1942 static int spapr_dtb_pre_load(void *opaque)
1943 {
1944     SpaprMachineState *spapr = (SpaprMachineState *)opaque;
1945 
1946     g_free(spapr->fdt_blob);
1947     spapr->fdt_blob = NULL;
1948     spapr->fdt_size = 0;
1949 
1950     return 0;
1951 }
1952 
1953 static const VMStateDescription vmstate_spapr_dtb = {
1954     .name = "spapr_dtb",
1955     .version_id = 1,
1956     .minimum_version_id = 1,
1957     .needed = spapr_dtb_needed,
1958     .pre_load = spapr_dtb_pre_load,
1959     .fields = (VMStateField[]) {
1960         VMSTATE_UINT32(fdt_initial_size, SpaprMachineState),
1961         VMSTATE_UINT32(fdt_size, SpaprMachineState),
1962         VMSTATE_VBUFFER_ALLOC_UINT32(fdt_blob, SpaprMachineState, 0, NULL,
1963                                      fdt_size),
1964         VMSTATE_END_OF_LIST()
1965     },
1966 };
1967 
1968 static const VMStateDescription vmstate_spapr = {
1969     .name = "spapr",
1970     .version_id = 3,
1971     .minimum_version_id = 1,
1972     .pre_load = spapr_pre_load,
1973     .post_load = spapr_post_load,
1974     .pre_save = spapr_pre_save,
1975     .fields = (VMStateField[]) {
1976         /* used to be @next_irq */
1977         VMSTATE_UNUSED_BUFFER(version_before_3, 0, 4),
1978 
1979         /* RTC offset */
1980         VMSTATE_UINT64_TEST(rtc_offset, SpaprMachineState, version_before_3),
1981 
1982         VMSTATE_PPC_TIMEBASE_V(tb, SpaprMachineState, 2),
1983         VMSTATE_END_OF_LIST()
1984     },
1985     .subsections = (const VMStateDescription*[]) {
1986         &vmstate_spapr_ov5_cas,
1987         &vmstate_spapr_patb_entry,
1988         &vmstate_spapr_pending_events,
1989         &vmstate_spapr_cap_htm,
1990         &vmstate_spapr_cap_vsx,
1991         &vmstate_spapr_cap_dfp,
1992         &vmstate_spapr_cap_cfpc,
1993         &vmstate_spapr_cap_sbbc,
1994         &vmstate_spapr_cap_ibs,
1995         &vmstate_spapr_cap_hpt_maxpagesize,
1996         &vmstate_spapr_irq_map,
1997         &vmstate_spapr_cap_nested_kvm_hv,
1998         &vmstate_spapr_dtb,
1999         &vmstate_spapr_cap_large_decr,
2000         &vmstate_spapr_cap_ccf_assist,
2001         &vmstate_spapr_cap_fwnmi,
2002         NULL
2003     }
2004 };
2005 
2006 static int htab_save_setup(QEMUFile *f, void *opaque)
2007 {
2008     SpaprMachineState *spapr = opaque;
2009 
2010     /* "Iteration" header */
2011     if (!spapr->htab_shift) {
2012         qemu_put_be32(f, -1);
2013     } else {
2014         qemu_put_be32(f, spapr->htab_shift);
2015     }
2016 
2017     if (spapr->htab) {
2018         spapr->htab_save_index = 0;
2019         spapr->htab_first_pass = true;
2020     } else {
2021         if (spapr->htab_shift) {
2022             assert(kvm_enabled());
2023         }
2024     }
2025 
2026 
2027     return 0;
2028 }
2029 
2030 static void htab_save_chunk(QEMUFile *f, SpaprMachineState *spapr,
2031                             int chunkstart, int n_valid, int n_invalid)
2032 {
2033     qemu_put_be32(f, chunkstart);
2034     qemu_put_be16(f, n_valid);
2035     qemu_put_be16(f, n_invalid);
2036     qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),
2037                     HASH_PTE_SIZE_64 * n_valid);
2038 }
2039 
2040 static void htab_save_end_marker(QEMUFile *f)
2041 {
2042     qemu_put_be32(f, 0);
2043     qemu_put_be16(f, 0);
2044     qemu_put_be16(f, 0);
2045 }
2046 
2047 static void htab_save_first_pass(QEMUFile *f, SpaprMachineState *spapr,
2048                                  int64_t max_ns)
2049 {
2050     bool has_timeout = max_ns != -1;
2051     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
2052     int index = spapr->htab_save_index;
2053     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2054 
2055     assert(spapr->htab_first_pass);
2056 
2057     do {
2058         int chunkstart;
2059 
2060         /* Consume invalid HPTEs */
2061         while ((index < htabslots)
2062                && !HPTE_VALID(HPTE(spapr->htab, index))) {
2063             CLEAN_HPTE(HPTE(spapr->htab, index));
2064             index++;
2065         }
2066 
2067         /* Consume valid HPTEs */
2068         chunkstart = index;
2069         while ((index < htabslots) && (index - chunkstart < USHRT_MAX)
2070                && HPTE_VALID(HPTE(spapr->htab, index))) {
2071             CLEAN_HPTE(HPTE(spapr->htab, index));
2072             index++;
2073         }
2074 
2075         if (index > chunkstart) {
2076             int n_valid = index - chunkstart;
2077 
2078             htab_save_chunk(f, spapr, chunkstart, n_valid, 0);
2079 
2080             if (has_timeout &&
2081                 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
2082                 break;
2083             }
2084         }
2085     } while ((index < htabslots) && !qemu_file_rate_limit(f));
2086 
2087     if (index >= htabslots) {
2088         assert(index == htabslots);
2089         index = 0;
2090         spapr->htab_first_pass = false;
2091     }
2092     spapr->htab_save_index = index;
2093 }
2094 
2095 static int htab_save_later_pass(QEMUFile *f, SpaprMachineState *spapr,
2096                                 int64_t max_ns)
2097 {
2098     bool final = max_ns < 0;
2099     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
2100     int examined = 0, sent = 0;
2101     int index = spapr->htab_save_index;
2102     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2103 
2104     assert(!spapr->htab_first_pass);
2105 
2106     do {
2107         int chunkstart, invalidstart;
2108 
2109         /* Consume non-dirty HPTEs */
2110         while ((index < htabslots)
2111                && !HPTE_DIRTY(HPTE(spapr->htab, index))) {
2112             index++;
2113             examined++;
2114         }
2115 
2116         chunkstart = index;
2117         /* Consume valid dirty HPTEs */
2118         while ((index < htabslots) && (index - chunkstart < USHRT_MAX)
2119                && HPTE_DIRTY(HPTE(spapr->htab, index))
2120                && HPTE_VALID(HPTE(spapr->htab, index))) {
2121             CLEAN_HPTE(HPTE(spapr->htab, index));
2122             index++;
2123             examined++;
2124         }
2125 
2126         invalidstart = index;
2127         /* Consume invalid dirty HPTEs */
2128         while ((index < htabslots) && (index - invalidstart < USHRT_MAX)
2129                && HPTE_DIRTY(HPTE(spapr->htab, index))
2130                && !HPTE_VALID(HPTE(spapr->htab, index))) {
2131             CLEAN_HPTE(HPTE(spapr->htab, index));
2132             index++;
2133             examined++;
2134         }
2135 
2136         if (index > chunkstart) {
2137             int n_valid = invalidstart - chunkstart;
2138             int n_invalid = index - invalidstart;
2139 
2140             htab_save_chunk(f, spapr, chunkstart, n_valid, n_invalid);
2141             sent += index - chunkstart;
2142 
2143             if (!final && (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
2144                 break;
2145             }
2146         }
2147 
2148         if (examined >= htabslots) {
2149             break;
2150         }
2151 
2152         if (index >= htabslots) {
2153             assert(index == htabslots);
2154             index = 0;
2155         }
2156     } while ((examined < htabslots) && (!qemu_file_rate_limit(f) || final));
2157 
2158     if (index >= htabslots) {
2159         assert(index == htabslots);
2160         index = 0;
2161     }
2162 
2163     spapr->htab_save_index = index;
2164 
2165     return (examined >= htabslots) && (sent == 0) ? 1 : 0;
2166 }
2167 
2168 #define MAX_ITERATION_NS    5000000 /* 5 ms */
2169 #define MAX_KVM_BUF_SIZE    2048
2170 
2171 static int htab_save_iterate(QEMUFile *f, void *opaque)
2172 {
2173     SpaprMachineState *spapr = opaque;
2174     int fd;
2175     int rc = 0;
2176 
2177     /* Iteration header */
2178     if (!spapr->htab_shift) {
2179         qemu_put_be32(f, -1);
2180         return 1;
2181     } else {
2182         qemu_put_be32(f, 0);
2183     }
2184 
2185     if (!spapr->htab) {
2186         assert(kvm_enabled());
2187 
2188         fd = get_htab_fd(spapr);
2189         if (fd < 0) {
2190             return fd;
2191         }
2192 
2193         rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, MAX_ITERATION_NS);
2194         if (rc < 0) {
2195             return rc;
2196         }
2197     } else  if (spapr->htab_first_pass) {
2198         htab_save_first_pass(f, spapr, MAX_ITERATION_NS);
2199     } else {
2200         rc = htab_save_later_pass(f, spapr, MAX_ITERATION_NS);
2201     }
2202 
2203     htab_save_end_marker(f);
2204 
2205     return rc;
2206 }
2207 
2208 static int htab_save_complete(QEMUFile *f, void *opaque)
2209 {
2210     SpaprMachineState *spapr = opaque;
2211     int fd;
2212 
2213     /* Iteration header */
2214     if (!spapr->htab_shift) {
2215         qemu_put_be32(f, -1);
2216         return 0;
2217     } else {
2218         qemu_put_be32(f, 0);
2219     }
2220 
2221     if (!spapr->htab) {
2222         int rc;
2223 
2224         assert(kvm_enabled());
2225 
2226         fd = get_htab_fd(spapr);
2227         if (fd < 0) {
2228             return fd;
2229         }
2230 
2231         rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, -1);
2232         if (rc < 0) {
2233             return rc;
2234         }
2235     } else {
2236         if (spapr->htab_first_pass) {
2237             htab_save_first_pass(f, spapr, -1);
2238         }
2239         htab_save_later_pass(f, spapr, -1);
2240     }
2241 
2242     /* End marker */
2243     htab_save_end_marker(f);
2244 
2245     return 0;
2246 }
2247 
2248 static int htab_load(QEMUFile *f, void *opaque, int version_id)
2249 {
2250     SpaprMachineState *spapr = opaque;
2251     uint32_t section_hdr;
2252     int fd = -1;
2253     Error *local_err = NULL;
2254 
2255     if (version_id < 1 || version_id > 1) {
2256         error_report("htab_load() bad version");
2257         return -EINVAL;
2258     }
2259 
2260     section_hdr = qemu_get_be32(f);
2261 
2262     if (section_hdr == -1) {
2263         spapr_free_hpt(spapr);
2264         return 0;
2265     }
2266 
2267     if (section_hdr) {
2268         /* First section gives the htab size */
2269         spapr_reallocate_hpt(spapr, section_hdr, &local_err);
2270         if (local_err) {
2271             error_report_err(local_err);
2272             return -EINVAL;
2273         }
2274         return 0;
2275     }
2276 
2277     if (!spapr->htab) {
2278         assert(kvm_enabled());
2279 
2280         fd = kvmppc_get_htab_fd(true, 0, &local_err);
2281         if (fd < 0) {
2282             error_report_err(local_err);
2283             return fd;
2284         }
2285     }
2286 
2287     while (true) {
2288         uint32_t index;
2289         uint16_t n_valid, n_invalid;
2290 
2291         index = qemu_get_be32(f);
2292         n_valid = qemu_get_be16(f);
2293         n_invalid = qemu_get_be16(f);
2294 
2295         if ((index == 0) && (n_valid == 0) && (n_invalid == 0)) {
2296             /* End of Stream */
2297             break;
2298         }
2299 
2300         if ((index + n_valid + n_invalid) >
2301             (HTAB_SIZE(spapr) / HASH_PTE_SIZE_64)) {
2302             /* Bad index in stream */
2303             error_report(
2304                 "htab_load() bad index %d (%hd+%hd entries) in htab stream (htab_shift=%d)",
2305                 index, n_valid, n_invalid, spapr->htab_shift);
2306             return -EINVAL;
2307         }
2308 
2309         if (spapr->htab) {
2310             if (n_valid) {
2311                 qemu_get_buffer(f, HPTE(spapr->htab, index),
2312                                 HASH_PTE_SIZE_64 * n_valid);
2313             }
2314             if (n_invalid) {
2315                 memset(HPTE(spapr->htab, index + n_valid), 0,
2316                        HASH_PTE_SIZE_64 * n_invalid);
2317             }
2318         } else {
2319             int rc;
2320 
2321             assert(fd >= 0);
2322 
2323             rc = kvmppc_load_htab_chunk(f, fd, index, n_valid, n_invalid);
2324             if (rc < 0) {
2325                 return rc;
2326             }
2327         }
2328     }
2329 
2330     if (!spapr->htab) {
2331         assert(fd >= 0);
2332         close(fd);
2333     }
2334 
2335     return 0;
2336 }
2337 
2338 static void htab_save_cleanup(void *opaque)
2339 {
2340     SpaprMachineState *spapr = opaque;
2341 
2342     close_htab_fd(spapr);
2343 }
2344 
2345 static SaveVMHandlers savevm_htab_handlers = {
2346     .save_setup = htab_save_setup,
2347     .save_live_iterate = htab_save_iterate,
2348     .save_live_complete_precopy = htab_save_complete,
2349     .save_cleanup = htab_save_cleanup,
2350     .load_state = htab_load,
2351 };
2352 
2353 static void spapr_boot_set(void *opaque, const char *boot_device,
2354                            Error **errp)
2355 {
2356     MachineState *machine = MACHINE(opaque);
2357     machine->boot_order = g_strdup(boot_device);
2358 }
2359 
2360 static void spapr_create_lmb_dr_connectors(SpaprMachineState *spapr)
2361 {
2362     MachineState *machine = MACHINE(spapr);
2363     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
2364     uint32_t nr_lmbs = (machine->maxram_size - machine->ram_size)/lmb_size;
2365     int i;
2366 
2367     for (i = 0; i < nr_lmbs; i++) {
2368         uint64_t addr;
2369 
2370         addr = i * lmb_size + machine->device_memory->base;
2371         spapr_dr_connector_new(OBJECT(spapr), TYPE_SPAPR_DRC_LMB,
2372                                addr / lmb_size);
2373     }
2374 }
2375 
2376 /*
2377  * If RAM size, maxmem size and individual node mem sizes aren't aligned
2378  * to SPAPR_MEMORY_BLOCK_SIZE(256MB), then refuse to start the guest
2379  * since we can't support such unaligned sizes with DRCONF_MEMORY.
2380  */
2381 static void spapr_validate_node_memory(MachineState *machine, Error **errp)
2382 {
2383     int i;
2384 
2385     if (machine->ram_size % SPAPR_MEMORY_BLOCK_SIZE) {
2386         error_setg(errp, "Memory size 0x" RAM_ADDR_FMT
2387                    " is not aligned to %" PRIu64 " MiB",
2388                    machine->ram_size,
2389                    SPAPR_MEMORY_BLOCK_SIZE / MiB);
2390         return;
2391     }
2392 
2393     if (machine->maxram_size % SPAPR_MEMORY_BLOCK_SIZE) {
2394         error_setg(errp, "Maximum memory size 0x" RAM_ADDR_FMT
2395                    " is not aligned to %" PRIu64 " MiB",
2396                    machine->ram_size,
2397                    SPAPR_MEMORY_BLOCK_SIZE / MiB);
2398         return;
2399     }
2400 
2401     for (i = 0; i < machine->numa_state->num_nodes; i++) {
2402         if (machine->numa_state->nodes[i].node_mem % SPAPR_MEMORY_BLOCK_SIZE) {
2403             error_setg(errp,
2404                        "Node %d memory size 0x%" PRIx64
2405                        " is not aligned to %" PRIu64 " MiB",
2406                        i, machine->numa_state->nodes[i].node_mem,
2407                        SPAPR_MEMORY_BLOCK_SIZE / MiB);
2408             return;
2409         }
2410     }
2411 }
2412 
2413 /* find cpu slot in machine->possible_cpus by core_id */
2414 static CPUArchId *spapr_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
2415 {
2416     int index = id / ms->smp.threads;
2417 
2418     if (index >= ms->possible_cpus->len) {
2419         return NULL;
2420     }
2421     if (idx) {
2422         *idx = index;
2423     }
2424     return &ms->possible_cpus->cpus[index];
2425 }
2426 
2427 static void spapr_set_vsmt_mode(SpaprMachineState *spapr, Error **errp)
2428 {
2429     MachineState *ms = MACHINE(spapr);
2430     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
2431     Error *local_err = NULL;
2432     bool vsmt_user = !!spapr->vsmt;
2433     int kvm_smt = kvmppc_smt_threads();
2434     int ret;
2435     unsigned int smp_threads = ms->smp.threads;
2436 
2437     if (!kvm_enabled() && (smp_threads > 1)) {
2438         error_setg(&local_err, "TCG cannot support more than 1 thread/core "
2439                      "on a pseries machine");
2440         goto out;
2441     }
2442     if (!is_power_of_2(smp_threads)) {
2443         error_setg(&local_err, "Cannot support %d threads/core on a pseries "
2444                      "machine because it must be a power of 2", smp_threads);
2445         goto out;
2446     }
2447 
2448     /* Detemine the VSMT mode to use: */
2449     if (vsmt_user) {
2450         if (spapr->vsmt < smp_threads) {
2451             error_setg(&local_err, "Cannot support VSMT mode %d"
2452                          " because it must be >= threads/core (%d)",
2453                          spapr->vsmt, smp_threads);
2454             goto out;
2455         }
2456         /* In this case, spapr->vsmt has been set by the command line */
2457     } else if (!smc->smp_threads_vsmt) {
2458         /*
2459          * Default VSMT value is tricky, because we need it to be as
2460          * consistent as possible (for migration), but this requires
2461          * changing it for at least some existing cases.  We pick 8 as
2462          * the value that we'd get with KVM on POWER8, the
2463          * overwhelmingly common case in production systems.
2464          */
2465         spapr->vsmt = MAX(8, smp_threads);
2466     } else {
2467         spapr->vsmt = smp_threads;
2468     }
2469 
2470     /* KVM: If necessary, set the SMT mode: */
2471     if (kvm_enabled() && (spapr->vsmt != kvm_smt)) {
2472         ret = kvmppc_set_smt_threads(spapr->vsmt);
2473         if (ret) {
2474             /* Looks like KVM isn't able to change VSMT mode */
2475             error_setg(&local_err,
2476                        "Failed to set KVM's VSMT mode to %d (errno %d)",
2477                        spapr->vsmt, ret);
2478             /* We can live with that if the default one is big enough
2479              * for the number of threads, and a submultiple of the one
2480              * we want.  In this case we'll waste some vcpu ids, but
2481              * behaviour will be correct */
2482             if ((kvm_smt >= smp_threads) && ((spapr->vsmt % kvm_smt) == 0)) {
2483                 warn_report_err(local_err);
2484                 local_err = NULL;
2485                 goto out;
2486             } else {
2487                 if (!vsmt_user) {
2488                     error_append_hint(&local_err,
2489                                       "On PPC, a VM with %d threads/core"
2490                                       " on a host with %d threads/core"
2491                                       " requires the use of VSMT mode %d.\n",
2492                                       smp_threads, kvm_smt, spapr->vsmt);
2493                 }
2494                 kvmppc_error_append_smt_possible_hint(&local_err);
2495                 goto out;
2496             }
2497         }
2498     }
2499     /* else TCG: nothing to do currently */
2500 out:
2501     error_propagate(errp, local_err);
2502 }
2503 
2504 static void spapr_init_cpus(SpaprMachineState *spapr)
2505 {
2506     MachineState *machine = MACHINE(spapr);
2507     MachineClass *mc = MACHINE_GET_CLASS(machine);
2508     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
2509     const char *type = spapr_get_cpu_core_type(machine->cpu_type);
2510     const CPUArchIdList *possible_cpus;
2511     unsigned int smp_cpus = machine->smp.cpus;
2512     unsigned int smp_threads = machine->smp.threads;
2513     unsigned int max_cpus = machine->smp.max_cpus;
2514     int boot_cores_nr = smp_cpus / smp_threads;
2515     int i;
2516 
2517     possible_cpus = mc->possible_cpu_arch_ids(machine);
2518     if (mc->has_hotpluggable_cpus) {
2519         if (smp_cpus % smp_threads) {
2520             error_report("smp_cpus (%u) must be multiple of threads (%u)",
2521                          smp_cpus, smp_threads);
2522             exit(1);
2523         }
2524         if (max_cpus % smp_threads) {
2525             error_report("max_cpus (%u) must be multiple of threads (%u)",
2526                          max_cpus, smp_threads);
2527             exit(1);
2528         }
2529     } else {
2530         if (max_cpus != smp_cpus) {
2531             error_report("This machine version does not support CPU hotplug");
2532             exit(1);
2533         }
2534         boot_cores_nr = possible_cpus->len;
2535     }
2536 
2537     if (smc->pre_2_10_has_unused_icps) {
2538         int i;
2539 
2540         for (i = 0; i < spapr_max_server_number(spapr); i++) {
2541             /* Dummy entries get deregistered when real ICPState objects
2542              * are registered during CPU core hotplug.
2543              */
2544             pre_2_10_vmstate_register_dummy_icp(i);
2545         }
2546     }
2547 
2548     for (i = 0; i < possible_cpus->len; i++) {
2549         int core_id = i * smp_threads;
2550 
2551         if (mc->has_hotpluggable_cpus) {
2552             spapr_dr_connector_new(OBJECT(spapr), TYPE_SPAPR_DRC_CPU,
2553                                    spapr_vcpu_id(spapr, core_id));
2554         }
2555 
2556         if (i < boot_cores_nr) {
2557             Object *core  = object_new(type);
2558             int nr_threads = smp_threads;
2559 
2560             /* Handle the partially filled core for older machine types */
2561             if ((i + 1) * smp_threads >= smp_cpus) {
2562                 nr_threads = smp_cpus - i * smp_threads;
2563             }
2564 
2565             object_property_set_int(core, nr_threads, "nr-threads",
2566                                     &error_fatal);
2567             object_property_set_int(core, core_id, CPU_CORE_PROP_CORE_ID,
2568                                     &error_fatal);
2569             object_property_set_bool(core, true, "realized", &error_fatal);
2570 
2571             object_unref(core);
2572         }
2573     }
2574 }
2575 
2576 static PCIHostState *spapr_create_default_phb(void)
2577 {
2578     DeviceState *dev;
2579 
2580     dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
2581     qdev_prop_set_uint32(dev, "index", 0);
2582     qdev_init_nofail(dev);
2583 
2584     return PCI_HOST_BRIDGE(dev);
2585 }
2586 
2587 /* pSeries LPAR / sPAPR hardware init */
2588 static void spapr_machine_init(MachineState *machine)
2589 {
2590     SpaprMachineState *spapr = SPAPR_MACHINE(machine);
2591     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
2592     const char *kernel_filename = machine->kernel_filename;
2593     const char *initrd_filename = machine->initrd_filename;
2594     PCIHostState *phb;
2595     int i;
2596     MemoryRegion *sysmem = get_system_memory();
2597     MemoryRegion *ram = g_new(MemoryRegion, 1);
2598     hwaddr node0_size = spapr_node0_size(machine);
2599     long load_limit, fw_size;
2600     char *filename;
2601     Error *resize_hpt_err = NULL;
2602 
2603     msi_nonbroken = true;
2604 
2605     QLIST_INIT(&spapr->phbs);
2606     QTAILQ_INIT(&spapr->pending_dimm_unplugs);
2607 
2608     /* Determine capabilities to run with */
2609     spapr_caps_init(spapr);
2610 
2611     kvmppc_check_papr_resize_hpt(&resize_hpt_err);
2612     if (spapr->resize_hpt == SPAPR_RESIZE_HPT_DEFAULT) {
2613         /*
2614          * If the user explicitly requested a mode we should either
2615          * supply it, or fail completely (which we do below).  But if
2616          * it's not set explicitly, we reset our mode to something
2617          * that works
2618          */
2619         if (resize_hpt_err) {
2620             spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
2621             error_free(resize_hpt_err);
2622             resize_hpt_err = NULL;
2623         } else {
2624             spapr->resize_hpt = smc->resize_hpt_default;
2625         }
2626     }
2627 
2628     assert(spapr->resize_hpt != SPAPR_RESIZE_HPT_DEFAULT);
2629 
2630     if ((spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) && resize_hpt_err) {
2631         /*
2632          * User requested HPT resize, but this host can't supply it.  Bail out
2633          */
2634         error_report_err(resize_hpt_err);
2635         exit(1);
2636     }
2637 
2638     spapr->rma_size = node0_size;
2639 
2640     /* With KVM, we don't actually know whether KVM supports an
2641      * unbounded RMA (PR KVM) or is limited by the hash table size
2642      * (HV KVM using VRMA), so we always assume the latter
2643      *
2644      * In that case, we also limit the initial allocations for RTAS
2645      * etc... to 256M since we have no way to know what the VRMA size
2646      * is going to be as it depends on the size of the hash table
2647      * which isn't determined yet.
2648      */
2649     if (kvm_enabled()) {
2650         spapr->vrma_adjust = 1;
2651         spapr->rma_size = MIN(spapr->rma_size, 0x10000000);
2652     }
2653 
2654     /* Actually we don't support unbounded RMA anymore since we added
2655      * proper emulation of HV mode. The max we can get is 16G which
2656      * also happens to be what we configure for PAPR mode so make sure
2657      * we don't do anything bigger than that
2658      */
2659     spapr->rma_size = MIN(spapr->rma_size, 0x400000000ull);
2660 
2661     if (spapr->rma_size > node0_size) {
2662         error_report("Numa node 0 has to span the RMA (%#08"HWADDR_PRIx")",
2663                      spapr->rma_size);
2664         exit(1);
2665     }
2666 
2667     /* Setup a load limit for the ramdisk leaving room for SLOF and FDT */
2668     load_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR) - FW_OVERHEAD;
2669 
2670     /*
2671      * VSMT must be set in order to be able to compute VCPU ids, ie to
2672      * call spapr_max_server_number() or spapr_vcpu_id().
2673      */
2674     spapr_set_vsmt_mode(spapr, &error_fatal);
2675 
2676     /* Set up Interrupt Controller before we create the VCPUs */
2677     spapr_irq_init(spapr, &error_fatal);
2678 
2679     /* Set up containers for ibm,client-architecture-support negotiated options
2680      */
2681     spapr->ov5 = spapr_ovec_new();
2682     spapr->ov5_cas = spapr_ovec_new();
2683 
2684     if (smc->dr_lmb_enabled) {
2685         spapr_ovec_set(spapr->ov5, OV5_DRCONF_MEMORY);
2686         spapr_validate_node_memory(machine, &error_fatal);
2687     }
2688 
2689     spapr_ovec_set(spapr->ov5, OV5_FORM1_AFFINITY);
2690 
2691     /* advertise support for dedicated HP event source to guests */
2692     if (spapr->use_hotplug_event_source) {
2693         spapr_ovec_set(spapr->ov5, OV5_HP_EVT);
2694     }
2695 
2696     /* advertise support for HPT resizing */
2697     if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {
2698         spapr_ovec_set(spapr->ov5, OV5_HPT_RESIZE);
2699     }
2700 
2701     /* advertise support for ibm,dyamic-memory-v2 */
2702     spapr_ovec_set(spapr->ov5, OV5_DRMEM_V2);
2703 
2704     /* advertise XIVE on POWER9 machines */
2705     if (spapr->irq->xive) {
2706         spapr_ovec_set(spapr->ov5, OV5_XIVE_EXPLOIT);
2707     }
2708 
2709     /* init CPUs */
2710     spapr_init_cpus(spapr);
2711 
2712     /*
2713      * check we don't have a memory-less/cpu-less NUMA node
2714      * Firmware relies on the existing memory/cpu topology to provide the
2715      * NUMA topology to the kernel.
2716      * And the linux kernel needs to know the NUMA topology at start
2717      * to be able to hotplug CPUs later.
2718      */
2719     if (machine->numa_state->num_nodes) {
2720         for (i = 0; i < machine->numa_state->num_nodes; ++i) {
2721             /* check for memory-less node */
2722             if (machine->numa_state->nodes[i].node_mem == 0) {
2723                 CPUState *cs;
2724                 int found = 0;
2725                 /* check for cpu-less node */
2726                 CPU_FOREACH(cs) {
2727                     PowerPCCPU *cpu = POWERPC_CPU(cs);
2728                     if (cpu->node_id == i) {
2729                         found = 1;
2730                         break;
2731                     }
2732                 }
2733                 /* memory-less and cpu-less node */
2734                 if (!found) {
2735                     error_report(
2736                        "Memory-less/cpu-less nodes are not supported (node %d)",
2737                                  i);
2738                     exit(1);
2739                 }
2740             }
2741         }
2742 
2743     }
2744 
2745     /*
2746      * NVLink2-connected GPU RAM needs to be placed on a separate NUMA node.
2747      * We assign a new numa ID per GPU in spapr_pci_collect_nvgpu() which is
2748      * called from vPHB reset handler so we initialize the counter here.
2749      * If no NUMA is configured from the QEMU side, we start from 1 as GPU RAM
2750      * must be equally distant from any other node.
2751      * The final value of spapr->gpu_numa_id is going to be written to
2752      * max-associativity-domains in spapr_build_fdt().
2753      */
2754     spapr->gpu_numa_id = MAX(1, machine->numa_state->num_nodes);
2755 
2756     if ((!kvm_enabled() || kvmppc_has_cap_mmu_radix()) &&
2757         ppc_type_check_compat(machine->cpu_type, CPU_POWERPC_LOGICAL_3_00, 0,
2758                               spapr->max_compat_pvr)) {
2759         /* KVM and TCG always allow GTSE with radix... */
2760         spapr_ovec_set(spapr->ov5, OV5_MMU_RADIX_GTSE);
2761     }
2762     /* ... but not with hash (currently). */
2763 
2764     if (kvm_enabled()) {
2765         /* Enable H_LOGICAL_CI_* so SLOF can talk to in-kernel devices */
2766         kvmppc_enable_logical_ci_hcalls();
2767         kvmppc_enable_set_mode_hcall();
2768 
2769         /* H_CLEAR_MOD/_REF are mandatory in PAPR, but off by default */
2770         kvmppc_enable_clear_ref_mod_hcalls();
2771 
2772         /* Enable H_PAGE_INIT */
2773         kvmppc_enable_h_page_init();
2774     }
2775 
2776     /* allocate RAM */
2777     memory_region_allocate_system_memory(ram, NULL, "ppc_spapr.ram",
2778                                          machine->ram_size);
2779     memory_region_add_subregion(sysmem, 0, ram);
2780 
2781     /* always allocate the device memory information */
2782     machine->device_memory = g_malloc0(sizeof(*machine->device_memory));
2783 
2784     /* initialize hotplug memory address space */
2785     if (machine->ram_size < machine->maxram_size) {
2786         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
2787         /*
2788          * Limit the number of hotpluggable memory slots to half the number
2789          * slots that KVM supports, leaving the other half for PCI and other
2790          * devices. However ensure that number of slots doesn't drop below 32.
2791          */
2792         int max_memslots = kvm_enabled() ? kvm_get_max_memslots() / 2 :
2793                            SPAPR_MAX_RAM_SLOTS;
2794 
2795         if (max_memslots < SPAPR_MAX_RAM_SLOTS) {
2796             max_memslots = SPAPR_MAX_RAM_SLOTS;
2797         }
2798         if (machine->ram_slots > max_memslots) {
2799             error_report("Specified number of memory slots %"
2800                          PRIu64" exceeds max supported %d",
2801                          machine->ram_slots, max_memslots);
2802             exit(1);
2803         }
2804 
2805         machine->device_memory->base = ROUND_UP(machine->ram_size,
2806                                                 SPAPR_DEVICE_MEM_ALIGN);
2807         memory_region_init(&machine->device_memory->mr, OBJECT(spapr),
2808                            "device-memory", device_mem_size);
2809         memory_region_add_subregion(sysmem, machine->device_memory->base,
2810                                     &machine->device_memory->mr);
2811     }
2812 
2813     if (smc->dr_lmb_enabled) {
2814         spapr_create_lmb_dr_connectors(spapr);
2815     }
2816 
2817     /* Set up RTAS event infrastructure */
2818     spapr_events_init(spapr);
2819 
2820     /* Set up the RTC RTAS interfaces */
2821     spapr_rtc_create(spapr);
2822 
2823     /* Set up VIO bus */
2824     spapr->vio_bus = spapr_vio_bus_init();
2825 
2826     for (i = 0; i < serial_max_hds(); i++) {
2827         if (serial_hd(i)) {
2828             spapr_vty_create(spapr->vio_bus, serial_hd(i));
2829         }
2830     }
2831 
2832     /* We always have at least the nvram device on VIO */
2833     spapr_create_nvram(spapr);
2834 
2835     /*
2836      * Setup hotplug / dynamic-reconfiguration connectors. top-level
2837      * connectors (described in root DT node's "ibm,drc-types" property)
2838      * are pre-initialized here. additional child connectors (such as
2839      * connectors for a PHBs PCI slots) are added as needed during their
2840      * parent's realization.
2841      */
2842     if (smc->dr_phb_enabled) {
2843         for (i = 0; i < SPAPR_MAX_PHBS; i++) {
2844             spapr_dr_connector_new(OBJECT(machine), TYPE_SPAPR_DRC_PHB, i);
2845         }
2846     }
2847 
2848     /* Set up PCI */
2849     spapr_pci_rtas_init();
2850 
2851     phb = spapr_create_default_phb();
2852 
2853     for (i = 0; i < nb_nics; i++) {
2854         NICInfo *nd = &nd_table[i];
2855 
2856         if (!nd->model) {
2857             nd->model = g_strdup("spapr-vlan");
2858         }
2859 
2860         if (g_str_equal(nd->model, "spapr-vlan") ||
2861             g_str_equal(nd->model, "ibmveth")) {
2862             spapr_vlan_create(spapr->vio_bus, nd);
2863         } else {
2864             pci_nic_init_nofail(&nd_table[i], phb->bus, nd->model, NULL);
2865         }
2866     }
2867 
2868     for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
2869         spapr_vscsi_create(spapr->vio_bus);
2870     }
2871 
2872     /* Graphics */
2873     if (spapr_vga_init(phb->bus, &error_fatal)) {
2874         spapr->has_graphics = true;
2875         machine->usb |= defaults_enabled() && !machine->usb_disabled;
2876     }
2877 
2878     if (machine->usb) {
2879         if (smc->use_ohci_by_default) {
2880             pci_create_simple(phb->bus, -1, "pci-ohci");
2881         } else {
2882             pci_create_simple(phb->bus, -1, "nec-usb-xhci");
2883         }
2884 
2885         if (spapr->has_graphics) {
2886             USBBus *usb_bus = usb_bus_find(-1);
2887 
2888             usb_create_simple(usb_bus, "usb-kbd");
2889             usb_create_simple(usb_bus, "usb-mouse");
2890         }
2891     }
2892 
2893     if (spapr->rma_size < (MIN_RMA_SLOF * MiB)) {
2894         error_report(
2895             "pSeries SLOF firmware requires >= %ldM guest RMA (Real Mode Area memory)",
2896             MIN_RMA_SLOF);
2897         exit(1);
2898     }
2899 
2900     if (kernel_filename) {
2901         uint64_t lowaddr = 0;
2902 
2903         spapr->kernel_size = load_elf(kernel_filename, NULL,
2904                                       translate_kernel_address, NULL,
2905                                       NULL, &lowaddr, NULL, NULL, 1,
2906                                       PPC_ELF_MACHINE, 0, 0);
2907         if (spapr->kernel_size == ELF_LOAD_WRONG_ENDIAN) {
2908             spapr->kernel_size = load_elf(kernel_filename, NULL,
2909                                           translate_kernel_address, NULL, NULL,
2910                                           &lowaddr, NULL, NULL, 0,
2911                                           PPC_ELF_MACHINE, 0, 0);
2912             spapr->kernel_le = spapr->kernel_size > 0;
2913         }
2914         if (spapr->kernel_size < 0) {
2915             error_report("error loading %s: %s", kernel_filename,
2916                          load_elf_strerror(spapr->kernel_size));
2917             exit(1);
2918         }
2919 
2920         /* load initrd */
2921         if (initrd_filename) {
2922             /* Try to locate the initrd in the gap between the kernel
2923              * and the firmware. Add a bit of space just in case
2924              */
2925             spapr->initrd_base = (KERNEL_LOAD_ADDR + spapr->kernel_size
2926                                   + 0x1ffff) & ~0xffff;
2927             spapr->initrd_size = load_image_targphys(initrd_filename,
2928                                                      spapr->initrd_base,
2929                                                      load_limit
2930                                                      - spapr->initrd_base);
2931             if (spapr->initrd_size < 0) {
2932                 error_report("could not load initial ram disk '%s'",
2933                              initrd_filename);
2934                 exit(1);
2935             }
2936         }
2937     }
2938 
2939     if (bios_name == NULL) {
2940         bios_name = FW_FILE_NAME;
2941     }
2942     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
2943     if (!filename) {
2944         error_report("Could not find LPAR firmware '%s'", bios_name);
2945         exit(1);
2946     }
2947     fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);
2948     if (fw_size <= 0) {
2949         error_report("Could not load LPAR firmware '%s'", filename);
2950         exit(1);
2951     }
2952     g_free(filename);
2953 
2954     /* FIXME: Should register things through the MachineState's qdev
2955      * interface, this is a legacy from the sPAPREnvironment structure
2956      * which predated MachineState but had a similar function */
2957     vmstate_register(NULL, 0, &vmstate_spapr, spapr);
2958     register_savevm_live("spapr/htab", VMSTATE_INSTANCE_ID_ANY, 1,
2959                          &savevm_htab_handlers, spapr);
2960 
2961     qbus_set_hotplug_handler(sysbus_get_default(), OBJECT(machine),
2962                              &error_fatal);
2963 
2964     qemu_register_boot_set(spapr_boot_set, spapr);
2965 
2966     /*
2967      * Nothing needs to be done to resume a suspended guest because
2968      * suspending does not change the machine state, so no need for
2969      * a ->wakeup method.
2970      */
2971     qemu_register_wakeup_support();
2972 
2973     if (kvm_enabled()) {
2974         /* to stop and start vmclock */
2975         qemu_add_vm_change_state_handler(cpu_ppc_clock_vm_state_change,
2976                                          &spapr->tb);
2977 
2978         kvmppc_spapr_enable_inkernel_multitce();
2979     }
2980 
2981     qemu_cond_init(&spapr->mc_delivery_cond);
2982 }
2983 
2984 static int spapr_kvm_type(MachineState *machine, const char *vm_type)
2985 {
2986     if (!vm_type) {
2987         return 0;
2988     }
2989 
2990     if (!strcmp(vm_type, "HV")) {
2991         return 1;
2992     }
2993 
2994     if (!strcmp(vm_type, "PR")) {
2995         return 2;
2996     }
2997 
2998     error_report("Unknown kvm-type specified '%s'", vm_type);
2999     exit(1);
3000 }
3001 
3002 /*
3003  * Implementation of an interface to adjust firmware path
3004  * for the bootindex property handling.
3005  */
3006 static char *spapr_get_fw_dev_path(FWPathProvider *p, BusState *bus,
3007                                    DeviceState *dev)
3008 {
3009 #define CAST(type, obj, name) \
3010     ((type *)object_dynamic_cast(OBJECT(obj), (name)))
3011     SCSIDevice *d = CAST(SCSIDevice,  dev, TYPE_SCSI_DEVICE);
3012     SpaprPhbState *phb = CAST(SpaprPhbState, dev, TYPE_SPAPR_PCI_HOST_BRIDGE);
3013     VHostSCSICommon *vsc = CAST(VHostSCSICommon, dev, TYPE_VHOST_SCSI_COMMON);
3014 
3015     if (d) {
3016         void *spapr = CAST(void, bus->parent, "spapr-vscsi");
3017         VirtIOSCSI *virtio = CAST(VirtIOSCSI, bus->parent, TYPE_VIRTIO_SCSI);
3018         USBDevice *usb = CAST(USBDevice, bus->parent, TYPE_USB_DEVICE);
3019 
3020         if (spapr) {
3021             /*
3022              * Replace "channel@0/disk@0,0" with "disk@8000000000000000":
3023              * In the top 16 bits of the 64-bit LUN, we use SRP luns of the form
3024              * 0x8000 | (target << 8) | (bus << 5) | lun
3025              * (see the "Logical unit addressing format" table in SAM5)
3026              */
3027             unsigned id = 0x8000 | (d->id << 8) | (d->channel << 5) | d->lun;
3028             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3029                                    (uint64_t)id << 48);
3030         } else if (virtio) {
3031             /*
3032              * We use SRP luns of the form 01000000 | (target << 8) | lun
3033              * in the top 32 bits of the 64-bit LUN
3034              * Note: the quote above is from SLOF and it is wrong,
3035              * the actual binding is:
3036              * swap 0100 or 10 << or 20 << ( target lun-id -- srplun )
3037              */
3038             unsigned id = 0x1000000 | (d->id << 16) | d->lun;
3039             if (d->lun >= 256) {
3040                 /* Use the LUN "flat space addressing method" */
3041                 id |= 0x4000;
3042             }
3043             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3044                                    (uint64_t)id << 32);
3045         } else if (usb) {
3046             /*
3047              * We use SRP luns of the form 01000000 | (usb-port << 16) | lun
3048              * in the top 32 bits of the 64-bit LUN
3049              */
3050             unsigned usb_port = atoi(usb->port->path);
3051             unsigned id = 0x1000000 | (usb_port << 16) | d->lun;
3052             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3053                                    (uint64_t)id << 32);
3054         }
3055     }
3056 
3057     /*
3058      * SLOF probes the USB devices, and if it recognizes that the device is a
3059      * storage device, it changes its name to "storage" instead of "usb-host",
3060      * and additionally adds a child node for the SCSI LUN, so the correct
3061      * boot path in SLOF is something like .../storage@1/disk@xxx" instead.
3062      */
3063     if (strcmp("usb-host", qdev_fw_name(dev)) == 0) {
3064         USBDevice *usbdev = CAST(USBDevice, dev, TYPE_USB_DEVICE);
3065         if (usb_host_dev_is_scsi_storage(usbdev)) {
3066             return g_strdup_printf("storage@%s/disk", usbdev->port->path);
3067         }
3068     }
3069 
3070     if (phb) {
3071         /* Replace "pci" with "pci@800000020000000" */
3072         return g_strdup_printf("pci@%"PRIX64, phb->buid);
3073     }
3074 
3075     if (vsc) {
3076         /* Same logic as virtio above */
3077         unsigned id = 0x1000000 | (vsc->target << 16) | vsc->lun;
3078         return g_strdup_printf("disk@%"PRIX64, (uint64_t)id << 32);
3079     }
3080 
3081     if (g_str_equal("pci-bridge", qdev_fw_name(dev))) {
3082         /* SLOF uses "pci" instead of "pci-bridge" for PCI bridges */
3083         PCIDevice *pcidev = CAST(PCIDevice, dev, TYPE_PCI_DEVICE);
3084         return g_strdup_printf("pci@%x", PCI_SLOT(pcidev->devfn));
3085     }
3086 
3087     return NULL;
3088 }
3089 
3090 static char *spapr_get_kvm_type(Object *obj, Error **errp)
3091 {
3092     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3093 
3094     return g_strdup(spapr->kvm_type);
3095 }
3096 
3097 static void spapr_set_kvm_type(Object *obj, const char *value, Error **errp)
3098 {
3099     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3100 
3101     g_free(spapr->kvm_type);
3102     spapr->kvm_type = g_strdup(value);
3103 }
3104 
3105 static bool spapr_get_modern_hotplug_events(Object *obj, Error **errp)
3106 {
3107     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3108 
3109     return spapr->use_hotplug_event_source;
3110 }
3111 
3112 static void spapr_set_modern_hotplug_events(Object *obj, bool value,
3113                                             Error **errp)
3114 {
3115     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3116 
3117     spapr->use_hotplug_event_source = value;
3118 }
3119 
3120 static bool spapr_get_msix_emulation(Object *obj, Error **errp)
3121 {
3122     return true;
3123 }
3124 
3125 static char *spapr_get_resize_hpt(Object *obj, Error **errp)
3126 {
3127     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3128 
3129     switch (spapr->resize_hpt) {
3130     case SPAPR_RESIZE_HPT_DEFAULT:
3131         return g_strdup("default");
3132     case SPAPR_RESIZE_HPT_DISABLED:
3133         return g_strdup("disabled");
3134     case SPAPR_RESIZE_HPT_ENABLED:
3135         return g_strdup("enabled");
3136     case SPAPR_RESIZE_HPT_REQUIRED:
3137         return g_strdup("required");
3138     }
3139     g_assert_not_reached();
3140 }
3141 
3142 static void spapr_set_resize_hpt(Object *obj, const char *value, Error **errp)
3143 {
3144     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3145 
3146     if (strcmp(value, "default") == 0) {
3147         spapr->resize_hpt = SPAPR_RESIZE_HPT_DEFAULT;
3148     } else if (strcmp(value, "disabled") == 0) {
3149         spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
3150     } else if (strcmp(value, "enabled") == 0) {
3151         spapr->resize_hpt = SPAPR_RESIZE_HPT_ENABLED;
3152     } else if (strcmp(value, "required") == 0) {
3153         spapr->resize_hpt = SPAPR_RESIZE_HPT_REQUIRED;
3154     } else {
3155         error_setg(errp, "Bad value for \"resize-hpt\" property");
3156     }
3157 }
3158 
3159 static void spapr_get_vsmt(Object *obj, Visitor *v, const char *name,
3160                                    void *opaque, Error **errp)
3161 {
3162     visit_type_uint32(v, name, (uint32_t *)opaque, errp);
3163 }
3164 
3165 static void spapr_set_vsmt(Object *obj, Visitor *v, const char *name,
3166                                    void *opaque, Error **errp)
3167 {
3168     visit_type_uint32(v, name, (uint32_t *)opaque, errp);
3169 }
3170 
3171 static char *spapr_get_ic_mode(Object *obj, Error **errp)
3172 {
3173     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3174 
3175     if (spapr->irq == &spapr_irq_xics_legacy) {
3176         return g_strdup("legacy");
3177     } else if (spapr->irq == &spapr_irq_xics) {
3178         return g_strdup("xics");
3179     } else if (spapr->irq == &spapr_irq_xive) {
3180         return g_strdup("xive");
3181     } else if (spapr->irq == &spapr_irq_dual) {
3182         return g_strdup("dual");
3183     }
3184     g_assert_not_reached();
3185 }
3186 
3187 static void spapr_set_ic_mode(Object *obj, const char *value, Error **errp)
3188 {
3189     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3190 
3191     if (SPAPR_MACHINE_GET_CLASS(spapr)->legacy_irq_allocation) {
3192         error_setg(errp, "This machine only uses the legacy XICS backend, don't pass ic-mode");
3193         return;
3194     }
3195 
3196     /* The legacy IRQ backend can not be set */
3197     if (strcmp(value, "xics") == 0) {
3198         spapr->irq = &spapr_irq_xics;
3199     } else if (strcmp(value, "xive") == 0) {
3200         spapr->irq = &spapr_irq_xive;
3201     } else if (strcmp(value, "dual") == 0) {
3202         spapr->irq = &spapr_irq_dual;
3203     } else {
3204         error_setg(errp, "Bad value for \"ic-mode\" property");
3205     }
3206 }
3207 
3208 static char *spapr_get_host_model(Object *obj, Error **errp)
3209 {
3210     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3211 
3212     return g_strdup(spapr->host_model);
3213 }
3214 
3215 static void spapr_set_host_model(Object *obj, const char *value, Error **errp)
3216 {
3217     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3218 
3219     g_free(spapr->host_model);
3220     spapr->host_model = g_strdup(value);
3221 }
3222 
3223 static char *spapr_get_host_serial(Object *obj, Error **errp)
3224 {
3225     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3226 
3227     return g_strdup(spapr->host_serial);
3228 }
3229 
3230 static void spapr_set_host_serial(Object *obj, const char *value, Error **errp)
3231 {
3232     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3233 
3234     g_free(spapr->host_serial);
3235     spapr->host_serial = g_strdup(value);
3236 }
3237 
3238 static void spapr_instance_init(Object *obj)
3239 {
3240     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3241     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
3242 
3243     spapr->htab_fd = -1;
3244     spapr->use_hotplug_event_source = true;
3245     object_property_add_str(obj, "kvm-type",
3246                             spapr_get_kvm_type, spapr_set_kvm_type, NULL);
3247     object_property_set_description(obj, "kvm-type",
3248                                     "Specifies the KVM virtualization mode (HV, PR)",
3249                                     NULL);
3250     object_property_add_bool(obj, "modern-hotplug-events",
3251                             spapr_get_modern_hotplug_events,
3252                             spapr_set_modern_hotplug_events,
3253                             NULL);
3254     object_property_set_description(obj, "modern-hotplug-events",
3255                                     "Use dedicated hotplug event mechanism in"
3256                                     " place of standard EPOW events when possible"
3257                                     " (required for memory hot-unplug support)",
3258                                     NULL);
3259     ppc_compat_add_property(obj, "max-cpu-compat", &spapr->max_compat_pvr,
3260                             "Maximum permitted CPU compatibility mode",
3261                             &error_fatal);
3262 
3263     object_property_add_str(obj, "resize-hpt",
3264                             spapr_get_resize_hpt, spapr_set_resize_hpt, NULL);
3265     object_property_set_description(obj, "resize-hpt",
3266                                     "Resizing of the Hash Page Table (enabled, disabled, required)",
3267                                     NULL);
3268     object_property_add(obj, "vsmt", "uint32", spapr_get_vsmt,
3269                         spapr_set_vsmt, NULL, &spapr->vsmt, &error_abort);
3270     object_property_set_description(obj, "vsmt",
3271                                     "Virtual SMT: KVM behaves as if this were"
3272                                     " the host's SMT mode", &error_abort);
3273     object_property_add_bool(obj, "vfio-no-msix-emulation",
3274                              spapr_get_msix_emulation, NULL, NULL);
3275 
3276     /* The machine class defines the default interrupt controller mode */
3277     spapr->irq = smc->irq;
3278     object_property_add_str(obj, "ic-mode", spapr_get_ic_mode,
3279                             spapr_set_ic_mode, NULL);
3280     object_property_set_description(obj, "ic-mode",
3281                  "Specifies the interrupt controller mode (xics, xive, dual)",
3282                  NULL);
3283 
3284     object_property_add_str(obj, "host-model",
3285         spapr_get_host_model, spapr_set_host_model,
3286         &error_abort);
3287     object_property_set_description(obj, "host-model",
3288         "Host model to advertise in guest device tree", &error_abort);
3289     object_property_add_str(obj, "host-serial",
3290         spapr_get_host_serial, spapr_set_host_serial,
3291         &error_abort);
3292     object_property_set_description(obj, "host-serial",
3293         "Host serial number to advertise in guest device tree", &error_abort);
3294 }
3295 
3296 static void spapr_machine_finalizefn(Object *obj)
3297 {
3298     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3299 
3300     g_free(spapr->kvm_type);
3301 }
3302 
3303 void spapr_do_system_reset_on_cpu(CPUState *cs, run_on_cpu_data arg)
3304 {
3305     cpu_synchronize_state(cs);
3306     ppc_cpu_do_system_reset(cs);
3307 }
3308 
3309 static void spapr_nmi(NMIState *n, int cpu_index, Error **errp)
3310 {
3311     CPUState *cs;
3312 
3313     CPU_FOREACH(cs) {
3314         async_run_on_cpu(cs, spapr_do_system_reset_on_cpu, RUN_ON_CPU_NULL);
3315     }
3316 }
3317 
3318 int spapr_lmb_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
3319                           void *fdt, int *fdt_start_offset, Error **errp)
3320 {
3321     uint64_t addr;
3322     uint32_t node;
3323 
3324     addr = spapr_drc_index(drc) * SPAPR_MEMORY_BLOCK_SIZE;
3325     node = object_property_get_uint(OBJECT(drc->dev), PC_DIMM_NODE_PROP,
3326                                     &error_abort);
3327     *fdt_start_offset = spapr_populate_memory_node(fdt, node, addr,
3328                                                    SPAPR_MEMORY_BLOCK_SIZE);
3329     return 0;
3330 }
3331 
3332 static void spapr_add_lmbs(DeviceState *dev, uint64_t addr_start, uint64_t size,
3333                            bool dedicated_hp_event_source, Error **errp)
3334 {
3335     SpaprDrc *drc;
3336     uint32_t nr_lmbs = size/SPAPR_MEMORY_BLOCK_SIZE;
3337     int i;
3338     uint64_t addr = addr_start;
3339     bool hotplugged = spapr_drc_hotplugged(dev);
3340     Error *local_err = NULL;
3341 
3342     for (i = 0; i < nr_lmbs; i++) {
3343         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3344                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3345         g_assert(drc);
3346 
3347         spapr_drc_attach(drc, dev, &local_err);
3348         if (local_err) {
3349             while (addr > addr_start) {
3350                 addr -= SPAPR_MEMORY_BLOCK_SIZE;
3351                 drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3352                                       addr / SPAPR_MEMORY_BLOCK_SIZE);
3353                 spapr_drc_detach(drc);
3354             }
3355             error_propagate(errp, local_err);
3356             return;
3357         }
3358         if (!hotplugged) {
3359             spapr_drc_reset(drc);
3360         }
3361         addr += SPAPR_MEMORY_BLOCK_SIZE;
3362     }
3363     /* send hotplug notification to the
3364      * guest only in case of hotplugged memory
3365      */
3366     if (hotplugged) {
3367         if (dedicated_hp_event_source) {
3368             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3369                                   addr_start / SPAPR_MEMORY_BLOCK_SIZE);
3370             spapr_hotplug_req_add_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
3371                                                    nr_lmbs,
3372                                                    spapr_drc_index(drc));
3373         } else {
3374             spapr_hotplug_req_add_by_count(SPAPR_DR_CONNECTOR_TYPE_LMB,
3375                                            nr_lmbs);
3376         }
3377     }
3378 }
3379 
3380 static void spapr_memory_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3381                               Error **errp)
3382 {
3383     Error *local_err = NULL;
3384     SpaprMachineState *ms = SPAPR_MACHINE(hotplug_dev);
3385     PCDIMMDevice *dimm = PC_DIMM(dev);
3386     uint64_t size, addr;
3387 
3388     size = memory_device_get_region_size(MEMORY_DEVICE(dev), &error_abort);
3389 
3390     pc_dimm_plug(dimm, MACHINE(ms), &local_err);
3391     if (local_err) {
3392         goto out;
3393     }
3394 
3395     addr = object_property_get_uint(OBJECT(dimm),
3396                                     PC_DIMM_ADDR_PROP, &local_err);
3397     if (local_err) {
3398         goto out_unplug;
3399     }
3400 
3401     spapr_add_lmbs(dev, addr, size, spapr_ovec_test(ms->ov5_cas, OV5_HP_EVT),
3402                    &local_err);
3403     if (local_err) {
3404         goto out_unplug;
3405     }
3406 
3407     return;
3408 
3409 out_unplug:
3410     pc_dimm_unplug(dimm, MACHINE(ms));
3411 out:
3412     error_propagate(errp, local_err);
3413 }
3414 
3415 static void spapr_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3416                                   Error **errp)
3417 {
3418     const SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(hotplug_dev);
3419     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3420     PCDIMMDevice *dimm = PC_DIMM(dev);
3421     Error *local_err = NULL;
3422     uint64_t size;
3423     Object *memdev;
3424     hwaddr pagesize;
3425 
3426     if (!smc->dr_lmb_enabled) {
3427         error_setg(errp, "Memory hotplug not supported for this machine");
3428         return;
3429     }
3430 
3431     size = memory_device_get_region_size(MEMORY_DEVICE(dimm), &local_err);
3432     if (local_err) {
3433         error_propagate(errp, local_err);
3434         return;
3435     }
3436 
3437     if (size % SPAPR_MEMORY_BLOCK_SIZE) {
3438         error_setg(errp, "Hotplugged memory size must be a multiple of "
3439                       "%" PRIu64 " MB", SPAPR_MEMORY_BLOCK_SIZE / MiB);
3440         return;
3441     }
3442 
3443     memdev = object_property_get_link(OBJECT(dimm), PC_DIMM_MEMDEV_PROP,
3444                                       &error_abort);
3445     pagesize = host_memory_backend_pagesize(MEMORY_BACKEND(memdev));
3446     spapr_check_pagesize(spapr, pagesize, &local_err);
3447     if (local_err) {
3448         error_propagate(errp, local_err);
3449         return;
3450     }
3451 
3452     pc_dimm_pre_plug(dimm, MACHINE(hotplug_dev), NULL, errp);
3453 }
3454 
3455 struct SpaprDimmState {
3456     PCDIMMDevice *dimm;
3457     uint32_t nr_lmbs;
3458     QTAILQ_ENTRY(SpaprDimmState) next;
3459 };
3460 
3461 static SpaprDimmState *spapr_pending_dimm_unplugs_find(SpaprMachineState *s,
3462                                                        PCDIMMDevice *dimm)
3463 {
3464     SpaprDimmState *dimm_state = NULL;
3465 
3466     QTAILQ_FOREACH(dimm_state, &s->pending_dimm_unplugs, next) {
3467         if (dimm_state->dimm == dimm) {
3468             break;
3469         }
3470     }
3471     return dimm_state;
3472 }
3473 
3474 static SpaprDimmState *spapr_pending_dimm_unplugs_add(SpaprMachineState *spapr,
3475                                                       uint32_t nr_lmbs,
3476                                                       PCDIMMDevice *dimm)
3477 {
3478     SpaprDimmState *ds = NULL;
3479 
3480     /*
3481      * If this request is for a DIMM whose removal had failed earlier
3482      * (due to guest's refusal to remove the LMBs), we would have this
3483      * dimm already in the pending_dimm_unplugs list. In that
3484      * case don't add again.
3485      */
3486     ds = spapr_pending_dimm_unplugs_find(spapr, dimm);
3487     if (!ds) {
3488         ds = g_malloc0(sizeof(SpaprDimmState));
3489         ds->nr_lmbs = nr_lmbs;
3490         ds->dimm = dimm;
3491         QTAILQ_INSERT_HEAD(&spapr->pending_dimm_unplugs, ds, next);
3492     }
3493     return ds;
3494 }
3495 
3496 static void spapr_pending_dimm_unplugs_remove(SpaprMachineState *spapr,
3497                                               SpaprDimmState *dimm_state)
3498 {
3499     QTAILQ_REMOVE(&spapr->pending_dimm_unplugs, dimm_state, next);
3500     g_free(dimm_state);
3501 }
3502 
3503 static SpaprDimmState *spapr_recover_pending_dimm_state(SpaprMachineState *ms,
3504                                                         PCDIMMDevice *dimm)
3505 {
3506     SpaprDrc *drc;
3507     uint64_t size = memory_device_get_region_size(MEMORY_DEVICE(dimm),
3508                                                   &error_abort);
3509     uint32_t nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3510     uint32_t avail_lmbs = 0;
3511     uint64_t addr_start, addr;
3512     int i;
3513 
3514     addr_start = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3515                                          &error_abort);
3516 
3517     addr = addr_start;
3518     for (i = 0; i < nr_lmbs; i++) {
3519         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3520                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3521         g_assert(drc);
3522         if (drc->dev) {
3523             avail_lmbs++;
3524         }
3525         addr += SPAPR_MEMORY_BLOCK_SIZE;
3526     }
3527 
3528     return spapr_pending_dimm_unplugs_add(ms, avail_lmbs, dimm);
3529 }
3530 
3531 /* Callback to be called during DRC release. */
3532 void spapr_lmb_release(DeviceState *dev)
3533 {
3534     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
3535     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_ctrl);
3536     SpaprDimmState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));
3537 
3538     /* This information will get lost if a migration occurs
3539      * during the unplug process. In this case recover it. */
3540     if (ds == NULL) {
3541         ds = spapr_recover_pending_dimm_state(spapr, PC_DIMM(dev));
3542         g_assert(ds);
3543         /* The DRC being examined by the caller at least must be counted */
3544         g_assert(ds->nr_lmbs);
3545     }
3546 
3547     if (--ds->nr_lmbs) {
3548         return;
3549     }
3550 
3551     /*
3552      * Now that all the LMBs have been removed by the guest, call the
3553      * unplug handler chain. This can never fail.
3554      */
3555     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
3556     object_unparent(OBJECT(dev));
3557 }
3558 
3559 static void spapr_memory_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3560 {
3561     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3562     SpaprDimmState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));
3563 
3564     pc_dimm_unplug(PC_DIMM(dev), MACHINE(hotplug_dev));
3565     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
3566     spapr_pending_dimm_unplugs_remove(spapr, ds);
3567 }
3568 
3569 static void spapr_memory_unplug_request(HotplugHandler *hotplug_dev,
3570                                         DeviceState *dev, Error **errp)
3571 {
3572     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3573     Error *local_err = NULL;
3574     PCDIMMDevice *dimm = PC_DIMM(dev);
3575     uint32_t nr_lmbs;
3576     uint64_t size, addr_start, addr;
3577     int i;
3578     SpaprDrc *drc;
3579 
3580     size = memory_device_get_region_size(MEMORY_DEVICE(dimm), &error_abort);
3581     nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3582 
3583     addr_start = object_property_get_uint(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3584                                          &local_err);
3585     if (local_err) {
3586         goto out;
3587     }
3588 
3589     /*
3590      * An existing pending dimm state for this DIMM means that there is an
3591      * unplug operation in progress, waiting for the spapr_lmb_release
3592      * callback to complete the job (BQL can't cover that far). In this case,
3593      * bail out to avoid detaching DRCs that were already released.
3594      */
3595     if (spapr_pending_dimm_unplugs_find(spapr, dimm)) {
3596         error_setg(&local_err,
3597                    "Memory unplug already in progress for device %s",
3598                    dev->id);
3599         goto out;
3600     }
3601 
3602     spapr_pending_dimm_unplugs_add(spapr, nr_lmbs, dimm);
3603 
3604     addr = addr_start;
3605     for (i = 0; i < nr_lmbs; i++) {
3606         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3607                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3608         g_assert(drc);
3609 
3610         spapr_drc_detach(drc);
3611         addr += SPAPR_MEMORY_BLOCK_SIZE;
3612     }
3613 
3614     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3615                           addr_start / SPAPR_MEMORY_BLOCK_SIZE);
3616     spapr_hotplug_req_remove_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
3617                                               nr_lmbs, spapr_drc_index(drc));
3618 out:
3619     error_propagate(errp, local_err);
3620 }
3621 
3622 /* Callback to be called during DRC release. */
3623 void spapr_core_release(DeviceState *dev)
3624 {
3625     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
3626 
3627     /* Call the unplug handler chain. This can never fail. */
3628     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
3629     object_unparent(OBJECT(dev));
3630 }
3631 
3632 static void spapr_core_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3633 {
3634     MachineState *ms = MACHINE(hotplug_dev);
3635     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(ms);
3636     CPUCore *cc = CPU_CORE(dev);
3637     CPUArchId *core_slot = spapr_find_cpu_slot(ms, cc->core_id, NULL);
3638 
3639     if (smc->pre_2_10_has_unused_icps) {
3640         SpaprCpuCore *sc = SPAPR_CPU_CORE(OBJECT(dev));
3641         int i;
3642 
3643         for (i = 0; i < cc->nr_threads; i++) {
3644             CPUState *cs = CPU(sc->threads[i]);
3645 
3646             pre_2_10_vmstate_register_dummy_icp(cs->cpu_index);
3647         }
3648     }
3649 
3650     assert(core_slot);
3651     core_slot->cpu = NULL;
3652     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
3653 }
3654 
3655 static
3656 void spapr_core_unplug_request(HotplugHandler *hotplug_dev, DeviceState *dev,
3657                                Error **errp)
3658 {
3659     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3660     int index;
3661     SpaprDrc *drc;
3662     CPUCore *cc = CPU_CORE(dev);
3663 
3664     if (!spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index)) {
3665         error_setg(errp, "Unable to find CPU core with core-id: %d",
3666                    cc->core_id);
3667         return;
3668     }
3669     if (index == 0) {
3670         error_setg(errp, "Boot CPU core may not be unplugged");
3671         return;
3672     }
3673 
3674     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU,
3675                           spapr_vcpu_id(spapr, cc->core_id));
3676     g_assert(drc);
3677 
3678     if (!spapr_drc_unplug_requested(drc)) {
3679         spapr_drc_detach(drc);
3680         spapr_hotplug_req_remove_by_index(drc);
3681     }
3682 }
3683 
3684 int spapr_core_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
3685                            void *fdt, int *fdt_start_offset, Error **errp)
3686 {
3687     SpaprCpuCore *core = SPAPR_CPU_CORE(drc->dev);
3688     CPUState *cs = CPU(core->threads[0]);
3689     PowerPCCPU *cpu = POWERPC_CPU(cs);
3690     DeviceClass *dc = DEVICE_GET_CLASS(cs);
3691     int id = spapr_get_vcpu_id(cpu);
3692     char *nodename;
3693     int offset;
3694 
3695     nodename = g_strdup_printf("%s@%x", dc->fw_name, id);
3696     offset = fdt_add_subnode(fdt, 0, nodename);
3697     g_free(nodename);
3698 
3699     spapr_populate_cpu_dt(cs, fdt, offset, spapr);
3700 
3701     *fdt_start_offset = offset;
3702     return 0;
3703 }
3704 
3705 static void spapr_core_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3706                             Error **errp)
3707 {
3708     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3709     MachineClass *mc = MACHINE_GET_CLASS(spapr);
3710     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3711     SpaprCpuCore *core = SPAPR_CPU_CORE(OBJECT(dev));
3712     CPUCore *cc = CPU_CORE(dev);
3713     CPUState *cs;
3714     SpaprDrc *drc;
3715     Error *local_err = NULL;
3716     CPUArchId *core_slot;
3717     int index;
3718     bool hotplugged = spapr_drc_hotplugged(dev);
3719     int i;
3720 
3721     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
3722     if (!core_slot) {
3723         error_setg(errp, "Unable to find CPU core with core-id: %d",
3724                    cc->core_id);
3725         return;
3726     }
3727     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU,
3728                           spapr_vcpu_id(spapr, cc->core_id));
3729 
3730     g_assert(drc || !mc->has_hotpluggable_cpus);
3731 
3732     if (drc) {
3733         spapr_drc_attach(drc, dev, &local_err);
3734         if (local_err) {
3735             error_propagate(errp, local_err);
3736             return;
3737         }
3738 
3739         if (hotplugged) {
3740             /*
3741              * Send hotplug notification interrupt to the guest only
3742              * in case of hotplugged CPUs.
3743              */
3744             spapr_hotplug_req_add_by_index(drc);
3745         } else {
3746             spapr_drc_reset(drc);
3747         }
3748     }
3749 
3750     core_slot->cpu = OBJECT(dev);
3751 
3752     if (smc->pre_2_10_has_unused_icps) {
3753         for (i = 0; i < cc->nr_threads; i++) {
3754             cs = CPU(core->threads[i]);
3755             pre_2_10_vmstate_unregister_dummy_icp(cs->cpu_index);
3756         }
3757     }
3758 
3759     /*
3760      * Set compatibility mode to match the boot CPU, which was either set
3761      * by the machine reset code or by CAS.
3762      */
3763     if (hotplugged) {
3764         for (i = 0; i < cc->nr_threads; i++) {
3765             ppc_set_compat(core->threads[i], POWERPC_CPU(first_cpu)->compat_pvr,
3766                            &local_err);
3767             if (local_err) {
3768                 error_propagate(errp, local_err);
3769                 return;
3770             }
3771         }
3772     }
3773 }
3774 
3775 static void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3776                                 Error **errp)
3777 {
3778     MachineState *machine = MACHINE(OBJECT(hotplug_dev));
3779     MachineClass *mc = MACHINE_GET_CLASS(hotplug_dev);
3780     Error *local_err = NULL;
3781     CPUCore *cc = CPU_CORE(dev);
3782     const char *base_core_type = spapr_get_cpu_core_type(machine->cpu_type);
3783     const char *type = object_get_typename(OBJECT(dev));
3784     CPUArchId *core_slot;
3785     int index;
3786     unsigned int smp_threads = machine->smp.threads;
3787 
3788     if (dev->hotplugged && !mc->has_hotpluggable_cpus) {
3789         error_setg(&local_err, "CPU hotplug not supported for this machine");
3790         goto out;
3791     }
3792 
3793     if (strcmp(base_core_type, type)) {
3794         error_setg(&local_err, "CPU core type should be %s", base_core_type);
3795         goto out;
3796     }
3797 
3798     if (cc->core_id % smp_threads) {
3799         error_setg(&local_err, "invalid core id %d", cc->core_id);
3800         goto out;
3801     }
3802 
3803     /*
3804      * In general we should have homogeneous threads-per-core, but old
3805      * (pre hotplug support) machine types allow the last core to have
3806      * reduced threads as a compatibility hack for when we allowed
3807      * total vcpus not a multiple of threads-per-core.
3808      */
3809     if (mc->has_hotpluggable_cpus && (cc->nr_threads != smp_threads)) {
3810         error_setg(&local_err, "invalid nr-threads %d, must be %d",
3811                    cc->nr_threads, smp_threads);
3812         goto out;
3813     }
3814 
3815     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
3816     if (!core_slot) {
3817         error_setg(&local_err, "core id %d out of range", cc->core_id);
3818         goto out;
3819     }
3820 
3821     if (core_slot->cpu) {
3822         error_setg(&local_err, "core %d already populated", cc->core_id);
3823         goto out;
3824     }
3825 
3826     numa_cpu_pre_plug(core_slot, dev, &local_err);
3827 
3828 out:
3829     error_propagate(errp, local_err);
3830 }
3831 
3832 int spapr_phb_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
3833                           void *fdt, int *fdt_start_offset, Error **errp)
3834 {
3835     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(drc->dev);
3836     int intc_phandle;
3837 
3838     intc_phandle = spapr_irq_get_phandle(spapr, spapr->fdt_blob, errp);
3839     if (intc_phandle <= 0) {
3840         return -1;
3841     }
3842 
3843     if (spapr_dt_phb(spapr, sphb, intc_phandle, fdt, fdt_start_offset)) {
3844         error_setg(errp, "unable to create FDT node for PHB %d", sphb->index);
3845         return -1;
3846     }
3847 
3848     /* generally SLOF creates these, for hotplug it's up to QEMU */
3849     _FDT(fdt_setprop_string(fdt, *fdt_start_offset, "name", "pci"));
3850 
3851     return 0;
3852 }
3853 
3854 static void spapr_phb_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3855                                Error **errp)
3856 {
3857     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3858     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
3859     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
3860     const unsigned windows_supported = spapr_phb_windows_supported(sphb);
3861 
3862     if (dev->hotplugged && !smc->dr_phb_enabled) {
3863         error_setg(errp, "PHB hotplug not supported for this machine");
3864         return;
3865     }
3866 
3867     if (sphb->index == (uint32_t)-1) {
3868         error_setg(errp, "\"index\" for PAPR PHB is mandatory");
3869         return;
3870     }
3871 
3872     /*
3873      * This will check that sphb->index doesn't exceed the maximum number of
3874      * PHBs for the current machine type.
3875      */
3876     smc->phb_placement(spapr, sphb->index,
3877                        &sphb->buid, &sphb->io_win_addr,
3878                        &sphb->mem_win_addr, &sphb->mem64_win_addr,
3879                        windows_supported, sphb->dma_liobn,
3880                        &sphb->nv2_gpa_win_addr, &sphb->nv2_atsd_win_addr,
3881                        errp);
3882 }
3883 
3884 static void spapr_phb_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3885                            Error **errp)
3886 {
3887     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3888     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
3889     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
3890     SpaprDrc *drc;
3891     bool hotplugged = spapr_drc_hotplugged(dev);
3892     Error *local_err = NULL;
3893 
3894     if (!smc->dr_phb_enabled) {
3895         return;
3896     }
3897 
3898     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_PHB, sphb->index);
3899     /* hotplug hooks should check it's enabled before getting this far */
3900     assert(drc);
3901 
3902     spapr_drc_attach(drc, DEVICE(dev), &local_err);
3903     if (local_err) {
3904         error_propagate(errp, local_err);
3905         return;
3906     }
3907 
3908     if (hotplugged) {
3909         spapr_hotplug_req_add_by_index(drc);
3910     } else {
3911         spapr_drc_reset(drc);
3912     }
3913 }
3914 
3915 void spapr_phb_release(DeviceState *dev)
3916 {
3917     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
3918 
3919     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
3920     object_unparent(OBJECT(dev));
3921 }
3922 
3923 static void spapr_phb_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3924 {
3925     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
3926 }
3927 
3928 static void spapr_phb_unplug_request(HotplugHandler *hotplug_dev,
3929                                      DeviceState *dev, Error **errp)
3930 {
3931     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
3932     SpaprDrc *drc;
3933 
3934     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_PHB, sphb->index);
3935     assert(drc);
3936 
3937     if (!spapr_drc_unplug_requested(drc)) {
3938         spapr_drc_detach(drc);
3939         spapr_hotplug_req_remove_by_index(drc);
3940     }
3941 }
3942 
3943 static void spapr_tpm_proxy_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3944                                  Error **errp)
3945 {
3946     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3947     SpaprTpmProxy *tpm_proxy = SPAPR_TPM_PROXY(dev);
3948 
3949     if (spapr->tpm_proxy != NULL) {
3950         error_setg(errp, "Only one TPM proxy can be specified for this machine");
3951         return;
3952     }
3953 
3954     spapr->tpm_proxy = tpm_proxy;
3955 }
3956 
3957 static void spapr_tpm_proxy_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3958 {
3959     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3960 
3961     object_property_set_bool(OBJECT(dev), false, "realized", NULL);
3962     object_unparent(OBJECT(dev));
3963     spapr->tpm_proxy = NULL;
3964 }
3965 
3966 static void spapr_machine_device_plug(HotplugHandler *hotplug_dev,
3967                                       DeviceState *dev, Error **errp)
3968 {
3969     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
3970         spapr_memory_plug(hotplug_dev, dev, errp);
3971     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3972         spapr_core_plug(hotplug_dev, dev, errp);
3973     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
3974         spapr_phb_plug(hotplug_dev, dev, errp);
3975     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
3976         spapr_tpm_proxy_plug(hotplug_dev, dev, errp);
3977     }
3978 }
3979 
3980 static void spapr_machine_device_unplug(HotplugHandler *hotplug_dev,
3981                                         DeviceState *dev, Error **errp)
3982 {
3983     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
3984         spapr_memory_unplug(hotplug_dev, dev);
3985     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3986         spapr_core_unplug(hotplug_dev, dev);
3987     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
3988         spapr_phb_unplug(hotplug_dev, dev);
3989     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
3990         spapr_tpm_proxy_unplug(hotplug_dev, dev);
3991     }
3992 }
3993 
3994 static void spapr_machine_device_unplug_request(HotplugHandler *hotplug_dev,
3995                                                 DeviceState *dev, Error **errp)
3996 {
3997     SpaprMachineState *sms = SPAPR_MACHINE(OBJECT(hotplug_dev));
3998     MachineClass *mc = MACHINE_GET_CLASS(sms);
3999     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4000 
4001     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4002         if (spapr_ovec_test(sms->ov5_cas, OV5_HP_EVT)) {
4003             spapr_memory_unplug_request(hotplug_dev, dev, errp);
4004         } else {
4005             /* NOTE: this means there is a window after guest reset, prior to
4006              * CAS negotiation, where unplug requests will fail due to the
4007              * capability not being detected yet. This is a bit different than
4008              * the case with PCI unplug, where the events will be queued and
4009              * eventually handled by the guest after boot
4010              */
4011             error_setg(errp, "Memory hot unplug not supported for this guest");
4012         }
4013     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4014         if (!mc->has_hotpluggable_cpus) {
4015             error_setg(errp, "CPU hot unplug not supported on this machine");
4016             return;
4017         }
4018         spapr_core_unplug_request(hotplug_dev, dev, errp);
4019     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4020         if (!smc->dr_phb_enabled) {
4021             error_setg(errp, "PHB hot unplug not supported on this machine");
4022             return;
4023         }
4024         spapr_phb_unplug_request(hotplug_dev, dev, errp);
4025     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4026         spapr_tpm_proxy_unplug(hotplug_dev, dev);
4027     }
4028 }
4029 
4030 static void spapr_machine_device_pre_plug(HotplugHandler *hotplug_dev,
4031                                           DeviceState *dev, Error **errp)
4032 {
4033     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4034         spapr_memory_pre_plug(hotplug_dev, dev, errp);
4035     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4036         spapr_core_pre_plug(hotplug_dev, dev, errp);
4037     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4038         spapr_phb_pre_plug(hotplug_dev, dev, errp);
4039     }
4040 }
4041 
4042 static HotplugHandler *spapr_get_hotplug_handler(MachineState *machine,
4043                                                  DeviceState *dev)
4044 {
4045     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
4046         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE) ||
4047         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE) ||
4048         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4049         return HOTPLUG_HANDLER(machine);
4050     }
4051     if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
4052         PCIDevice *pcidev = PCI_DEVICE(dev);
4053         PCIBus *root = pci_device_root_bus(pcidev);
4054         SpaprPhbState *phb =
4055             (SpaprPhbState *)object_dynamic_cast(OBJECT(BUS(root)->parent),
4056                                                  TYPE_SPAPR_PCI_HOST_BRIDGE);
4057 
4058         if (phb) {
4059             return HOTPLUG_HANDLER(phb);
4060         }
4061     }
4062     return NULL;
4063 }
4064 
4065 static CpuInstanceProperties
4066 spapr_cpu_index_to_props(MachineState *machine, unsigned cpu_index)
4067 {
4068     CPUArchId *core_slot;
4069     MachineClass *mc = MACHINE_GET_CLASS(machine);
4070 
4071     /* make sure possible_cpu are intialized */
4072     mc->possible_cpu_arch_ids(machine);
4073     /* get CPU core slot containing thread that matches cpu_index */
4074     core_slot = spapr_find_cpu_slot(machine, cpu_index, NULL);
4075     assert(core_slot);
4076     return core_slot->props;
4077 }
4078 
4079 static int64_t spapr_get_default_cpu_node_id(const MachineState *ms, int idx)
4080 {
4081     return idx / ms->smp.cores % ms->numa_state->num_nodes;
4082 }
4083 
4084 static const CPUArchIdList *spapr_possible_cpu_arch_ids(MachineState *machine)
4085 {
4086     int i;
4087     unsigned int smp_threads = machine->smp.threads;
4088     unsigned int smp_cpus = machine->smp.cpus;
4089     const char *core_type;
4090     int spapr_max_cores = machine->smp.max_cpus / smp_threads;
4091     MachineClass *mc = MACHINE_GET_CLASS(machine);
4092 
4093     if (!mc->has_hotpluggable_cpus) {
4094         spapr_max_cores = QEMU_ALIGN_UP(smp_cpus, smp_threads) / smp_threads;
4095     }
4096     if (machine->possible_cpus) {
4097         assert(machine->possible_cpus->len == spapr_max_cores);
4098         return machine->possible_cpus;
4099     }
4100 
4101     core_type = spapr_get_cpu_core_type(machine->cpu_type);
4102     if (!core_type) {
4103         error_report("Unable to find sPAPR CPU Core definition");
4104         exit(1);
4105     }
4106 
4107     machine->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
4108                              sizeof(CPUArchId) * spapr_max_cores);
4109     machine->possible_cpus->len = spapr_max_cores;
4110     for (i = 0; i < machine->possible_cpus->len; i++) {
4111         int core_id = i * smp_threads;
4112 
4113         machine->possible_cpus->cpus[i].type = core_type;
4114         machine->possible_cpus->cpus[i].vcpus_count = smp_threads;
4115         machine->possible_cpus->cpus[i].arch_id = core_id;
4116         machine->possible_cpus->cpus[i].props.has_core_id = true;
4117         machine->possible_cpus->cpus[i].props.core_id = core_id;
4118     }
4119     return machine->possible_cpus;
4120 }
4121 
4122 static void spapr_phb_placement(SpaprMachineState *spapr, uint32_t index,
4123                                 uint64_t *buid, hwaddr *pio,
4124                                 hwaddr *mmio32, hwaddr *mmio64,
4125                                 unsigned n_dma, uint32_t *liobns,
4126                                 hwaddr *nv2gpa, hwaddr *nv2atsd, Error **errp)
4127 {
4128     /*
4129      * New-style PHB window placement.
4130      *
4131      * Goals: Gives large (1TiB), naturally aligned 64-bit MMIO window
4132      * for each PHB, in addition to 2GiB 32-bit MMIO and 64kiB PIO
4133      * windows.
4134      *
4135      * Some guest kernels can't work with MMIO windows above 1<<46
4136      * (64TiB), so we place up to 31 PHBs in the area 32TiB..64TiB
4137      *
4138      * 32TiB..(33TiB+1984kiB) contains the 64kiB PIO windows for each
4139      * PHB stacked together.  (32TiB+2GiB)..(32TiB+64GiB) contains the
4140      * 2GiB 32-bit MMIO windows for each PHB.  Then 33..64TiB has the
4141      * 1TiB 64-bit MMIO windows for each PHB.
4142      */
4143     const uint64_t base_buid = 0x800000020000000ULL;
4144     int i;
4145 
4146     /* Sanity check natural alignments */
4147     QEMU_BUILD_BUG_ON((SPAPR_PCI_BASE % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
4148     QEMU_BUILD_BUG_ON((SPAPR_PCI_LIMIT % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
4149     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM64_WIN_SIZE % SPAPR_PCI_MEM32_WIN_SIZE) != 0);
4150     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM32_WIN_SIZE % SPAPR_PCI_IO_WIN_SIZE) != 0);
4151     /* Sanity check bounds */
4152     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_IO_WIN_SIZE) >
4153                       SPAPR_PCI_MEM32_WIN_SIZE);
4154     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_MEM32_WIN_SIZE) >
4155                       SPAPR_PCI_MEM64_WIN_SIZE);
4156 
4157     if (index >= SPAPR_MAX_PHBS) {
4158         error_setg(errp, "\"index\" for PAPR PHB is too large (max %llu)",
4159                    SPAPR_MAX_PHBS - 1);
4160         return;
4161     }
4162 
4163     *buid = base_buid + index;
4164     for (i = 0; i < n_dma; ++i) {
4165         liobns[i] = SPAPR_PCI_LIOBN(index, i);
4166     }
4167 
4168     *pio = SPAPR_PCI_BASE + index * SPAPR_PCI_IO_WIN_SIZE;
4169     *mmio32 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM32_WIN_SIZE;
4170     *mmio64 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM64_WIN_SIZE;
4171 
4172     *nv2gpa = SPAPR_PCI_NV2RAM64_WIN_BASE + index * SPAPR_PCI_NV2RAM64_WIN_SIZE;
4173     *nv2atsd = SPAPR_PCI_NV2ATSD_WIN_BASE + index * SPAPR_PCI_NV2ATSD_WIN_SIZE;
4174 }
4175 
4176 static ICSState *spapr_ics_get(XICSFabric *dev, int irq)
4177 {
4178     SpaprMachineState *spapr = SPAPR_MACHINE(dev);
4179 
4180     return ics_valid_irq(spapr->ics, irq) ? spapr->ics : NULL;
4181 }
4182 
4183 static void spapr_ics_resend(XICSFabric *dev)
4184 {
4185     SpaprMachineState *spapr = SPAPR_MACHINE(dev);
4186 
4187     ics_resend(spapr->ics);
4188 }
4189 
4190 static ICPState *spapr_icp_get(XICSFabric *xi, int vcpu_id)
4191 {
4192     PowerPCCPU *cpu = spapr_find_cpu(vcpu_id);
4193 
4194     return cpu ? spapr_cpu_state(cpu)->icp : NULL;
4195 }
4196 
4197 static void spapr_pic_print_info(InterruptStatsProvider *obj,
4198                                  Monitor *mon)
4199 {
4200     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
4201 
4202     spapr_irq_print_info(spapr, mon);
4203     monitor_printf(mon, "irqchip: %s\n",
4204                    kvm_irqchip_in_kernel() ? "in-kernel" : "emulated");
4205 }
4206 
4207 /*
4208  * This is a XIVE only operation
4209  */
4210 static int spapr_match_nvt(XiveFabric *xfb, uint8_t format,
4211                            uint8_t nvt_blk, uint32_t nvt_idx,
4212                            bool cam_ignore, uint8_t priority,
4213                            uint32_t logic_serv, XiveTCTXMatch *match)
4214 {
4215     SpaprMachineState *spapr = SPAPR_MACHINE(xfb);
4216     XivePresenter *xptr = XIVE_PRESENTER(spapr->active_intc);
4217     XivePresenterClass *xpc = XIVE_PRESENTER_GET_CLASS(xptr);
4218     int count;
4219 
4220     count = xpc->match_nvt(xptr, format, nvt_blk, nvt_idx, cam_ignore,
4221                            priority, logic_serv, match);
4222     if (count < 0) {
4223         return count;
4224     }
4225 
4226     /*
4227      * When we implement the save and restore of the thread interrupt
4228      * contexts in the enter/exit CPU handlers of the machine and the
4229      * escalations in QEMU, we should be able to handle non dispatched
4230      * vCPUs.
4231      *
4232      * Until this is done, the sPAPR machine should find at least one
4233      * matching context always.
4234      */
4235     if (count == 0) {
4236         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVT %x/%x is not dispatched\n",
4237                       nvt_blk, nvt_idx);
4238     }
4239 
4240     return count;
4241 }
4242 
4243 int spapr_get_vcpu_id(PowerPCCPU *cpu)
4244 {
4245     return cpu->vcpu_id;
4246 }
4247 
4248 void spapr_set_vcpu_id(PowerPCCPU *cpu, int cpu_index, Error **errp)
4249 {
4250     SpaprMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
4251     MachineState *ms = MACHINE(spapr);
4252     int vcpu_id;
4253 
4254     vcpu_id = spapr_vcpu_id(spapr, cpu_index);
4255 
4256     if (kvm_enabled() && !kvm_vcpu_id_is_valid(vcpu_id)) {
4257         error_setg(errp, "Can't create CPU with id %d in KVM", vcpu_id);
4258         error_append_hint(errp, "Adjust the number of cpus to %d "
4259                           "or try to raise the number of threads per core\n",
4260                           vcpu_id * ms->smp.threads / spapr->vsmt);
4261         return;
4262     }
4263 
4264     cpu->vcpu_id = vcpu_id;
4265 }
4266 
4267 PowerPCCPU *spapr_find_cpu(int vcpu_id)
4268 {
4269     CPUState *cs;
4270 
4271     CPU_FOREACH(cs) {
4272         PowerPCCPU *cpu = POWERPC_CPU(cs);
4273 
4274         if (spapr_get_vcpu_id(cpu) == vcpu_id) {
4275             return cpu;
4276         }
4277     }
4278 
4279     return NULL;
4280 }
4281 
4282 static void spapr_cpu_exec_enter(PPCVirtualHypervisor *vhyp, PowerPCCPU *cpu)
4283 {
4284     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
4285 
4286     /* These are only called by TCG, KVM maintains dispatch state */
4287 
4288     spapr_cpu->prod = false;
4289     if (spapr_cpu->vpa_addr) {
4290         CPUState *cs = CPU(cpu);
4291         uint32_t dispatch;
4292 
4293         dispatch = ldl_be_phys(cs->as,
4294                                spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER);
4295         dispatch++;
4296         if ((dispatch & 1) != 0) {
4297             qemu_log_mask(LOG_GUEST_ERROR,
4298                           "VPA: incorrect dispatch counter value for "
4299                           "dispatched partition %u, correcting.\n", dispatch);
4300             dispatch++;
4301         }
4302         stl_be_phys(cs->as,
4303                     spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER, dispatch);
4304     }
4305 }
4306 
4307 static void spapr_cpu_exec_exit(PPCVirtualHypervisor *vhyp, PowerPCCPU *cpu)
4308 {
4309     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
4310 
4311     if (spapr_cpu->vpa_addr) {
4312         CPUState *cs = CPU(cpu);
4313         uint32_t dispatch;
4314 
4315         dispatch = ldl_be_phys(cs->as,
4316                                spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER);
4317         dispatch++;
4318         if ((dispatch & 1) != 1) {
4319             qemu_log_mask(LOG_GUEST_ERROR,
4320                           "VPA: incorrect dispatch counter value for "
4321                           "preempted partition %u, correcting.\n", dispatch);
4322             dispatch++;
4323         }
4324         stl_be_phys(cs->as,
4325                     spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER, dispatch);
4326     }
4327 }
4328 
4329 static void spapr_machine_class_init(ObjectClass *oc, void *data)
4330 {
4331     MachineClass *mc = MACHINE_CLASS(oc);
4332     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(oc);
4333     FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);
4334     NMIClass *nc = NMI_CLASS(oc);
4335     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
4336     PPCVirtualHypervisorClass *vhc = PPC_VIRTUAL_HYPERVISOR_CLASS(oc);
4337     XICSFabricClass *xic = XICS_FABRIC_CLASS(oc);
4338     InterruptStatsProviderClass *ispc = INTERRUPT_STATS_PROVIDER_CLASS(oc);
4339     XiveFabricClass *xfc = XIVE_FABRIC_CLASS(oc);
4340 
4341     mc->desc = "pSeries Logical Partition (PAPR compliant)";
4342     mc->ignore_boot_device_suffixes = true;
4343 
4344     /*
4345      * We set up the default / latest behaviour here.  The class_init
4346      * functions for the specific versioned machine types can override
4347      * these details for backwards compatibility
4348      */
4349     mc->init = spapr_machine_init;
4350     mc->reset = spapr_machine_reset;
4351     mc->block_default_type = IF_SCSI;
4352     mc->max_cpus = 1024;
4353     mc->no_parallel = 1;
4354     mc->default_boot_order = "";
4355     mc->default_ram_size = 512 * MiB;
4356     mc->default_display = "std";
4357     mc->kvm_type = spapr_kvm_type;
4358     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_SPAPR_PCI_HOST_BRIDGE);
4359     mc->pci_allow_0_address = true;
4360     assert(!mc->get_hotplug_handler);
4361     mc->get_hotplug_handler = spapr_get_hotplug_handler;
4362     hc->pre_plug = spapr_machine_device_pre_plug;
4363     hc->plug = spapr_machine_device_plug;
4364     mc->cpu_index_to_instance_props = spapr_cpu_index_to_props;
4365     mc->get_default_cpu_node_id = spapr_get_default_cpu_node_id;
4366     mc->possible_cpu_arch_ids = spapr_possible_cpu_arch_ids;
4367     hc->unplug_request = spapr_machine_device_unplug_request;
4368     hc->unplug = spapr_machine_device_unplug;
4369 
4370     smc->dr_lmb_enabled = true;
4371     smc->update_dt_enabled = true;
4372     mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("power9_v2.0");
4373     mc->has_hotpluggable_cpus = true;
4374     smc->resize_hpt_default = SPAPR_RESIZE_HPT_ENABLED;
4375     fwc->get_dev_path = spapr_get_fw_dev_path;
4376     nc->nmi_monitor_handler = spapr_nmi;
4377     smc->phb_placement = spapr_phb_placement;
4378     vhc->hypercall = emulate_spapr_hypercall;
4379     vhc->hpt_mask = spapr_hpt_mask;
4380     vhc->map_hptes = spapr_map_hptes;
4381     vhc->unmap_hptes = spapr_unmap_hptes;
4382     vhc->hpte_set_c = spapr_hpte_set_c;
4383     vhc->hpte_set_r = spapr_hpte_set_r;
4384     vhc->get_pate = spapr_get_pate;
4385     vhc->encode_hpt_for_kvm_pr = spapr_encode_hpt_for_kvm_pr;
4386     vhc->cpu_exec_enter = spapr_cpu_exec_enter;
4387     vhc->cpu_exec_exit = spapr_cpu_exec_exit;
4388     xic->ics_get = spapr_ics_get;
4389     xic->ics_resend = spapr_ics_resend;
4390     xic->icp_get = spapr_icp_get;
4391     ispc->print_info = spapr_pic_print_info;
4392     /* Force NUMA node memory size to be a multiple of
4393      * SPAPR_MEMORY_BLOCK_SIZE (256M) since that's the granularity
4394      * in which LMBs are represented and hot-added
4395      */
4396     mc->numa_mem_align_shift = 28;
4397     mc->numa_mem_supported = true;
4398     mc->auto_enable_numa = true;
4399 
4400     smc->default_caps.caps[SPAPR_CAP_HTM] = SPAPR_CAP_OFF;
4401     smc->default_caps.caps[SPAPR_CAP_VSX] = SPAPR_CAP_ON;
4402     smc->default_caps.caps[SPAPR_CAP_DFP] = SPAPR_CAP_ON;
4403     smc->default_caps.caps[SPAPR_CAP_CFPC] = SPAPR_CAP_WORKAROUND;
4404     smc->default_caps.caps[SPAPR_CAP_SBBC] = SPAPR_CAP_WORKAROUND;
4405     smc->default_caps.caps[SPAPR_CAP_IBS] = SPAPR_CAP_WORKAROUND;
4406     smc->default_caps.caps[SPAPR_CAP_HPT_MAXPAGESIZE] = 16; /* 64kiB */
4407     smc->default_caps.caps[SPAPR_CAP_NESTED_KVM_HV] = SPAPR_CAP_OFF;
4408     smc->default_caps.caps[SPAPR_CAP_LARGE_DECREMENTER] = SPAPR_CAP_ON;
4409     smc->default_caps.caps[SPAPR_CAP_CCF_ASSIST] = SPAPR_CAP_ON;
4410     smc->default_caps.caps[SPAPR_CAP_FWNMI_MCE] = SPAPR_CAP_OFF;
4411     spapr_caps_add_properties(smc, &error_abort);
4412     smc->irq = &spapr_irq_dual;
4413     smc->dr_phb_enabled = true;
4414     smc->linux_pci_probe = true;
4415     smc->smp_threads_vsmt = true;
4416     smc->nr_xirqs = SPAPR_NR_XIRQS;
4417     xfc->match_nvt = spapr_match_nvt;
4418 }
4419 
4420 static const TypeInfo spapr_machine_info = {
4421     .name          = TYPE_SPAPR_MACHINE,
4422     .parent        = TYPE_MACHINE,
4423     .abstract      = true,
4424     .instance_size = sizeof(SpaprMachineState),
4425     .instance_init = spapr_instance_init,
4426     .instance_finalize = spapr_machine_finalizefn,
4427     .class_size    = sizeof(SpaprMachineClass),
4428     .class_init    = spapr_machine_class_init,
4429     .interfaces = (InterfaceInfo[]) {
4430         { TYPE_FW_PATH_PROVIDER },
4431         { TYPE_NMI },
4432         { TYPE_HOTPLUG_HANDLER },
4433         { TYPE_PPC_VIRTUAL_HYPERVISOR },
4434         { TYPE_XICS_FABRIC },
4435         { TYPE_INTERRUPT_STATS_PROVIDER },
4436         { TYPE_XIVE_FABRIC },
4437         { }
4438     },
4439 };
4440 
4441 #define DEFINE_SPAPR_MACHINE(suffix, verstr, latest)                 \
4442     static void spapr_machine_##suffix##_class_init(ObjectClass *oc, \
4443                                                     void *data)      \
4444     {                                                                \
4445         MachineClass *mc = MACHINE_CLASS(oc);                        \
4446         spapr_machine_##suffix##_class_options(mc);                  \
4447         if (latest) {                                                \
4448             mc->alias = "pseries";                                   \
4449             mc->is_default = 1;                                      \
4450         }                                                            \
4451     }                                                                \
4452     static const TypeInfo spapr_machine_##suffix##_info = {          \
4453         .name = MACHINE_TYPE_NAME("pseries-" verstr),                \
4454         .parent = TYPE_SPAPR_MACHINE,                                \
4455         .class_init = spapr_machine_##suffix##_class_init,           \
4456     };                                                               \
4457     static void spapr_machine_register_##suffix(void)                \
4458     {                                                                \
4459         type_register(&spapr_machine_##suffix##_info);               \
4460     }                                                                \
4461     type_init(spapr_machine_register_##suffix)
4462 
4463 /*
4464  * pseries-5.0
4465  */
4466 static void spapr_machine_5_0_class_options(MachineClass *mc)
4467 {
4468     /* Defaults for the latest behaviour inherited from the base class */
4469 }
4470 
4471 DEFINE_SPAPR_MACHINE(5_0, "5.0", true);
4472 
4473 /*
4474  * pseries-4.2
4475  */
4476 static void spapr_machine_4_2_class_options(MachineClass *mc)
4477 {
4478     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4479 
4480     spapr_machine_5_0_class_options(mc);
4481     compat_props_add(mc->compat_props, hw_compat_4_2, hw_compat_4_2_len);
4482     smc->default_caps.caps[SPAPR_CAP_CCF_ASSIST] = SPAPR_CAP_OFF;
4483 }
4484 
4485 DEFINE_SPAPR_MACHINE(4_2, "4.2", false);
4486 
4487 /*
4488  * pseries-4.1
4489  */
4490 static void spapr_machine_4_1_class_options(MachineClass *mc)
4491 {
4492     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4493     static GlobalProperty compat[] = {
4494         /* Only allow 4kiB and 64kiB IOMMU pagesizes */
4495         { TYPE_SPAPR_PCI_HOST_BRIDGE, "pgsz", "0x11000" },
4496     };
4497 
4498     spapr_machine_4_2_class_options(mc);
4499     smc->linux_pci_probe = false;
4500     smc->smp_threads_vsmt = false;
4501     compat_props_add(mc->compat_props, hw_compat_4_1, hw_compat_4_1_len);
4502     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4503 }
4504 
4505 DEFINE_SPAPR_MACHINE(4_1, "4.1", false);
4506 
4507 /*
4508  * pseries-4.0
4509  */
4510 static void phb_placement_4_0(SpaprMachineState *spapr, uint32_t index,
4511                               uint64_t *buid, hwaddr *pio,
4512                               hwaddr *mmio32, hwaddr *mmio64,
4513                               unsigned n_dma, uint32_t *liobns,
4514                               hwaddr *nv2gpa, hwaddr *nv2atsd, Error **errp)
4515 {
4516     spapr_phb_placement(spapr, index, buid, pio, mmio32, mmio64, n_dma, liobns,
4517                         nv2gpa, nv2atsd, errp);
4518     *nv2gpa = 0;
4519     *nv2atsd = 0;
4520 }
4521 
4522 static void spapr_machine_4_0_class_options(MachineClass *mc)
4523 {
4524     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4525 
4526     spapr_machine_4_1_class_options(mc);
4527     compat_props_add(mc->compat_props, hw_compat_4_0, hw_compat_4_0_len);
4528     smc->phb_placement = phb_placement_4_0;
4529     smc->irq = &spapr_irq_xics;
4530     smc->pre_4_1_migration = true;
4531 }
4532 
4533 DEFINE_SPAPR_MACHINE(4_0, "4.0", false);
4534 
4535 /*
4536  * pseries-3.1
4537  */
4538 static void spapr_machine_3_1_class_options(MachineClass *mc)
4539 {
4540     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4541 
4542     spapr_machine_4_0_class_options(mc);
4543     compat_props_add(mc->compat_props, hw_compat_3_1, hw_compat_3_1_len);
4544 
4545     mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("power8_v2.0");
4546     smc->update_dt_enabled = false;
4547     smc->dr_phb_enabled = false;
4548     smc->broken_host_serial_model = true;
4549     smc->default_caps.caps[SPAPR_CAP_CFPC] = SPAPR_CAP_BROKEN;
4550     smc->default_caps.caps[SPAPR_CAP_SBBC] = SPAPR_CAP_BROKEN;
4551     smc->default_caps.caps[SPAPR_CAP_IBS] = SPAPR_CAP_BROKEN;
4552     smc->default_caps.caps[SPAPR_CAP_LARGE_DECREMENTER] = SPAPR_CAP_OFF;
4553 }
4554 
4555 DEFINE_SPAPR_MACHINE(3_1, "3.1", false);
4556 
4557 /*
4558  * pseries-3.0
4559  */
4560 
4561 static void spapr_machine_3_0_class_options(MachineClass *mc)
4562 {
4563     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4564 
4565     spapr_machine_3_1_class_options(mc);
4566     compat_props_add(mc->compat_props, hw_compat_3_0, hw_compat_3_0_len);
4567 
4568     smc->legacy_irq_allocation = true;
4569     smc->nr_xirqs = 0x400;
4570     smc->irq = &spapr_irq_xics_legacy;
4571 }
4572 
4573 DEFINE_SPAPR_MACHINE(3_0, "3.0", false);
4574 
4575 /*
4576  * pseries-2.12
4577  */
4578 static void spapr_machine_2_12_class_options(MachineClass *mc)
4579 {
4580     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4581     static GlobalProperty compat[] = {
4582         { TYPE_POWERPC_CPU, "pre-3.0-migration", "on" },
4583         { TYPE_SPAPR_CPU_CORE, "pre-3.0-migration", "on" },
4584     };
4585 
4586     spapr_machine_3_0_class_options(mc);
4587     compat_props_add(mc->compat_props, hw_compat_2_12, hw_compat_2_12_len);
4588     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4589 
4590     /* We depend on kvm_enabled() to choose a default value for the
4591      * hpt-max-page-size capability. Of course we can't do it here
4592      * because this is too early and the HW accelerator isn't initialzed
4593      * yet. Postpone this to machine init (see default_caps_with_cpu()).
4594      */
4595     smc->default_caps.caps[SPAPR_CAP_HPT_MAXPAGESIZE] = 0;
4596 }
4597 
4598 DEFINE_SPAPR_MACHINE(2_12, "2.12", false);
4599 
4600 static void spapr_machine_2_12_sxxm_class_options(MachineClass *mc)
4601 {
4602     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4603 
4604     spapr_machine_2_12_class_options(mc);
4605     smc->default_caps.caps[SPAPR_CAP_CFPC] = SPAPR_CAP_WORKAROUND;
4606     smc->default_caps.caps[SPAPR_CAP_SBBC] = SPAPR_CAP_WORKAROUND;
4607     smc->default_caps.caps[SPAPR_CAP_IBS] = SPAPR_CAP_FIXED_CCD;
4608 }
4609 
4610 DEFINE_SPAPR_MACHINE(2_12_sxxm, "2.12-sxxm", false);
4611 
4612 /*
4613  * pseries-2.11
4614  */
4615 
4616 static void spapr_machine_2_11_class_options(MachineClass *mc)
4617 {
4618     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4619 
4620     spapr_machine_2_12_class_options(mc);
4621     smc->default_caps.caps[SPAPR_CAP_HTM] = SPAPR_CAP_ON;
4622     compat_props_add(mc->compat_props, hw_compat_2_11, hw_compat_2_11_len);
4623 }
4624 
4625 DEFINE_SPAPR_MACHINE(2_11, "2.11", false);
4626 
4627 /*
4628  * pseries-2.10
4629  */
4630 
4631 static void spapr_machine_2_10_class_options(MachineClass *mc)
4632 {
4633     spapr_machine_2_11_class_options(mc);
4634     compat_props_add(mc->compat_props, hw_compat_2_10, hw_compat_2_10_len);
4635 }
4636 
4637 DEFINE_SPAPR_MACHINE(2_10, "2.10", false);
4638 
4639 /*
4640  * pseries-2.9
4641  */
4642 
4643 static void spapr_machine_2_9_class_options(MachineClass *mc)
4644 {
4645     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4646     static GlobalProperty compat[] = {
4647         { TYPE_POWERPC_CPU, "pre-2.10-migration", "on" },
4648     };
4649 
4650     spapr_machine_2_10_class_options(mc);
4651     compat_props_add(mc->compat_props, hw_compat_2_9, hw_compat_2_9_len);
4652     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4653     mc->numa_auto_assign_ram = numa_legacy_auto_assign_ram;
4654     smc->pre_2_10_has_unused_icps = true;
4655     smc->resize_hpt_default = SPAPR_RESIZE_HPT_DISABLED;
4656 }
4657 
4658 DEFINE_SPAPR_MACHINE(2_9, "2.9", false);
4659 
4660 /*
4661  * pseries-2.8
4662  */
4663 
4664 static void spapr_machine_2_8_class_options(MachineClass *mc)
4665 {
4666     static GlobalProperty compat[] = {
4667         { TYPE_SPAPR_PCI_HOST_BRIDGE, "pcie-extended-configuration-space", "off" },
4668     };
4669 
4670     spapr_machine_2_9_class_options(mc);
4671     compat_props_add(mc->compat_props, hw_compat_2_8, hw_compat_2_8_len);
4672     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4673     mc->numa_mem_align_shift = 23;
4674 }
4675 
4676 DEFINE_SPAPR_MACHINE(2_8, "2.8", false);
4677 
4678 /*
4679  * pseries-2.7
4680  */
4681 
4682 static void phb_placement_2_7(SpaprMachineState *spapr, uint32_t index,
4683                               uint64_t *buid, hwaddr *pio,
4684                               hwaddr *mmio32, hwaddr *mmio64,
4685                               unsigned n_dma, uint32_t *liobns,
4686                               hwaddr *nv2gpa, hwaddr *nv2atsd, Error **errp)
4687 {
4688     /* Legacy PHB placement for pseries-2.7 and earlier machine types */
4689     const uint64_t base_buid = 0x800000020000000ULL;
4690     const hwaddr phb_spacing = 0x1000000000ULL; /* 64 GiB */
4691     const hwaddr mmio_offset = 0xa0000000; /* 2 GiB + 512 MiB */
4692     const hwaddr pio_offset = 0x80000000; /* 2 GiB */
4693     const uint32_t max_index = 255;
4694     const hwaddr phb0_alignment = 0x10000000000ULL; /* 1 TiB */
4695 
4696     uint64_t ram_top = MACHINE(spapr)->ram_size;
4697     hwaddr phb0_base, phb_base;
4698     int i;
4699 
4700     /* Do we have device memory? */
4701     if (MACHINE(spapr)->maxram_size > ram_top) {
4702         /* Can't just use maxram_size, because there may be an
4703          * alignment gap between normal and device memory regions
4704          */
4705         ram_top = MACHINE(spapr)->device_memory->base +
4706             memory_region_size(&MACHINE(spapr)->device_memory->mr);
4707     }
4708 
4709     phb0_base = QEMU_ALIGN_UP(ram_top, phb0_alignment);
4710 
4711     if (index > max_index) {
4712         error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",
4713                    max_index);
4714         return;
4715     }
4716 
4717     *buid = base_buid + index;
4718     for (i = 0; i < n_dma; ++i) {
4719         liobns[i] = SPAPR_PCI_LIOBN(index, i);
4720     }
4721 
4722     phb_base = phb0_base + index * phb_spacing;
4723     *pio = phb_base + pio_offset;
4724     *mmio32 = phb_base + mmio_offset;
4725     /*
4726      * We don't set the 64-bit MMIO window, relying on the PHB's
4727      * fallback behaviour of automatically splitting a large "32-bit"
4728      * window into contiguous 32-bit and 64-bit windows
4729      */
4730 
4731     *nv2gpa = 0;
4732     *nv2atsd = 0;
4733 }
4734 
4735 static void spapr_machine_2_7_class_options(MachineClass *mc)
4736 {
4737     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4738     static GlobalProperty compat[] = {
4739         { TYPE_SPAPR_PCI_HOST_BRIDGE, "mem_win_size", "0xf80000000", },
4740         { TYPE_SPAPR_PCI_HOST_BRIDGE, "mem64_win_size", "0", },
4741         { TYPE_POWERPC_CPU, "pre-2.8-migration", "on", },
4742         { TYPE_SPAPR_PCI_HOST_BRIDGE, "pre-2.8-migration", "on", },
4743     };
4744 
4745     spapr_machine_2_8_class_options(mc);
4746     mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("power7_v2.3");
4747     mc->default_machine_opts = "modern-hotplug-events=off";
4748     compat_props_add(mc->compat_props, hw_compat_2_7, hw_compat_2_7_len);
4749     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4750     smc->phb_placement = phb_placement_2_7;
4751 }
4752 
4753 DEFINE_SPAPR_MACHINE(2_7, "2.7", false);
4754 
4755 /*
4756  * pseries-2.6
4757  */
4758 
4759 static void spapr_machine_2_6_class_options(MachineClass *mc)
4760 {
4761     static GlobalProperty compat[] = {
4762         { TYPE_SPAPR_PCI_HOST_BRIDGE, "ddw", "off" },
4763     };
4764 
4765     spapr_machine_2_7_class_options(mc);
4766     mc->has_hotpluggable_cpus = false;
4767     compat_props_add(mc->compat_props, hw_compat_2_6, hw_compat_2_6_len);
4768     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4769 }
4770 
4771 DEFINE_SPAPR_MACHINE(2_6, "2.6", false);
4772 
4773 /*
4774  * pseries-2.5
4775  */
4776 
4777 static void spapr_machine_2_5_class_options(MachineClass *mc)
4778 {
4779     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4780     static GlobalProperty compat[] = {
4781         { "spapr-vlan", "use-rx-buffer-pools", "off" },
4782     };
4783 
4784     spapr_machine_2_6_class_options(mc);
4785     smc->use_ohci_by_default = true;
4786     compat_props_add(mc->compat_props, hw_compat_2_5, hw_compat_2_5_len);
4787     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4788 }
4789 
4790 DEFINE_SPAPR_MACHINE(2_5, "2.5", false);
4791 
4792 /*
4793  * pseries-2.4
4794  */
4795 
4796 static void spapr_machine_2_4_class_options(MachineClass *mc)
4797 {
4798     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4799 
4800     spapr_machine_2_5_class_options(mc);
4801     smc->dr_lmb_enabled = false;
4802     compat_props_add(mc->compat_props, hw_compat_2_4, hw_compat_2_4_len);
4803 }
4804 
4805 DEFINE_SPAPR_MACHINE(2_4, "2.4", false);
4806 
4807 /*
4808  * pseries-2.3
4809  */
4810 
4811 static void spapr_machine_2_3_class_options(MachineClass *mc)
4812 {
4813     static GlobalProperty compat[] = {
4814         { "spapr-pci-host-bridge", "dynamic-reconfiguration", "off" },
4815     };
4816     spapr_machine_2_4_class_options(mc);
4817     compat_props_add(mc->compat_props, hw_compat_2_3, hw_compat_2_3_len);
4818     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4819 }
4820 DEFINE_SPAPR_MACHINE(2_3, "2.3", false);
4821 
4822 /*
4823  * pseries-2.2
4824  */
4825 
4826 static void spapr_machine_2_2_class_options(MachineClass *mc)
4827 {
4828     static GlobalProperty compat[] = {
4829         { TYPE_SPAPR_PCI_HOST_BRIDGE, "mem_win_size", "0x20000000" },
4830     };
4831 
4832     spapr_machine_2_3_class_options(mc);
4833     compat_props_add(mc->compat_props, hw_compat_2_2, hw_compat_2_2_len);
4834     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4835     mc->default_machine_opts = "modern-hotplug-events=off,suppress-vmdesc=on";
4836 }
4837 DEFINE_SPAPR_MACHINE(2_2, "2.2", false);
4838 
4839 /*
4840  * pseries-2.1
4841  */
4842 
4843 static void spapr_machine_2_1_class_options(MachineClass *mc)
4844 {
4845     spapr_machine_2_2_class_options(mc);
4846     compat_props_add(mc->compat_props, hw_compat_2_1, hw_compat_2_1_len);
4847 }
4848 DEFINE_SPAPR_MACHINE(2_1, "2.1", false);
4849 
4850 static void spapr_machine_register_types(void)
4851 {
4852     type_register_static(&spapr_machine_info);
4853 }
4854 
4855 type_init(spapr_machine_register_types)
4856