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