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