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