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