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