xref: /openbmc/qemu/hw/ppc/spapr.c (revision 5f361ea187ba5f876757d4c90952ff23810f24f5)
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     /* init CPUs */
2921     spapr_init_cpus(spapr);
2922 
2923     /* Init numa_assoc_array */
2924     spapr_numa_associativity_init(spapr, machine);
2925 
2926     if ((!kvm_enabled() || kvmppc_has_cap_mmu_radix()) &&
2927         ppc_type_check_compat(machine->cpu_type, CPU_POWERPC_LOGICAL_3_00, 0,
2928                               spapr->max_compat_pvr)) {
2929         spapr_ovec_set(spapr->ov5, OV5_MMU_RADIX_300);
2930         /* KVM and TCG always allow GTSE with radix... */
2931         spapr_ovec_set(spapr->ov5, OV5_MMU_RADIX_GTSE);
2932     }
2933     /* ... but not with hash (currently). */
2934 
2935     if (kvm_enabled()) {
2936         /* Enable H_LOGICAL_CI_* so SLOF can talk to in-kernel devices */
2937         kvmppc_enable_logical_ci_hcalls();
2938         kvmppc_enable_set_mode_hcall();
2939 
2940         /* H_CLEAR_MOD/_REF are mandatory in PAPR, but off by default */
2941         kvmppc_enable_clear_ref_mod_hcalls();
2942 
2943         /* Enable H_PAGE_INIT */
2944         kvmppc_enable_h_page_init();
2945     }
2946 
2947     /* map RAM */
2948     memory_region_add_subregion(sysmem, 0, machine->ram);
2949 
2950     /* initialize hotplug memory address space */
2951     if (machine->ram_size < machine->maxram_size) {
2952         ram_addr_t device_mem_size = machine->maxram_size - machine->ram_size;
2953         hwaddr device_mem_base;
2954 
2955         /*
2956          * Limit the number of hotpluggable memory slots to half the number
2957          * slots that KVM supports, leaving the other half for PCI and other
2958          * devices. However ensure that number of slots doesn't drop below 32.
2959          */
2960         int max_memslots = kvm_enabled() ? kvm_get_max_memslots() / 2 :
2961                            SPAPR_MAX_RAM_SLOTS;
2962 
2963         if (max_memslots < SPAPR_MAX_RAM_SLOTS) {
2964             max_memslots = SPAPR_MAX_RAM_SLOTS;
2965         }
2966         if (machine->ram_slots > max_memslots) {
2967             error_report("Specified number of memory slots %"
2968                          PRIu64" exceeds max supported %d",
2969                          machine->ram_slots, max_memslots);
2970             exit(1);
2971         }
2972 
2973         device_mem_base = ROUND_UP(machine->ram_size, SPAPR_DEVICE_MEM_ALIGN);
2974         machine_memory_devices_init(machine, device_mem_base, device_mem_size);
2975     }
2976 
2977     spapr_create_lmb_dr_connectors(spapr);
2978 
2979     if (mc->nvdimm_supported) {
2980         spapr_create_nvdimm_dr_connectors(spapr);
2981     }
2982 
2983     /* Set up RTAS event infrastructure */
2984     spapr_events_init(spapr);
2985 
2986     /* Set up the RTC RTAS interfaces */
2987     spapr_rtc_create(spapr);
2988 
2989     /* Set up VIO bus */
2990     spapr->vio_bus = spapr_vio_bus_init();
2991 
2992     for (i = 0; serial_hd(i); i++) {
2993         spapr_vty_create(spapr->vio_bus, serial_hd(i));
2994     }
2995 
2996     /* We always have at least the nvram device on VIO */
2997     spapr_create_nvram(spapr);
2998 
2999     /*
3000      * Setup hotplug / dynamic-reconfiguration connectors. top-level
3001      * connectors (described in root DT node's "ibm,drc-types" property)
3002      * are pre-initialized here. additional child connectors (such as
3003      * connectors for a PHBs PCI slots) are added as needed during their
3004      * parent's realization.
3005      */
3006     if (smc->dr_phb_enabled) {
3007         for (i = 0; i < SPAPR_MAX_PHBS; i++) {
3008             spapr_dr_connector_new(OBJECT(machine), TYPE_SPAPR_DRC_PHB, i);
3009         }
3010     }
3011 
3012     /* Set up PCI */
3013     spapr_pci_rtas_init();
3014 
3015     phb = spapr_create_default_phb();
3016 
3017     while ((nd = qemu_find_nic_info("spapr-vlan", true, "ibmveth"))) {
3018         spapr_vlan_create(spapr->vio_bus, nd);
3019     }
3020 
3021     pci_init_nic_devices(phb->bus, NULL);
3022 
3023     for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
3024         spapr_vscsi_create(spapr->vio_bus);
3025     }
3026 
3027     /* Graphics */
3028     has_vga = spapr_vga_init(phb->bus, &error_fatal);
3029     if (has_vga) {
3030         spapr->want_stdout_path = !machine->enable_graphics;
3031         machine->usb |= defaults_enabled() && !machine->usb_disabled;
3032     } else {
3033         spapr->want_stdout_path = true;
3034     }
3035 
3036     if (machine->usb) {
3037         pci_create_simple(phb->bus, -1, "nec-usb-xhci");
3038 
3039         if (has_vga) {
3040             USBBus *usb_bus;
3041 
3042             usb_bus = USB_BUS(object_resolve_type_unambiguous(TYPE_USB_BUS,
3043                                                               &error_abort));
3044             usb_create_simple(usb_bus, "usb-kbd");
3045             usb_create_simple(usb_bus, "usb-mouse");
3046         }
3047     }
3048 
3049     if (kernel_filename) {
3050         uint64_t loaded_addr = 0;
3051 
3052         spapr->kernel_size = load_elf(kernel_filename, NULL,
3053                                       translate_kernel_address, spapr,
3054                                       NULL, &loaded_addr, NULL, NULL,
3055                                       ELFDATA2MSB, PPC_ELF_MACHINE, 0, 0);
3056         if (spapr->kernel_size == ELF_LOAD_WRONG_ENDIAN) {
3057             spapr->kernel_size = load_elf(kernel_filename, NULL,
3058                                           translate_kernel_address, spapr,
3059                                           NULL, &loaded_addr, NULL, NULL,
3060                                           ELFDATA2LSB, PPC_ELF_MACHINE, 0, 0);
3061             spapr->kernel_le = spapr->kernel_size > 0;
3062         }
3063         if (spapr->kernel_size < 0) {
3064             error_report("error loading %s: %s", kernel_filename,
3065                          load_elf_strerror(spapr->kernel_size));
3066             exit(1);
3067         }
3068 
3069         if (spapr->kernel_addr != loaded_addr) {
3070             warn_report("spapr: kernel_addr changed from 0x%"PRIx64
3071                         " to 0x%"PRIx64,
3072                         spapr->kernel_addr, loaded_addr);
3073             spapr->kernel_addr = loaded_addr;
3074         }
3075 
3076         /* load initrd */
3077         if (initrd_filename) {
3078             /* Try to locate the initrd in the gap between the kernel
3079              * and the firmware. Add a bit of space just in case
3080              */
3081             spapr->initrd_base = (spapr->kernel_addr + spapr->kernel_size
3082                                   + 0x1ffff) & ~0xffff;
3083             spapr->initrd_size = load_image_targphys(initrd_filename,
3084                                                      spapr->initrd_base,
3085                                                      load_limit
3086                                                      - spapr->initrd_base);
3087             if (spapr->initrd_size < 0) {
3088                 error_report("could not load initial ram disk '%s'",
3089                              initrd_filename);
3090                 exit(1);
3091             }
3092         }
3093     }
3094 
3095     /* FIXME: Should register things through the MachineState's qdev
3096      * interface, this is a legacy from the sPAPREnvironment structure
3097      * which predated MachineState but had a similar function */
3098     vmstate_register(NULL, 0, &vmstate_spapr, spapr);
3099     register_savevm_live("spapr/htab", VMSTATE_INSTANCE_ID_ANY, 1,
3100                          &savevm_htab_handlers, spapr);
3101 
3102     qbus_set_hotplug_handler(sysbus_get_default(), OBJECT(machine));
3103 
3104     qemu_register_boot_set(spapr_boot_set, spapr);
3105 
3106     /*
3107      * Nothing needs to be done to resume a suspended guest because
3108      * suspending does not change the machine state, so no need for
3109      * a ->wakeup method.
3110      */
3111     qemu_register_wakeup_support();
3112 
3113     if (kvm_enabled()) {
3114         /* to stop and start vmclock */
3115         qemu_add_vm_change_state_handler(cpu_ppc_clock_vm_state_change,
3116                                          &spapr->tb);
3117 
3118         kvmppc_spapr_enable_inkernel_multitce();
3119     }
3120 
3121     qemu_cond_init(&spapr->fwnmi_machine_check_interlock_cond);
3122     if (spapr->vof) {
3123         spapr->vof->fw_size = fw_size; /* for claim() on itself */
3124         spapr_register_hypercall(KVMPPC_H_VOF_CLIENT, spapr_h_vof_client);
3125     }
3126 
3127     spapr_watchdog_init(spapr);
3128 }
3129 
3130 #define DEFAULT_KVM_TYPE "auto"
3131 static int spapr_kvm_type(MachineState *machine, const char *vm_type)
3132 {
3133     /*
3134      * The use of g_ascii_strcasecmp() for 'hv' and 'pr' is to
3135      * accommodate the 'HV' and 'PV' formats that exists in the
3136      * wild. The 'auto' mode is being introduced already as
3137      * lower-case, thus we don't need to bother checking for
3138      * "AUTO".
3139      */
3140     if (!vm_type || !strcmp(vm_type, DEFAULT_KVM_TYPE)) {
3141         return 0;
3142     }
3143 
3144     if (!g_ascii_strcasecmp(vm_type, "hv")) {
3145         return 1;
3146     }
3147 
3148     if (!g_ascii_strcasecmp(vm_type, "pr")) {
3149         return 2;
3150     }
3151 
3152     error_report("Unknown kvm-type specified '%s'", vm_type);
3153     return -1;
3154 }
3155 
3156 /*
3157  * Implementation of an interface to adjust firmware path
3158  * for the bootindex property handling.
3159  */
3160 static char *spapr_get_fw_dev_path(FWPathProvider *p, BusState *bus,
3161                                    DeviceState *dev)
3162 {
3163 #define CAST(type, obj, name) \
3164     ((type *)object_dynamic_cast(OBJECT(obj), (name)))
3165     SCSIDevice *d = CAST(SCSIDevice,  dev, TYPE_SCSI_DEVICE);
3166     SpaprPhbState *phb = CAST(SpaprPhbState, dev, TYPE_SPAPR_PCI_HOST_BRIDGE);
3167     VHostSCSICommon *vsc = CAST(VHostSCSICommon, dev, TYPE_VHOST_SCSI_COMMON);
3168     PCIDevice *pcidev = CAST(PCIDevice, dev, TYPE_PCI_DEVICE);
3169 
3170     if (d && bus) {
3171         void *spapr = CAST(void, bus->parent, "spapr-vscsi");
3172         VirtIOSCSI *virtio = CAST(VirtIOSCSI, bus->parent, TYPE_VIRTIO_SCSI);
3173         USBDevice *usb = CAST(USBDevice, bus->parent, TYPE_USB_DEVICE);
3174 
3175         if (spapr) {
3176             /*
3177              * Replace "channel@0/disk@0,0" with "disk@8000000000000000":
3178              * In the top 16 bits of the 64-bit LUN, we use SRP luns of the form
3179              * 0x8000 | (target << 8) | (bus << 5) | lun
3180              * (see the "Logical unit addressing format" table in SAM5)
3181              */
3182             unsigned id = 0x8000 | (d->id << 8) | (d->channel << 5) | d->lun;
3183             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3184                                    (uint64_t)id << 48);
3185         } else if (virtio) {
3186             /*
3187              * We use SRP luns of the form 01000000 | (target << 8) | lun
3188              * in the top 32 bits of the 64-bit LUN
3189              * Note: the quote above is from SLOF and it is wrong,
3190              * the actual binding is:
3191              * swap 0100 or 10 << or 20 << ( target lun-id -- srplun )
3192              */
3193             unsigned id = 0x1000000 | (d->id << 16) | d->lun;
3194             if (d->lun >= 256) {
3195                 /* Use the LUN "flat space addressing method" */
3196                 id |= 0x4000;
3197             }
3198             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3199                                    (uint64_t)id << 32);
3200         } else if (usb) {
3201             /*
3202              * We use SRP luns of the form 01000000 | (usb-port << 16) | lun
3203              * in the top 32 bits of the 64-bit LUN
3204              */
3205             unsigned usb_port = atoi(usb->port->path);
3206             unsigned id = 0x1000000 | (usb_port << 16) | d->lun;
3207             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
3208                                    (uint64_t)id << 32);
3209         }
3210     }
3211 
3212     /*
3213      * SLOF probes the USB devices, and if it recognizes that the device is a
3214      * storage device, it changes its name to "storage" instead of "usb-host",
3215      * and additionally adds a child node for the SCSI LUN, so the correct
3216      * boot path in SLOF is something like .../storage@1/disk@xxx" instead.
3217      */
3218     if (strcmp("usb-host", qdev_fw_name(dev)) == 0) {
3219         USBDevice *usbdev = CAST(USBDevice, dev, TYPE_USB_DEVICE);
3220         if (usb_device_is_scsi_storage(usbdev)) {
3221             return g_strdup_printf("storage@%s/disk", usbdev->port->path);
3222         }
3223     }
3224 
3225     if (phb) {
3226         /* Replace "pci" with "pci@800000020000000" */
3227         return g_strdup_printf("pci@%"PRIX64, phb->buid);
3228     }
3229 
3230     if (vsc) {
3231         /* Same logic as virtio above */
3232         unsigned id = 0x1000000 | (vsc->target << 16) | vsc->lun;
3233         return g_strdup_printf("disk@%"PRIX64, (uint64_t)id << 32);
3234     }
3235 
3236     if (g_str_equal("pci-bridge", qdev_fw_name(dev))) {
3237         /* SLOF uses "pci" instead of "pci-bridge" for PCI bridges */
3238         PCIDevice *pdev = CAST(PCIDevice, dev, TYPE_PCI_DEVICE);
3239         return g_strdup_printf("pci@%x", PCI_SLOT(pdev->devfn));
3240     }
3241 
3242     if (pcidev) {
3243         return spapr_pci_fw_dev_name(pcidev);
3244     }
3245 
3246     return NULL;
3247 }
3248 
3249 static char *spapr_get_kvm_type(Object *obj, Error **errp)
3250 {
3251     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3252 
3253     return g_strdup(spapr->kvm_type);
3254 }
3255 
3256 static void spapr_set_kvm_type(Object *obj, const char *value, Error **errp)
3257 {
3258     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3259 
3260     g_free(spapr->kvm_type);
3261     spapr->kvm_type = g_strdup(value);
3262 }
3263 
3264 static bool spapr_get_modern_hotplug_events(Object *obj, Error **errp)
3265 {
3266     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3267 
3268     return spapr->use_hotplug_event_source;
3269 }
3270 
3271 static void spapr_set_modern_hotplug_events(Object *obj, bool value,
3272                                             Error **errp)
3273 {
3274     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3275 
3276     spapr->use_hotplug_event_source = value;
3277 }
3278 
3279 static bool spapr_get_msix_emulation(Object *obj, Error **errp)
3280 {
3281     return true;
3282 }
3283 
3284 static char *spapr_get_resize_hpt(Object *obj, Error **errp)
3285 {
3286     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3287 
3288     switch (spapr->resize_hpt) {
3289     case SPAPR_RESIZE_HPT_DEFAULT:
3290         return g_strdup("default");
3291     case SPAPR_RESIZE_HPT_DISABLED:
3292         return g_strdup("disabled");
3293     case SPAPR_RESIZE_HPT_ENABLED:
3294         return g_strdup("enabled");
3295     case SPAPR_RESIZE_HPT_REQUIRED:
3296         return g_strdup("required");
3297     }
3298     g_assert_not_reached();
3299 }
3300 
3301 static void spapr_set_resize_hpt(Object *obj, const char *value, Error **errp)
3302 {
3303     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3304 
3305     if (strcmp(value, "default") == 0) {
3306         spapr->resize_hpt = SPAPR_RESIZE_HPT_DEFAULT;
3307     } else if (strcmp(value, "disabled") == 0) {
3308         spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
3309     } else if (strcmp(value, "enabled") == 0) {
3310         spapr->resize_hpt = SPAPR_RESIZE_HPT_ENABLED;
3311     } else if (strcmp(value, "required") == 0) {
3312         spapr->resize_hpt = SPAPR_RESIZE_HPT_REQUIRED;
3313     } else {
3314         error_setg(errp, "Bad value for \"resize-hpt\" property");
3315     }
3316 }
3317 
3318 static bool spapr_get_vof(Object *obj, Error **errp)
3319 {
3320     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3321 
3322     return spapr->vof != NULL;
3323 }
3324 
3325 static void spapr_set_vof(Object *obj, bool value, Error **errp)
3326 {
3327     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3328 
3329     if (spapr->vof) {
3330         vof_cleanup(spapr->vof);
3331         g_free(spapr->vof);
3332         spapr->vof = NULL;
3333     }
3334     if (!value) {
3335         return;
3336     }
3337     spapr->vof = g_malloc0(sizeof(*spapr->vof));
3338 }
3339 
3340 static char *spapr_get_ic_mode(Object *obj, Error **errp)
3341 {
3342     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3343 
3344     if (spapr->irq == &spapr_irq_xics_legacy) {
3345         return g_strdup("legacy");
3346     } else if (spapr->irq == &spapr_irq_xics) {
3347         return g_strdup("xics");
3348     } else if (spapr->irq == &spapr_irq_xive) {
3349         return g_strdup("xive");
3350     } else if (spapr->irq == &spapr_irq_dual) {
3351         return g_strdup("dual");
3352     }
3353     g_assert_not_reached();
3354 }
3355 
3356 static void spapr_set_ic_mode(Object *obj, const char *value, Error **errp)
3357 {
3358     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3359 
3360     if (SPAPR_MACHINE_GET_CLASS(spapr)->legacy_irq_allocation) {
3361         error_setg(errp, "This machine only uses the legacy XICS backend, don't pass ic-mode");
3362         return;
3363     }
3364 
3365     /* The legacy IRQ backend can not be set */
3366     if (strcmp(value, "xics") == 0) {
3367         spapr->irq = &spapr_irq_xics;
3368     } else if (strcmp(value, "xive") == 0) {
3369         spapr->irq = &spapr_irq_xive;
3370     } else if (strcmp(value, "dual") == 0) {
3371         spapr->irq = &spapr_irq_dual;
3372     } else {
3373         error_setg(errp, "Bad value for \"ic-mode\" property");
3374     }
3375 }
3376 
3377 static char *spapr_get_host_model(Object *obj, Error **errp)
3378 {
3379     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3380 
3381     return g_strdup(spapr->host_model);
3382 }
3383 
3384 static void spapr_set_host_model(Object *obj, const char *value, Error **errp)
3385 {
3386     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3387 
3388     g_free(spapr->host_model);
3389     spapr->host_model = g_strdup(value);
3390 }
3391 
3392 static char *spapr_get_host_serial(Object *obj, Error **errp)
3393 {
3394     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3395 
3396     return g_strdup(spapr->host_serial);
3397 }
3398 
3399 static void spapr_set_host_serial(Object *obj, const char *value, Error **errp)
3400 {
3401     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3402 
3403     g_free(spapr->host_serial);
3404     spapr->host_serial = g_strdup(value);
3405 }
3406 
3407 static void spapr_instance_init(Object *obj)
3408 {
3409     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3410     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
3411     MachineState *ms = MACHINE(spapr);
3412     MachineClass *mc = MACHINE_GET_CLASS(ms);
3413 
3414     /*
3415      * NVDIMM support went live in 5.1 without considering that, in
3416      * other archs, the user needs to enable NVDIMM support with the
3417      * 'nvdimm' machine option and the default behavior is NVDIMM
3418      * support disabled. It is too late to roll back to the standard
3419      * behavior without breaking 5.1 guests.
3420      */
3421     if (mc->nvdimm_supported) {
3422         ms->nvdimms_state->is_enabled = true;
3423     }
3424 
3425     spapr->htab_fd = -1;
3426     spapr->use_hotplug_event_source = true;
3427     spapr->kvm_type = g_strdup(DEFAULT_KVM_TYPE);
3428     object_property_add_str(obj, "kvm-type",
3429                             spapr_get_kvm_type, spapr_set_kvm_type);
3430     object_property_set_description(obj, "kvm-type",
3431                                     "Specifies the KVM virtualization mode (auto,"
3432                                     " hv, pr). Defaults to 'auto'. This mode will use"
3433                                     " any available KVM module loaded in the host,"
3434                                     " where kvm_hv takes precedence if both kvm_hv and"
3435                                     " kvm_pr are loaded.");
3436     object_property_add_bool(obj, "modern-hotplug-events",
3437                             spapr_get_modern_hotplug_events,
3438                             spapr_set_modern_hotplug_events);
3439     object_property_set_description(obj, "modern-hotplug-events",
3440                                     "Use dedicated hotplug event mechanism in"
3441                                     " place of standard EPOW events when possible"
3442                                     " (required for memory hot-unplug support)");
3443     ppc_compat_add_property(obj, "max-cpu-compat", &spapr->max_compat_pvr,
3444                             "Maximum permitted CPU compatibility mode");
3445 
3446     object_property_add_str(obj, "resize-hpt",
3447                             spapr_get_resize_hpt, spapr_set_resize_hpt);
3448     object_property_set_description(obj, "resize-hpt",
3449                                     "Resizing of the Hash Page Table (enabled, disabled, required)");
3450     object_property_add_uint32_ptr(obj, "vsmt",
3451                                    &spapr->vsmt, OBJ_PROP_FLAG_READWRITE);
3452     object_property_set_description(obj, "vsmt",
3453                                     "Virtual SMT: KVM behaves as if this were"
3454                                     " the host's SMT mode");
3455 
3456     object_property_add_bool(obj, "vfio-no-msix-emulation",
3457                              spapr_get_msix_emulation, NULL);
3458 
3459     object_property_add_uint64_ptr(obj, "kernel-addr",
3460                                    &spapr->kernel_addr, OBJ_PROP_FLAG_READWRITE);
3461     object_property_set_description(obj, "kernel-addr",
3462                                     stringify(KERNEL_LOAD_ADDR)
3463                                     " for -kernel is the default");
3464     spapr->kernel_addr = KERNEL_LOAD_ADDR;
3465 
3466     object_property_add_bool(obj, "x-vof", spapr_get_vof, spapr_set_vof);
3467     object_property_set_description(obj, "x-vof",
3468                                     "Enable Virtual Open Firmware (experimental)");
3469 
3470     /* The machine class defines the default interrupt controller mode */
3471     spapr->irq = smc->irq;
3472     object_property_add_str(obj, "ic-mode", spapr_get_ic_mode,
3473                             spapr_set_ic_mode);
3474     object_property_set_description(obj, "ic-mode",
3475                  "Specifies the interrupt controller mode (xics, xive, dual)");
3476 
3477     object_property_add_str(obj, "host-model",
3478         spapr_get_host_model, spapr_set_host_model);
3479     object_property_set_description(obj, "host-model",
3480         "Host model to advertise in guest device tree");
3481     object_property_add_str(obj, "host-serial",
3482         spapr_get_host_serial, spapr_set_host_serial);
3483     object_property_set_description(obj, "host-serial",
3484         "Host serial number to advertise in guest device tree");
3485 }
3486 
3487 static void spapr_machine_finalizefn(Object *obj)
3488 {
3489     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
3490 
3491     g_free(spapr->kvm_type);
3492 }
3493 
3494 void spapr_do_system_reset_on_cpu(CPUState *cs, run_on_cpu_data arg)
3495 {
3496     SpaprMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
3497     CPUPPCState *env = cpu_env(cs);
3498 
3499     cpu_synchronize_state(cs);
3500     /* If FWNMI is inactive, addr will be -1, which will deliver to 0x100 */
3501     if (spapr->fwnmi_system_reset_addr != -1) {
3502         uint64_t rtas_addr, addr;
3503 
3504         /* get rtas addr from fdt */
3505         rtas_addr = spapr_get_rtas_addr();
3506         if (!rtas_addr) {
3507             qemu_system_guest_panicked(NULL);
3508             return;
3509         }
3510 
3511         addr = rtas_addr + RTAS_ERROR_LOG_MAX + cs->cpu_index * sizeof(uint64_t)*2;
3512         stq_be_phys(&address_space_memory, addr, env->gpr[3]);
3513         stq_be_phys(&address_space_memory, addr + sizeof(uint64_t), 0);
3514         env->gpr[3] = addr;
3515     }
3516     ppc_cpu_do_system_reset(cs);
3517     if (spapr->fwnmi_system_reset_addr != -1) {
3518         env->nip = spapr->fwnmi_system_reset_addr;
3519     }
3520 }
3521 
3522 static void spapr_nmi(NMIState *n, int cpu_index, Error **errp)
3523 {
3524     CPUState *cs;
3525 
3526     CPU_FOREACH(cs) {
3527         async_run_on_cpu(cs, spapr_do_system_reset_on_cpu, RUN_ON_CPU_NULL);
3528     }
3529 }
3530 
3531 int spapr_lmb_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
3532                           void *fdt, int *fdt_start_offset, Error **errp)
3533 {
3534     uint64_t addr;
3535     uint32_t node;
3536 
3537     addr = spapr_drc_index(drc) * SPAPR_MEMORY_BLOCK_SIZE;
3538     node = object_property_get_uint(OBJECT(drc->dev), PC_DIMM_NODE_PROP,
3539                                     &error_abort);
3540     *fdt_start_offset = spapr_dt_memory_node(spapr, fdt, node, addr,
3541                                              SPAPR_MEMORY_BLOCK_SIZE);
3542     return 0;
3543 }
3544 
3545 static void spapr_add_lmbs(DeviceState *dev, uint64_t addr_start, uint64_t size,
3546                            bool dedicated_hp_event_source)
3547 {
3548     SpaprDrc *drc;
3549     uint32_t nr_lmbs = size/SPAPR_MEMORY_BLOCK_SIZE;
3550     int i;
3551     uint64_t addr = addr_start;
3552     bool hotplugged = spapr_drc_hotplugged(dev);
3553 
3554     for (i = 0; i < nr_lmbs; i++) {
3555         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3556                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3557         g_assert(drc);
3558 
3559         /*
3560          * memory_device_get_free_addr() provided a range of free addresses
3561          * that doesn't overlap with any existing mapping at pre-plug. The
3562          * corresponding LMB DRCs are thus assumed to be all attachable.
3563          */
3564         spapr_drc_attach(drc, dev);
3565         if (!hotplugged) {
3566             spapr_drc_reset(drc);
3567         }
3568         addr += SPAPR_MEMORY_BLOCK_SIZE;
3569     }
3570     /* send hotplug notification to the
3571      * guest only in case of hotplugged memory
3572      */
3573     if (hotplugged) {
3574         if (dedicated_hp_event_source) {
3575             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3576                                   addr_start / SPAPR_MEMORY_BLOCK_SIZE);
3577             g_assert(drc);
3578             spapr_hotplug_req_add_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
3579                                                    nr_lmbs,
3580                                                    spapr_drc_index(drc));
3581         } else {
3582             spapr_hotplug_req_add_by_count(SPAPR_DR_CONNECTOR_TYPE_LMB,
3583                                            nr_lmbs);
3584         }
3585     }
3586 }
3587 
3588 static void spapr_memory_plug(HotplugHandler *hotplug_dev, DeviceState *dev)
3589 {
3590     SpaprMachineState *ms = SPAPR_MACHINE(hotplug_dev);
3591     PCDIMMDevice *dimm = PC_DIMM(dev);
3592     uint64_t size, addr;
3593     int64_t slot;
3594     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
3595 
3596     size = memory_device_get_region_size(MEMORY_DEVICE(dev), &error_abort);
3597 
3598     pc_dimm_plug(dimm, MACHINE(ms));
3599 
3600     if (!is_nvdimm) {
3601         addr = object_property_get_uint(OBJECT(dimm),
3602                                         PC_DIMM_ADDR_PROP, &error_abort);
3603         spapr_add_lmbs(dev, addr, size,
3604                        spapr_ovec_test(ms->ov5_cas, OV5_HP_EVT));
3605     } else {
3606         slot = object_property_get_int(OBJECT(dimm),
3607                                        PC_DIMM_SLOT_PROP, &error_abort);
3608         /* We should have valid slot number at this point */
3609         g_assert(slot >= 0);
3610         spapr_add_nvdimm(dev, slot);
3611     }
3612 }
3613 
3614 static void spapr_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3615                                   Error **errp)
3616 {
3617     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3618     bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);
3619     PCDIMMDevice *dimm = PC_DIMM(dev);
3620     Error *local_err = NULL;
3621     uint64_t size;
3622     Object *memdev;
3623     hwaddr pagesize;
3624 
3625     size = memory_device_get_region_size(MEMORY_DEVICE(dimm), &local_err);
3626     if (local_err) {
3627         error_propagate(errp, local_err);
3628         return;
3629     }
3630 
3631     if (is_nvdimm) {
3632         if (!spapr_nvdimm_validate(hotplug_dev, NVDIMM(dev), size, errp)) {
3633             return;
3634         }
3635     } else if (size % SPAPR_MEMORY_BLOCK_SIZE) {
3636         error_setg(errp, "Hotplugged memory size must be a multiple of "
3637                    "%" PRIu64 " MB", SPAPR_MEMORY_BLOCK_SIZE / MiB);
3638         return;
3639     }
3640 
3641     memdev = object_property_get_link(OBJECT(dimm), PC_DIMM_MEMDEV_PROP,
3642                                       &error_abort);
3643     pagesize = host_memory_backend_pagesize(MEMORY_BACKEND(memdev));
3644     if (!spapr_check_pagesize(spapr, pagesize, errp)) {
3645         return;
3646     }
3647 
3648     pc_dimm_pre_plug(dimm, MACHINE(hotplug_dev), errp);
3649 }
3650 
3651 struct SpaprDimmState {
3652     PCDIMMDevice *dimm;
3653     uint32_t nr_lmbs;
3654     QTAILQ_ENTRY(SpaprDimmState) next;
3655 };
3656 
3657 static SpaprDimmState *spapr_pending_dimm_unplugs_find(SpaprMachineState *s,
3658                                                        PCDIMMDevice *dimm)
3659 {
3660     SpaprDimmState *dimm_state = NULL;
3661 
3662     QTAILQ_FOREACH(dimm_state, &s->pending_dimm_unplugs, next) {
3663         if (dimm_state->dimm == dimm) {
3664             break;
3665         }
3666     }
3667     return dimm_state;
3668 }
3669 
3670 static SpaprDimmState *spapr_pending_dimm_unplugs_add(SpaprMachineState *spapr,
3671                                                       uint32_t nr_lmbs,
3672                                                       PCDIMMDevice *dimm)
3673 {
3674     SpaprDimmState *ds = NULL;
3675 
3676     /*
3677      * If this request is for a DIMM whose removal had failed earlier
3678      * (due to guest's refusal to remove the LMBs), we would have this
3679      * dimm already in the pending_dimm_unplugs list. In that
3680      * case don't add again.
3681      */
3682     ds = spapr_pending_dimm_unplugs_find(spapr, dimm);
3683     if (!ds) {
3684         ds = g_new0(SpaprDimmState, 1);
3685         ds->nr_lmbs = nr_lmbs;
3686         ds->dimm = dimm;
3687         QTAILQ_INSERT_HEAD(&spapr->pending_dimm_unplugs, ds, next);
3688     }
3689     return ds;
3690 }
3691 
3692 static void spapr_pending_dimm_unplugs_remove(SpaprMachineState *spapr,
3693                                               SpaprDimmState *dimm_state)
3694 {
3695     QTAILQ_REMOVE(&spapr->pending_dimm_unplugs, dimm_state, next);
3696     g_free(dimm_state);
3697 }
3698 
3699 static SpaprDimmState *spapr_recover_pending_dimm_state(SpaprMachineState *ms,
3700                                                         PCDIMMDevice *dimm)
3701 {
3702     SpaprDrc *drc;
3703     uint64_t size = memory_device_get_region_size(MEMORY_DEVICE(dimm),
3704                                                   &error_abort);
3705     uint32_t nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3706     uint32_t avail_lmbs = 0;
3707     uint64_t addr_start, addr;
3708     int i;
3709 
3710     addr_start = object_property_get_uint(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3711                                           &error_abort);
3712 
3713     addr = addr_start;
3714     for (i = 0; i < nr_lmbs; i++) {
3715         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3716                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3717         g_assert(drc);
3718         if (drc->dev) {
3719             avail_lmbs++;
3720         }
3721         addr += SPAPR_MEMORY_BLOCK_SIZE;
3722     }
3723 
3724     return spapr_pending_dimm_unplugs_add(ms, avail_lmbs, dimm);
3725 }
3726 
3727 void spapr_memory_unplug_rollback(SpaprMachineState *spapr, DeviceState *dev)
3728 {
3729     SpaprDimmState *ds;
3730     PCDIMMDevice *dimm;
3731     SpaprDrc *drc;
3732     uint32_t nr_lmbs;
3733     uint64_t size, addr_start, addr;
3734     int i;
3735 
3736     if (!dev) {
3737         return;
3738     }
3739 
3740     dimm = PC_DIMM(dev);
3741     ds = spapr_pending_dimm_unplugs_find(spapr, dimm);
3742 
3743     /*
3744      * 'ds == NULL' would mean that the DIMM doesn't have a pending
3745      * unplug state, but one of its DRC is marked as unplug_requested.
3746      * This is bad and weird enough to g_assert() out.
3747      */
3748     g_assert(ds);
3749 
3750     spapr_pending_dimm_unplugs_remove(spapr, ds);
3751 
3752     size = memory_device_get_region_size(MEMORY_DEVICE(dimm), &error_abort);
3753     nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3754 
3755     addr_start = object_property_get_uint(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3756                                           &error_abort);
3757 
3758     addr = addr_start;
3759     for (i = 0; i < nr_lmbs; i++) {
3760         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3761                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3762         g_assert(drc);
3763 
3764         drc->unplug_requested = false;
3765         addr += SPAPR_MEMORY_BLOCK_SIZE;
3766     }
3767 
3768     /*
3769      * Tell QAPI that something happened and the memory
3770      * hotunplug wasn't successful.
3771      */
3772     qapi_event_send_device_unplug_guest_error(dev->id,
3773                                               dev->canonical_path);
3774 }
3775 
3776 /* Callback to be called during DRC release. */
3777 void spapr_lmb_release(DeviceState *dev)
3778 {
3779     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
3780     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_ctrl);
3781     SpaprDimmState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));
3782 
3783     /* This information will get lost if a migration occurs
3784      * during the unplug process. In this case recover it. */
3785     if (ds == NULL) {
3786         ds = spapr_recover_pending_dimm_state(spapr, PC_DIMM(dev));
3787         g_assert(ds);
3788         /* The DRC being examined by the caller at least must be counted */
3789         g_assert(ds->nr_lmbs);
3790     }
3791 
3792     if (--ds->nr_lmbs) {
3793         return;
3794     }
3795 
3796     /*
3797      * Now that all the LMBs have been removed by the guest, call the
3798      * unplug handler chain. This can never fail.
3799      */
3800     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
3801     object_unparent(OBJECT(dev));
3802 }
3803 
3804 static void spapr_memory_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3805 {
3806     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3807     SpaprDimmState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));
3808 
3809     /* We really shouldn't get this far without anything to unplug */
3810     g_assert(ds);
3811 
3812     pc_dimm_unplug(PC_DIMM(dev), MACHINE(hotplug_dev));
3813     qdev_unrealize(dev);
3814     spapr_pending_dimm_unplugs_remove(spapr, ds);
3815 }
3816 
3817 static void spapr_memory_unplug_request(HotplugHandler *hotplug_dev,
3818                                         DeviceState *dev, Error **errp)
3819 {
3820     SpaprMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3821     PCDIMMDevice *dimm = PC_DIMM(dev);
3822     uint32_t nr_lmbs;
3823     uint64_t size, addr_start, addr;
3824     int i;
3825     SpaprDrc *drc;
3826 
3827     if (object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM)) {
3828         error_setg(errp, "nvdimm device hot unplug is not supported yet.");
3829         return;
3830     }
3831 
3832     size = memory_device_get_region_size(MEMORY_DEVICE(dimm), &error_abort);
3833     nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3834 
3835     addr_start = object_property_get_uint(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3836                                           &error_abort);
3837 
3838     /*
3839      * An existing pending dimm state for this DIMM means that there is an
3840      * unplug operation in progress, waiting for the spapr_lmb_release
3841      * callback to complete the job (BQL can't cover that far). In this case,
3842      * bail out to avoid detaching DRCs that were already released.
3843      */
3844     if (spapr_pending_dimm_unplugs_find(spapr, dimm)) {
3845         error_setg(errp, "Memory unplug already in progress for device %s",
3846                    dev->id);
3847         return;
3848     }
3849 
3850     spapr_pending_dimm_unplugs_add(spapr, nr_lmbs, dimm);
3851 
3852     addr = addr_start;
3853     for (i = 0; i < nr_lmbs; i++) {
3854         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3855                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3856         g_assert(drc);
3857 
3858         spapr_drc_unplug_request(drc);
3859         addr += SPAPR_MEMORY_BLOCK_SIZE;
3860     }
3861 
3862     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3863                           addr_start / SPAPR_MEMORY_BLOCK_SIZE);
3864     spapr_hotplug_req_remove_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
3865                                               nr_lmbs, spapr_drc_index(drc));
3866 }
3867 
3868 /* Callback to be called during DRC release. */
3869 void spapr_core_release(DeviceState *dev)
3870 {
3871     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
3872 
3873     /* Call the unplug handler chain. This can never fail. */
3874     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
3875     object_unparent(OBJECT(dev));
3876 }
3877 
3878 static void spapr_core_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
3879 {
3880     MachineState *ms = MACHINE(hotplug_dev);
3881     CPUCore *cc = CPU_CORE(dev);
3882     CPUArchId *core_slot = spapr_find_cpu_slot(ms, cc->core_id, NULL);
3883 
3884     assert(core_slot);
3885     core_slot->cpu = NULL;
3886     qdev_unrealize(dev);
3887 }
3888 
3889 static
3890 void spapr_core_unplug_request(HotplugHandler *hotplug_dev, DeviceState *dev,
3891                                Error **errp)
3892 {
3893     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3894     int index;
3895     SpaprDrc *drc;
3896     CPUCore *cc = CPU_CORE(dev);
3897 
3898     if (!spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index)) {
3899         error_setg(errp, "Unable to find CPU core with core-id: %d",
3900                    cc->core_id);
3901         return;
3902     }
3903     if (index == 0) {
3904         error_setg(errp, "Boot CPU core may not be unplugged");
3905         return;
3906     }
3907 
3908     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU,
3909                           spapr_vcpu_id(spapr, cc->core_id));
3910     g_assert(drc);
3911 
3912     if (!spapr_drc_unplug_requested(drc)) {
3913         spapr_drc_unplug_request(drc);
3914     }
3915 
3916     /*
3917      * spapr_hotplug_req_remove_by_index is left unguarded, out of the
3918      * "!spapr_drc_unplug_requested" check, to allow for multiple IRQ
3919      * pulses removing the same CPU. Otherwise, in an failed hotunplug
3920      * attempt (e.g. the kernel will refuse to remove the last online
3921      * CPU), we will never attempt it again because unplug_requested
3922      * will still be 'true' in that case.
3923      */
3924     spapr_hotplug_req_remove_by_index(drc);
3925 }
3926 
3927 int spapr_core_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
3928                            void *fdt, int *fdt_start_offset, Error **errp)
3929 {
3930     SpaprCpuCore *core = SPAPR_CPU_CORE(drc->dev);
3931     CPUState *cs = CPU(core->threads[0]);
3932     PowerPCCPU *cpu = POWERPC_CPU(cs);
3933     DeviceClass *dc = DEVICE_GET_CLASS(cs);
3934     int id = spapr_get_vcpu_id(cpu);
3935     g_autofree char *nodename = NULL;
3936     int offset;
3937 
3938     nodename = g_strdup_printf("%s@%x", dc->fw_name, id);
3939     offset = fdt_add_subnode(fdt, 0, nodename);
3940 
3941     spapr_dt_cpu(cs, fdt, offset, spapr);
3942 
3943     /*
3944      * spapr_dt_cpu() does not fill the 'name' property in the
3945      * CPU node. The function is called during boot process, before
3946      * and after CAS, and overwriting the 'name' property written
3947      * by SLOF is not allowed.
3948      *
3949      * Write it manually after spapr_dt_cpu(). This makes the hotplug
3950      * CPUs more compatible with the coldplugged ones, which have
3951      * the 'name' property. Linux Kernel also relies on this
3952      * property to identify CPU nodes.
3953      */
3954     _FDT((fdt_setprop_string(fdt, offset, "name", nodename)));
3955 
3956     *fdt_start_offset = offset;
3957     return 0;
3958 }
3959 
3960 static void spapr_core_plug(HotplugHandler *hotplug_dev, DeviceState *dev)
3961 {
3962     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3963     MachineClass *mc = MACHINE_GET_CLASS(spapr);
3964     SpaprCpuCore *core = SPAPR_CPU_CORE(OBJECT(dev));
3965     CPUCore *cc = CPU_CORE(dev);
3966     SpaprDrc *drc;
3967     CPUArchId *core_slot;
3968     int index;
3969     bool hotplugged = spapr_drc_hotplugged(dev);
3970     int i;
3971 
3972     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
3973     g_assert(core_slot); /* Already checked in spapr_core_pre_plug() */
3974 
3975     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU,
3976                           spapr_vcpu_id(spapr, cc->core_id));
3977 
3978     g_assert(drc || !mc->has_hotpluggable_cpus);
3979 
3980     if (drc) {
3981         /*
3982          * spapr_core_pre_plug() already buys us this is a brand new
3983          * core being plugged into a free slot. Nothing should already
3984          * be attached to the corresponding DRC.
3985          */
3986         spapr_drc_attach(drc, dev);
3987 
3988         if (hotplugged) {
3989             /*
3990              * Send hotplug notification interrupt to the guest only
3991              * in case of hotplugged CPUs.
3992              */
3993             spapr_hotplug_req_add_by_index(drc);
3994         } else {
3995             spapr_drc_reset(drc);
3996         }
3997     }
3998 
3999     core_slot->cpu = CPU(dev);
4000 
4001     /*
4002      * Set compatibility mode to match the boot CPU, which was either set
4003      * by the machine reset code or by CAS. This really shouldn't fail at
4004      * this point.
4005      */
4006     if (hotplugged) {
4007         for (i = 0; i < cc->nr_threads; i++) {
4008             ppc_set_compat(core->threads[i], POWERPC_CPU(first_cpu)->compat_pvr,
4009                            &error_abort);
4010         }
4011     }
4012 
4013 }
4014 
4015 static void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
4016                                 Error **errp)
4017 {
4018     MachineState *machine = MACHINE(OBJECT(hotplug_dev));
4019     MachineClass *mc = MACHINE_GET_CLASS(hotplug_dev);
4020     CPUCore *cc = CPU_CORE(dev);
4021     const char *base_core_type = spapr_get_cpu_core_type(machine->cpu_type);
4022     const char *type = object_get_typename(OBJECT(dev));
4023     CPUArchId *core_slot;
4024     int index;
4025     unsigned int smp_threads = machine->smp.threads;
4026 
4027     if (dev->hotplugged && !mc->has_hotpluggable_cpus) {
4028         error_setg(errp, "CPU hotplug not supported for this machine");
4029         return;
4030     }
4031 
4032     if (strcmp(base_core_type, type)) {
4033         error_setg(errp, "CPU core type should be %s", base_core_type);
4034         return;
4035     }
4036 
4037     if (cc->core_id % smp_threads) {
4038         error_setg(errp, "invalid core id %d", cc->core_id);
4039         return;
4040     }
4041 
4042     /*
4043      * In general we should have homogeneous threads-per-core, but old
4044      * (pre hotplug support) machine types allow the last core to have
4045      * reduced threads as a compatibility hack for when we allowed
4046      * total vcpus not a multiple of threads-per-core.
4047      */
4048     if (mc->has_hotpluggable_cpus && (cc->nr_threads != smp_threads)) {
4049         error_setg(errp, "invalid nr-threads %d, must be %d", cc->nr_threads,
4050                    smp_threads);
4051         return;
4052     }
4053 
4054     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
4055     if (!core_slot) {
4056         error_setg(errp, "core id %d out of range", cc->core_id);
4057         return;
4058     }
4059 
4060     if (core_slot->cpu) {
4061         error_setg(errp, "core %d already populated", cc->core_id);
4062         return;
4063     }
4064 
4065     numa_cpu_pre_plug(core_slot, dev, errp);
4066 }
4067 
4068 int spapr_phb_dt_populate(SpaprDrc *drc, SpaprMachineState *spapr,
4069                           void *fdt, int *fdt_start_offset, Error **errp)
4070 {
4071     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(drc->dev);
4072     int intc_phandle;
4073 
4074     intc_phandle = spapr_irq_get_phandle(spapr, spapr->fdt_blob, errp);
4075     if (intc_phandle <= 0) {
4076         return -1;
4077     }
4078 
4079     if (spapr_dt_phb(spapr, sphb, intc_phandle, fdt, fdt_start_offset)) {
4080         error_setg(errp, "unable to create FDT node for PHB %d", sphb->index);
4081         return -1;
4082     }
4083 
4084     /* generally SLOF creates these, for hotplug it's up to QEMU */
4085     _FDT(fdt_setprop_string(fdt, *fdt_start_offset, "name", "pci"));
4086 
4087     return 0;
4088 }
4089 
4090 static bool spapr_phb_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
4091                                Error **errp)
4092 {
4093     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
4094     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
4095     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
4096     const unsigned windows_supported = spapr_phb_windows_supported(sphb);
4097     SpaprDrc *drc;
4098 
4099     if (dev->hotplugged && !smc->dr_phb_enabled) {
4100         error_setg(errp, "PHB hotplug not supported for this machine");
4101         return false;
4102     }
4103 
4104     if (sphb->index == (uint32_t)-1) {
4105         error_setg(errp, "\"index\" for PAPR PHB is mandatory");
4106         return false;
4107     }
4108 
4109     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_PHB, sphb->index);
4110     if (drc && drc->dev) {
4111         error_setg(errp, "PHB %d already attached", sphb->index);
4112         return false;
4113     }
4114 
4115     /*
4116      * This will check that sphb->index doesn't exceed the maximum number of
4117      * PHBs for the current machine type.
4118      */
4119     return
4120         smc->phb_placement(spapr, sphb->index,
4121                            &sphb->buid, &sphb->io_win_addr,
4122                            &sphb->mem_win_addr, &sphb->mem64_win_addr,
4123                            windows_supported, sphb->dma_liobn,
4124                            errp);
4125 }
4126 
4127 static void spapr_phb_plug(HotplugHandler *hotplug_dev, DeviceState *dev)
4128 {
4129     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
4130     SpaprMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
4131     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
4132     SpaprDrc *drc;
4133     bool hotplugged = spapr_drc_hotplugged(dev);
4134 
4135     if (!smc->dr_phb_enabled) {
4136         return;
4137     }
4138 
4139     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_PHB, sphb->index);
4140     /* hotplug hooks should check it's enabled before getting this far */
4141     assert(drc);
4142 
4143     /* spapr_phb_pre_plug() already checked the DRC is attachable */
4144     spapr_drc_attach(drc, dev);
4145 
4146     if (hotplugged) {
4147         spapr_hotplug_req_add_by_index(drc);
4148     } else {
4149         spapr_drc_reset(drc);
4150     }
4151 }
4152 
4153 void spapr_phb_release(DeviceState *dev)
4154 {
4155     HotplugHandler *hotplug_ctrl = qdev_get_hotplug_handler(dev);
4156 
4157     hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);
4158     object_unparent(OBJECT(dev));
4159 }
4160 
4161 static void spapr_phb_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
4162 {
4163     qdev_unrealize(dev);
4164 }
4165 
4166 static void spapr_phb_unplug_request(HotplugHandler *hotplug_dev,
4167                                      DeviceState *dev, Error **errp)
4168 {
4169     SpaprPhbState *sphb = SPAPR_PCI_HOST_BRIDGE(dev);
4170     SpaprDrc *drc;
4171 
4172     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_PHB, sphb->index);
4173     assert(drc);
4174 
4175     if (!spapr_drc_unplug_requested(drc)) {
4176         spapr_drc_unplug_request(drc);
4177         spapr_hotplug_req_remove_by_index(drc);
4178     } else {
4179         error_setg(errp,
4180                    "PCI Host Bridge unplug already in progress for device %s",
4181                    dev->id);
4182     }
4183 }
4184 
4185 static
4186 bool spapr_tpm_proxy_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
4187                               Error **errp)
4188 {
4189     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
4190 
4191     if (spapr->tpm_proxy != NULL) {
4192         error_setg(errp, "Only one TPM proxy can be specified for this machine");
4193         return false;
4194     }
4195 
4196     return true;
4197 }
4198 
4199 static void spapr_tpm_proxy_plug(HotplugHandler *hotplug_dev, DeviceState *dev)
4200 {
4201     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
4202     SpaprTpmProxy *tpm_proxy = SPAPR_TPM_PROXY(dev);
4203 
4204     /* Already checked in spapr_tpm_proxy_pre_plug() */
4205     g_assert(spapr->tpm_proxy == NULL);
4206 
4207     spapr->tpm_proxy = tpm_proxy;
4208 }
4209 
4210 static void spapr_tpm_proxy_unplug(HotplugHandler *hotplug_dev, DeviceState *dev)
4211 {
4212     SpaprMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
4213 
4214     qdev_unrealize(dev);
4215     object_unparent(OBJECT(dev));
4216     spapr->tpm_proxy = NULL;
4217 }
4218 
4219 static void spapr_machine_device_plug(HotplugHandler *hotplug_dev,
4220                                       DeviceState *dev, Error **errp)
4221 {
4222     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4223         spapr_memory_plug(hotplug_dev, dev);
4224     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4225         spapr_core_plug(hotplug_dev, dev);
4226     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4227         spapr_phb_plug(hotplug_dev, dev);
4228     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4229         spapr_tpm_proxy_plug(hotplug_dev, dev);
4230     }
4231 }
4232 
4233 static void spapr_machine_device_unplug(HotplugHandler *hotplug_dev,
4234                                         DeviceState *dev, Error **errp)
4235 {
4236     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4237         spapr_memory_unplug(hotplug_dev, dev);
4238     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4239         spapr_core_unplug(hotplug_dev, dev);
4240     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4241         spapr_phb_unplug(hotplug_dev, dev);
4242     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4243         spapr_tpm_proxy_unplug(hotplug_dev, dev);
4244     }
4245 }
4246 
4247 bool spapr_memory_hot_unplug_supported(SpaprMachineState *spapr)
4248 {
4249     return spapr_ovec_test(spapr->ov5_cas, OV5_HP_EVT) ||
4250         /*
4251          * CAS will process all pending unplug requests.
4252          *
4253          * HACK: a guest could theoretically have cleared all bits in OV5,
4254          * but none of the guests we care for do.
4255          */
4256         spapr_ovec_empty(spapr->ov5_cas);
4257 }
4258 
4259 static void spapr_machine_device_unplug_request(HotplugHandler *hotplug_dev,
4260                                                 DeviceState *dev, Error **errp)
4261 {
4262     SpaprMachineState *sms = SPAPR_MACHINE(OBJECT(hotplug_dev));
4263     MachineClass *mc = MACHINE_GET_CLASS(sms);
4264     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4265 
4266     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4267         if (spapr_memory_hot_unplug_supported(sms)) {
4268             spapr_memory_unplug_request(hotplug_dev, dev, errp);
4269         } else {
4270             error_setg(errp, "Memory hot unplug not supported for this guest");
4271         }
4272     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4273         if (!mc->has_hotpluggable_cpus) {
4274             error_setg(errp, "CPU hot unplug not supported on this machine");
4275             return;
4276         }
4277         spapr_core_unplug_request(hotplug_dev, dev, errp);
4278     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4279         if (!smc->dr_phb_enabled) {
4280             error_setg(errp, "PHB hot unplug not supported on this machine");
4281             return;
4282         }
4283         spapr_phb_unplug_request(hotplug_dev, dev, errp);
4284     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4285         spapr_tpm_proxy_unplug(hotplug_dev, dev);
4286     }
4287 }
4288 
4289 static void spapr_machine_device_pre_plug(HotplugHandler *hotplug_dev,
4290                                           DeviceState *dev, Error **errp)
4291 {
4292     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
4293         spapr_memory_pre_plug(hotplug_dev, dev, errp);
4294     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
4295         spapr_core_pre_plug(hotplug_dev, dev, errp);
4296     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
4297         spapr_phb_pre_plug(hotplug_dev, dev, errp);
4298     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4299         spapr_tpm_proxy_pre_plug(hotplug_dev, dev, errp);
4300     }
4301 }
4302 
4303 static HotplugHandler *spapr_get_hotplug_handler(MachineState *machine,
4304                                                  DeviceState *dev)
4305 {
4306     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
4307         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE) ||
4308         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_PCI_HOST_BRIDGE) ||
4309         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_TPM_PROXY)) {
4310         return HOTPLUG_HANDLER(machine);
4311     }
4312     if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
4313         PCIDevice *pcidev = PCI_DEVICE(dev);
4314         PCIBus *root = pci_device_root_bus(pcidev);
4315         SpaprPhbState *phb =
4316             (SpaprPhbState *)object_dynamic_cast(OBJECT(BUS(root)->parent),
4317                                                  TYPE_SPAPR_PCI_HOST_BRIDGE);
4318 
4319         if (phb) {
4320             return HOTPLUG_HANDLER(phb);
4321         }
4322     }
4323     return NULL;
4324 }
4325 
4326 static CpuInstanceProperties
4327 spapr_cpu_index_to_props(MachineState *machine, unsigned cpu_index)
4328 {
4329     CPUArchId *core_slot;
4330     MachineClass *mc = MACHINE_GET_CLASS(machine);
4331 
4332     /* make sure possible_cpu are initialized */
4333     mc->possible_cpu_arch_ids(machine);
4334     /* get CPU core slot containing thread that matches cpu_index */
4335     core_slot = spapr_find_cpu_slot(machine, cpu_index, NULL);
4336     assert(core_slot);
4337     return core_slot->props;
4338 }
4339 
4340 static int64_t spapr_get_default_cpu_node_id(const MachineState *ms, int idx)
4341 {
4342     return idx / ms->smp.cores % ms->numa_state->num_nodes;
4343 }
4344 
4345 static const CPUArchIdList *spapr_possible_cpu_arch_ids(MachineState *machine)
4346 {
4347     int i;
4348     unsigned int smp_threads = machine->smp.threads;
4349     unsigned int smp_cpus = machine->smp.cpus;
4350     const char *core_type;
4351     int spapr_max_cores = machine->smp.max_cpus / smp_threads;
4352     MachineClass *mc = MACHINE_GET_CLASS(machine);
4353 
4354     if (!mc->has_hotpluggable_cpus) {
4355         spapr_max_cores = QEMU_ALIGN_UP(smp_cpus, smp_threads) / smp_threads;
4356     }
4357     if (machine->possible_cpus) {
4358         assert(machine->possible_cpus->len == spapr_max_cores);
4359         return machine->possible_cpus;
4360     }
4361 
4362     core_type = spapr_get_cpu_core_type(machine->cpu_type);
4363     if (!core_type) {
4364         error_report("Unable to find sPAPR CPU Core definition");
4365         exit(1);
4366     }
4367 
4368     machine->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
4369                              sizeof(CPUArchId) * spapr_max_cores);
4370     machine->possible_cpus->len = spapr_max_cores;
4371     for (i = 0; i < machine->possible_cpus->len; i++) {
4372         int core_id = i * smp_threads;
4373 
4374         machine->possible_cpus->cpus[i].type = core_type;
4375         machine->possible_cpus->cpus[i].vcpus_count = smp_threads;
4376         machine->possible_cpus->cpus[i].arch_id = core_id;
4377         machine->possible_cpus->cpus[i].props.has_core_id = true;
4378         machine->possible_cpus->cpus[i].props.core_id = core_id;
4379     }
4380     return machine->possible_cpus;
4381 }
4382 
4383 static bool spapr_phb_placement(SpaprMachineState *spapr, uint32_t index,
4384                                 uint64_t *buid, hwaddr *pio,
4385                                 hwaddr *mmio32, hwaddr *mmio64,
4386                                 unsigned n_dma, uint32_t *liobns, Error **errp)
4387 {
4388     /*
4389      * New-style PHB window placement.
4390      *
4391      * Goals: Gives large (1TiB), naturally aligned 64-bit MMIO window
4392      * for each PHB, in addition to 2GiB 32-bit MMIO and 64kiB PIO
4393      * windows.
4394      *
4395      * Some guest kernels can't work with MMIO windows above 1<<46
4396      * (64TiB), so we place up to 31 PHBs in the area 32TiB..64TiB
4397      *
4398      * 32TiB..(33TiB+1984kiB) contains the 64kiB PIO windows for each
4399      * PHB stacked together.  (32TiB+2GiB)..(32TiB+64GiB) contains the
4400      * 2GiB 32-bit MMIO windows for each PHB.  Then 33..64TiB has the
4401      * 1TiB 64-bit MMIO windows for each PHB.
4402      */
4403     const uint64_t base_buid = 0x800000020000000ULL;
4404     int i;
4405 
4406     /* Sanity check natural alignments */
4407     QEMU_BUILD_BUG_ON((SPAPR_PCI_BASE % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
4408     QEMU_BUILD_BUG_ON((SPAPR_PCI_LIMIT % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
4409     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM64_WIN_SIZE % SPAPR_PCI_MEM32_WIN_SIZE) != 0);
4410     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM32_WIN_SIZE % SPAPR_PCI_IO_WIN_SIZE) != 0);
4411     /* Sanity check bounds */
4412     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_IO_WIN_SIZE) >
4413                       SPAPR_PCI_MEM32_WIN_SIZE);
4414     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_MEM32_WIN_SIZE) >
4415                       SPAPR_PCI_MEM64_WIN_SIZE);
4416 
4417     if (index >= SPAPR_MAX_PHBS) {
4418         error_setg(errp, "\"index\" for PAPR PHB is too large (max %llu)",
4419                    SPAPR_MAX_PHBS - 1);
4420         return false;
4421     }
4422 
4423     *buid = base_buid + index;
4424     for (i = 0; i < n_dma; ++i) {
4425         liobns[i] = SPAPR_PCI_LIOBN(index, i);
4426     }
4427 
4428     *pio = SPAPR_PCI_BASE + index * SPAPR_PCI_IO_WIN_SIZE;
4429     *mmio32 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM32_WIN_SIZE;
4430     *mmio64 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM64_WIN_SIZE;
4431     return true;
4432 }
4433 
4434 static ICSState *spapr_ics_get(XICSFabric *dev, int irq)
4435 {
4436     SpaprMachineState *spapr = SPAPR_MACHINE(dev);
4437 
4438     return ics_valid_irq(spapr->ics, irq) ? spapr->ics : NULL;
4439 }
4440 
4441 static void spapr_ics_resend(XICSFabric *dev)
4442 {
4443     SpaprMachineState *spapr = SPAPR_MACHINE(dev);
4444 
4445     ics_resend(spapr->ics);
4446 }
4447 
4448 static ICPState *spapr_icp_get(XICSFabric *xi, int vcpu_id)
4449 {
4450     PowerPCCPU *cpu = spapr_find_cpu(vcpu_id);
4451 
4452     return cpu ? spapr_cpu_state(cpu)->icp : NULL;
4453 }
4454 
4455 static void spapr_pic_print_info(InterruptStatsProvider *obj, GString *buf)
4456 {
4457     SpaprMachineState *spapr = SPAPR_MACHINE(obj);
4458 
4459     spapr_irq_print_info(spapr, buf);
4460     g_string_append_printf(buf, "irqchip: %s\n",
4461                            kvm_irqchip_in_kernel() ? "in-kernel" : "emulated");
4462 }
4463 
4464 /*
4465  * This is a XIVE only operation
4466  */
4467 static int spapr_match_nvt(XiveFabric *xfb, uint8_t format,
4468                            uint8_t nvt_blk, uint32_t nvt_idx,
4469                            bool crowd, bool cam_ignore, uint8_t priority,
4470                            uint32_t logic_serv, XiveTCTXMatch *match)
4471 {
4472     SpaprMachineState *spapr = SPAPR_MACHINE(xfb);
4473     XivePresenter *xptr = XIVE_PRESENTER(spapr->active_intc);
4474     XivePresenterClass *xpc = XIVE_PRESENTER_GET_CLASS(xptr);
4475     int count;
4476 
4477     count = xpc->match_nvt(xptr, format, nvt_blk, nvt_idx, crowd, cam_ignore,
4478                            priority, logic_serv, match);
4479     if (count < 0) {
4480         return count;
4481     }
4482 
4483     /*
4484      * When we implement the save and restore of the thread interrupt
4485      * contexts in the enter/exit CPU handlers of the machine and the
4486      * escalations in QEMU, we should be able to handle non dispatched
4487      * vCPUs.
4488      *
4489      * Until this is done, the sPAPR machine should find at least one
4490      * matching context always.
4491      */
4492     if (count == 0) {
4493         qemu_log_mask(LOG_GUEST_ERROR, "XIVE: NVT %x/%x is not dispatched\n",
4494                       nvt_blk, nvt_idx);
4495     }
4496 
4497     return count;
4498 }
4499 
4500 int spapr_get_vcpu_id(PowerPCCPU *cpu)
4501 {
4502     return cpu->vcpu_id;
4503 }
4504 
4505 bool spapr_set_vcpu_id(PowerPCCPU *cpu, int cpu_index, Error **errp)
4506 {
4507     SpaprMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
4508     MachineState *ms = MACHINE(spapr);
4509     int vcpu_id;
4510 
4511     vcpu_id = spapr_vcpu_id(spapr, cpu_index);
4512 
4513     if (kvm_enabled() && !kvm_vcpu_id_is_valid(vcpu_id)) {
4514         error_setg(errp, "Can't create CPU with id %d in KVM", vcpu_id);
4515         error_append_hint(errp, "Adjust the number of cpus to %d "
4516                           "or try to raise the number of threads per core\n",
4517                           vcpu_id * ms->smp.threads / spapr->vsmt);
4518         return false;
4519     }
4520 
4521     cpu->vcpu_id = vcpu_id;
4522     return true;
4523 }
4524 
4525 PowerPCCPU *spapr_find_cpu(int vcpu_id)
4526 {
4527     CPUState *cs;
4528 
4529     CPU_FOREACH(cs) {
4530         PowerPCCPU *cpu = POWERPC_CPU(cs);
4531 
4532         if (spapr_get_vcpu_id(cpu) == vcpu_id) {
4533             return cpu;
4534         }
4535     }
4536 
4537     return NULL;
4538 }
4539 
4540 static bool spapr_cpu_in_nested(PowerPCCPU *cpu)
4541 {
4542     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
4543 
4544     return spapr_cpu->in_nested;
4545 }
4546 
4547 static void spapr_cpu_exec_enter(PPCVirtualHypervisor *vhyp, PowerPCCPU *cpu)
4548 {
4549     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
4550 
4551     /* These are only called by TCG, KVM maintains dispatch state */
4552 
4553     spapr_cpu->prod = false;
4554     if (spapr_cpu->vpa_addr) {
4555         CPUState *cs = CPU(cpu);
4556         uint32_t dispatch;
4557 
4558         dispatch = ldl_be_phys(cs->as,
4559                                spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER);
4560         dispatch++;
4561         if ((dispatch & 1) != 0) {
4562             qemu_log_mask(LOG_GUEST_ERROR,
4563                           "VPA: incorrect dispatch counter value for "
4564                           "dispatched partition %u, correcting.\n", dispatch);
4565             dispatch++;
4566         }
4567         stl_be_phys(cs->as,
4568                     spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER, dispatch);
4569     }
4570 }
4571 
4572 static void spapr_cpu_exec_exit(PPCVirtualHypervisor *vhyp, PowerPCCPU *cpu)
4573 {
4574     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
4575 
4576     if (spapr_cpu->vpa_addr) {
4577         CPUState *cs = CPU(cpu);
4578         uint32_t dispatch;
4579 
4580         dispatch = ldl_be_phys(cs->as,
4581                                spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER);
4582         dispatch++;
4583         if ((dispatch & 1) != 1) {
4584             qemu_log_mask(LOG_GUEST_ERROR,
4585                           "VPA: incorrect dispatch counter value for "
4586                           "preempted partition %u, correcting.\n", dispatch);
4587             dispatch++;
4588         }
4589         stl_be_phys(cs->as,
4590                     spapr_cpu->vpa_addr + VPA_DISPATCH_COUNTER, dispatch);
4591     }
4592 }
4593 
4594 static void spapr_machine_class_init(ObjectClass *oc, void *data)
4595 {
4596     MachineClass *mc = MACHINE_CLASS(oc);
4597     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(oc);
4598     FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);
4599     NMIClass *nc = NMI_CLASS(oc);
4600     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
4601     PPCVirtualHypervisorClass *vhc = PPC_VIRTUAL_HYPERVISOR_CLASS(oc);
4602     XICSFabricClass *xic = XICS_FABRIC_CLASS(oc);
4603     InterruptStatsProviderClass *ispc = INTERRUPT_STATS_PROVIDER_CLASS(oc);
4604     XiveFabricClass *xfc = XIVE_FABRIC_CLASS(oc);
4605     VofMachineIfClass *vmc = VOF_MACHINE_CLASS(oc);
4606 
4607     mc->desc = "pSeries Logical Partition (PAPR compliant)";
4608     mc->ignore_boot_device_suffixes = true;
4609 
4610     /*
4611      * We set up the default / latest behaviour here.  The class_init
4612      * functions for the specific versioned machine types can override
4613      * these details for backwards compatibility
4614      */
4615     mc->init = spapr_machine_init;
4616     mc->reset = spapr_machine_reset;
4617     mc->block_default_type = IF_SCSI;
4618 
4619     /*
4620      * While KVM determines max cpus in kvm_init() using kvm_max_vcpus(),
4621      * In TCG the limit is restricted by the range of CPU IPIs available.
4622      */
4623     mc->max_cpus = SPAPR_IRQ_NR_IPIS;
4624 
4625     mc->no_parallel = 1;
4626     mc->default_boot_order = "";
4627     mc->default_ram_size = 512 * MiB;
4628     mc->default_ram_id = "ppc_spapr.ram";
4629     mc->default_display = "std";
4630     mc->kvm_type = spapr_kvm_type;
4631     machine_class_allow_dynamic_sysbus_dev(mc, TYPE_SPAPR_PCI_HOST_BRIDGE);
4632     mc->pci_allow_0_address = true;
4633     assert(!mc->get_hotplug_handler);
4634     mc->get_hotplug_handler = spapr_get_hotplug_handler;
4635     hc->pre_plug = spapr_machine_device_pre_plug;
4636     hc->plug = spapr_machine_device_plug;
4637     mc->cpu_index_to_instance_props = spapr_cpu_index_to_props;
4638     mc->get_default_cpu_node_id = spapr_get_default_cpu_node_id;
4639     mc->possible_cpu_arch_ids = spapr_possible_cpu_arch_ids;
4640     hc->unplug_request = spapr_machine_device_unplug_request;
4641     hc->unplug = spapr_machine_device_unplug;
4642 
4643     smc->update_dt_enabled = true;
4644     mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("power10_v2.0");
4645     mc->has_hotpluggable_cpus = true;
4646     mc->nvdimm_supported = true;
4647     smc->resize_hpt_default = SPAPR_RESIZE_HPT_ENABLED;
4648     fwc->get_dev_path = spapr_get_fw_dev_path;
4649     nc->nmi_monitor_handler = spapr_nmi;
4650     smc->phb_placement = spapr_phb_placement;
4651     vhc->cpu_in_nested = spapr_cpu_in_nested;
4652     vhc->deliver_hv_excp = spapr_exit_nested;
4653     vhc->hypercall = emulate_spapr_hypercall;
4654     vhc->hpt_mask = spapr_hpt_mask;
4655     vhc->map_hptes = spapr_map_hptes;
4656     vhc->unmap_hptes = spapr_unmap_hptes;
4657     vhc->hpte_set_c = spapr_hpte_set_c;
4658     vhc->hpte_set_r = spapr_hpte_set_r;
4659     vhc->get_pate = spapr_get_pate;
4660     vhc->encode_hpt_for_kvm_pr = spapr_encode_hpt_for_kvm_pr;
4661     vhc->cpu_exec_enter = spapr_cpu_exec_enter;
4662     vhc->cpu_exec_exit = spapr_cpu_exec_exit;
4663     xic->ics_get = spapr_ics_get;
4664     xic->ics_resend = spapr_ics_resend;
4665     xic->icp_get = spapr_icp_get;
4666     ispc->print_info = spapr_pic_print_info;
4667     /* Force NUMA node memory size to be a multiple of
4668      * SPAPR_MEMORY_BLOCK_SIZE (256M) since that's the granularity
4669      * in which LMBs are represented and hot-added
4670      */
4671     mc->numa_mem_align_shift = 28;
4672     mc->auto_enable_numa = true;
4673 
4674     smc->default_caps.caps[SPAPR_CAP_HTM] = SPAPR_CAP_OFF;
4675     smc->default_caps.caps[SPAPR_CAP_VSX] = SPAPR_CAP_ON;
4676     smc->default_caps.caps[SPAPR_CAP_DFP] = SPAPR_CAP_ON;
4677     smc->default_caps.caps[SPAPR_CAP_CFPC] = SPAPR_CAP_WORKAROUND;
4678     smc->default_caps.caps[SPAPR_CAP_SBBC] = SPAPR_CAP_WORKAROUND;
4679     smc->default_caps.caps[SPAPR_CAP_IBS] = SPAPR_CAP_WORKAROUND;
4680     smc->default_caps.caps[SPAPR_CAP_HPT_MAXPAGESIZE] = 16; /* 64kiB */
4681     smc->default_caps.caps[SPAPR_CAP_NESTED_KVM_HV] = SPAPR_CAP_OFF;
4682     smc->default_caps.caps[SPAPR_CAP_NESTED_PAPR] = SPAPR_CAP_OFF;
4683     smc->default_caps.caps[SPAPR_CAP_LARGE_DECREMENTER] = SPAPR_CAP_ON;
4684     smc->default_caps.caps[SPAPR_CAP_CCF_ASSIST] = SPAPR_CAP_ON;
4685     smc->default_caps.caps[SPAPR_CAP_FWNMI] = SPAPR_CAP_ON;
4686     smc->default_caps.caps[SPAPR_CAP_RPT_INVALIDATE] = SPAPR_CAP_OFF;
4687     smc->default_caps.caps[SPAPR_CAP_DAWR1] = SPAPR_CAP_ON;
4688 
4689     /*
4690      * This cap specifies whether the AIL 3 mode for
4691      * H_SET_RESOURCE is supported. The default is modified
4692      * by default_caps_with_cpu().
4693      */
4694     smc->default_caps.caps[SPAPR_CAP_AIL_MODE_3] = SPAPR_CAP_ON;
4695     spapr_caps_add_properties(smc);
4696     smc->irq = &spapr_irq_dual;
4697     smc->dr_phb_enabled = true;
4698     smc->linux_pci_probe = true;
4699     smc->smp_threads_vsmt = true;
4700     smc->nr_xirqs = SPAPR_NR_XIRQS;
4701     xfc->match_nvt = spapr_match_nvt;
4702     vmc->client_architecture_support = spapr_vof_client_architecture_support;
4703     vmc->quiesce = spapr_vof_quiesce;
4704     vmc->setprop = spapr_vof_setprop;
4705 }
4706 
4707 static const TypeInfo spapr_machine_info = {
4708     .name          = TYPE_SPAPR_MACHINE,
4709     .parent        = TYPE_MACHINE,
4710     .abstract      = true,
4711     .instance_size = sizeof(SpaprMachineState),
4712     .instance_init = spapr_instance_init,
4713     .instance_finalize = spapr_machine_finalizefn,
4714     .class_size    = sizeof(SpaprMachineClass),
4715     .class_init    = spapr_machine_class_init,
4716     .interfaces = (InterfaceInfo[]) {
4717         { TYPE_FW_PATH_PROVIDER },
4718         { TYPE_NMI },
4719         { TYPE_HOTPLUG_HANDLER },
4720         { TYPE_PPC_VIRTUAL_HYPERVISOR },
4721         { TYPE_XICS_FABRIC },
4722         { TYPE_INTERRUPT_STATS_PROVIDER },
4723         { TYPE_XIVE_FABRIC },
4724         { TYPE_VOF_MACHINE_IF },
4725         { }
4726     },
4727 };
4728 
4729 static void spapr_machine_latest_class_options(MachineClass *mc)
4730 {
4731     mc->alias = "pseries";
4732     mc->is_default = true;
4733 }
4734 
4735 #define DEFINE_SPAPR_MACHINE_IMPL(latest, ...)                       \
4736     static void MACHINE_VER_SYM(class_init, spapr, __VA_ARGS__)(     \
4737         ObjectClass *oc,                                             \
4738         void *data)                                                  \
4739     {                                                                \
4740         MachineClass *mc = MACHINE_CLASS(oc);                        \
4741         MACHINE_VER_SYM(class_options, spapr, __VA_ARGS__)(mc);      \
4742         MACHINE_VER_DEPRECATION(__VA_ARGS__);                        \
4743         if (latest) {                                                \
4744             spapr_machine_latest_class_options(mc);                  \
4745         }                                                            \
4746     }                                                                \
4747     static const TypeInfo MACHINE_VER_SYM(info, spapr, __VA_ARGS__) = \
4748     {                                                                \
4749         .name = MACHINE_VER_TYPE_NAME("pseries", __VA_ARGS__),       \
4750         .parent = TYPE_SPAPR_MACHINE,                                \
4751         .class_init = MACHINE_VER_SYM(class_init, spapr, __VA_ARGS__), \
4752     };                                                               \
4753     static void MACHINE_VER_SYM(register, spapr, __VA_ARGS__)(void)  \
4754     {                                                                \
4755         MACHINE_VER_DELETION(__VA_ARGS__);                           \
4756         type_register_static(&MACHINE_VER_SYM(info, spapr, __VA_ARGS__));   \
4757     }                                                                \
4758     type_init(MACHINE_VER_SYM(register, spapr, __VA_ARGS__))
4759 
4760 #define DEFINE_SPAPR_MACHINE_AS_LATEST(major, minor) \
4761     DEFINE_SPAPR_MACHINE_IMPL(true, major, minor)
4762 #define DEFINE_SPAPR_MACHINE(major, minor) \
4763     DEFINE_SPAPR_MACHINE_IMPL(false, major, minor)
4764 
4765 /*
4766  * pseries-10.0
4767  */
4768 static void spapr_machine_10_0_class_options(MachineClass *mc)
4769 {
4770     /* Defaults for the latest behaviour inherited from the base class */
4771 }
4772 
4773 DEFINE_SPAPR_MACHINE_AS_LATEST(10, 0);
4774 
4775 /*
4776  * pseries-9.2
4777  */
4778 static void spapr_machine_9_2_class_options(MachineClass *mc)
4779 {
4780     spapr_machine_10_0_class_options(mc);
4781     compat_props_add(mc->compat_props, hw_compat_9_2, hw_compat_9_2_len);
4782 }
4783 
4784 DEFINE_SPAPR_MACHINE(9, 2);
4785 
4786 /*
4787  * pseries-9.1
4788  */
4789 static void spapr_machine_9_1_class_options(MachineClass *mc)
4790 {
4791     spapr_machine_9_2_class_options(mc);
4792     compat_props_add(mc->compat_props, hw_compat_9_1, hw_compat_9_1_len);
4793 }
4794 
4795 DEFINE_SPAPR_MACHINE(9, 1);
4796 
4797 /*
4798  * pseries-9.0
4799  */
4800 static void spapr_machine_9_0_class_options(MachineClass *mc)
4801 {
4802     spapr_machine_9_1_class_options(mc);
4803     compat_props_add(mc->compat_props, hw_compat_9_0, hw_compat_9_0_len);
4804 }
4805 
4806 DEFINE_SPAPR_MACHINE(9, 0);
4807 
4808 /*
4809  * pseries-8.2
4810  */
4811 static void spapr_machine_8_2_class_options(MachineClass *mc)
4812 {
4813     spapr_machine_9_0_class_options(mc);
4814     compat_props_add(mc->compat_props, hw_compat_8_2, hw_compat_8_2_len);
4815 }
4816 
4817 DEFINE_SPAPR_MACHINE(8, 2);
4818 
4819 /*
4820  * pseries-8.1
4821  */
4822 static void spapr_machine_8_1_class_options(MachineClass *mc)
4823 {
4824     spapr_machine_8_2_class_options(mc);
4825     compat_props_add(mc->compat_props, hw_compat_8_1, hw_compat_8_1_len);
4826 }
4827 
4828 DEFINE_SPAPR_MACHINE(8, 1);
4829 
4830 /*
4831  * pseries-8.0
4832  */
4833 static void spapr_machine_8_0_class_options(MachineClass *mc)
4834 {
4835     spapr_machine_8_1_class_options(mc);
4836     compat_props_add(mc->compat_props, hw_compat_8_0, hw_compat_8_0_len);
4837 }
4838 
4839 DEFINE_SPAPR_MACHINE(8, 0);
4840 
4841 /*
4842  * pseries-7.2
4843  */
4844 static void spapr_machine_7_2_class_options(MachineClass *mc)
4845 {
4846     spapr_machine_8_0_class_options(mc);
4847     compat_props_add(mc->compat_props, hw_compat_7_2, hw_compat_7_2_len);
4848 }
4849 
4850 DEFINE_SPAPR_MACHINE(7, 2);
4851 
4852 /*
4853  * pseries-7.1
4854  */
4855 static void spapr_machine_7_1_class_options(MachineClass *mc)
4856 {
4857     spapr_machine_7_2_class_options(mc);
4858     compat_props_add(mc->compat_props, hw_compat_7_1, hw_compat_7_1_len);
4859 }
4860 
4861 DEFINE_SPAPR_MACHINE(7, 1);
4862 
4863 /*
4864  * pseries-7.0
4865  */
4866 static void spapr_machine_7_0_class_options(MachineClass *mc)
4867 {
4868     spapr_machine_7_1_class_options(mc);
4869     compat_props_add(mc->compat_props, hw_compat_7_0, hw_compat_7_0_len);
4870 }
4871 
4872 DEFINE_SPAPR_MACHINE(7, 0);
4873 
4874 /*
4875  * pseries-6.2
4876  */
4877 static void spapr_machine_6_2_class_options(MachineClass *mc)
4878 {
4879     spapr_machine_7_0_class_options(mc);
4880     compat_props_add(mc->compat_props, hw_compat_6_2, hw_compat_6_2_len);
4881 }
4882 
4883 DEFINE_SPAPR_MACHINE(6, 2);
4884 
4885 /*
4886  * pseries-6.1
4887  */
4888 static void spapr_machine_6_1_class_options(MachineClass *mc)
4889 {
4890     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4891 
4892     spapr_machine_6_2_class_options(mc);
4893     compat_props_add(mc->compat_props, hw_compat_6_1, hw_compat_6_1_len);
4894     smc->pre_6_2_numa_affinity = true;
4895     mc->smp_props.prefer_sockets = true;
4896 }
4897 
4898 DEFINE_SPAPR_MACHINE(6, 1);
4899 
4900 /*
4901  * pseries-6.0
4902  */
4903 static void spapr_machine_6_0_class_options(MachineClass *mc)
4904 {
4905     spapr_machine_6_1_class_options(mc);
4906     compat_props_add(mc->compat_props, hw_compat_6_0, hw_compat_6_0_len);
4907 }
4908 
4909 DEFINE_SPAPR_MACHINE(6, 0);
4910 
4911 /*
4912  * pseries-5.2
4913  */
4914 static void spapr_machine_5_2_class_options(MachineClass *mc)
4915 {
4916     spapr_machine_6_0_class_options(mc);
4917     compat_props_add(mc->compat_props, hw_compat_5_2, hw_compat_5_2_len);
4918 }
4919 
4920 DEFINE_SPAPR_MACHINE(5, 2);
4921 
4922 /*
4923  * pseries-5.1
4924  */
4925 static void spapr_machine_5_1_class_options(MachineClass *mc)
4926 {
4927     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4928 
4929     spapr_machine_5_2_class_options(mc);
4930     compat_props_add(mc->compat_props, hw_compat_5_1, hw_compat_5_1_len);
4931     smc->pre_5_2_numa_associativity = true;
4932 }
4933 
4934 DEFINE_SPAPR_MACHINE(5, 1);
4935 
4936 /*
4937  * pseries-5.0
4938  */
4939 static void spapr_machine_5_0_class_options(MachineClass *mc)
4940 {
4941     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4942     static GlobalProperty compat[] = {
4943         { TYPE_SPAPR_PCI_HOST_BRIDGE, "pre-5.1-associativity", "on" },
4944     };
4945 
4946     spapr_machine_5_1_class_options(mc);
4947     compat_props_add(mc->compat_props, hw_compat_5_0, hw_compat_5_0_len);
4948     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4949     mc->numa_mem_supported = true;
4950     smc->pre_5_1_assoc_refpoints = true;
4951 }
4952 
4953 DEFINE_SPAPR_MACHINE(5, 0);
4954 
4955 /*
4956  * pseries-4.2
4957  */
4958 static void spapr_machine_4_2_class_options(MachineClass *mc)
4959 {
4960     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4961 
4962     spapr_machine_5_0_class_options(mc);
4963     compat_props_add(mc->compat_props, hw_compat_4_2, hw_compat_4_2_len);
4964     smc->default_caps.caps[SPAPR_CAP_CCF_ASSIST] = SPAPR_CAP_OFF;
4965     smc->default_caps.caps[SPAPR_CAP_FWNMI] = SPAPR_CAP_OFF;
4966     smc->rma_limit = 16 * GiB;
4967     mc->nvdimm_supported = false;
4968 }
4969 
4970 DEFINE_SPAPR_MACHINE(4, 2);
4971 
4972 /*
4973  * pseries-4.1
4974  */
4975 static void spapr_machine_4_1_class_options(MachineClass *mc)
4976 {
4977     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
4978     static GlobalProperty compat[] = {
4979         /* Only allow 4kiB and 64kiB IOMMU pagesizes */
4980         { TYPE_SPAPR_PCI_HOST_BRIDGE, "pgsz", "0x11000" },
4981     };
4982 
4983     spapr_machine_4_2_class_options(mc);
4984     smc->linux_pci_probe = false;
4985     smc->smp_threads_vsmt = false;
4986     compat_props_add(mc->compat_props, hw_compat_4_1, hw_compat_4_1_len);
4987     compat_props_add(mc->compat_props, compat, G_N_ELEMENTS(compat));
4988 }
4989 
4990 DEFINE_SPAPR_MACHINE(4, 1);
4991 
4992 /*
4993  * pseries-4.0
4994  */
4995 static bool phb_placement_4_0(SpaprMachineState *spapr, uint32_t index,
4996                               uint64_t *buid, hwaddr *pio,
4997                               hwaddr *mmio32, hwaddr *mmio64,
4998                               unsigned n_dma, uint32_t *liobns, Error **errp)
4999 {
5000     if (!spapr_phb_placement(spapr, index, buid, pio, mmio32, mmio64, n_dma,
5001                              liobns, errp)) {
5002         return false;
5003     }
5004     return true;
5005 }
5006 static void spapr_machine_4_0_class_options(MachineClass *mc)
5007 {
5008     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
5009 
5010     spapr_machine_4_1_class_options(mc);
5011     compat_props_add(mc->compat_props, hw_compat_4_0, hw_compat_4_0_len);
5012     smc->phb_placement = phb_placement_4_0;
5013     smc->irq = &spapr_irq_xics;
5014     smc->pre_4_1_migration = true;
5015 }
5016 
5017 DEFINE_SPAPR_MACHINE(4, 0);
5018 
5019 /*
5020  * pseries-3.1
5021  */
5022 static void spapr_machine_3_1_class_options(MachineClass *mc)
5023 {
5024     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
5025 
5026     spapr_machine_4_0_class_options(mc);
5027     compat_props_add(mc->compat_props, hw_compat_3_1, hw_compat_3_1_len);
5028 
5029     mc->default_cpu_type = POWERPC_CPU_TYPE_NAME("power8_v2.0");
5030     smc->update_dt_enabled = false;
5031     smc->dr_phb_enabled = false;
5032     smc->broken_host_serial_model = true;
5033     smc->default_caps.caps[SPAPR_CAP_CFPC] = SPAPR_CAP_BROKEN;
5034     smc->default_caps.caps[SPAPR_CAP_SBBC] = SPAPR_CAP_BROKEN;
5035     smc->default_caps.caps[SPAPR_CAP_IBS] = SPAPR_CAP_BROKEN;
5036     smc->default_caps.caps[SPAPR_CAP_LARGE_DECREMENTER] = SPAPR_CAP_OFF;
5037 }
5038 
5039 DEFINE_SPAPR_MACHINE(3, 1);
5040 
5041 /*
5042  * pseries-3.0
5043  */
5044 
5045 static void spapr_machine_3_0_class_options(MachineClass *mc)
5046 {
5047     SpaprMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
5048 
5049     spapr_machine_3_1_class_options(mc);
5050     compat_props_add(mc->compat_props, hw_compat_3_0, hw_compat_3_0_len);
5051 
5052     smc->legacy_irq_allocation = true;
5053     smc->nr_xirqs = 0x400;
5054     smc->irq = &spapr_irq_xics_legacy;
5055 }
5056 
5057 DEFINE_SPAPR_MACHINE(3, 0);
5058 
5059 static void spapr_machine_register_types(void)
5060 {
5061     type_register_static(&spapr_machine_info);
5062 }
5063 
5064 type_init(spapr_machine_register_types)
5065