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