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