xref: /openbmc/qemu/hw/ppc/spapr.c (revision 9aa3397f)
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  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  *
26  */
27 #include "qemu/osdep.h"
28 #include "qapi/error.h"
29 #include "qapi/visitor.h"
30 #include "sysemu/sysemu.h"
31 #include "sysemu/numa.h"
32 #include "hw/hw.h"
33 #include "qemu/log.h"
34 #include "hw/fw-path-provider.h"
35 #include "elf.h"
36 #include "net/net.h"
37 #include "sysemu/device_tree.h"
38 #include "sysemu/block-backend.h"
39 #include "sysemu/cpus.h"
40 #include "sysemu/hw_accel.h"
41 #include "kvm_ppc.h"
42 #include "migration/misc.h"
43 #include "migration/global_state.h"
44 #include "migration/register.h"
45 #include "mmu-hash64.h"
46 #include "mmu-book3s-v3.h"
47 #include "qom/cpu.h"
48 
49 #include "hw/boards.h"
50 #include "hw/ppc/ppc.h"
51 #include "hw/loader.h"
52 
53 #include "hw/ppc/fdt.h"
54 #include "hw/ppc/spapr.h"
55 #include "hw/ppc/spapr_vio.h"
56 #include "hw/pci-host/spapr.h"
57 #include "hw/ppc/xics.h"
58 #include "hw/pci/msi.h"
59 
60 #include "hw/pci/pci.h"
61 #include "hw/scsi/scsi.h"
62 #include "hw/virtio/virtio-scsi.h"
63 #include "hw/virtio/vhost-scsi-common.h"
64 
65 #include "exec/address-spaces.h"
66 #include "hw/usb.h"
67 #include "qemu/config-file.h"
68 #include "qemu/error-report.h"
69 #include "trace.h"
70 #include "hw/nmi.h"
71 #include "hw/intc/intc.h"
72 
73 #include "hw/compat.h"
74 #include "qemu/cutils.h"
75 #include "hw/ppc/spapr_cpu_core.h"
76 #include "qmp-commands.h"
77 
78 #include <libfdt.h>
79 
80 /* SLOF memory layout:
81  *
82  * SLOF raw image loaded at 0, copies its romfs right below the flat
83  * device-tree, then position SLOF itself 31M below that
84  *
85  * So we set FW_OVERHEAD to 40MB which should account for all of that
86  * and more
87  *
88  * We load our kernel at 4M, leaving space for SLOF initial image
89  */
90 #define FDT_MAX_SIZE            0x100000
91 #define RTAS_MAX_SIZE           0x10000
92 #define RTAS_MAX_ADDR           0x80000000 /* RTAS must stay below that */
93 #define FW_MAX_SIZE             0x400000
94 #define FW_FILE_NAME            "slof.bin"
95 #define FW_OVERHEAD             0x2800000
96 #define KERNEL_LOAD_ADDR        FW_MAX_SIZE
97 
98 #define MIN_RMA_SLOF            128UL
99 
100 #define PHANDLE_XICP            0x00001111
101 
102 static ICSState *spapr_ics_create(sPAPRMachineState *spapr,
103                                   const char *type_ics,
104                                   int nr_irqs, Error **errp)
105 {
106     Error *local_err = NULL;
107     Object *obj;
108 
109     obj = object_new(type_ics);
110     object_property_add_child(OBJECT(spapr), "ics", obj, &error_abort);
111     object_property_add_const_link(obj, ICS_PROP_XICS, OBJECT(spapr),
112                                    &error_abort);
113     object_property_set_int(obj, nr_irqs, "nr-irqs", &local_err);
114     if (local_err) {
115         goto error;
116     }
117     object_property_set_bool(obj, true, "realized", &local_err);
118     if (local_err) {
119         goto error;
120     }
121 
122     return ICS_SIMPLE(obj);
123 
124 error:
125     error_propagate(errp, local_err);
126     return NULL;
127 }
128 
129 static bool pre_2_10_vmstate_dummy_icp_needed(void *opaque)
130 {
131     /* Dummy entries correspond to unused ICPState objects in older QEMUs,
132      * and newer QEMUs don't even have them. In both cases, we don't want
133      * to send anything on the wire.
134      */
135     return false;
136 }
137 
138 static const VMStateDescription pre_2_10_vmstate_dummy_icp = {
139     .name = "icp/server",
140     .version_id = 1,
141     .minimum_version_id = 1,
142     .needed = pre_2_10_vmstate_dummy_icp_needed,
143     .fields = (VMStateField[]) {
144         VMSTATE_UNUSED(4), /* uint32_t xirr */
145         VMSTATE_UNUSED(1), /* uint8_t pending_priority */
146         VMSTATE_UNUSED(1), /* uint8_t mfrr */
147         VMSTATE_END_OF_LIST()
148     },
149 };
150 
151 static void pre_2_10_vmstate_register_dummy_icp(int i)
152 {
153     vmstate_register(NULL, i, &pre_2_10_vmstate_dummy_icp,
154                      (void *)(uintptr_t) i);
155 }
156 
157 static void pre_2_10_vmstate_unregister_dummy_icp(int i)
158 {
159     vmstate_unregister(NULL, &pre_2_10_vmstate_dummy_icp,
160                        (void *)(uintptr_t) i);
161 }
162 
163 static inline int xics_max_server_number(void)
164 {
165     return DIV_ROUND_UP(max_cpus * kvmppc_smt_threads(), smp_threads);
166 }
167 
168 static void xics_system_init(MachineState *machine, int nr_irqs, Error **errp)
169 {
170     sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
171     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
172 
173     if (kvm_enabled()) {
174         if (machine_kernel_irqchip_allowed(machine) &&
175             !xics_kvm_init(spapr, errp)) {
176             spapr->icp_type = TYPE_KVM_ICP;
177             spapr->ics = spapr_ics_create(spapr, TYPE_ICS_KVM, nr_irqs, errp);
178         }
179         if (machine_kernel_irqchip_required(machine) && !spapr->ics) {
180             error_prepend(errp, "kernel_irqchip requested but unavailable: ");
181             return;
182         }
183     }
184 
185     if (!spapr->ics) {
186         xics_spapr_init(spapr);
187         spapr->icp_type = TYPE_ICP;
188         spapr->ics = spapr_ics_create(spapr, TYPE_ICS_SIMPLE, nr_irqs, errp);
189         if (!spapr->ics) {
190             return;
191         }
192     }
193 
194     if (smc->pre_2_10_has_unused_icps) {
195         int i;
196 
197         for (i = 0; i < xics_max_server_number(); i++) {
198             /* Dummy entries get deregistered when real ICPState objects
199              * are registered during CPU core hotplug.
200              */
201             pre_2_10_vmstate_register_dummy_icp(i);
202         }
203     }
204 }
205 
206 static int spapr_fixup_cpu_smt_dt(void *fdt, int offset, PowerPCCPU *cpu,
207                                   int smt_threads)
208 {
209     int i, ret = 0;
210     uint32_t servers_prop[smt_threads];
211     uint32_t gservers_prop[smt_threads * 2];
212     int index = spapr_vcpu_id(cpu);
213 
214     if (cpu->compat_pvr) {
215         ret = fdt_setprop_cell(fdt, offset, "cpu-version", cpu->compat_pvr);
216         if (ret < 0) {
217             return ret;
218         }
219     }
220 
221     /* Build interrupt servers and gservers properties */
222     for (i = 0; i < smt_threads; i++) {
223         servers_prop[i] = cpu_to_be32(index + i);
224         /* Hack, direct the group queues back to cpu 0 */
225         gservers_prop[i*2] = cpu_to_be32(index + i);
226         gservers_prop[i*2 + 1] = 0;
227     }
228     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-server#s",
229                       servers_prop, sizeof(servers_prop));
230     if (ret < 0) {
231         return ret;
232     }
233     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-gserver#s",
234                       gservers_prop, sizeof(gservers_prop));
235 
236     return ret;
237 }
238 
239 static int spapr_fixup_cpu_numa_dt(void *fdt, int offset, PowerPCCPU *cpu)
240 {
241     int index = spapr_vcpu_id(cpu);
242     uint32_t associativity[] = {cpu_to_be32(0x5),
243                                 cpu_to_be32(0x0),
244                                 cpu_to_be32(0x0),
245                                 cpu_to_be32(0x0),
246                                 cpu_to_be32(cpu->node_id),
247                                 cpu_to_be32(index)};
248 
249     /* Advertise NUMA via ibm,associativity */
250     return fdt_setprop(fdt, offset, "ibm,associativity", associativity,
251                           sizeof(associativity));
252 }
253 
254 /* Populate the "ibm,pa-features" property */
255 static void spapr_populate_pa_features(CPUPPCState *env, void *fdt, int offset,
256                                       bool legacy_guest)
257 {
258     uint8_t pa_features_206[] = { 6, 0,
259         0xf6, 0x1f, 0xc7, 0x00, 0x80, 0xc0 };
260     uint8_t pa_features_207[] = { 24, 0,
261         0xf6, 0x1f, 0xc7, 0xc0, 0x80, 0xf0,
262         0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
263         0x00, 0x00, 0x00, 0x00, 0x80, 0x00,
264         0x80, 0x00, 0x80, 0x00, 0x00, 0x00 };
265     uint8_t pa_features_300[] = { 66, 0,
266         /* 0: MMU|FPU|SLB|RUN|DABR|NX, 1: fri[nzpm]|DABRX|SPRG3|SLB0|PP110 */
267         /* 2: VPM|DS205|PPR|DS202|DS206, 3: LSD|URG, SSO, 5: LE|CFAR|EB|LSQ */
268         0xf6, 0x1f, 0xc7, 0xc0, 0x80, 0xf0, /* 0 - 5 */
269         /* 6: DS207 */
270         0x80, 0x00, 0x00, 0x00, 0x00, 0x00, /* 6 - 11 */
271         /* 16: Vector */
272         0x00, 0x00, 0x00, 0x00, 0x80, 0x00, /* 12 - 17 */
273         /* 18: Vec. Scalar, 20: Vec. XOR, 22: HTM */
274         0x80, 0x00, 0x80, 0x00, 0x00, 0x00, /* 18 - 23 */
275         /* 24: Ext. Dec, 26: 64 bit ftrs, 28: PM ftrs */
276         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 24 - 29 */
277         /* 30: MMR, 32: LE atomic, 34: EBB + ext EBB */
278         0x80, 0x00, 0x80, 0x00, 0xC0, 0x00, /* 30 - 35 */
279         /* 36: SPR SO, 38: Copy/Paste, 40: Radix MMU */
280         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 36 - 41 */
281         /* 42: PM, 44: PC RA, 46: SC vec'd */
282         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 42 - 47 */
283         /* 48: SIMD, 50: QP BFP, 52: String */
284         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 48 - 53 */
285         /* 54: DecFP, 56: DecI, 58: SHA */
286         0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 54 - 59 */
287         /* 60: NM atomic, 62: RNG */
288         0x80, 0x00, 0x80, 0x00, 0x00, 0x00, /* 60 - 65 */
289     };
290     uint8_t *pa_features;
291     size_t pa_size;
292 
293     switch (POWERPC_MMU_VER(env->mmu_model)) {
294     case POWERPC_MMU_VER_2_06:
295         pa_features = pa_features_206;
296         pa_size = sizeof(pa_features_206);
297         break;
298     case POWERPC_MMU_VER_2_07:
299         pa_features = pa_features_207;
300         pa_size = sizeof(pa_features_207);
301         break;
302     case POWERPC_MMU_VER_3_00:
303         pa_features = pa_features_300;
304         pa_size = sizeof(pa_features_300);
305         break;
306     default:
307         return;
308     }
309 
310     if (env->ci_large_pages) {
311         /*
312          * Note: we keep CI large pages off by default because a 64K capable
313          * guest provisioned with large pages might otherwise try to map a qemu
314          * framebuffer (or other kind of memory mapped PCI BAR) using 64K pages
315          * even if that qemu runs on a 4k host.
316          * We dd this bit back here if we are confident this is not an issue
317          */
318         pa_features[3] |= 0x20;
319     }
320     if (kvmppc_has_cap_htm() && pa_size > 24) {
321         pa_features[24] |= 0x80;    /* Transactional memory support */
322     }
323     if (legacy_guest && pa_size > 40) {
324         /* Workaround for broken kernels that attempt (guest) radix
325          * mode when they can't handle it, if they see the radix bit set
326          * in pa-features. So hide it from them. */
327         pa_features[40 + 2] &= ~0x80; /* Radix MMU */
328     }
329 
330     _FDT((fdt_setprop(fdt, offset, "ibm,pa-features", pa_features, pa_size)));
331 }
332 
333 static int spapr_fixup_cpu_dt(void *fdt, sPAPRMachineState *spapr)
334 {
335     int ret = 0, offset, cpus_offset;
336     CPUState *cs;
337     char cpu_model[32];
338     int smt = kvmppc_smt_threads();
339     uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};
340 
341     CPU_FOREACH(cs) {
342         PowerPCCPU *cpu = POWERPC_CPU(cs);
343         CPUPPCState *env = &cpu->env;
344         DeviceClass *dc = DEVICE_GET_CLASS(cs);
345         int index = spapr_vcpu_id(cpu);
346         int compat_smt = MIN(smp_threads, ppc_compat_max_threads(cpu));
347 
348         if ((index % smt) != 0) {
349             continue;
350         }
351 
352         snprintf(cpu_model, 32, "%s@%x", dc->fw_name, index);
353 
354         cpus_offset = fdt_path_offset(fdt, "/cpus");
355         if (cpus_offset < 0) {
356             cpus_offset = fdt_add_subnode(fdt, fdt_path_offset(fdt, "/"),
357                                           "cpus");
358             if (cpus_offset < 0) {
359                 return cpus_offset;
360             }
361         }
362         offset = fdt_subnode_offset(fdt, cpus_offset, cpu_model);
363         if (offset < 0) {
364             offset = fdt_add_subnode(fdt, cpus_offset, cpu_model);
365             if (offset < 0) {
366                 return offset;
367             }
368         }
369 
370         ret = fdt_setprop(fdt, offset, "ibm,pft-size",
371                           pft_size_prop, sizeof(pft_size_prop));
372         if (ret < 0) {
373             return ret;
374         }
375 
376         if (nb_numa_nodes > 1) {
377             ret = spapr_fixup_cpu_numa_dt(fdt, offset, cpu);
378             if (ret < 0) {
379                 return ret;
380             }
381         }
382 
383         ret = spapr_fixup_cpu_smt_dt(fdt, offset, cpu, compat_smt);
384         if (ret < 0) {
385             return ret;
386         }
387 
388         spapr_populate_pa_features(env, fdt, offset,
389                                          spapr->cas_legacy_guest_workaround);
390     }
391     return ret;
392 }
393 
394 static hwaddr spapr_node0_size(void)
395 {
396     MachineState *machine = MACHINE(qdev_get_machine());
397 
398     if (nb_numa_nodes) {
399         int i;
400         for (i = 0; i < nb_numa_nodes; ++i) {
401             if (numa_info[i].node_mem) {
402                 return MIN(pow2floor(numa_info[i].node_mem),
403                            machine->ram_size);
404             }
405         }
406     }
407     return machine->ram_size;
408 }
409 
410 static void add_str(GString *s, const gchar *s1)
411 {
412     g_string_append_len(s, s1, strlen(s1) + 1);
413 }
414 
415 static int spapr_populate_memory_node(void *fdt, int nodeid, hwaddr start,
416                                        hwaddr size)
417 {
418     uint32_t associativity[] = {
419         cpu_to_be32(0x4), /* length */
420         cpu_to_be32(0x0), cpu_to_be32(0x0),
421         cpu_to_be32(0x0), cpu_to_be32(nodeid)
422     };
423     char mem_name[32];
424     uint64_t mem_reg_property[2];
425     int off;
426 
427     mem_reg_property[0] = cpu_to_be64(start);
428     mem_reg_property[1] = cpu_to_be64(size);
429 
430     sprintf(mem_name, "memory@" TARGET_FMT_lx, start);
431     off = fdt_add_subnode(fdt, 0, mem_name);
432     _FDT(off);
433     _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
434     _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property,
435                       sizeof(mem_reg_property))));
436     _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity,
437                       sizeof(associativity))));
438     return off;
439 }
440 
441 static int spapr_populate_memory(sPAPRMachineState *spapr, void *fdt)
442 {
443     MachineState *machine = MACHINE(spapr);
444     hwaddr mem_start, node_size;
445     int i, nb_nodes = nb_numa_nodes;
446     NodeInfo *nodes = numa_info;
447     NodeInfo ramnode;
448 
449     /* No NUMA nodes, assume there is just one node with whole RAM */
450     if (!nb_numa_nodes) {
451         nb_nodes = 1;
452         ramnode.node_mem = machine->ram_size;
453         nodes = &ramnode;
454     }
455 
456     for (i = 0, mem_start = 0; i < nb_nodes; ++i) {
457         if (!nodes[i].node_mem) {
458             continue;
459         }
460         if (mem_start >= machine->ram_size) {
461             node_size = 0;
462         } else {
463             node_size = nodes[i].node_mem;
464             if (node_size > machine->ram_size - mem_start) {
465                 node_size = machine->ram_size - mem_start;
466             }
467         }
468         if (!mem_start) {
469             /* ppc_spapr_init() checks for rma_size <= node0_size already */
470             spapr_populate_memory_node(fdt, i, 0, spapr->rma_size);
471             mem_start += spapr->rma_size;
472             node_size -= spapr->rma_size;
473         }
474         for ( ; node_size; ) {
475             hwaddr sizetmp = pow2floor(node_size);
476 
477             /* mem_start != 0 here */
478             if (ctzl(mem_start) < ctzl(sizetmp)) {
479                 sizetmp = 1ULL << ctzl(mem_start);
480             }
481 
482             spapr_populate_memory_node(fdt, i, mem_start, sizetmp);
483             node_size -= sizetmp;
484             mem_start += sizetmp;
485         }
486     }
487 
488     return 0;
489 }
490 
491 static void spapr_populate_cpu_dt(CPUState *cs, void *fdt, int offset,
492                                   sPAPRMachineState *spapr)
493 {
494     PowerPCCPU *cpu = POWERPC_CPU(cs);
495     CPUPPCState *env = &cpu->env;
496     PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
497     int index = spapr_vcpu_id(cpu);
498     uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
499                        0xffffffff, 0xffffffff};
500     uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq()
501         : SPAPR_TIMEBASE_FREQ;
502     uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
503     uint32_t page_sizes_prop[64];
504     size_t page_sizes_prop_size;
505     uint32_t vcpus_per_socket = smp_threads * smp_cores;
506     uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};
507     int compat_smt = MIN(smp_threads, ppc_compat_max_threads(cpu));
508     sPAPRDRConnector *drc;
509     int drc_index;
510     uint32_t radix_AP_encodings[PPC_PAGE_SIZES_MAX_SZ];
511     int i;
512 
513     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index);
514     if (drc) {
515         drc_index = spapr_drc_index(drc);
516         _FDT((fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index)));
517     }
518 
519     _FDT((fdt_setprop_cell(fdt, offset, "reg", index)));
520     _FDT((fdt_setprop_string(fdt, offset, "device_type", "cpu")));
521 
522     _FDT((fdt_setprop_cell(fdt, offset, "cpu-version", env->spr[SPR_PVR])));
523     _FDT((fdt_setprop_cell(fdt, offset, "d-cache-block-size",
524                            env->dcache_line_size)));
525     _FDT((fdt_setprop_cell(fdt, offset, "d-cache-line-size",
526                            env->dcache_line_size)));
527     _FDT((fdt_setprop_cell(fdt, offset, "i-cache-block-size",
528                            env->icache_line_size)));
529     _FDT((fdt_setprop_cell(fdt, offset, "i-cache-line-size",
530                            env->icache_line_size)));
531 
532     if (pcc->l1_dcache_size) {
533         _FDT((fdt_setprop_cell(fdt, offset, "d-cache-size",
534                                pcc->l1_dcache_size)));
535     } else {
536         warn_report("Unknown L1 dcache size for cpu");
537     }
538     if (pcc->l1_icache_size) {
539         _FDT((fdt_setprop_cell(fdt, offset, "i-cache-size",
540                                pcc->l1_icache_size)));
541     } else {
542         warn_report("Unknown L1 icache size for cpu");
543     }
544 
545     _FDT((fdt_setprop_cell(fdt, offset, "timebase-frequency", tbfreq)));
546     _FDT((fdt_setprop_cell(fdt, offset, "clock-frequency", cpufreq)));
547     _FDT((fdt_setprop_cell(fdt, offset, "slb-size", env->slb_nr)));
548     _FDT((fdt_setprop_cell(fdt, offset, "ibm,slb-size", env->slb_nr)));
549     _FDT((fdt_setprop_string(fdt, offset, "status", "okay")));
550     _FDT((fdt_setprop(fdt, offset, "64-bit", NULL, 0)));
551 
552     if (env->spr_cb[SPR_PURR].oea_read) {
553         _FDT((fdt_setprop(fdt, offset, "ibm,purr", NULL, 0)));
554     }
555 
556     if (env->mmu_model & POWERPC_MMU_1TSEG) {
557         _FDT((fdt_setprop(fdt, offset, "ibm,processor-segment-sizes",
558                           segs, sizeof(segs))));
559     }
560 
561     /* Advertise VMX/VSX (vector extensions) if available
562      *   0 / no property == no vector extensions
563      *   1               == VMX / Altivec available
564      *   2               == VSX available */
565     if (env->insns_flags & PPC_ALTIVEC) {
566         uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;
567 
568         _FDT((fdt_setprop_cell(fdt, offset, "ibm,vmx", vmx)));
569     }
570 
571     /* Advertise DFP (Decimal Floating Point) if available
572      *   0 / no property == no DFP
573      *   1               == DFP available */
574     if (env->insns_flags2 & PPC2_DFP) {
575         _FDT((fdt_setprop_cell(fdt, offset, "ibm,dfp", 1)));
576     }
577 
578     page_sizes_prop_size = ppc_create_page_sizes_prop(env, page_sizes_prop,
579                                                   sizeof(page_sizes_prop));
580     if (page_sizes_prop_size) {
581         _FDT((fdt_setprop(fdt, offset, "ibm,segment-page-sizes",
582                           page_sizes_prop, page_sizes_prop_size)));
583     }
584 
585     spapr_populate_pa_features(env, fdt, offset, false);
586 
587     _FDT((fdt_setprop_cell(fdt, offset, "ibm,chip-id",
588                            cs->cpu_index / vcpus_per_socket)));
589 
590     _FDT((fdt_setprop(fdt, offset, "ibm,pft-size",
591                       pft_size_prop, sizeof(pft_size_prop))));
592 
593     if (nb_numa_nodes > 1) {
594         _FDT(spapr_fixup_cpu_numa_dt(fdt, offset, cpu));
595     }
596 
597     _FDT(spapr_fixup_cpu_smt_dt(fdt, offset, cpu, compat_smt));
598 
599     if (pcc->radix_page_info) {
600         for (i = 0; i < pcc->radix_page_info->count; i++) {
601             radix_AP_encodings[i] =
602                 cpu_to_be32(pcc->radix_page_info->entries[i]);
603         }
604         _FDT((fdt_setprop(fdt, offset, "ibm,processor-radix-AP-encodings",
605                           radix_AP_encodings,
606                           pcc->radix_page_info->count *
607                           sizeof(radix_AP_encodings[0]))));
608     }
609 }
610 
611 static void spapr_populate_cpus_dt_node(void *fdt, sPAPRMachineState *spapr)
612 {
613     CPUState *cs;
614     int cpus_offset;
615     char *nodename;
616     int smt = kvmppc_smt_threads();
617 
618     cpus_offset = fdt_add_subnode(fdt, 0, "cpus");
619     _FDT(cpus_offset);
620     _FDT((fdt_setprop_cell(fdt, cpus_offset, "#address-cells", 0x1)));
621     _FDT((fdt_setprop_cell(fdt, cpus_offset, "#size-cells", 0x0)));
622 
623     /*
624      * We walk the CPUs in reverse order to ensure that CPU DT nodes
625      * created by fdt_add_subnode() end up in the right order in FDT
626      * for the guest kernel the enumerate the CPUs correctly.
627      */
628     CPU_FOREACH_REVERSE(cs) {
629         PowerPCCPU *cpu = POWERPC_CPU(cs);
630         int index = spapr_vcpu_id(cpu);
631         DeviceClass *dc = DEVICE_GET_CLASS(cs);
632         int offset;
633 
634         if ((index % smt) != 0) {
635             continue;
636         }
637 
638         nodename = g_strdup_printf("%s@%x", dc->fw_name, index);
639         offset = fdt_add_subnode(fdt, cpus_offset, nodename);
640         g_free(nodename);
641         _FDT(offset);
642         spapr_populate_cpu_dt(cs, fdt, offset, spapr);
643     }
644 
645 }
646 
647 /*
648  * Adds ibm,dynamic-reconfiguration-memory node.
649  * Refer to docs/specs/ppc-spapr-hotplug.txt for the documentation
650  * of this device tree node.
651  */
652 static int spapr_populate_drconf_memory(sPAPRMachineState *spapr, void *fdt)
653 {
654     MachineState *machine = MACHINE(spapr);
655     int ret, i, offset;
656     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
657     uint32_t prop_lmb_size[] = {0, cpu_to_be32(lmb_size)};
658     uint32_t hotplug_lmb_start = spapr->hotplug_memory.base / lmb_size;
659     uint32_t nr_lmbs = (spapr->hotplug_memory.base +
660                        memory_region_size(&spapr->hotplug_memory.mr)) /
661                        lmb_size;
662     uint32_t *int_buf, *cur_index, buf_len;
663     int nr_nodes = nb_numa_nodes ? nb_numa_nodes : 1;
664 
665     /*
666      * Don't create the node if there is no hotpluggable memory
667      */
668     if (machine->ram_size == machine->maxram_size) {
669         return 0;
670     }
671 
672     /*
673      * Allocate enough buffer size to fit in ibm,dynamic-memory
674      * or ibm,associativity-lookup-arrays
675      */
676     buf_len = MAX(nr_lmbs * SPAPR_DR_LMB_LIST_ENTRY_SIZE + 1, nr_nodes * 4 + 2)
677               * sizeof(uint32_t);
678     cur_index = int_buf = g_malloc0(buf_len);
679 
680     offset = fdt_add_subnode(fdt, 0, "ibm,dynamic-reconfiguration-memory");
681 
682     ret = fdt_setprop(fdt, offset, "ibm,lmb-size", prop_lmb_size,
683                     sizeof(prop_lmb_size));
684     if (ret < 0) {
685         goto out;
686     }
687 
688     ret = fdt_setprop_cell(fdt, offset, "ibm,memory-flags-mask", 0xff);
689     if (ret < 0) {
690         goto out;
691     }
692 
693     ret = fdt_setprop_cell(fdt, offset, "ibm,memory-preservation-time", 0x0);
694     if (ret < 0) {
695         goto out;
696     }
697 
698     /* ibm,dynamic-memory */
699     int_buf[0] = cpu_to_be32(nr_lmbs);
700     cur_index++;
701     for (i = 0; i < nr_lmbs; i++) {
702         uint64_t addr = i * lmb_size;
703         uint32_t *dynamic_memory = cur_index;
704 
705         if (i >= hotplug_lmb_start) {
706             sPAPRDRConnector *drc;
707 
708             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB, i);
709             g_assert(drc);
710 
711             dynamic_memory[0] = cpu_to_be32(addr >> 32);
712             dynamic_memory[1] = cpu_to_be32(addr & 0xffffffff);
713             dynamic_memory[2] = cpu_to_be32(spapr_drc_index(drc));
714             dynamic_memory[3] = cpu_to_be32(0); /* reserved */
715             dynamic_memory[4] = cpu_to_be32(numa_get_node(addr, NULL));
716             if (memory_region_present(get_system_memory(), addr)) {
717                 dynamic_memory[5] = cpu_to_be32(SPAPR_LMB_FLAGS_ASSIGNED);
718             } else {
719                 dynamic_memory[5] = cpu_to_be32(0);
720             }
721         } else {
722             /*
723              * LMB information for RMA, boot time RAM and gap b/n RAM and
724              * hotplug memory region -- all these are marked as reserved
725              * and as having no valid DRC.
726              */
727             dynamic_memory[0] = cpu_to_be32(addr >> 32);
728             dynamic_memory[1] = cpu_to_be32(addr & 0xffffffff);
729             dynamic_memory[2] = cpu_to_be32(0);
730             dynamic_memory[3] = cpu_to_be32(0); /* reserved */
731             dynamic_memory[4] = cpu_to_be32(-1);
732             dynamic_memory[5] = cpu_to_be32(SPAPR_LMB_FLAGS_RESERVED |
733                                             SPAPR_LMB_FLAGS_DRC_INVALID);
734         }
735 
736         cur_index += SPAPR_DR_LMB_LIST_ENTRY_SIZE;
737     }
738     ret = fdt_setprop(fdt, offset, "ibm,dynamic-memory", int_buf, buf_len);
739     if (ret < 0) {
740         goto out;
741     }
742 
743     /* ibm,associativity-lookup-arrays */
744     cur_index = int_buf;
745     int_buf[0] = cpu_to_be32(nr_nodes);
746     int_buf[1] = cpu_to_be32(4); /* Number of entries per associativity list */
747     cur_index += 2;
748     for (i = 0; i < nr_nodes; i++) {
749         uint32_t associativity[] = {
750             cpu_to_be32(0x0),
751             cpu_to_be32(0x0),
752             cpu_to_be32(0x0),
753             cpu_to_be32(i)
754         };
755         memcpy(cur_index, associativity, sizeof(associativity));
756         cur_index += 4;
757     }
758     ret = fdt_setprop(fdt, offset, "ibm,associativity-lookup-arrays", int_buf,
759             (cur_index - int_buf) * sizeof(uint32_t));
760 out:
761     g_free(int_buf);
762     return ret;
763 }
764 
765 static int spapr_dt_cas_updates(sPAPRMachineState *spapr, void *fdt,
766                                 sPAPROptionVector *ov5_updates)
767 {
768     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
769     int ret = 0, offset;
770 
771     /* Generate ibm,dynamic-reconfiguration-memory node if required */
772     if (spapr_ovec_test(ov5_updates, OV5_DRCONF_MEMORY)) {
773         g_assert(smc->dr_lmb_enabled);
774         ret = spapr_populate_drconf_memory(spapr, fdt);
775         if (ret) {
776             goto out;
777         }
778     }
779 
780     offset = fdt_path_offset(fdt, "/chosen");
781     if (offset < 0) {
782         offset = fdt_add_subnode(fdt, 0, "chosen");
783         if (offset < 0) {
784             return offset;
785         }
786     }
787     ret = spapr_ovec_populate_dt(fdt, offset, spapr->ov5_cas,
788                                  "ibm,architecture-vec-5");
789 
790 out:
791     return ret;
792 }
793 
794 static bool spapr_hotplugged_dev_before_cas(void)
795 {
796     Object *drc_container, *obj;
797     ObjectProperty *prop;
798     ObjectPropertyIterator iter;
799 
800     drc_container = container_get(object_get_root(), "/dr-connector");
801     object_property_iter_init(&iter, drc_container);
802     while ((prop = object_property_iter_next(&iter))) {
803         if (!strstart(prop->type, "link<", NULL)) {
804             continue;
805         }
806         obj = object_property_get_link(drc_container, prop->name, NULL);
807         if (spapr_drc_needed(obj)) {
808             return true;
809         }
810     }
811     return false;
812 }
813 
814 int spapr_h_cas_compose_response(sPAPRMachineState *spapr,
815                                  target_ulong addr, target_ulong size,
816                                  sPAPROptionVector *ov5_updates)
817 {
818     void *fdt, *fdt_skel;
819     sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };
820 
821     if (spapr_hotplugged_dev_before_cas()) {
822         return 1;
823     }
824 
825     size -= sizeof(hdr);
826 
827     /* Create skeleton */
828     fdt_skel = g_malloc0(size);
829     _FDT((fdt_create(fdt_skel, size)));
830     _FDT((fdt_begin_node(fdt_skel, "")));
831     _FDT((fdt_end_node(fdt_skel)));
832     _FDT((fdt_finish(fdt_skel)));
833     fdt = g_malloc0(size);
834     _FDT((fdt_open_into(fdt_skel, fdt, size)));
835     g_free(fdt_skel);
836 
837     /* Fixup cpu nodes */
838     _FDT((spapr_fixup_cpu_dt(fdt, spapr)));
839 
840     if (spapr_dt_cas_updates(spapr, fdt, ov5_updates)) {
841         return -1;
842     }
843 
844     /* Pack resulting tree */
845     _FDT((fdt_pack(fdt)));
846 
847     if (fdt_totalsize(fdt) + sizeof(hdr) > size) {
848         trace_spapr_cas_failed(size);
849         return -1;
850     }
851 
852     cpu_physical_memory_write(addr, &hdr, sizeof(hdr));
853     cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));
854     trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));
855     g_free(fdt);
856 
857     return 0;
858 }
859 
860 static void spapr_dt_rtas(sPAPRMachineState *spapr, void *fdt)
861 {
862     int rtas;
863     GString *hypertas = g_string_sized_new(256);
864     GString *qemu_hypertas = g_string_sized_new(256);
865     uint32_t refpoints[] = { cpu_to_be32(0x4), cpu_to_be32(0x4) };
866     uint64_t max_hotplug_addr = spapr->hotplug_memory.base +
867         memory_region_size(&spapr->hotplug_memory.mr);
868     uint32_t lrdr_capacity[] = {
869         cpu_to_be32(max_hotplug_addr >> 32),
870         cpu_to_be32(max_hotplug_addr & 0xffffffff),
871         0, cpu_to_be32(SPAPR_MEMORY_BLOCK_SIZE),
872         cpu_to_be32(max_cpus / smp_threads),
873     };
874 
875     _FDT(rtas = fdt_add_subnode(fdt, 0, "rtas"));
876 
877     /* hypertas */
878     add_str(hypertas, "hcall-pft");
879     add_str(hypertas, "hcall-term");
880     add_str(hypertas, "hcall-dabr");
881     add_str(hypertas, "hcall-interrupt");
882     add_str(hypertas, "hcall-tce");
883     add_str(hypertas, "hcall-vio");
884     add_str(hypertas, "hcall-splpar");
885     add_str(hypertas, "hcall-bulk");
886     add_str(hypertas, "hcall-set-mode");
887     add_str(hypertas, "hcall-sprg0");
888     add_str(hypertas, "hcall-copy");
889     add_str(hypertas, "hcall-debug");
890     add_str(qemu_hypertas, "hcall-memop1");
891 
892     if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {
893         add_str(hypertas, "hcall-multi-tce");
894     }
895 
896     if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {
897         add_str(hypertas, "hcall-hpt-resize");
898     }
899 
900     _FDT(fdt_setprop(fdt, rtas, "ibm,hypertas-functions",
901                      hypertas->str, hypertas->len));
902     g_string_free(hypertas, TRUE);
903     _FDT(fdt_setprop(fdt, rtas, "qemu,hypertas-functions",
904                      qemu_hypertas->str, qemu_hypertas->len));
905     g_string_free(qemu_hypertas, TRUE);
906 
907     _FDT(fdt_setprop(fdt, rtas, "ibm,associativity-reference-points",
908                      refpoints, sizeof(refpoints)));
909 
910     _FDT(fdt_setprop_cell(fdt, rtas, "rtas-error-log-max",
911                           RTAS_ERROR_LOG_MAX));
912     _FDT(fdt_setprop_cell(fdt, rtas, "rtas-event-scan-rate",
913                           RTAS_EVENT_SCAN_RATE));
914 
915     if (msi_nonbroken) {
916         _FDT(fdt_setprop(fdt, rtas, "ibm,change-msix-capable", NULL, 0));
917     }
918 
919     /*
920      * According to PAPR, rtas ibm,os-term does not guarantee a return
921      * back to the guest cpu.
922      *
923      * While an additional ibm,extended-os-term property indicates
924      * that rtas call return will always occur. Set this property.
925      */
926     _FDT(fdt_setprop(fdt, rtas, "ibm,extended-os-term", NULL, 0));
927 
928     _FDT(fdt_setprop(fdt, rtas, "ibm,lrdr-capacity",
929                      lrdr_capacity, sizeof(lrdr_capacity)));
930 
931     spapr_dt_rtas_tokens(fdt, rtas);
932 }
933 
934 /* Prepare ibm,arch-vec-5-platform-support, which indicates the MMU features
935  * that the guest may request and thus the valid values for bytes 24..26 of
936  * option vector 5: */
937 static void spapr_dt_ov5_platform_support(void *fdt, int chosen)
938 {
939     PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu);
940 
941     char val[2 * 4] = {
942         23, 0x00, /* Xive mode: 0 = legacy (as in ISA 2.7), 1 = Exploitation */
943         24, 0x00, /* Hash/Radix, filled in below. */
944         25, 0x00, /* Hash options: Segment Tables == no, GTSE == no. */
945         26, 0x40, /* Radix options: GTSE == yes. */
946     };
947 
948     if (kvm_enabled()) {
949         if (kvmppc_has_cap_mmu_radix() && kvmppc_has_cap_mmu_hash_v3()) {
950             val[3] = 0x80; /* OV5_MMU_BOTH */
951         } else if (kvmppc_has_cap_mmu_radix()) {
952             val[3] = 0x40; /* OV5_MMU_RADIX_300 */
953         } else {
954             val[3] = 0x00; /* Hash */
955         }
956     } else {
957         if (first_ppc_cpu->env.mmu_model & POWERPC_MMU_V3) {
958             /* V3 MMU supports both hash and radix (with dynamic switching) */
959             val[3] = 0xC0;
960         } else {
961             /* Otherwise we can only do hash */
962             val[3] = 0x00;
963         }
964     }
965     _FDT(fdt_setprop(fdt, chosen, "ibm,arch-vec-5-platform-support",
966                      val, sizeof(val)));
967 }
968 
969 static void spapr_dt_chosen(sPAPRMachineState *spapr, void *fdt)
970 {
971     MachineState *machine = MACHINE(spapr);
972     int chosen;
973     const char *boot_device = machine->boot_order;
974     char *stdout_path = spapr_vio_stdout_path(spapr->vio_bus);
975     size_t cb = 0;
976     char *bootlist = get_boot_devices_list(&cb, true);
977 
978     _FDT(chosen = fdt_add_subnode(fdt, 0, "chosen"));
979 
980     _FDT(fdt_setprop_string(fdt, chosen, "bootargs", machine->kernel_cmdline));
981     _FDT(fdt_setprop_cell(fdt, chosen, "linux,initrd-start",
982                           spapr->initrd_base));
983     _FDT(fdt_setprop_cell(fdt, chosen, "linux,initrd-end",
984                           spapr->initrd_base + spapr->initrd_size));
985 
986     if (spapr->kernel_size) {
987         uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
988                               cpu_to_be64(spapr->kernel_size) };
989 
990         _FDT(fdt_setprop(fdt, chosen, "qemu,boot-kernel",
991                          &kprop, sizeof(kprop)));
992         if (spapr->kernel_le) {
993             _FDT(fdt_setprop(fdt, chosen, "qemu,boot-kernel-le", NULL, 0));
994         }
995     }
996     if (boot_menu) {
997         _FDT((fdt_setprop_cell(fdt, chosen, "qemu,boot-menu", boot_menu)));
998     }
999     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-width", graphic_width));
1000     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-height", graphic_height));
1001     _FDT(fdt_setprop_cell(fdt, chosen, "qemu,graphic-depth", graphic_depth));
1002 
1003     if (cb && bootlist) {
1004         int i;
1005 
1006         for (i = 0; i < cb; i++) {
1007             if (bootlist[i] == '\n') {
1008                 bootlist[i] = ' ';
1009             }
1010         }
1011         _FDT(fdt_setprop_string(fdt, chosen, "qemu,boot-list", bootlist));
1012     }
1013 
1014     if (boot_device && strlen(boot_device)) {
1015         _FDT(fdt_setprop_string(fdt, chosen, "qemu,boot-device", boot_device));
1016     }
1017 
1018     if (!spapr->has_graphics && stdout_path) {
1019         _FDT(fdt_setprop_string(fdt, chosen, "linux,stdout-path", stdout_path));
1020     }
1021 
1022     spapr_dt_ov5_platform_support(fdt, chosen);
1023 
1024     g_free(stdout_path);
1025     g_free(bootlist);
1026 }
1027 
1028 static void spapr_dt_hypervisor(sPAPRMachineState *spapr, void *fdt)
1029 {
1030     /* The /hypervisor node isn't in PAPR - this is a hack to allow PR
1031      * KVM to work under pHyp with some guest co-operation */
1032     int hypervisor;
1033     uint8_t hypercall[16];
1034 
1035     _FDT(hypervisor = fdt_add_subnode(fdt, 0, "hypervisor"));
1036     /* indicate KVM hypercall interface */
1037     _FDT(fdt_setprop_string(fdt, hypervisor, "compatible", "linux,kvm"));
1038     if (kvmppc_has_cap_fixup_hcalls()) {
1039         /*
1040          * Older KVM versions with older guest kernels were broken
1041          * with the magic page, don't allow the guest to map it.
1042          */
1043         if (!kvmppc_get_hypercall(first_cpu->env_ptr, hypercall,
1044                                   sizeof(hypercall))) {
1045             _FDT(fdt_setprop(fdt, hypervisor, "hcall-instructions",
1046                              hypercall, sizeof(hypercall)));
1047         }
1048     }
1049 }
1050 
1051 static void *spapr_build_fdt(sPAPRMachineState *spapr,
1052                              hwaddr rtas_addr,
1053                              hwaddr rtas_size)
1054 {
1055     MachineState *machine = MACHINE(qdev_get_machine());
1056     MachineClass *mc = MACHINE_GET_CLASS(machine);
1057     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
1058     int ret;
1059     void *fdt;
1060     sPAPRPHBState *phb;
1061     char *buf;
1062 
1063     fdt = g_malloc0(FDT_MAX_SIZE);
1064     _FDT((fdt_create_empty_tree(fdt, FDT_MAX_SIZE)));
1065 
1066     /* Root node */
1067     _FDT(fdt_setprop_string(fdt, 0, "device_type", "chrp"));
1068     _FDT(fdt_setprop_string(fdt, 0, "model", "IBM pSeries (emulated by qemu)"));
1069     _FDT(fdt_setprop_string(fdt, 0, "compatible", "qemu,pseries"));
1070 
1071     /*
1072      * Add info to guest to indentify which host is it being run on
1073      * and what is the uuid of the guest
1074      */
1075     if (kvmppc_get_host_model(&buf)) {
1076         _FDT(fdt_setprop_string(fdt, 0, "host-model", buf));
1077         g_free(buf);
1078     }
1079     if (kvmppc_get_host_serial(&buf)) {
1080         _FDT(fdt_setprop_string(fdt, 0, "host-serial", buf));
1081         g_free(buf);
1082     }
1083 
1084     buf = qemu_uuid_unparse_strdup(&qemu_uuid);
1085 
1086     _FDT(fdt_setprop_string(fdt, 0, "vm,uuid", buf));
1087     if (qemu_uuid_set) {
1088         _FDT(fdt_setprop_string(fdt, 0, "system-id", buf));
1089     }
1090     g_free(buf);
1091 
1092     if (qemu_get_vm_name()) {
1093         _FDT(fdt_setprop_string(fdt, 0, "ibm,partition-name",
1094                                 qemu_get_vm_name()));
1095     }
1096 
1097     _FDT(fdt_setprop_cell(fdt, 0, "#address-cells", 2));
1098     _FDT(fdt_setprop_cell(fdt, 0, "#size-cells", 2));
1099 
1100     /* /interrupt controller */
1101     spapr_dt_xics(xics_max_server_number(), fdt, PHANDLE_XICP);
1102 
1103     ret = spapr_populate_memory(spapr, fdt);
1104     if (ret < 0) {
1105         error_report("couldn't setup memory nodes in fdt");
1106         exit(1);
1107     }
1108 
1109     /* /vdevice */
1110     spapr_dt_vdevice(spapr->vio_bus, fdt);
1111 
1112     if (object_resolve_path_type("", TYPE_SPAPR_RNG, NULL)) {
1113         ret = spapr_rng_populate_dt(fdt);
1114         if (ret < 0) {
1115             error_report("could not set up rng device in the fdt");
1116             exit(1);
1117         }
1118     }
1119 
1120     QLIST_FOREACH(phb, &spapr->phbs, list) {
1121         ret = spapr_populate_pci_dt(phb, PHANDLE_XICP, fdt);
1122         if (ret < 0) {
1123             error_report("couldn't setup PCI devices in fdt");
1124             exit(1);
1125         }
1126     }
1127 
1128     /* cpus */
1129     spapr_populate_cpus_dt_node(fdt, spapr);
1130 
1131     if (smc->dr_lmb_enabled) {
1132         _FDT(spapr_drc_populate_dt(fdt, 0, NULL, SPAPR_DR_CONNECTOR_TYPE_LMB));
1133     }
1134 
1135     if (mc->has_hotpluggable_cpus) {
1136         int offset = fdt_path_offset(fdt, "/cpus");
1137         ret = spapr_drc_populate_dt(fdt, offset, NULL,
1138                                     SPAPR_DR_CONNECTOR_TYPE_CPU);
1139         if (ret < 0) {
1140             error_report("Couldn't set up CPU DR device tree properties");
1141             exit(1);
1142         }
1143     }
1144 
1145     /* /event-sources */
1146     spapr_dt_events(spapr, fdt);
1147 
1148     /* /rtas */
1149     spapr_dt_rtas(spapr, fdt);
1150 
1151     /* /chosen */
1152     spapr_dt_chosen(spapr, fdt);
1153 
1154     /* /hypervisor */
1155     if (kvm_enabled()) {
1156         spapr_dt_hypervisor(spapr, fdt);
1157     }
1158 
1159     /* Build memory reserve map */
1160     if (spapr->kernel_size) {
1161         _FDT((fdt_add_mem_rsv(fdt, KERNEL_LOAD_ADDR, spapr->kernel_size)));
1162     }
1163     if (spapr->initrd_size) {
1164         _FDT((fdt_add_mem_rsv(fdt, spapr->initrd_base, spapr->initrd_size)));
1165     }
1166 
1167     /* ibm,client-architecture-support updates */
1168     ret = spapr_dt_cas_updates(spapr, fdt, spapr->ov5_cas);
1169     if (ret < 0) {
1170         error_report("couldn't setup CAS properties fdt");
1171         exit(1);
1172     }
1173 
1174     return fdt;
1175 }
1176 
1177 static uint64_t translate_kernel_address(void *opaque, uint64_t addr)
1178 {
1179     return (addr & 0x0fffffff) + KERNEL_LOAD_ADDR;
1180 }
1181 
1182 static void emulate_spapr_hypercall(PPCVirtualHypervisor *vhyp,
1183                                     PowerPCCPU *cpu)
1184 {
1185     CPUPPCState *env = &cpu->env;
1186 
1187     /* The TCG path should also be holding the BQL at this point */
1188     g_assert(qemu_mutex_iothread_locked());
1189 
1190     if (msr_pr) {
1191         hcall_dprintf("Hypercall made with MSR[PR]=1\n");
1192         env->gpr[3] = H_PRIVILEGE;
1193     } else {
1194         env->gpr[3] = spapr_hypercall(cpu, env->gpr[3], &env->gpr[4]);
1195     }
1196 }
1197 
1198 static uint64_t spapr_get_patbe(PPCVirtualHypervisor *vhyp)
1199 {
1200     sPAPRMachineState *spapr = SPAPR_MACHINE(vhyp);
1201 
1202     return spapr->patb_entry;
1203 }
1204 
1205 #define HPTE(_table, _i)   (void *)(((uint64_t *)(_table)) + ((_i) * 2))
1206 #define HPTE_VALID(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_VALID)
1207 #define HPTE_DIRTY(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_HPTE_DIRTY)
1208 #define CLEAN_HPTE(_hpte)  ((*(uint64_t *)(_hpte)) &= tswap64(~HPTE64_V_HPTE_DIRTY))
1209 #define DIRTY_HPTE(_hpte)  ((*(uint64_t *)(_hpte)) |= tswap64(HPTE64_V_HPTE_DIRTY))
1210 
1211 /*
1212  * Get the fd to access the kernel htab, re-opening it if necessary
1213  */
1214 static int get_htab_fd(sPAPRMachineState *spapr)
1215 {
1216     if (spapr->htab_fd >= 0) {
1217         return spapr->htab_fd;
1218     }
1219 
1220     spapr->htab_fd = kvmppc_get_htab_fd(false);
1221     if (spapr->htab_fd < 0) {
1222         error_report("Unable to open fd for reading hash table from KVM: %s",
1223                      strerror(errno));
1224     }
1225 
1226     return spapr->htab_fd;
1227 }
1228 
1229 void close_htab_fd(sPAPRMachineState *spapr)
1230 {
1231     if (spapr->htab_fd >= 0) {
1232         close(spapr->htab_fd);
1233     }
1234     spapr->htab_fd = -1;
1235 }
1236 
1237 static hwaddr spapr_hpt_mask(PPCVirtualHypervisor *vhyp)
1238 {
1239     sPAPRMachineState *spapr = SPAPR_MACHINE(vhyp);
1240 
1241     return HTAB_SIZE(spapr) / HASH_PTEG_SIZE_64 - 1;
1242 }
1243 
1244 static const ppc_hash_pte64_t *spapr_map_hptes(PPCVirtualHypervisor *vhyp,
1245                                                 hwaddr ptex, int n)
1246 {
1247     sPAPRMachineState *spapr = SPAPR_MACHINE(vhyp);
1248     hwaddr pte_offset = ptex * HASH_PTE_SIZE_64;
1249 
1250     if (!spapr->htab) {
1251         /*
1252          * HTAB is controlled by KVM. Fetch into temporary buffer
1253          */
1254         ppc_hash_pte64_t *hptes = g_malloc(n * HASH_PTE_SIZE_64);
1255         kvmppc_read_hptes(hptes, ptex, n);
1256         return hptes;
1257     }
1258 
1259     /*
1260      * HTAB is controlled by QEMU. Just point to the internally
1261      * accessible PTEG.
1262      */
1263     return (const ppc_hash_pte64_t *)(spapr->htab + pte_offset);
1264 }
1265 
1266 static void spapr_unmap_hptes(PPCVirtualHypervisor *vhyp,
1267                               const ppc_hash_pte64_t *hptes,
1268                               hwaddr ptex, int n)
1269 {
1270     sPAPRMachineState *spapr = SPAPR_MACHINE(vhyp);
1271 
1272     if (!spapr->htab) {
1273         g_free((void *)hptes);
1274     }
1275 
1276     /* Nothing to do for qemu managed HPT */
1277 }
1278 
1279 static void spapr_store_hpte(PPCVirtualHypervisor *vhyp, hwaddr ptex,
1280                              uint64_t pte0, uint64_t pte1)
1281 {
1282     sPAPRMachineState *spapr = SPAPR_MACHINE(vhyp);
1283     hwaddr offset = ptex * HASH_PTE_SIZE_64;
1284 
1285     if (!spapr->htab) {
1286         kvmppc_write_hpte(ptex, pte0, pte1);
1287     } else {
1288         stq_p(spapr->htab + offset, pte0);
1289         stq_p(spapr->htab + offset + HASH_PTE_SIZE_64 / 2, pte1);
1290     }
1291 }
1292 
1293 int spapr_hpt_shift_for_ramsize(uint64_t ramsize)
1294 {
1295     int shift;
1296 
1297     /* We aim for a hash table of size 1/128 the size of RAM (rounded
1298      * up).  The PAPR recommendation is actually 1/64 of RAM size, but
1299      * that's much more than is needed for Linux guests */
1300     shift = ctz64(pow2ceil(ramsize)) - 7;
1301     shift = MAX(shift, 18); /* Minimum architected size */
1302     shift = MIN(shift, 46); /* Maximum architected size */
1303     return shift;
1304 }
1305 
1306 void spapr_free_hpt(sPAPRMachineState *spapr)
1307 {
1308     g_free(spapr->htab);
1309     spapr->htab = NULL;
1310     spapr->htab_shift = 0;
1311     close_htab_fd(spapr);
1312 }
1313 
1314 void spapr_reallocate_hpt(sPAPRMachineState *spapr, int shift,
1315                           Error **errp)
1316 {
1317     long rc;
1318 
1319     /* Clean up any HPT info from a previous boot */
1320     spapr_free_hpt(spapr);
1321 
1322     rc = kvmppc_reset_htab(shift);
1323     if (rc < 0) {
1324         /* kernel-side HPT needed, but couldn't allocate one */
1325         error_setg_errno(errp, errno,
1326                          "Failed to allocate KVM HPT of order %d (try smaller maxmem?)",
1327                          shift);
1328         /* This is almost certainly fatal, but if the caller really
1329          * wants to carry on with shift == 0, it's welcome to try */
1330     } else if (rc > 0) {
1331         /* kernel-side HPT allocated */
1332         if (rc != shift) {
1333             error_setg(errp,
1334                        "Requested order %d HPT, but kernel allocated order %ld (try smaller maxmem?)",
1335                        shift, rc);
1336         }
1337 
1338         spapr->htab_shift = shift;
1339         spapr->htab = NULL;
1340     } else {
1341         /* kernel-side HPT not needed, allocate in userspace instead */
1342         size_t size = 1ULL << shift;
1343         int i;
1344 
1345         spapr->htab = qemu_memalign(size, size);
1346         if (!spapr->htab) {
1347             error_setg_errno(errp, errno,
1348                              "Could not allocate HPT of order %d", shift);
1349             return;
1350         }
1351 
1352         memset(spapr->htab, 0, size);
1353         spapr->htab_shift = shift;
1354 
1355         for (i = 0; i < size / HASH_PTE_SIZE_64; i++) {
1356             DIRTY_HPTE(HPTE(spapr->htab, i));
1357         }
1358     }
1359 }
1360 
1361 void spapr_setup_hpt_and_vrma(sPAPRMachineState *spapr)
1362 {
1363     int hpt_shift;
1364 
1365     if ((spapr->resize_hpt == SPAPR_RESIZE_HPT_DISABLED)
1366         || (spapr->cas_reboot
1367             && !spapr_ovec_test(spapr->ov5_cas, OV5_HPT_RESIZE))) {
1368         hpt_shift = spapr_hpt_shift_for_ramsize(MACHINE(spapr)->maxram_size);
1369     } else {
1370         hpt_shift = spapr_hpt_shift_for_ramsize(MACHINE(spapr)->ram_size);
1371     }
1372     spapr_reallocate_hpt(spapr, hpt_shift, &error_fatal);
1373 
1374     if (spapr->vrma_adjust) {
1375         spapr->rma_size = kvmppc_rma_size(spapr_node0_size(),
1376                                           spapr->htab_shift);
1377     }
1378     /* We're setting up a hash table, so that means we're not radix */
1379     spapr->patb_entry = 0;
1380 }
1381 
1382 static void find_unknown_sysbus_device(SysBusDevice *sbdev, void *opaque)
1383 {
1384     bool matched = false;
1385 
1386     if (object_dynamic_cast(OBJECT(sbdev), TYPE_SPAPR_PCI_HOST_BRIDGE)) {
1387         matched = true;
1388     }
1389 
1390     if (!matched) {
1391         error_report("Device %s is not supported by this machine yet.",
1392                      qdev_fw_name(DEVICE(sbdev)));
1393         exit(1);
1394     }
1395 }
1396 
1397 static void ppc_spapr_reset(void)
1398 {
1399     MachineState *machine = MACHINE(qdev_get_machine());
1400     sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
1401     PowerPCCPU *first_ppc_cpu;
1402     uint32_t rtas_limit;
1403     hwaddr rtas_addr, fdt_addr;
1404     void *fdt;
1405     int rc;
1406 
1407     /* Check for unknown sysbus devices */
1408     foreach_dynamic_sysbus_device(find_unknown_sysbus_device, NULL);
1409 
1410     if (kvm_enabled() && kvmppc_has_cap_mmu_radix()) {
1411         /* If using KVM with radix mode available, VCPUs can be started
1412          * without a HPT because KVM will start them in radix mode.
1413          * Set the GR bit in PATB so that we know there is no HPT. */
1414         spapr->patb_entry = PATBE1_GR;
1415     } else {
1416         spapr_setup_hpt_and_vrma(spapr);
1417     }
1418 
1419     qemu_devices_reset();
1420     spapr_clear_pending_events(spapr);
1421 
1422     /*
1423      * We place the device tree and RTAS just below either the top of the RMA,
1424      * or just below 2GB, whichever is lowere, so that it can be
1425      * processed with 32-bit real mode code if necessary
1426      */
1427     rtas_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR);
1428     rtas_addr = rtas_limit - RTAS_MAX_SIZE;
1429     fdt_addr = rtas_addr - FDT_MAX_SIZE;
1430 
1431     /* if this reset wasn't generated by CAS, we should reset our
1432      * negotiated options and start from scratch */
1433     if (!spapr->cas_reboot) {
1434         spapr_ovec_cleanup(spapr->ov5_cas);
1435         spapr->ov5_cas = spapr_ovec_new();
1436 
1437         ppc_set_compat_all(spapr->max_compat_pvr, &error_fatal);
1438     }
1439 
1440     fdt = spapr_build_fdt(spapr, rtas_addr, spapr->rtas_size);
1441 
1442     spapr_load_rtas(spapr, fdt, rtas_addr);
1443 
1444     rc = fdt_pack(fdt);
1445 
1446     /* Should only fail if we've built a corrupted tree */
1447     assert(rc == 0);
1448 
1449     if (fdt_totalsize(fdt) > FDT_MAX_SIZE) {
1450         error_report("FDT too big ! 0x%x bytes (max is 0x%x)",
1451                      fdt_totalsize(fdt), FDT_MAX_SIZE);
1452         exit(1);
1453     }
1454 
1455     /* Load the fdt */
1456     qemu_fdt_dumpdtb(fdt, fdt_totalsize(fdt));
1457     cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt));
1458     g_free(fdt);
1459 
1460     /* Set up the entry state */
1461     first_ppc_cpu = POWERPC_CPU(first_cpu);
1462     first_ppc_cpu->env.gpr[3] = fdt_addr;
1463     first_ppc_cpu->env.gpr[5] = 0;
1464     first_cpu->halted = 0;
1465     first_ppc_cpu->env.nip = SPAPR_ENTRY_POINT;
1466 
1467     spapr->cas_reboot = false;
1468 }
1469 
1470 static void spapr_create_nvram(sPAPRMachineState *spapr)
1471 {
1472     DeviceState *dev = qdev_create(&spapr->vio_bus->bus, "spapr-nvram");
1473     DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);
1474 
1475     if (dinfo) {
1476         qdev_prop_set_drive(dev, "drive", blk_by_legacy_dinfo(dinfo),
1477                             &error_fatal);
1478     }
1479 
1480     qdev_init_nofail(dev);
1481 
1482     spapr->nvram = (struct sPAPRNVRAM *)dev;
1483 }
1484 
1485 static void spapr_rtc_create(sPAPRMachineState *spapr)
1486 {
1487     object_initialize(&spapr->rtc, sizeof(spapr->rtc), TYPE_SPAPR_RTC);
1488     object_property_add_child(OBJECT(spapr), "rtc", OBJECT(&spapr->rtc),
1489                               &error_fatal);
1490     object_property_set_bool(OBJECT(&spapr->rtc), true, "realized",
1491                               &error_fatal);
1492     object_property_add_alias(OBJECT(spapr), "rtc-time", OBJECT(&spapr->rtc),
1493                               "date", &error_fatal);
1494 }
1495 
1496 /* Returns whether we want to use VGA or not */
1497 static bool spapr_vga_init(PCIBus *pci_bus, Error **errp)
1498 {
1499     switch (vga_interface_type) {
1500     case VGA_NONE:
1501         return false;
1502     case VGA_DEVICE:
1503         return true;
1504     case VGA_STD:
1505     case VGA_VIRTIO:
1506         return pci_vga_init(pci_bus) != NULL;
1507     default:
1508         error_setg(errp,
1509                    "Unsupported VGA mode, only -vga std or -vga virtio is supported");
1510         return false;
1511     }
1512 }
1513 
1514 static int spapr_post_load(void *opaque, int version_id)
1515 {
1516     sPAPRMachineState *spapr = (sPAPRMachineState *)opaque;
1517     int err = 0;
1518 
1519     if (!object_dynamic_cast(OBJECT(spapr->ics), TYPE_ICS_KVM)) {
1520         CPUState *cs;
1521         CPU_FOREACH(cs) {
1522             PowerPCCPU *cpu = POWERPC_CPU(cs);
1523             icp_resend(ICP(cpu->intc));
1524         }
1525     }
1526 
1527     /* In earlier versions, there was no separate qdev for the PAPR
1528      * RTC, so the RTC offset was stored directly in sPAPREnvironment.
1529      * So when migrating from those versions, poke the incoming offset
1530      * value into the RTC device */
1531     if (version_id < 3) {
1532         err = spapr_rtc_import_offset(&spapr->rtc, spapr->rtc_offset);
1533     }
1534 
1535     if (spapr->patb_entry) {
1536         PowerPCCPU *cpu = POWERPC_CPU(first_cpu);
1537         bool radix = !!(spapr->patb_entry & PATBE1_GR);
1538         bool gtse = !!(cpu->env.spr[SPR_LPCR] & LPCR_GTSE);
1539 
1540         err = kvmppc_configure_v3_mmu(cpu, radix, gtse, spapr->patb_entry);
1541         if (err) {
1542             error_report("Process table config unsupported by the host");
1543             return -EINVAL;
1544         }
1545     }
1546 
1547     return err;
1548 }
1549 
1550 static bool version_before_3(void *opaque, int version_id)
1551 {
1552     return version_id < 3;
1553 }
1554 
1555 static bool spapr_pending_events_needed(void *opaque)
1556 {
1557     sPAPRMachineState *spapr = (sPAPRMachineState *)opaque;
1558     return !QTAILQ_EMPTY(&spapr->pending_events);
1559 }
1560 
1561 static const VMStateDescription vmstate_spapr_event_entry = {
1562     .name = "spapr_event_log_entry",
1563     .version_id = 1,
1564     .minimum_version_id = 1,
1565     .fields = (VMStateField[]) {
1566         VMSTATE_UINT32(summary, sPAPREventLogEntry),
1567         VMSTATE_UINT32(extended_length, sPAPREventLogEntry),
1568         VMSTATE_VBUFFER_ALLOC_UINT32(extended_log, sPAPREventLogEntry, 0,
1569                                      NULL, extended_length),
1570         VMSTATE_END_OF_LIST()
1571     },
1572 };
1573 
1574 static const VMStateDescription vmstate_spapr_pending_events = {
1575     .name = "spapr_pending_events",
1576     .version_id = 1,
1577     .minimum_version_id = 1,
1578     .needed = spapr_pending_events_needed,
1579     .fields = (VMStateField[]) {
1580         VMSTATE_QTAILQ_V(pending_events, sPAPRMachineState, 1,
1581                          vmstate_spapr_event_entry, sPAPREventLogEntry, next),
1582         VMSTATE_END_OF_LIST()
1583     },
1584 };
1585 
1586 static bool spapr_ov5_cas_needed(void *opaque)
1587 {
1588     sPAPRMachineState *spapr = opaque;
1589     sPAPROptionVector *ov5_mask = spapr_ovec_new();
1590     sPAPROptionVector *ov5_legacy = spapr_ovec_new();
1591     sPAPROptionVector *ov5_removed = spapr_ovec_new();
1592     bool cas_needed;
1593 
1594     /* Prior to the introduction of sPAPROptionVector, we had two option
1595      * vectors we dealt with: OV5_FORM1_AFFINITY, and OV5_DRCONF_MEMORY.
1596      * Both of these options encode machine topology into the device-tree
1597      * in such a way that the now-booted OS should still be able to interact
1598      * appropriately with QEMU regardless of what options were actually
1599      * negotiatied on the source side.
1600      *
1601      * As such, we can avoid migrating the CAS-negotiated options if these
1602      * are the only options available on the current machine/platform.
1603      * Since these are the only options available for pseries-2.7 and
1604      * earlier, this allows us to maintain old->new/new->old migration
1605      * compatibility.
1606      *
1607      * For QEMU 2.8+, there are additional CAS-negotiatable options available
1608      * via default pseries-2.8 machines and explicit command-line parameters.
1609      * Some of these options, like OV5_HP_EVT, *do* require QEMU to be aware
1610      * of the actual CAS-negotiated values to continue working properly. For
1611      * example, availability of memory unplug depends on knowing whether
1612      * OV5_HP_EVT was negotiated via CAS.
1613      *
1614      * Thus, for any cases where the set of available CAS-negotiatable
1615      * options extends beyond OV5_FORM1_AFFINITY and OV5_DRCONF_MEMORY, we
1616      * include the CAS-negotiated options in the migration stream.
1617      */
1618     spapr_ovec_set(ov5_mask, OV5_FORM1_AFFINITY);
1619     spapr_ovec_set(ov5_mask, OV5_DRCONF_MEMORY);
1620 
1621     /* spapr_ovec_diff returns true if bits were removed. we avoid using
1622      * the mask itself since in the future it's possible "legacy" bits may be
1623      * removed via machine options, which could generate a false positive
1624      * that breaks migration.
1625      */
1626     spapr_ovec_intersect(ov5_legacy, spapr->ov5, ov5_mask);
1627     cas_needed = spapr_ovec_diff(ov5_removed, spapr->ov5, ov5_legacy);
1628 
1629     spapr_ovec_cleanup(ov5_mask);
1630     spapr_ovec_cleanup(ov5_legacy);
1631     spapr_ovec_cleanup(ov5_removed);
1632 
1633     return cas_needed;
1634 }
1635 
1636 static const VMStateDescription vmstate_spapr_ov5_cas = {
1637     .name = "spapr_option_vector_ov5_cas",
1638     .version_id = 1,
1639     .minimum_version_id = 1,
1640     .needed = spapr_ov5_cas_needed,
1641     .fields = (VMStateField[]) {
1642         VMSTATE_STRUCT_POINTER_V(ov5_cas, sPAPRMachineState, 1,
1643                                  vmstate_spapr_ovec, sPAPROptionVector),
1644         VMSTATE_END_OF_LIST()
1645     },
1646 };
1647 
1648 static bool spapr_patb_entry_needed(void *opaque)
1649 {
1650     sPAPRMachineState *spapr = opaque;
1651 
1652     return !!spapr->patb_entry;
1653 }
1654 
1655 static const VMStateDescription vmstate_spapr_patb_entry = {
1656     .name = "spapr_patb_entry",
1657     .version_id = 1,
1658     .minimum_version_id = 1,
1659     .needed = spapr_patb_entry_needed,
1660     .fields = (VMStateField[]) {
1661         VMSTATE_UINT64(patb_entry, sPAPRMachineState),
1662         VMSTATE_END_OF_LIST()
1663     },
1664 };
1665 
1666 static const VMStateDescription vmstate_spapr = {
1667     .name = "spapr",
1668     .version_id = 3,
1669     .minimum_version_id = 1,
1670     .post_load = spapr_post_load,
1671     .fields = (VMStateField[]) {
1672         /* used to be @next_irq */
1673         VMSTATE_UNUSED_BUFFER(version_before_3, 0, 4),
1674 
1675         /* RTC offset */
1676         VMSTATE_UINT64_TEST(rtc_offset, sPAPRMachineState, version_before_3),
1677 
1678         VMSTATE_PPC_TIMEBASE_V(tb, sPAPRMachineState, 2),
1679         VMSTATE_END_OF_LIST()
1680     },
1681     .subsections = (const VMStateDescription*[]) {
1682         &vmstate_spapr_ov5_cas,
1683         &vmstate_spapr_patb_entry,
1684         &vmstate_spapr_pending_events,
1685         NULL
1686     }
1687 };
1688 
1689 static int htab_save_setup(QEMUFile *f, void *opaque)
1690 {
1691     sPAPRMachineState *spapr = opaque;
1692 
1693     /* "Iteration" header */
1694     if (!spapr->htab_shift) {
1695         qemu_put_be32(f, -1);
1696     } else {
1697         qemu_put_be32(f, spapr->htab_shift);
1698     }
1699 
1700     if (spapr->htab) {
1701         spapr->htab_save_index = 0;
1702         spapr->htab_first_pass = true;
1703     } else {
1704         if (spapr->htab_shift) {
1705             assert(kvm_enabled());
1706         }
1707     }
1708 
1709 
1710     return 0;
1711 }
1712 
1713 static void htab_save_first_pass(QEMUFile *f, sPAPRMachineState *spapr,
1714                                  int64_t max_ns)
1715 {
1716     bool has_timeout = max_ns != -1;
1717     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
1718     int index = spapr->htab_save_index;
1719     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1720 
1721     assert(spapr->htab_first_pass);
1722 
1723     do {
1724         int chunkstart;
1725 
1726         /* Consume invalid HPTEs */
1727         while ((index < htabslots)
1728                && !HPTE_VALID(HPTE(spapr->htab, index))) {
1729             CLEAN_HPTE(HPTE(spapr->htab, index));
1730             index++;
1731         }
1732 
1733         /* Consume valid HPTEs */
1734         chunkstart = index;
1735         while ((index < htabslots) && (index - chunkstart < USHRT_MAX)
1736                && HPTE_VALID(HPTE(spapr->htab, index))) {
1737             CLEAN_HPTE(HPTE(spapr->htab, index));
1738             index++;
1739         }
1740 
1741         if (index > chunkstart) {
1742             int n_valid = index - chunkstart;
1743 
1744             qemu_put_be32(f, chunkstart);
1745             qemu_put_be16(f, n_valid);
1746             qemu_put_be16(f, 0);
1747             qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),
1748                             HASH_PTE_SIZE_64 * n_valid);
1749 
1750             if (has_timeout &&
1751                 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
1752                 break;
1753             }
1754         }
1755     } while ((index < htabslots) && !qemu_file_rate_limit(f));
1756 
1757     if (index >= htabslots) {
1758         assert(index == htabslots);
1759         index = 0;
1760         spapr->htab_first_pass = false;
1761     }
1762     spapr->htab_save_index = index;
1763 }
1764 
1765 static int htab_save_later_pass(QEMUFile *f, sPAPRMachineState *spapr,
1766                                 int64_t max_ns)
1767 {
1768     bool final = max_ns < 0;
1769     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
1770     int examined = 0, sent = 0;
1771     int index = spapr->htab_save_index;
1772     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1773 
1774     assert(!spapr->htab_first_pass);
1775 
1776     do {
1777         int chunkstart, invalidstart;
1778 
1779         /* Consume non-dirty HPTEs */
1780         while ((index < htabslots)
1781                && !HPTE_DIRTY(HPTE(spapr->htab, index))) {
1782             index++;
1783             examined++;
1784         }
1785 
1786         chunkstart = index;
1787         /* Consume valid dirty HPTEs */
1788         while ((index < htabslots) && (index - chunkstart < USHRT_MAX)
1789                && HPTE_DIRTY(HPTE(spapr->htab, index))
1790                && HPTE_VALID(HPTE(spapr->htab, index))) {
1791             CLEAN_HPTE(HPTE(spapr->htab, index));
1792             index++;
1793             examined++;
1794         }
1795 
1796         invalidstart = index;
1797         /* Consume invalid dirty HPTEs */
1798         while ((index < htabslots) && (index - invalidstart < USHRT_MAX)
1799                && HPTE_DIRTY(HPTE(spapr->htab, index))
1800                && !HPTE_VALID(HPTE(spapr->htab, index))) {
1801             CLEAN_HPTE(HPTE(spapr->htab, index));
1802             index++;
1803             examined++;
1804         }
1805 
1806         if (index > chunkstart) {
1807             int n_valid = invalidstart - chunkstart;
1808             int n_invalid = index - invalidstart;
1809 
1810             qemu_put_be32(f, chunkstart);
1811             qemu_put_be16(f, n_valid);
1812             qemu_put_be16(f, n_invalid);
1813             qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),
1814                             HASH_PTE_SIZE_64 * n_valid);
1815             sent += index - chunkstart;
1816 
1817             if (!final && (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
1818                 break;
1819             }
1820         }
1821 
1822         if (examined >= htabslots) {
1823             break;
1824         }
1825 
1826         if (index >= htabslots) {
1827             assert(index == htabslots);
1828             index = 0;
1829         }
1830     } while ((examined < htabslots) && (!qemu_file_rate_limit(f) || final));
1831 
1832     if (index >= htabslots) {
1833         assert(index == htabslots);
1834         index = 0;
1835     }
1836 
1837     spapr->htab_save_index = index;
1838 
1839     return (examined >= htabslots) && (sent == 0) ? 1 : 0;
1840 }
1841 
1842 #define MAX_ITERATION_NS    5000000 /* 5 ms */
1843 #define MAX_KVM_BUF_SIZE    2048
1844 
1845 static int htab_save_iterate(QEMUFile *f, void *opaque)
1846 {
1847     sPAPRMachineState *spapr = opaque;
1848     int fd;
1849     int rc = 0;
1850 
1851     /* Iteration header */
1852     if (!spapr->htab_shift) {
1853         qemu_put_be32(f, -1);
1854         return 1;
1855     } else {
1856         qemu_put_be32(f, 0);
1857     }
1858 
1859     if (!spapr->htab) {
1860         assert(kvm_enabled());
1861 
1862         fd = get_htab_fd(spapr);
1863         if (fd < 0) {
1864             return fd;
1865         }
1866 
1867         rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, MAX_ITERATION_NS);
1868         if (rc < 0) {
1869             return rc;
1870         }
1871     } else  if (spapr->htab_first_pass) {
1872         htab_save_first_pass(f, spapr, MAX_ITERATION_NS);
1873     } else {
1874         rc = htab_save_later_pass(f, spapr, MAX_ITERATION_NS);
1875     }
1876 
1877     /* End marker */
1878     qemu_put_be32(f, 0);
1879     qemu_put_be16(f, 0);
1880     qemu_put_be16(f, 0);
1881 
1882     return rc;
1883 }
1884 
1885 static int htab_save_complete(QEMUFile *f, void *opaque)
1886 {
1887     sPAPRMachineState *spapr = opaque;
1888     int fd;
1889 
1890     /* Iteration header */
1891     if (!spapr->htab_shift) {
1892         qemu_put_be32(f, -1);
1893         return 0;
1894     } else {
1895         qemu_put_be32(f, 0);
1896     }
1897 
1898     if (!spapr->htab) {
1899         int rc;
1900 
1901         assert(kvm_enabled());
1902 
1903         fd = get_htab_fd(spapr);
1904         if (fd < 0) {
1905             return fd;
1906         }
1907 
1908         rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, -1);
1909         if (rc < 0) {
1910             return rc;
1911         }
1912     } else {
1913         if (spapr->htab_first_pass) {
1914             htab_save_first_pass(f, spapr, -1);
1915         }
1916         htab_save_later_pass(f, spapr, -1);
1917     }
1918 
1919     /* End marker */
1920     qemu_put_be32(f, 0);
1921     qemu_put_be16(f, 0);
1922     qemu_put_be16(f, 0);
1923 
1924     return 0;
1925 }
1926 
1927 static int htab_load(QEMUFile *f, void *opaque, int version_id)
1928 {
1929     sPAPRMachineState *spapr = opaque;
1930     uint32_t section_hdr;
1931     int fd = -1;
1932 
1933     if (version_id < 1 || version_id > 1) {
1934         error_report("htab_load() bad version");
1935         return -EINVAL;
1936     }
1937 
1938     section_hdr = qemu_get_be32(f);
1939 
1940     if (section_hdr == -1) {
1941         spapr_free_hpt(spapr);
1942         return 0;
1943     }
1944 
1945     if (section_hdr) {
1946         Error *local_err = NULL;
1947 
1948         /* First section gives the htab size */
1949         spapr_reallocate_hpt(spapr, section_hdr, &local_err);
1950         if (local_err) {
1951             error_report_err(local_err);
1952             return -EINVAL;
1953         }
1954         return 0;
1955     }
1956 
1957     if (!spapr->htab) {
1958         assert(kvm_enabled());
1959 
1960         fd = kvmppc_get_htab_fd(true);
1961         if (fd < 0) {
1962             error_report("Unable to open fd to restore KVM hash table: %s",
1963                          strerror(errno));
1964         }
1965     }
1966 
1967     while (true) {
1968         uint32_t index;
1969         uint16_t n_valid, n_invalid;
1970 
1971         index = qemu_get_be32(f);
1972         n_valid = qemu_get_be16(f);
1973         n_invalid = qemu_get_be16(f);
1974 
1975         if ((index == 0) && (n_valid == 0) && (n_invalid == 0)) {
1976             /* End of Stream */
1977             break;
1978         }
1979 
1980         if ((index + n_valid + n_invalid) >
1981             (HTAB_SIZE(spapr) / HASH_PTE_SIZE_64)) {
1982             /* Bad index in stream */
1983             error_report(
1984                 "htab_load() bad index %d (%hd+%hd entries) in htab stream (htab_shift=%d)",
1985                 index, n_valid, n_invalid, spapr->htab_shift);
1986             return -EINVAL;
1987         }
1988 
1989         if (spapr->htab) {
1990             if (n_valid) {
1991                 qemu_get_buffer(f, HPTE(spapr->htab, index),
1992                                 HASH_PTE_SIZE_64 * n_valid);
1993             }
1994             if (n_invalid) {
1995                 memset(HPTE(spapr->htab, index + n_valid), 0,
1996                        HASH_PTE_SIZE_64 * n_invalid);
1997             }
1998         } else {
1999             int rc;
2000 
2001             assert(fd >= 0);
2002 
2003             rc = kvmppc_load_htab_chunk(f, fd, index, n_valid, n_invalid);
2004             if (rc < 0) {
2005                 return rc;
2006             }
2007         }
2008     }
2009 
2010     if (!spapr->htab) {
2011         assert(fd >= 0);
2012         close(fd);
2013     }
2014 
2015     return 0;
2016 }
2017 
2018 static void htab_save_cleanup(void *opaque)
2019 {
2020     sPAPRMachineState *spapr = opaque;
2021 
2022     close_htab_fd(spapr);
2023 }
2024 
2025 static SaveVMHandlers savevm_htab_handlers = {
2026     .save_setup = htab_save_setup,
2027     .save_live_iterate = htab_save_iterate,
2028     .save_live_complete_precopy = htab_save_complete,
2029     .save_cleanup = htab_save_cleanup,
2030     .load_state = htab_load,
2031 };
2032 
2033 static void spapr_boot_set(void *opaque, const char *boot_device,
2034                            Error **errp)
2035 {
2036     MachineState *machine = MACHINE(qdev_get_machine());
2037     machine->boot_order = g_strdup(boot_device);
2038 }
2039 
2040 static void spapr_create_lmb_dr_connectors(sPAPRMachineState *spapr)
2041 {
2042     MachineState *machine = MACHINE(spapr);
2043     uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;
2044     uint32_t nr_lmbs = (machine->maxram_size - machine->ram_size)/lmb_size;
2045     int i;
2046 
2047     for (i = 0; i < nr_lmbs; i++) {
2048         uint64_t addr;
2049 
2050         addr = i * lmb_size + spapr->hotplug_memory.base;
2051         spapr_dr_connector_new(OBJECT(spapr), TYPE_SPAPR_DRC_LMB,
2052                                addr / lmb_size);
2053     }
2054 }
2055 
2056 /*
2057  * If RAM size, maxmem size and individual node mem sizes aren't aligned
2058  * to SPAPR_MEMORY_BLOCK_SIZE(256MB), then refuse to start the guest
2059  * since we can't support such unaligned sizes with DRCONF_MEMORY.
2060  */
2061 static void spapr_validate_node_memory(MachineState *machine, Error **errp)
2062 {
2063     int i;
2064 
2065     if (machine->ram_size % SPAPR_MEMORY_BLOCK_SIZE) {
2066         error_setg(errp, "Memory size 0x" RAM_ADDR_FMT
2067                    " is not aligned to %llu MiB",
2068                    machine->ram_size,
2069                    SPAPR_MEMORY_BLOCK_SIZE / M_BYTE);
2070         return;
2071     }
2072 
2073     if (machine->maxram_size % SPAPR_MEMORY_BLOCK_SIZE) {
2074         error_setg(errp, "Maximum memory size 0x" RAM_ADDR_FMT
2075                    " is not aligned to %llu MiB",
2076                    machine->ram_size,
2077                    SPAPR_MEMORY_BLOCK_SIZE / M_BYTE);
2078         return;
2079     }
2080 
2081     for (i = 0; i < nb_numa_nodes; i++) {
2082         if (numa_info[i].node_mem % SPAPR_MEMORY_BLOCK_SIZE) {
2083             error_setg(errp,
2084                        "Node %d memory size 0x%" PRIx64
2085                        " is not aligned to %llu MiB",
2086                        i, numa_info[i].node_mem,
2087                        SPAPR_MEMORY_BLOCK_SIZE / M_BYTE);
2088             return;
2089         }
2090     }
2091 }
2092 
2093 /* find cpu slot in machine->possible_cpus by core_id */
2094 static CPUArchId *spapr_find_cpu_slot(MachineState *ms, uint32_t id, int *idx)
2095 {
2096     int index = id / smp_threads;
2097 
2098     if (index >= ms->possible_cpus->len) {
2099         return NULL;
2100     }
2101     if (idx) {
2102         *idx = index;
2103     }
2104     return &ms->possible_cpus->cpus[index];
2105 }
2106 
2107 static void spapr_init_cpus(sPAPRMachineState *spapr)
2108 {
2109     MachineState *machine = MACHINE(spapr);
2110     MachineClass *mc = MACHINE_GET_CLASS(machine);
2111     char *type = spapr_get_cpu_core_type(machine->cpu_model);
2112     int smt = kvmppc_smt_threads();
2113     const CPUArchIdList *possible_cpus;
2114     int boot_cores_nr = smp_cpus / smp_threads;
2115     int i;
2116 
2117     if (!type) {
2118         error_report("Unable to find sPAPR CPU Core definition");
2119         exit(1);
2120     }
2121 
2122     possible_cpus = mc->possible_cpu_arch_ids(machine);
2123     if (mc->has_hotpluggable_cpus) {
2124         if (smp_cpus % smp_threads) {
2125             error_report("smp_cpus (%u) must be multiple of threads (%u)",
2126                          smp_cpus, smp_threads);
2127             exit(1);
2128         }
2129         if (max_cpus % smp_threads) {
2130             error_report("max_cpus (%u) must be multiple of threads (%u)",
2131                          max_cpus, smp_threads);
2132             exit(1);
2133         }
2134     } else {
2135         if (max_cpus != smp_cpus) {
2136             error_report("This machine version does not support CPU hotplug");
2137             exit(1);
2138         }
2139         boot_cores_nr = possible_cpus->len;
2140     }
2141 
2142     for (i = 0; i < possible_cpus->len; i++) {
2143         int core_id = i * smp_threads;
2144 
2145         if (mc->has_hotpluggable_cpus) {
2146             spapr_dr_connector_new(OBJECT(spapr), TYPE_SPAPR_DRC_CPU,
2147                                    (core_id / smp_threads) * smt);
2148         }
2149 
2150         if (i < boot_cores_nr) {
2151             Object *core  = object_new(type);
2152             int nr_threads = smp_threads;
2153 
2154             /* Handle the partially filled core for older machine types */
2155             if ((i + 1) * smp_threads >= smp_cpus) {
2156                 nr_threads = smp_cpus - i * smp_threads;
2157             }
2158 
2159             object_property_set_int(core, nr_threads, "nr-threads",
2160                                     &error_fatal);
2161             object_property_set_int(core, core_id, CPU_CORE_PROP_CORE_ID,
2162                                     &error_fatal);
2163             object_property_set_bool(core, true, "realized", &error_fatal);
2164         }
2165     }
2166     g_free(type);
2167 }
2168 
2169 static void spapr_set_vsmt_mode(sPAPRMachineState *spapr, Error **errp)
2170 {
2171     Error *local_err = NULL;
2172     bool vsmt_user = !!spapr->vsmt;
2173     int kvm_smt = kvmppc_smt_threads();
2174     int ret;
2175 
2176     if (!kvm_enabled() && (smp_threads > 1)) {
2177         error_setg(&local_err, "TCG cannot support more than 1 thread/core "
2178                      "on a pseries machine");
2179         goto out;
2180     }
2181     if (!is_power_of_2(smp_threads)) {
2182         error_setg(&local_err, "Cannot support %d threads/core on a pseries "
2183                      "machine because it must be a power of 2", smp_threads);
2184         goto out;
2185     }
2186 
2187     /* Detemine the VSMT mode to use: */
2188     if (vsmt_user) {
2189         if (spapr->vsmt < smp_threads) {
2190             error_setg(&local_err, "Cannot support VSMT mode %d"
2191                          " because it must be >= threads/core (%d)",
2192                          spapr->vsmt, smp_threads);
2193             goto out;
2194         }
2195         /* In this case, spapr->vsmt has been set by the command line */
2196     } else {
2197         /* Choose a VSMT mode that may be higher than necessary but is
2198          * likely to be compatible with hosts that don't have VSMT. */
2199         spapr->vsmt = MAX(kvm_smt, smp_threads);
2200     }
2201 
2202     /* KVM: If necessary, set the SMT mode: */
2203     if (kvm_enabled() && (spapr->vsmt != kvm_smt)) {
2204         ret = kvmppc_set_smt_threads(spapr->vsmt);
2205         if (ret) {
2206             error_setg(&local_err,
2207                        "Failed to set KVM's VSMT mode to %d (errno %d)",
2208                        spapr->vsmt, ret);
2209             if (!vsmt_user) {
2210                 error_append_hint(&local_err, "On PPC, a VM with %d threads/"
2211                              "core on a host with %d threads/core requires "
2212                              " the use of VSMT mode %d.\n",
2213                              smp_threads, kvm_smt, spapr->vsmt);
2214             }
2215             kvmppc_hint_smt_possible(&local_err);
2216             goto out;
2217         }
2218     }
2219     /* else TCG: nothing to do currently */
2220 out:
2221     error_propagate(errp, local_err);
2222 }
2223 
2224 /* pSeries LPAR / sPAPR hardware init */
2225 static void ppc_spapr_init(MachineState *machine)
2226 {
2227     sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
2228     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
2229     const char *kernel_filename = machine->kernel_filename;
2230     const char *initrd_filename = machine->initrd_filename;
2231     PCIHostState *phb;
2232     int i;
2233     MemoryRegion *sysmem = get_system_memory();
2234     MemoryRegion *ram = g_new(MemoryRegion, 1);
2235     MemoryRegion *rma_region;
2236     void *rma = NULL;
2237     hwaddr rma_alloc_size;
2238     hwaddr node0_size = spapr_node0_size();
2239     long load_limit, fw_size;
2240     char *filename;
2241     Error *resize_hpt_err = NULL;
2242 
2243     msi_nonbroken = true;
2244 
2245     QLIST_INIT(&spapr->phbs);
2246     QTAILQ_INIT(&spapr->pending_dimm_unplugs);
2247 
2248     /* Check HPT resizing availability */
2249     kvmppc_check_papr_resize_hpt(&resize_hpt_err);
2250     if (spapr->resize_hpt == SPAPR_RESIZE_HPT_DEFAULT) {
2251         /*
2252          * If the user explicitly requested a mode we should either
2253          * supply it, or fail completely (which we do below).  But if
2254          * it's not set explicitly, we reset our mode to something
2255          * that works
2256          */
2257         if (resize_hpt_err) {
2258             spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
2259             error_free(resize_hpt_err);
2260             resize_hpt_err = NULL;
2261         } else {
2262             spapr->resize_hpt = smc->resize_hpt_default;
2263         }
2264     }
2265 
2266     assert(spapr->resize_hpt != SPAPR_RESIZE_HPT_DEFAULT);
2267 
2268     if ((spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) && resize_hpt_err) {
2269         /*
2270          * User requested HPT resize, but this host can't supply it.  Bail out
2271          */
2272         error_report_err(resize_hpt_err);
2273         exit(1);
2274     }
2275 
2276     /* Allocate RMA if necessary */
2277     rma_alloc_size = kvmppc_alloc_rma(&rma);
2278 
2279     if (rma_alloc_size == -1) {
2280         error_report("Unable to create RMA");
2281         exit(1);
2282     }
2283 
2284     if (rma_alloc_size && (rma_alloc_size < node0_size)) {
2285         spapr->rma_size = rma_alloc_size;
2286     } else {
2287         spapr->rma_size = node0_size;
2288 
2289         /* With KVM, we don't actually know whether KVM supports an
2290          * unbounded RMA (PR KVM) or is limited by the hash table size
2291          * (HV KVM using VRMA), so we always assume the latter
2292          *
2293          * In that case, we also limit the initial allocations for RTAS
2294          * etc... to 256M since we have no way to know what the VRMA size
2295          * is going to be as it depends on the size of the hash table
2296          * isn't determined yet.
2297          */
2298         if (kvm_enabled()) {
2299             spapr->vrma_adjust = 1;
2300             spapr->rma_size = MIN(spapr->rma_size, 0x10000000);
2301         }
2302 
2303         /* Actually we don't support unbounded RMA anymore since we
2304          * added proper emulation of HV mode. The max we can get is
2305          * 16G which also happens to be what we configure for PAPR
2306          * mode so make sure we don't do anything bigger than that
2307          */
2308         spapr->rma_size = MIN(spapr->rma_size, 0x400000000ull);
2309     }
2310 
2311     if (spapr->rma_size > node0_size) {
2312         error_report("Numa node 0 has to span the RMA (%#08"HWADDR_PRIx")",
2313                      spapr->rma_size);
2314         exit(1);
2315     }
2316 
2317     /* Setup a load limit for the ramdisk leaving room for SLOF and FDT */
2318     load_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR) - FW_OVERHEAD;
2319 
2320     /* Set up Interrupt Controller before we create the VCPUs */
2321     xics_system_init(machine, XICS_IRQS_SPAPR, &error_fatal);
2322 
2323     /* Set up containers for ibm,client-set-architecture negotiated options */
2324     spapr->ov5 = spapr_ovec_new();
2325     spapr->ov5_cas = spapr_ovec_new();
2326 
2327     if (smc->dr_lmb_enabled) {
2328         spapr_ovec_set(spapr->ov5, OV5_DRCONF_MEMORY);
2329         spapr_validate_node_memory(machine, &error_fatal);
2330     }
2331 
2332     spapr_ovec_set(spapr->ov5, OV5_FORM1_AFFINITY);
2333     if (!kvm_enabled() || kvmppc_has_cap_mmu_radix()) {
2334         /* KVM and TCG always allow GTSE with radix... */
2335         spapr_ovec_set(spapr->ov5, OV5_MMU_RADIX_GTSE);
2336     }
2337     /* ... but not with hash (currently). */
2338 
2339     /* advertise support for dedicated HP event source to guests */
2340     if (spapr->use_hotplug_event_source) {
2341         spapr_ovec_set(spapr->ov5, OV5_HP_EVT);
2342     }
2343 
2344     /* advertise support for HPT resizing */
2345     if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {
2346         spapr_ovec_set(spapr->ov5, OV5_HPT_RESIZE);
2347     }
2348 
2349     /* init CPUs */
2350     if (machine->cpu_model == NULL) {
2351         machine->cpu_model = kvm_enabled() ? "host" : smc->tcg_default_cpu;
2352     }
2353 
2354     spapr_cpu_parse_features(spapr);
2355 
2356     spapr_set_vsmt_mode(spapr, &error_fatal);
2357 
2358     spapr_init_cpus(spapr);
2359 
2360     if (kvm_enabled()) {
2361         /* Enable H_LOGICAL_CI_* so SLOF can talk to in-kernel devices */
2362         kvmppc_enable_logical_ci_hcalls();
2363         kvmppc_enable_set_mode_hcall();
2364 
2365         /* H_CLEAR_MOD/_REF are mandatory in PAPR, but off by default */
2366         kvmppc_enable_clear_ref_mod_hcalls();
2367     }
2368 
2369     /* allocate RAM */
2370     memory_region_allocate_system_memory(ram, NULL, "ppc_spapr.ram",
2371                                          machine->ram_size);
2372     memory_region_add_subregion(sysmem, 0, ram);
2373 
2374     if (rma_alloc_size && rma) {
2375         rma_region = g_new(MemoryRegion, 1);
2376         memory_region_init_ram_ptr(rma_region, NULL, "ppc_spapr.rma",
2377                                    rma_alloc_size, rma);
2378         vmstate_register_ram_global(rma_region);
2379         memory_region_add_subregion(sysmem, 0, rma_region);
2380     }
2381 
2382     /* initialize hotplug memory address space */
2383     if (machine->ram_size < machine->maxram_size) {
2384         ram_addr_t hotplug_mem_size = machine->maxram_size - machine->ram_size;
2385         /*
2386          * Limit the number of hotpluggable memory slots to half the number
2387          * slots that KVM supports, leaving the other half for PCI and other
2388          * devices. However ensure that number of slots doesn't drop below 32.
2389          */
2390         int max_memslots = kvm_enabled() ? kvm_get_max_memslots() / 2 :
2391                            SPAPR_MAX_RAM_SLOTS;
2392 
2393         if (max_memslots < SPAPR_MAX_RAM_SLOTS) {
2394             max_memslots = SPAPR_MAX_RAM_SLOTS;
2395         }
2396         if (machine->ram_slots > max_memslots) {
2397             error_report("Specified number of memory slots %"
2398                          PRIu64" exceeds max supported %d",
2399                          machine->ram_slots, max_memslots);
2400             exit(1);
2401         }
2402 
2403         spapr->hotplug_memory.base = ROUND_UP(machine->ram_size,
2404                                               SPAPR_HOTPLUG_MEM_ALIGN);
2405         memory_region_init(&spapr->hotplug_memory.mr, OBJECT(spapr),
2406                            "hotplug-memory", hotplug_mem_size);
2407         memory_region_add_subregion(sysmem, spapr->hotplug_memory.base,
2408                                     &spapr->hotplug_memory.mr);
2409     }
2410 
2411     if (smc->dr_lmb_enabled) {
2412         spapr_create_lmb_dr_connectors(spapr);
2413     }
2414 
2415     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin");
2416     if (!filename) {
2417         error_report("Could not find LPAR rtas '%s'", "spapr-rtas.bin");
2418         exit(1);
2419     }
2420     spapr->rtas_size = get_image_size(filename);
2421     if (spapr->rtas_size < 0) {
2422         error_report("Could not get size of LPAR rtas '%s'", filename);
2423         exit(1);
2424     }
2425     spapr->rtas_blob = g_malloc(spapr->rtas_size);
2426     if (load_image_size(filename, spapr->rtas_blob, spapr->rtas_size) < 0) {
2427         error_report("Could not load LPAR rtas '%s'", filename);
2428         exit(1);
2429     }
2430     if (spapr->rtas_size > RTAS_MAX_SIZE) {
2431         error_report("RTAS too big ! 0x%zx bytes (max is 0x%x)",
2432                      (size_t)spapr->rtas_size, RTAS_MAX_SIZE);
2433         exit(1);
2434     }
2435     g_free(filename);
2436 
2437     /* Set up RTAS event infrastructure */
2438     spapr_events_init(spapr);
2439 
2440     /* Set up the RTC RTAS interfaces */
2441     spapr_rtc_create(spapr);
2442 
2443     /* Set up VIO bus */
2444     spapr->vio_bus = spapr_vio_bus_init();
2445 
2446     for (i = 0; i < MAX_SERIAL_PORTS; i++) {
2447         if (serial_hds[i]) {
2448             spapr_vty_create(spapr->vio_bus, serial_hds[i]);
2449         }
2450     }
2451 
2452     /* We always have at least the nvram device on VIO */
2453     spapr_create_nvram(spapr);
2454 
2455     /* Set up PCI */
2456     spapr_pci_rtas_init();
2457 
2458     phb = spapr_create_phb(spapr, 0);
2459 
2460     for (i = 0; i < nb_nics; i++) {
2461         NICInfo *nd = &nd_table[i];
2462 
2463         if (!nd->model) {
2464             nd->model = g_strdup("ibmveth");
2465         }
2466 
2467         if (strcmp(nd->model, "ibmveth") == 0) {
2468             spapr_vlan_create(spapr->vio_bus, nd);
2469         } else {
2470             pci_nic_init_nofail(&nd_table[i], phb->bus, nd->model, NULL);
2471         }
2472     }
2473 
2474     for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
2475         spapr_vscsi_create(spapr->vio_bus);
2476     }
2477 
2478     /* Graphics */
2479     if (spapr_vga_init(phb->bus, &error_fatal)) {
2480         spapr->has_graphics = true;
2481         machine->usb |= defaults_enabled() && !machine->usb_disabled;
2482     }
2483 
2484     if (machine->usb) {
2485         if (smc->use_ohci_by_default) {
2486             pci_create_simple(phb->bus, -1, "pci-ohci");
2487         } else {
2488             pci_create_simple(phb->bus, -1, "nec-usb-xhci");
2489         }
2490 
2491         if (spapr->has_graphics) {
2492             USBBus *usb_bus = usb_bus_find(-1);
2493 
2494             usb_create_simple(usb_bus, "usb-kbd");
2495             usb_create_simple(usb_bus, "usb-mouse");
2496         }
2497     }
2498 
2499     if (spapr->rma_size < (MIN_RMA_SLOF << 20)) {
2500         error_report(
2501             "pSeries SLOF firmware requires >= %ldM guest RMA (Real Mode Area memory)",
2502             MIN_RMA_SLOF);
2503         exit(1);
2504     }
2505 
2506     if (kernel_filename) {
2507         uint64_t lowaddr = 0;
2508 
2509         spapr->kernel_size = load_elf(kernel_filename, translate_kernel_address,
2510                                       NULL, NULL, &lowaddr, NULL, 1,
2511                                       PPC_ELF_MACHINE, 0, 0);
2512         if (spapr->kernel_size == ELF_LOAD_WRONG_ENDIAN) {
2513             spapr->kernel_size = load_elf(kernel_filename,
2514                                           translate_kernel_address, NULL, NULL,
2515                                           &lowaddr, NULL, 0, PPC_ELF_MACHINE,
2516                                           0, 0);
2517             spapr->kernel_le = spapr->kernel_size > 0;
2518         }
2519         if (spapr->kernel_size < 0) {
2520             error_report("error loading %s: %s", kernel_filename,
2521                          load_elf_strerror(spapr->kernel_size));
2522             exit(1);
2523         }
2524 
2525         /* load initrd */
2526         if (initrd_filename) {
2527             /* Try to locate the initrd in the gap between the kernel
2528              * and the firmware. Add a bit of space just in case
2529              */
2530             spapr->initrd_base = (KERNEL_LOAD_ADDR + spapr->kernel_size
2531                                   + 0x1ffff) & ~0xffff;
2532             spapr->initrd_size = load_image_targphys(initrd_filename,
2533                                                      spapr->initrd_base,
2534                                                      load_limit
2535                                                      - spapr->initrd_base);
2536             if (spapr->initrd_size < 0) {
2537                 error_report("could not load initial ram disk '%s'",
2538                              initrd_filename);
2539                 exit(1);
2540             }
2541         }
2542     }
2543 
2544     if (bios_name == NULL) {
2545         bios_name = FW_FILE_NAME;
2546     }
2547     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
2548     if (!filename) {
2549         error_report("Could not find LPAR firmware '%s'", bios_name);
2550         exit(1);
2551     }
2552     fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);
2553     if (fw_size <= 0) {
2554         error_report("Could not load LPAR firmware '%s'", filename);
2555         exit(1);
2556     }
2557     g_free(filename);
2558 
2559     /* FIXME: Should register things through the MachineState's qdev
2560      * interface, this is a legacy from the sPAPREnvironment structure
2561      * which predated MachineState but had a similar function */
2562     vmstate_register(NULL, 0, &vmstate_spapr, spapr);
2563     register_savevm_live(NULL, "spapr/htab", -1, 1,
2564                          &savevm_htab_handlers, spapr);
2565 
2566     qemu_register_boot_set(spapr_boot_set, spapr);
2567 
2568     if (kvm_enabled()) {
2569         /* to stop and start vmclock */
2570         qemu_add_vm_change_state_handler(cpu_ppc_clock_vm_state_change,
2571                                          &spapr->tb);
2572 
2573         kvmppc_spapr_enable_inkernel_multitce();
2574     }
2575 }
2576 
2577 static int spapr_kvm_type(const char *vm_type)
2578 {
2579     if (!vm_type) {
2580         return 0;
2581     }
2582 
2583     if (!strcmp(vm_type, "HV")) {
2584         return 1;
2585     }
2586 
2587     if (!strcmp(vm_type, "PR")) {
2588         return 2;
2589     }
2590 
2591     error_report("Unknown kvm-type specified '%s'", vm_type);
2592     exit(1);
2593 }
2594 
2595 /*
2596  * Implementation of an interface to adjust firmware path
2597  * for the bootindex property handling.
2598  */
2599 static char *spapr_get_fw_dev_path(FWPathProvider *p, BusState *bus,
2600                                    DeviceState *dev)
2601 {
2602 #define CAST(type, obj, name) \
2603     ((type *)object_dynamic_cast(OBJECT(obj), (name)))
2604     SCSIDevice *d = CAST(SCSIDevice,  dev, TYPE_SCSI_DEVICE);
2605     sPAPRPHBState *phb = CAST(sPAPRPHBState, dev, TYPE_SPAPR_PCI_HOST_BRIDGE);
2606     VHostSCSICommon *vsc = CAST(VHostSCSICommon, dev, TYPE_VHOST_SCSI_COMMON);
2607 
2608     if (d) {
2609         void *spapr = CAST(void, bus->parent, "spapr-vscsi");
2610         VirtIOSCSI *virtio = CAST(VirtIOSCSI, bus->parent, TYPE_VIRTIO_SCSI);
2611         USBDevice *usb = CAST(USBDevice, bus->parent, TYPE_USB_DEVICE);
2612 
2613         if (spapr) {
2614             /*
2615              * Replace "channel@0/disk@0,0" with "disk@8000000000000000":
2616              * We use SRP luns of the form 8000 | (bus << 8) | (id << 5) | lun
2617              * in the top 16 bits of the 64-bit LUN
2618              */
2619             unsigned id = 0x8000 | (d->id << 8) | d->lun;
2620             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
2621                                    (uint64_t)id << 48);
2622         } else if (virtio) {
2623             /*
2624              * We use SRP luns of the form 01000000 | (target << 8) | lun
2625              * in the top 32 bits of the 64-bit LUN
2626              * Note: the quote above is from SLOF and it is wrong,
2627              * the actual binding is:
2628              * swap 0100 or 10 << or 20 << ( target lun-id -- srplun )
2629              */
2630             unsigned id = 0x1000000 | (d->id << 16) | d->lun;
2631             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
2632                                    (uint64_t)id << 32);
2633         } else if (usb) {
2634             /*
2635              * We use SRP luns of the form 01000000 | (usb-port << 16) | lun
2636              * in the top 32 bits of the 64-bit LUN
2637              */
2638             unsigned usb_port = atoi(usb->port->path);
2639             unsigned id = 0x1000000 | (usb_port << 16) | d->lun;
2640             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
2641                                    (uint64_t)id << 32);
2642         }
2643     }
2644 
2645     /*
2646      * SLOF probes the USB devices, and if it recognizes that the device is a
2647      * storage device, it changes its name to "storage" instead of "usb-host",
2648      * and additionally adds a child node for the SCSI LUN, so the correct
2649      * boot path in SLOF is something like .../storage@1/disk@xxx" instead.
2650      */
2651     if (strcmp("usb-host", qdev_fw_name(dev)) == 0) {
2652         USBDevice *usbdev = CAST(USBDevice, dev, TYPE_USB_DEVICE);
2653         if (usb_host_dev_is_scsi_storage(usbdev)) {
2654             return g_strdup_printf("storage@%s/disk", usbdev->port->path);
2655         }
2656     }
2657 
2658     if (phb) {
2659         /* Replace "pci" with "pci@800000020000000" */
2660         return g_strdup_printf("pci@%"PRIX64, phb->buid);
2661     }
2662 
2663     if (vsc) {
2664         /* Same logic as virtio above */
2665         unsigned id = 0x1000000 | (vsc->target << 16) | vsc->lun;
2666         return g_strdup_printf("disk@%"PRIX64, (uint64_t)id << 32);
2667     }
2668 
2669     if (g_str_equal("pci-bridge", qdev_fw_name(dev))) {
2670         /* SLOF uses "pci" instead of "pci-bridge" for PCI bridges */
2671         PCIDevice *pcidev = CAST(PCIDevice, dev, TYPE_PCI_DEVICE);
2672         return g_strdup_printf("pci@%x", PCI_SLOT(pcidev->devfn));
2673     }
2674 
2675     return NULL;
2676 }
2677 
2678 static char *spapr_get_kvm_type(Object *obj, Error **errp)
2679 {
2680     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2681 
2682     return g_strdup(spapr->kvm_type);
2683 }
2684 
2685 static void spapr_set_kvm_type(Object *obj, const char *value, Error **errp)
2686 {
2687     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2688 
2689     g_free(spapr->kvm_type);
2690     spapr->kvm_type = g_strdup(value);
2691 }
2692 
2693 static bool spapr_get_modern_hotplug_events(Object *obj, Error **errp)
2694 {
2695     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2696 
2697     return spapr->use_hotplug_event_source;
2698 }
2699 
2700 static void spapr_set_modern_hotplug_events(Object *obj, bool value,
2701                                             Error **errp)
2702 {
2703     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2704 
2705     spapr->use_hotplug_event_source = value;
2706 }
2707 
2708 static char *spapr_get_resize_hpt(Object *obj, Error **errp)
2709 {
2710     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2711 
2712     switch (spapr->resize_hpt) {
2713     case SPAPR_RESIZE_HPT_DEFAULT:
2714         return g_strdup("default");
2715     case SPAPR_RESIZE_HPT_DISABLED:
2716         return g_strdup("disabled");
2717     case SPAPR_RESIZE_HPT_ENABLED:
2718         return g_strdup("enabled");
2719     case SPAPR_RESIZE_HPT_REQUIRED:
2720         return g_strdup("required");
2721     }
2722     g_assert_not_reached();
2723 }
2724 
2725 static void spapr_set_resize_hpt(Object *obj, const char *value, Error **errp)
2726 {
2727     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2728 
2729     if (strcmp(value, "default") == 0) {
2730         spapr->resize_hpt = SPAPR_RESIZE_HPT_DEFAULT;
2731     } else if (strcmp(value, "disabled") == 0) {
2732         spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
2733     } else if (strcmp(value, "enabled") == 0) {
2734         spapr->resize_hpt = SPAPR_RESIZE_HPT_ENABLED;
2735     } else if (strcmp(value, "required") == 0) {
2736         spapr->resize_hpt = SPAPR_RESIZE_HPT_REQUIRED;
2737     } else {
2738         error_setg(errp, "Bad value for \"resize-hpt\" property");
2739     }
2740 }
2741 
2742 static void spapr_get_vsmt(Object *obj, Visitor *v, const char *name,
2743                                    void *opaque, Error **errp)
2744 {
2745     visit_type_uint32(v, name, (uint32_t *)opaque, errp);
2746 }
2747 
2748 static void spapr_set_vsmt(Object *obj, Visitor *v, const char *name,
2749                                    void *opaque, Error **errp)
2750 {
2751     visit_type_uint32(v, name, (uint32_t *)opaque, errp);
2752 }
2753 
2754 static void spapr_machine_initfn(Object *obj)
2755 {
2756     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2757 
2758     spapr->htab_fd = -1;
2759     spapr->use_hotplug_event_source = true;
2760     object_property_add_str(obj, "kvm-type",
2761                             spapr_get_kvm_type, spapr_set_kvm_type, NULL);
2762     object_property_set_description(obj, "kvm-type",
2763                                     "Specifies the KVM virtualization mode (HV, PR)",
2764                                     NULL);
2765     object_property_add_bool(obj, "modern-hotplug-events",
2766                             spapr_get_modern_hotplug_events,
2767                             spapr_set_modern_hotplug_events,
2768                             NULL);
2769     object_property_set_description(obj, "modern-hotplug-events",
2770                                     "Use dedicated hotplug event mechanism in"
2771                                     " place of standard EPOW events when possible"
2772                                     " (required for memory hot-unplug support)",
2773                                     NULL);
2774 
2775     ppc_compat_add_property(obj, "max-cpu-compat", &spapr->max_compat_pvr,
2776                             "Maximum permitted CPU compatibility mode",
2777                             &error_fatal);
2778 
2779     object_property_add_str(obj, "resize-hpt",
2780                             spapr_get_resize_hpt, spapr_set_resize_hpt, NULL);
2781     object_property_set_description(obj, "resize-hpt",
2782                                     "Resizing of the Hash Page Table (enabled, disabled, required)",
2783                                     NULL);
2784     object_property_add(obj, "vsmt", "uint32", spapr_get_vsmt,
2785                         spapr_set_vsmt, NULL, &spapr->vsmt, &error_abort);
2786     object_property_set_description(obj, "vsmt",
2787                                     "Virtual SMT: KVM behaves as if this were"
2788                                     " the host's SMT mode", &error_abort);
2789 }
2790 
2791 static void spapr_machine_finalizefn(Object *obj)
2792 {
2793     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
2794 
2795     g_free(spapr->kvm_type);
2796 }
2797 
2798 void spapr_do_system_reset_on_cpu(CPUState *cs, run_on_cpu_data arg)
2799 {
2800     cpu_synchronize_state(cs);
2801     ppc_cpu_do_system_reset(cs);
2802 }
2803 
2804 static void spapr_nmi(NMIState *n, int cpu_index, Error **errp)
2805 {
2806     CPUState *cs;
2807 
2808     CPU_FOREACH(cs) {
2809         async_run_on_cpu(cs, spapr_do_system_reset_on_cpu, RUN_ON_CPU_NULL);
2810     }
2811 }
2812 
2813 static void spapr_add_lmbs(DeviceState *dev, uint64_t addr_start, uint64_t size,
2814                            uint32_t node, bool dedicated_hp_event_source,
2815                            Error **errp)
2816 {
2817     sPAPRDRConnector *drc;
2818     uint32_t nr_lmbs = size/SPAPR_MEMORY_BLOCK_SIZE;
2819     int i, fdt_offset, fdt_size;
2820     void *fdt;
2821     uint64_t addr = addr_start;
2822     bool hotplugged = spapr_drc_hotplugged(dev);
2823     Error *local_err = NULL;
2824 
2825     for (i = 0; i < nr_lmbs; i++) {
2826         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
2827                               addr / SPAPR_MEMORY_BLOCK_SIZE);
2828         g_assert(drc);
2829 
2830         fdt = create_device_tree(&fdt_size);
2831         fdt_offset = spapr_populate_memory_node(fdt, node, addr,
2832                                                 SPAPR_MEMORY_BLOCK_SIZE);
2833 
2834         spapr_drc_attach(drc, dev, fdt, fdt_offset, &local_err);
2835         if (local_err) {
2836             while (addr > addr_start) {
2837                 addr -= SPAPR_MEMORY_BLOCK_SIZE;
2838                 drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
2839                                       addr / SPAPR_MEMORY_BLOCK_SIZE);
2840                 spapr_drc_detach(drc);
2841             }
2842             g_free(fdt);
2843             error_propagate(errp, local_err);
2844             return;
2845         }
2846         if (!hotplugged) {
2847             spapr_drc_reset(drc);
2848         }
2849         addr += SPAPR_MEMORY_BLOCK_SIZE;
2850     }
2851     /* send hotplug notification to the
2852      * guest only in case of hotplugged memory
2853      */
2854     if (hotplugged) {
2855         if (dedicated_hp_event_source) {
2856             drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
2857                                   addr_start / SPAPR_MEMORY_BLOCK_SIZE);
2858             spapr_hotplug_req_add_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
2859                                                    nr_lmbs,
2860                                                    spapr_drc_index(drc));
2861         } else {
2862             spapr_hotplug_req_add_by_count(SPAPR_DR_CONNECTOR_TYPE_LMB,
2863                                            nr_lmbs);
2864         }
2865     }
2866 }
2867 
2868 static void spapr_memory_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
2869                               uint32_t node, Error **errp)
2870 {
2871     Error *local_err = NULL;
2872     sPAPRMachineState *ms = SPAPR_MACHINE(hotplug_dev);
2873     PCDIMMDevice *dimm = PC_DIMM(dev);
2874     PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
2875     MemoryRegion *mr;
2876     uint64_t align, size, addr;
2877 
2878     mr = ddc->get_memory_region(dimm, &local_err);
2879     if (local_err) {
2880         goto out;
2881     }
2882     align = memory_region_get_alignment(mr);
2883     size = memory_region_size(mr);
2884 
2885     pc_dimm_memory_plug(dev, &ms->hotplug_memory, mr, align, &local_err);
2886     if (local_err) {
2887         goto out;
2888     }
2889 
2890     addr = object_property_get_uint(OBJECT(dimm),
2891                                     PC_DIMM_ADDR_PROP, &local_err);
2892     if (local_err) {
2893         goto out_unplug;
2894     }
2895 
2896     spapr_add_lmbs(dev, addr, size, node,
2897                    spapr_ovec_test(ms->ov5_cas, OV5_HP_EVT),
2898                    &local_err);
2899     if (local_err) {
2900         goto out_unplug;
2901     }
2902 
2903     return;
2904 
2905 out_unplug:
2906     pc_dimm_memory_unplug(dev, &ms->hotplug_memory, mr);
2907 out:
2908     error_propagate(errp, local_err);
2909 }
2910 
2911 static void spapr_memory_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
2912                                   Error **errp)
2913 {
2914     PCDIMMDevice *dimm = PC_DIMM(dev);
2915     PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
2916     MemoryRegion *mr;
2917     uint64_t size;
2918     char *mem_dev;
2919 
2920     mr = ddc->get_memory_region(dimm, errp);
2921     if (!mr) {
2922         return;
2923     }
2924     size = memory_region_size(mr);
2925 
2926     if (size % SPAPR_MEMORY_BLOCK_SIZE) {
2927         error_setg(errp, "Hotplugged memory size must be a multiple of "
2928                       "%lld MB", SPAPR_MEMORY_BLOCK_SIZE / M_BYTE);
2929         return;
2930     }
2931 
2932     mem_dev = object_property_get_str(OBJECT(dimm), PC_DIMM_MEMDEV_PROP, NULL);
2933     if (mem_dev && !kvmppc_is_mem_backend_page_size_ok(mem_dev)) {
2934         error_setg(errp, "Memory backend has bad page size. "
2935                    "Use 'memory-backend-file' with correct mem-path.");
2936         goto out;
2937     }
2938 
2939 out:
2940     g_free(mem_dev);
2941 }
2942 
2943 struct sPAPRDIMMState {
2944     PCDIMMDevice *dimm;
2945     uint32_t nr_lmbs;
2946     QTAILQ_ENTRY(sPAPRDIMMState) next;
2947 };
2948 
2949 static sPAPRDIMMState *spapr_pending_dimm_unplugs_find(sPAPRMachineState *s,
2950                                                        PCDIMMDevice *dimm)
2951 {
2952     sPAPRDIMMState *dimm_state = NULL;
2953 
2954     QTAILQ_FOREACH(dimm_state, &s->pending_dimm_unplugs, next) {
2955         if (dimm_state->dimm == dimm) {
2956             break;
2957         }
2958     }
2959     return dimm_state;
2960 }
2961 
2962 static sPAPRDIMMState *spapr_pending_dimm_unplugs_add(sPAPRMachineState *spapr,
2963                                                       uint32_t nr_lmbs,
2964                                                       PCDIMMDevice *dimm)
2965 {
2966     sPAPRDIMMState *ds = NULL;
2967 
2968     /*
2969      * If this request is for a DIMM whose removal had failed earlier
2970      * (due to guest's refusal to remove the LMBs), we would have this
2971      * dimm already in the pending_dimm_unplugs list. In that
2972      * case don't add again.
2973      */
2974     ds = spapr_pending_dimm_unplugs_find(spapr, dimm);
2975     if (!ds) {
2976         ds = g_malloc0(sizeof(sPAPRDIMMState));
2977         ds->nr_lmbs = nr_lmbs;
2978         ds->dimm = dimm;
2979         QTAILQ_INSERT_HEAD(&spapr->pending_dimm_unplugs, ds, next);
2980     }
2981     return ds;
2982 }
2983 
2984 static void spapr_pending_dimm_unplugs_remove(sPAPRMachineState *spapr,
2985                                               sPAPRDIMMState *dimm_state)
2986 {
2987     QTAILQ_REMOVE(&spapr->pending_dimm_unplugs, dimm_state, next);
2988     g_free(dimm_state);
2989 }
2990 
2991 static sPAPRDIMMState *spapr_recover_pending_dimm_state(sPAPRMachineState *ms,
2992                                                         PCDIMMDevice *dimm)
2993 {
2994     sPAPRDRConnector *drc;
2995     PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
2996     MemoryRegion *mr = ddc->get_memory_region(dimm, &error_abort);
2997     uint64_t size = memory_region_size(mr);
2998     uint32_t nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
2999     uint32_t avail_lmbs = 0;
3000     uint64_t addr_start, addr;
3001     int i;
3002 
3003     addr_start = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3004                                          &error_abort);
3005 
3006     addr = addr_start;
3007     for (i = 0; i < nr_lmbs; i++) {
3008         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3009                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3010         g_assert(drc);
3011         if (drc->dev) {
3012             avail_lmbs++;
3013         }
3014         addr += SPAPR_MEMORY_BLOCK_SIZE;
3015     }
3016 
3017     return spapr_pending_dimm_unplugs_add(ms, avail_lmbs, dimm);
3018 }
3019 
3020 /* Callback to be called during DRC release. */
3021 void spapr_lmb_release(DeviceState *dev)
3022 {
3023     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_hotplug_handler(dev));
3024     PCDIMMDevice *dimm = PC_DIMM(dev);
3025     PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
3026     MemoryRegion *mr = ddc->get_memory_region(dimm, &error_abort);
3027     sPAPRDIMMState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));
3028 
3029     /* This information will get lost if a migration occurs
3030      * during the unplug process. In this case recover it. */
3031     if (ds == NULL) {
3032         ds = spapr_recover_pending_dimm_state(spapr, PC_DIMM(dev));
3033         g_assert(ds);
3034         /* The DRC being examined by the caller at least must be counted */
3035         g_assert(ds->nr_lmbs);
3036     }
3037 
3038     if (--ds->nr_lmbs) {
3039         return;
3040     }
3041 
3042     spapr_pending_dimm_unplugs_remove(spapr, ds);
3043 
3044     /*
3045      * Now that all the LMBs have been removed by the guest, call the
3046      * pc-dimm unplug handler to cleanup up the pc-dimm device.
3047      */
3048     pc_dimm_memory_unplug(dev, &spapr->hotplug_memory, mr);
3049     object_unparent(OBJECT(dev));
3050 }
3051 
3052 static void spapr_memory_unplug_request(HotplugHandler *hotplug_dev,
3053                                         DeviceState *dev, Error **errp)
3054 {
3055     sPAPRMachineState *spapr = SPAPR_MACHINE(hotplug_dev);
3056     Error *local_err = NULL;
3057     PCDIMMDevice *dimm = PC_DIMM(dev);
3058     PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
3059     MemoryRegion *mr;
3060     uint32_t nr_lmbs;
3061     uint64_t size, addr_start, addr;
3062     int i;
3063     sPAPRDRConnector *drc;
3064 
3065     mr = ddc->get_memory_region(dimm, &local_err);
3066     if (local_err) {
3067         goto out;
3068     }
3069     size = memory_region_size(mr);
3070     nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;
3071 
3072     addr_start = object_property_get_uint(OBJECT(dimm), PC_DIMM_ADDR_PROP,
3073                                          &local_err);
3074     if (local_err) {
3075         goto out;
3076     }
3077 
3078     spapr_pending_dimm_unplugs_add(spapr, nr_lmbs, dimm);
3079 
3080     addr = addr_start;
3081     for (i = 0; i < nr_lmbs; i++) {
3082         drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3083                               addr / SPAPR_MEMORY_BLOCK_SIZE);
3084         g_assert(drc);
3085 
3086         spapr_drc_detach(drc);
3087         addr += SPAPR_MEMORY_BLOCK_SIZE;
3088     }
3089 
3090     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,
3091                           addr_start / SPAPR_MEMORY_BLOCK_SIZE);
3092     spapr_hotplug_req_remove_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,
3093                                               nr_lmbs, spapr_drc_index(drc));
3094 out:
3095     error_propagate(errp, local_err);
3096 }
3097 
3098 static void *spapr_populate_hotplug_cpu_dt(CPUState *cs, int *fdt_offset,
3099                                            sPAPRMachineState *spapr)
3100 {
3101     PowerPCCPU *cpu = POWERPC_CPU(cs);
3102     DeviceClass *dc = DEVICE_GET_CLASS(cs);
3103     int id = spapr_vcpu_id(cpu);
3104     void *fdt;
3105     int offset, fdt_size;
3106     char *nodename;
3107 
3108     fdt = create_device_tree(&fdt_size);
3109     nodename = g_strdup_printf("%s@%x", dc->fw_name, id);
3110     offset = fdt_add_subnode(fdt, 0, nodename);
3111 
3112     spapr_populate_cpu_dt(cs, fdt, offset, spapr);
3113     g_free(nodename);
3114 
3115     *fdt_offset = offset;
3116     return fdt;
3117 }
3118 
3119 /* Callback to be called during DRC release. */
3120 void spapr_core_release(DeviceState *dev)
3121 {
3122     MachineState *ms = MACHINE(qdev_get_hotplug_handler(dev));
3123     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(ms);
3124     CPUCore *cc = CPU_CORE(dev);
3125     CPUArchId *core_slot = spapr_find_cpu_slot(ms, cc->core_id, NULL);
3126 
3127     if (smc->pre_2_10_has_unused_icps) {
3128         sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev));
3129         sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc));
3130         const char *typename = object_class_get_name(scc->cpu_class);
3131         size_t size = object_type_get_instance_size(typename);
3132         int i;
3133 
3134         for (i = 0; i < cc->nr_threads; i++) {
3135             CPUState *cs = CPU(sc->threads + i * size);
3136 
3137             pre_2_10_vmstate_register_dummy_icp(cs->cpu_index);
3138         }
3139     }
3140 
3141     assert(core_slot);
3142     core_slot->cpu = NULL;
3143     object_unparent(OBJECT(dev));
3144 }
3145 
3146 static
3147 void spapr_core_unplug_request(HotplugHandler *hotplug_dev, DeviceState *dev,
3148                                Error **errp)
3149 {
3150     int index;
3151     sPAPRDRConnector *drc;
3152     CPUCore *cc = CPU_CORE(dev);
3153     int smt = kvmppc_smt_threads();
3154 
3155     if (!spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index)) {
3156         error_setg(errp, "Unable to find CPU core with core-id: %d",
3157                    cc->core_id);
3158         return;
3159     }
3160     if (index == 0) {
3161         error_setg(errp, "Boot CPU core may not be unplugged");
3162         return;
3163     }
3164 
3165     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index * smt);
3166     g_assert(drc);
3167 
3168     spapr_drc_detach(drc);
3169 
3170     spapr_hotplug_req_remove_by_index(drc);
3171 }
3172 
3173 static void spapr_core_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3174                             Error **errp)
3175 {
3176     sPAPRMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));
3177     MachineClass *mc = MACHINE_GET_CLASS(spapr);
3178     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3179     sPAPRCPUCore *core = SPAPR_CPU_CORE(OBJECT(dev));
3180     CPUCore *cc = CPU_CORE(dev);
3181     CPUState *cs = CPU(core->threads);
3182     sPAPRDRConnector *drc;
3183     Error *local_err = NULL;
3184     int smt = kvmppc_smt_threads();
3185     CPUArchId *core_slot;
3186     int index;
3187     bool hotplugged = spapr_drc_hotplugged(dev);
3188 
3189     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
3190     if (!core_slot) {
3191         error_setg(errp, "Unable to find CPU core with core-id: %d",
3192                    cc->core_id);
3193         return;
3194     }
3195     drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index * smt);
3196 
3197     g_assert(drc || !mc->has_hotpluggable_cpus);
3198 
3199     if (drc) {
3200         void *fdt;
3201         int fdt_offset;
3202 
3203         fdt = spapr_populate_hotplug_cpu_dt(cs, &fdt_offset, spapr);
3204 
3205         spapr_drc_attach(drc, dev, fdt, fdt_offset, &local_err);
3206         if (local_err) {
3207             g_free(fdt);
3208             error_propagate(errp, local_err);
3209             return;
3210         }
3211 
3212         if (hotplugged) {
3213             /*
3214              * Send hotplug notification interrupt to the guest only
3215              * in case of hotplugged CPUs.
3216              */
3217             spapr_hotplug_req_add_by_index(drc);
3218         } else {
3219             spapr_drc_reset(drc);
3220         }
3221     }
3222 
3223     core_slot->cpu = OBJECT(dev);
3224 
3225     if (smc->pre_2_10_has_unused_icps) {
3226         sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc));
3227         const char *typename = object_class_get_name(scc->cpu_class);
3228         size_t size = object_type_get_instance_size(typename);
3229         int i;
3230 
3231         for (i = 0; i < cc->nr_threads; i++) {
3232             sPAPRCPUCore *sc = SPAPR_CPU_CORE(dev);
3233             void *obj = sc->threads + i * size;
3234 
3235             cs = CPU(obj);
3236             pre_2_10_vmstate_unregister_dummy_icp(cs->cpu_index);
3237         }
3238     }
3239 }
3240 
3241 static void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
3242                                 Error **errp)
3243 {
3244     MachineState *machine = MACHINE(OBJECT(hotplug_dev));
3245     MachineClass *mc = MACHINE_GET_CLASS(hotplug_dev);
3246     Error *local_err = NULL;
3247     CPUCore *cc = CPU_CORE(dev);
3248     char *base_core_type = spapr_get_cpu_core_type(machine->cpu_model);
3249     const char *type = object_get_typename(OBJECT(dev));
3250     CPUArchId *core_slot;
3251     int index;
3252 
3253     if (dev->hotplugged && !mc->has_hotpluggable_cpus) {
3254         error_setg(&local_err, "CPU hotplug not supported for this machine");
3255         goto out;
3256     }
3257 
3258     if (strcmp(base_core_type, type)) {
3259         error_setg(&local_err, "CPU core type should be %s", base_core_type);
3260         goto out;
3261     }
3262 
3263     if (cc->core_id % smp_threads) {
3264         error_setg(&local_err, "invalid core id %d", cc->core_id);
3265         goto out;
3266     }
3267 
3268     /*
3269      * In general we should have homogeneous threads-per-core, but old
3270      * (pre hotplug support) machine types allow the last core to have
3271      * reduced threads as a compatibility hack for when we allowed
3272      * total vcpus not a multiple of threads-per-core.
3273      */
3274     if (mc->has_hotpluggable_cpus && (cc->nr_threads != smp_threads)) {
3275         error_setg(&local_err, "invalid nr-threads %d, must be %d",
3276                    cc->nr_threads, smp_threads);
3277         goto out;
3278     }
3279 
3280     core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);
3281     if (!core_slot) {
3282         error_setg(&local_err, "core id %d out of range", cc->core_id);
3283         goto out;
3284     }
3285 
3286     if (core_slot->cpu) {
3287         error_setg(&local_err, "core %d already populated", cc->core_id);
3288         goto out;
3289     }
3290 
3291     numa_cpu_pre_plug(core_slot, dev, &local_err);
3292 
3293 out:
3294     g_free(base_core_type);
3295     error_propagate(errp, local_err);
3296 }
3297 
3298 static void spapr_machine_device_plug(HotplugHandler *hotplug_dev,
3299                                       DeviceState *dev, Error **errp)
3300 {
3301     sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(qdev_get_machine());
3302 
3303     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
3304         int node;
3305 
3306         if (!smc->dr_lmb_enabled) {
3307             error_setg(errp, "Memory hotplug not supported for this machine");
3308             return;
3309         }
3310         node = object_property_get_uint(OBJECT(dev), PC_DIMM_NODE_PROP, errp);
3311         if (*errp) {
3312             return;
3313         }
3314         if (node < 0 || node >= MAX_NODES) {
3315             error_setg(errp, "Invaild node %d", node);
3316             return;
3317         }
3318 
3319         /*
3320          * Currently PowerPC kernel doesn't allow hot-adding memory to
3321          * memory-less node, but instead will silently add the memory
3322          * to the first node that has some memory. This causes two
3323          * unexpected behaviours for the user.
3324          *
3325          * - Memory gets hotplugged to a different node than what the user
3326          *   specified.
3327          * - Since pc-dimm subsystem in QEMU still thinks that memory belongs
3328          *   to memory-less node, a reboot will set things accordingly
3329          *   and the previously hotplugged memory now ends in the right node.
3330          *   This appears as if some memory moved from one node to another.
3331          *
3332          * So until kernel starts supporting memory hotplug to memory-less
3333          * nodes, just prevent such attempts upfront in QEMU.
3334          */
3335         if (nb_numa_nodes && !numa_info[node].node_mem) {
3336             error_setg(errp, "Can't hotplug memory to memory-less node %d",
3337                        node);
3338             return;
3339         }
3340 
3341         spapr_memory_plug(hotplug_dev, dev, node, errp);
3342     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3343         spapr_core_plug(hotplug_dev, dev, errp);
3344     }
3345 }
3346 
3347 static void spapr_machine_device_unplug_request(HotplugHandler *hotplug_dev,
3348                                                 DeviceState *dev, Error **errp)
3349 {
3350     sPAPRMachineState *sms = SPAPR_MACHINE(qdev_get_machine());
3351     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
3352 
3353     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
3354         if (spapr_ovec_test(sms->ov5_cas, OV5_HP_EVT)) {
3355             spapr_memory_unplug_request(hotplug_dev, dev, errp);
3356         } else {
3357             /* NOTE: this means there is a window after guest reset, prior to
3358              * CAS negotiation, where unplug requests will fail due to the
3359              * capability not being detected yet. This is a bit different than
3360              * the case with PCI unplug, where the events will be queued and
3361              * eventually handled by the guest after boot
3362              */
3363             error_setg(errp, "Memory hot unplug not supported for this guest");
3364         }
3365     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3366         if (!mc->has_hotpluggable_cpus) {
3367             error_setg(errp, "CPU hot unplug not supported on this machine");
3368             return;
3369         }
3370         spapr_core_unplug_request(hotplug_dev, dev, errp);
3371     }
3372 }
3373 
3374 static void spapr_machine_device_pre_plug(HotplugHandler *hotplug_dev,
3375                                           DeviceState *dev, Error **errp)
3376 {
3377     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {
3378         spapr_memory_pre_plug(hotplug_dev, dev, errp);
3379     } else if (object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3380         spapr_core_pre_plug(hotplug_dev, dev, errp);
3381     }
3382 }
3383 
3384 static HotplugHandler *spapr_get_hotplug_handler(MachineState *machine,
3385                                                  DeviceState *dev)
3386 {
3387     if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) ||
3388         object_dynamic_cast(OBJECT(dev), TYPE_SPAPR_CPU_CORE)) {
3389         return HOTPLUG_HANDLER(machine);
3390     }
3391     return NULL;
3392 }
3393 
3394 static CpuInstanceProperties
3395 spapr_cpu_index_to_props(MachineState *machine, unsigned cpu_index)
3396 {
3397     CPUArchId *core_slot;
3398     MachineClass *mc = MACHINE_GET_CLASS(machine);
3399 
3400     /* make sure possible_cpu are intialized */
3401     mc->possible_cpu_arch_ids(machine);
3402     /* get CPU core slot containing thread that matches cpu_index */
3403     core_slot = spapr_find_cpu_slot(machine, cpu_index, NULL);
3404     assert(core_slot);
3405     return core_slot->props;
3406 }
3407 
3408 static const CPUArchIdList *spapr_possible_cpu_arch_ids(MachineState *machine)
3409 {
3410     int i;
3411     int spapr_max_cores = max_cpus / smp_threads;
3412     MachineClass *mc = MACHINE_GET_CLASS(machine);
3413 
3414     if (!mc->has_hotpluggable_cpus) {
3415         spapr_max_cores = QEMU_ALIGN_UP(smp_cpus, smp_threads) / smp_threads;
3416     }
3417     if (machine->possible_cpus) {
3418         assert(machine->possible_cpus->len == spapr_max_cores);
3419         return machine->possible_cpus;
3420     }
3421 
3422     machine->possible_cpus = g_malloc0(sizeof(CPUArchIdList) +
3423                              sizeof(CPUArchId) * spapr_max_cores);
3424     machine->possible_cpus->len = spapr_max_cores;
3425     for (i = 0; i < machine->possible_cpus->len; i++) {
3426         int core_id = i * smp_threads;
3427 
3428         machine->possible_cpus->cpus[i].vcpus_count = smp_threads;
3429         machine->possible_cpus->cpus[i].arch_id = core_id;
3430         machine->possible_cpus->cpus[i].props.has_core_id = true;
3431         machine->possible_cpus->cpus[i].props.core_id = core_id;
3432 
3433         /* default distribution of CPUs over NUMA nodes */
3434         if (nb_numa_nodes) {
3435             /* preset values but do not enable them i.e. 'has_node_id = false',
3436              * numa init code will enable them later if manual mapping wasn't
3437              * present on CLI */
3438             machine->possible_cpus->cpus[i].props.node_id =
3439                 core_id / smp_threads / smp_cores % nb_numa_nodes;
3440         }
3441     }
3442     return machine->possible_cpus;
3443 }
3444 
3445 static void spapr_phb_placement(sPAPRMachineState *spapr, uint32_t index,
3446                                 uint64_t *buid, hwaddr *pio,
3447                                 hwaddr *mmio32, hwaddr *mmio64,
3448                                 unsigned n_dma, uint32_t *liobns, Error **errp)
3449 {
3450     /*
3451      * New-style PHB window placement.
3452      *
3453      * Goals: Gives large (1TiB), naturally aligned 64-bit MMIO window
3454      * for each PHB, in addition to 2GiB 32-bit MMIO and 64kiB PIO
3455      * windows.
3456      *
3457      * Some guest kernels can't work with MMIO windows above 1<<46
3458      * (64TiB), so we place up to 31 PHBs in the area 32TiB..64TiB
3459      *
3460      * 32TiB..(33TiB+1984kiB) contains the 64kiB PIO windows for each
3461      * PHB stacked together.  (32TiB+2GiB)..(32TiB+64GiB) contains the
3462      * 2GiB 32-bit MMIO windows for each PHB.  Then 33..64TiB has the
3463      * 1TiB 64-bit MMIO windows for each PHB.
3464      */
3465     const uint64_t base_buid = 0x800000020000000ULL;
3466 #define SPAPR_MAX_PHBS ((SPAPR_PCI_LIMIT - SPAPR_PCI_BASE) / \
3467                         SPAPR_PCI_MEM64_WIN_SIZE - 1)
3468     int i;
3469 
3470     /* Sanity check natural alignments */
3471     QEMU_BUILD_BUG_ON((SPAPR_PCI_BASE % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
3472     QEMU_BUILD_BUG_ON((SPAPR_PCI_LIMIT % SPAPR_PCI_MEM64_WIN_SIZE) != 0);
3473     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM64_WIN_SIZE % SPAPR_PCI_MEM32_WIN_SIZE) != 0);
3474     QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM32_WIN_SIZE % SPAPR_PCI_IO_WIN_SIZE) != 0);
3475     /* Sanity check bounds */
3476     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_IO_WIN_SIZE) >
3477                       SPAPR_PCI_MEM32_WIN_SIZE);
3478     QEMU_BUILD_BUG_ON((SPAPR_MAX_PHBS * SPAPR_PCI_MEM32_WIN_SIZE) >
3479                       SPAPR_PCI_MEM64_WIN_SIZE);
3480 
3481     if (index >= SPAPR_MAX_PHBS) {
3482         error_setg(errp, "\"index\" for PAPR PHB is too large (max %llu)",
3483                    SPAPR_MAX_PHBS - 1);
3484         return;
3485     }
3486 
3487     *buid = base_buid + index;
3488     for (i = 0; i < n_dma; ++i) {
3489         liobns[i] = SPAPR_PCI_LIOBN(index, i);
3490     }
3491 
3492     *pio = SPAPR_PCI_BASE + index * SPAPR_PCI_IO_WIN_SIZE;
3493     *mmio32 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM32_WIN_SIZE;
3494     *mmio64 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM64_WIN_SIZE;
3495 }
3496 
3497 static ICSState *spapr_ics_get(XICSFabric *dev, int irq)
3498 {
3499     sPAPRMachineState *spapr = SPAPR_MACHINE(dev);
3500 
3501     return ics_valid_irq(spapr->ics, irq) ? spapr->ics : NULL;
3502 }
3503 
3504 static void spapr_ics_resend(XICSFabric *dev)
3505 {
3506     sPAPRMachineState *spapr = SPAPR_MACHINE(dev);
3507 
3508     ics_resend(spapr->ics);
3509 }
3510 
3511 static ICPState *spapr_icp_get(XICSFabric *xi, int vcpu_id)
3512 {
3513     PowerPCCPU *cpu = spapr_find_cpu(vcpu_id);
3514 
3515     return cpu ? ICP(cpu->intc) : NULL;
3516 }
3517 
3518 static void spapr_pic_print_info(InterruptStatsProvider *obj,
3519                                  Monitor *mon)
3520 {
3521     sPAPRMachineState *spapr = SPAPR_MACHINE(obj);
3522     CPUState *cs;
3523 
3524     CPU_FOREACH(cs) {
3525         PowerPCCPU *cpu = POWERPC_CPU(cs);
3526 
3527         icp_pic_print_info(ICP(cpu->intc), mon);
3528     }
3529 
3530     ics_pic_print_info(spapr->ics, mon);
3531 }
3532 
3533 int spapr_vcpu_id(PowerPCCPU *cpu)
3534 {
3535     CPUState *cs = CPU(cpu);
3536 
3537     if (kvm_enabled()) {
3538         return kvm_arch_vcpu_id(cs);
3539     } else {
3540         return cs->cpu_index;
3541     }
3542 }
3543 
3544 PowerPCCPU *spapr_find_cpu(int vcpu_id)
3545 {
3546     CPUState *cs;
3547 
3548     CPU_FOREACH(cs) {
3549         PowerPCCPU *cpu = POWERPC_CPU(cs);
3550 
3551         if (spapr_vcpu_id(cpu) == vcpu_id) {
3552             return cpu;
3553         }
3554     }
3555 
3556     return NULL;
3557 }
3558 
3559 static void spapr_machine_class_init(ObjectClass *oc, void *data)
3560 {
3561     MachineClass *mc = MACHINE_CLASS(oc);
3562     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(oc);
3563     FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);
3564     NMIClass *nc = NMI_CLASS(oc);
3565     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
3566     PPCVirtualHypervisorClass *vhc = PPC_VIRTUAL_HYPERVISOR_CLASS(oc);
3567     XICSFabricClass *xic = XICS_FABRIC_CLASS(oc);
3568     InterruptStatsProviderClass *ispc = INTERRUPT_STATS_PROVIDER_CLASS(oc);
3569 
3570     mc->desc = "pSeries Logical Partition (PAPR compliant)";
3571 
3572     /*
3573      * We set up the default / latest behaviour here.  The class_init
3574      * functions for the specific versioned machine types can override
3575      * these details for backwards compatibility
3576      */
3577     mc->init = ppc_spapr_init;
3578     mc->reset = ppc_spapr_reset;
3579     mc->block_default_type = IF_SCSI;
3580     mc->max_cpus = 1024;
3581     mc->no_parallel = 1;
3582     mc->default_boot_order = "";
3583     mc->default_ram_size = 512 * M_BYTE;
3584     mc->kvm_type = spapr_kvm_type;
3585     mc->has_dynamic_sysbus = true;
3586     mc->pci_allow_0_address = true;
3587     mc->get_hotplug_handler = spapr_get_hotplug_handler;
3588     hc->pre_plug = spapr_machine_device_pre_plug;
3589     hc->plug = spapr_machine_device_plug;
3590     mc->cpu_index_to_instance_props = spapr_cpu_index_to_props;
3591     mc->possible_cpu_arch_ids = spapr_possible_cpu_arch_ids;
3592     hc->unplug_request = spapr_machine_device_unplug_request;
3593 
3594     smc->dr_lmb_enabled = true;
3595     smc->tcg_default_cpu = "POWER8";
3596     mc->has_hotpluggable_cpus = true;
3597     smc->resize_hpt_default = SPAPR_RESIZE_HPT_ENABLED;
3598     fwc->get_dev_path = spapr_get_fw_dev_path;
3599     nc->nmi_monitor_handler = spapr_nmi;
3600     smc->phb_placement = spapr_phb_placement;
3601     vhc->hypercall = emulate_spapr_hypercall;
3602     vhc->hpt_mask = spapr_hpt_mask;
3603     vhc->map_hptes = spapr_map_hptes;
3604     vhc->unmap_hptes = spapr_unmap_hptes;
3605     vhc->store_hpte = spapr_store_hpte;
3606     vhc->get_patbe = spapr_get_patbe;
3607     xic->ics_get = spapr_ics_get;
3608     xic->ics_resend = spapr_ics_resend;
3609     xic->icp_get = spapr_icp_get;
3610     ispc->print_info = spapr_pic_print_info;
3611     /* Force NUMA node memory size to be a multiple of
3612      * SPAPR_MEMORY_BLOCK_SIZE (256M) since that's the granularity
3613      * in which LMBs are represented and hot-added
3614      */
3615     mc->numa_mem_align_shift = 28;
3616 }
3617 
3618 static const TypeInfo spapr_machine_info = {
3619     .name          = TYPE_SPAPR_MACHINE,
3620     .parent        = TYPE_MACHINE,
3621     .abstract      = true,
3622     .instance_size = sizeof(sPAPRMachineState),
3623     .instance_init = spapr_machine_initfn,
3624     .instance_finalize = spapr_machine_finalizefn,
3625     .class_size    = sizeof(sPAPRMachineClass),
3626     .class_init    = spapr_machine_class_init,
3627     .interfaces = (InterfaceInfo[]) {
3628         { TYPE_FW_PATH_PROVIDER },
3629         { TYPE_NMI },
3630         { TYPE_HOTPLUG_HANDLER },
3631         { TYPE_PPC_VIRTUAL_HYPERVISOR },
3632         { TYPE_XICS_FABRIC },
3633         { TYPE_INTERRUPT_STATS_PROVIDER },
3634         { }
3635     },
3636 };
3637 
3638 #define DEFINE_SPAPR_MACHINE(suffix, verstr, latest)                 \
3639     static void spapr_machine_##suffix##_class_init(ObjectClass *oc, \
3640                                                     void *data)      \
3641     {                                                                \
3642         MachineClass *mc = MACHINE_CLASS(oc);                        \
3643         spapr_machine_##suffix##_class_options(mc);                  \
3644         if (latest) {                                                \
3645             mc->alias = "pseries";                                   \
3646             mc->is_default = 1;                                      \
3647         }                                                            \
3648     }                                                                \
3649     static void spapr_machine_##suffix##_instance_init(Object *obj)  \
3650     {                                                                \
3651         MachineState *machine = MACHINE(obj);                        \
3652         spapr_machine_##suffix##_instance_options(machine);          \
3653     }                                                                \
3654     static const TypeInfo spapr_machine_##suffix##_info = {          \
3655         .name = MACHINE_TYPE_NAME("pseries-" verstr),                \
3656         .parent = TYPE_SPAPR_MACHINE,                                \
3657         .class_init = spapr_machine_##suffix##_class_init,           \
3658         .instance_init = spapr_machine_##suffix##_instance_init,     \
3659     };                                                               \
3660     static void spapr_machine_register_##suffix(void)                \
3661     {                                                                \
3662         type_register(&spapr_machine_##suffix##_info);               \
3663     }                                                                \
3664     type_init(spapr_machine_register_##suffix)
3665 
3666 /*
3667  * pseries-2.11
3668  */
3669 static void spapr_machine_2_11_instance_options(MachineState *machine)
3670 {
3671 }
3672 
3673 static void spapr_machine_2_11_class_options(MachineClass *mc)
3674 {
3675     /* Defaults for the latest behaviour inherited from the base class */
3676 }
3677 
3678 DEFINE_SPAPR_MACHINE(2_11, "2.11", true);
3679 
3680 /*
3681  * pseries-2.10
3682  */
3683 #define SPAPR_COMPAT_2_10                                              \
3684     HW_COMPAT_2_10                                                     \
3685 
3686 static void spapr_machine_2_10_instance_options(MachineState *machine)
3687 {
3688 }
3689 
3690 static void spapr_machine_2_10_class_options(MachineClass *mc)
3691 {
3692     spapr_machine_2_11_class_options(mc);
3693     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_10);
3694 }
3695 
3696 DEFINE_SPAPR_MACHINE(2_10, "2.10", false);
3697 
3698 /*
3699  * pseries-2.9
3700  */
3701 #define SPAPR_COMPAT_2_9                                               \
3702     HW_COMPAT_2_9                                                      \
3703     {                                                                  \
3704         .driver = TYPE_POWERPC_CPU,                                    \
3705         .property = "pre-2.10-migration",                              \
3706         .value    = "on",                                              \
3707     },                                                                 \
3708 
3709 static void spapr_machine_2_9_instance_options(MachineState *machine)
3710 {
3711     spapr_machine_2_10_instance_options(machine);
3712 }
3713 
3714 static void spapr_machine_2_9_class_options(MachineClass *mc)
3715 {
3716     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3717 
3718     spapr_machine_2_10_class_options(mc);
3719     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_9);
3720     mc->numa_auto_assign_ram = numa_legacy_auto_assign_ram;
3721     smc->pre_2_10_has_unused_icps = true;
3722     smc->resize_hpt_default = SPAPR_RESIZE_HPT_DISABLED;
3723 }
3724 
3725 DEFINE_SPAPR_MACHINE(2_9, "2.9", false);
3726 
3727 /*
3728  * pseries-2.8
3729  */
3730 #define SPAPR_COMPAT_2_8                                        \
3731     HW_COMPAT_2_8                                               \
3732     {                                                           \
3733         .driver   = TYPE_SPAPR_PCI_HOST_BRIDGE,                 \
3734         .property = "pcie-extended-configuration-space",        \
3735         .value    = "off",                                      \
3736     },
3737 
3738 static void spapr_machine_2_8_instance_options(MachineState *machine)
3739 {
3740     spapr_machine_2_9_instance_options(machine);
3741 }
3742 
3743 static void spapr_machine_2_8_class_options(MachineClass *mc)
3744 {
3745     spapr_machine_2_9_class_options(mc);
3746     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_8);
3747     mc->numa_mem_align_shift = 23;
3748 }
3749 
3750 DEFINE_SPAPR_MACHINE(2_8, "2.8", false);
3751 
3752 /*
3753  * pseries-2.7
3754  */
3755 #define SPAPR_COMPAT_2_7                            \
3756     HW_COMPAT_2_7                                   \
3757     {                                               \
3758         .driver   = TYPE_SPAPR_PCI_HOST_BRIDGE,     \
3759         .property = "mem_win_size",                 \
3760         .value    = stringify(SPAPR_PCI_2_7_MMIO_WIN_SIZE),\
3761     },                                              \
3762     {                                               \
3763         .driver   = TYPE_SPAPR_PCI_HOST_BRIDGE,     \
3764         .property = "mem64_win_size",               \
3765         .value    = "0",                            \
3766     },                                              \
3767     {                                               \
3768         .driver = TYPE_POWERPC_CPU,                 \
3769         .property = "pre-2.8-migration",            \
3770         .value    = "on",                           \
3771     },                                              \
3772     {                                               \
3773         .driver = TYPE_SPAPR_PCI_HOST_BRIDGE,       \
3774         .property = "pre-2.8-migration",            \
3775         .value    = "on",                           \
3776     },
3777 
3778 static void phb_placement_2_7(sPAPRMachineState *spapr, uint32_t index,
3779                               uint64_t *buid, hwaddr *pio,
3780                               hwaddr *mmio32, hwaddr *mmio64,
3781                               unsigned n_dma, uint32_t *liobns, Error **errp)
3782 {
3783     /* Legacy PHB placement for pseries-2.7 and earlier machine types */
3784     const uint64_t base_buid = 0x800000020000000ULL;
3785     const hwaddr phb_spacing = 0x1000000000ULL; /* 64 GiB */
3786     const hwaddr mmio_offset = 0xa0000000; /* 2 GiB + 512 MiB */
3787     const hwaddr pio_offset = 0x80000000; /* 2 GiB */
3788     const uint32_t max_index = 255;
3789     const hwaddr phb0_alignment = 0x10000000000ULL; /* 1 TiB */
3790 
3791     uint64_t ram_top = MACHINE(spapr)->ram_size;
3792     hwaddr phb0_base, phb_base;
3793     int i;
3794 
3795     /* Do we have hotpluggable memory? */
3796     if (MACHINE(spapr)->maxram_size > ram_top) {
3797         /* Can't just use maxram_size, because there may be an
3798          * alignment gap between normal and hotpluggable memory
3799          * regions */
3800         ram_top = spapr->hotplug_memory.base +
3801             memory_region_size(&spapr->hotplug_memory.mr);
3802     }
3803 
3804     phb0_base = QEMU_ALIGN_UP(ram_top, phb0_alignment);
3805 
3806     if (index > max_index) {
3807         error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",
3808                    max_index);
3809         return;
3810     }
3811 
3812     *buid = base_buid + index;
3813     for (i = 0; i < n_dma; ++i) {
3814         liobns[i] = SPAPR_PCI_LIOBN(index, i);
3815     }
3816 
3817     phb_base = phb0_base + index * phb_spacing;
3818     *pio = phb_base + pio_offset;
3819     *mmio32 = phb_base + mmio_offset;
3820     /*
3821      * We don't set the 64-bit MMIO window, relying on the PHB's
3822      * fallback behaviour of automatically splitting a large "32-bit"
3823      * window into contiguous 32-bit and 64-bit windows
3824      */
3825 }
3826 
3827 static void spapr_machine_2_7_instance_options(MachineState *machine)
3828 {
3829     sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
3830 
3831     spapr_machine_2_8_instance_options(machine);
3832     spapr->use_hotplug_event_source = false;
3833 }
3834 
3835 static void spapr_machine_2_7_class_options(MachineClass *mc)
3836 {
3837     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3838 
3839     spapr_machine_2_8_class_options(mc);
3840     smc->tcg_default_cpu = "POWER7";
3841     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_7);
3842     smc->phb_placement = phb_placement_2_7;
3843 }
3844 
3845 DEFINE_SPAPR_MACHINE(2_7, "2.7", false);
3846 
3847 /*
3848  * pseries-2.6
3849  */
3850 #define SPAPR_COMPAT_2_6 \
3851     HW_COMPAT_2_6 \
3852     { \
3853         .driver   = TYPE_SPAPR_PCI_HOST_BRIDGE,\
3854         .property = "ddw",\
3855         .value    = stringify(off),\
3856     },
3857 
3858 static void spapr_machine_2_6_instance_options(MachineState *machine)
3859 {
3860     spapr_machine_2_7_instance_options(machine);
3861 }
3862 
3863 static void spapr_machine_2_6_class_options(MachineClass *mc)
3864 {
3865     spapr_machine_2_7_class_options(mc);
3866     mc->has_hotpluggable_cpus = false;
3867     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_6);
3868 }
3869 
3870 DEFINE_SPAPR_MACHINE(2_6, "2.6", false);
3871 
3872 /*
3873  * pseries-2.5
3874  */
3875 #define SPAPR_COMPAT_2_5 \
3876     HW_COMPAT_2_5 \
3877     { \
3878         .driver   = "spapr-vlan", \
3879         .property = "use-rx-buffer-pools", \
3880         .value    = "off", \
3881     },
3882 
3883 static void spapr_machine_2_5_instance_options(MachineState *machine)
3884 {
3885     spapr_machine_2_6_instance_options(machine);
3886 }
3887 
3888 static void spapr_machine_2_5_class_options(MachineClass *mc)
3889 {
3890     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3891 
3892     spapr_machine_2_6_class_options(mc);
3893     smc->use_ohci_by_default = true;
3894     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_5);
3895 }
3896 
3897 DEFINE_SPAPR_MACHINE(2_5, "2.5", false);
3898 
3899 /*
3900  * pseries-2.4
3901  */
3902 #define SPAPR_COMPAT_2_4 \
3903         HW_COMPAT_2_4
3904 
3905 static void spapr_machine_2_4_instance_options(MachineState *machine)
3906 {
3907     spapr_machine_2_5_instance_options(machine);
3908 }
3909 
3910 static void spapr_machine_2_4_class_options(MachineClass *mc)
3911 {
3912     sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);
3913 
3914     spapr_machine_2_5_class_options(mc);
3915     smc->dr_lmb_enabled = false;
3916     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_4);
3917 }
3918 
3919 DEFINE_SPAPR_MACHINE(2_4, "2.4", false);
3920 
3921 /*
3922  * pseries-2.3
3923  */
3924 #define SPAPR_COMPAT_2_3 \
3925         HW_COMPAT_2_3 \
3926         {\
3927             .driver   = "spapr-pci-host-bridge",\
3928             .property = "dynamic-reconfiguration",\
3929             .value    = "off",\
3930         },
3931 
3932 static void spapr_machine_2_3_instance_options(MachineState *machine)
3933 {
3934     spapr_machine_2_4_instance_options(machine);
3935 }
3936 
3937 static void spapr_machine_2_3_class_options(MachineClass *mc)
3938 {
3939     spapr_machine_2_4_class_options(mc);
3940     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_3);
3941 }
3942 DEFINE_SPAPR_MACHINE(2_3, "2.3", false);
3943 
3944 /*
3945  * pseries-2.2
3946  */
3947 
3948 #define SPAPR_COMPAT_2_2 \
3949         HW_COMPAT_2_2 \
3950         {\
3951             .driver   = TYPE_SPAPR_PCI_HOST_BRIDGE,\
3952             .property = "mem_win_size",\
3953             .value    = "0x20000000",\
3954         },
3955 
3956 static void spapr_machine_2_2_instance_options(MachineState *machine)
3957 {
3958     spapr_machine_2_3_instance_options(machine);
3959     machine->suppress_vmdesc = true;
3960 }
3961 
3962 static void spapr_machine_2_2_class_options(MachineClass *mc)
3963 {
3964     spapr_machine_2_3_class_options(mc);
3965     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_2);
3966 }
3967 DEFINE_SPAPR_MACHINE(2_2, "2.2", false);
3968 
3969 /*
3970  * pseries-2.1
3971  */
3972 #define SPAPR_COMPAT_2_1 \
3973         HW_COMPAT_2_1
3974 
3975 static void spapr_machine_2_1_instance_options(MachineState *machine)
3976 {
3977     spapr_machine_2_2_instance_options(machine);
3978 }
3979 
3980 static void spapr_machine_2_1_class_options(MachineClass *mc)
3981 {
3982     spapr_machine_2_2_class_options(mc);
3983     SET_MACHINE_COMPAT(mc, SPAPR_COMPAT_2_1);
3984 }
3985 DEFINE_SPAPR_MACHINE(2_1, "2.1", false);
3986 
3987 static void spapr_machine_register_types(void)
3988 {
3989     type_register_static(&spapr_machine_info);
3990 }
3991 
3992 type_init(spapr_machine_register_types)
3993