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