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