xref: /openbmc/qemu/hw/ppc/spapr.c (revision 6f2e2730)
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 "sysemu/sysemu.h"
28 #include "hw/hw.h"
29 #include "hw/fw-path-provider.h"
30 #include "elf.h"
31 #include "net/net.h"
32 #include "sysemu/blockdev.h"
33 #include "sysemu/cpus.h"
34 #include "sysemu/kvm.h"
35 #include "kvm_ppc.h"
36 #include "mmu-hash64.h"
37 #include "qom/cpu.h"
38 
39 #include "hw/boards.h"
40 #include "hw/ppc/ppc.h"
41 #include "hw/loader.h"
42 
43 #include "hw/ppc/spapr.h"
44 #include "hw/ppc/spapr_vio.h"
45 #include "hw/pci-host/spapr.h"
46 #include "hw/ppc/xics.h"
47 #include "hw/pci/msi.h"
48 
49 #include "hw/pci/pci.h"
50 #include "hw/scsi/scsi.h"
51 #include "hw/virtio/virtio-scsi.h"
52 
53 #include "exec/address-spaces.h"
54 #include "hw/usb.h"
55 #include "qemu/config-file.h"
56 #include "qemu/error-report.h"
57 #include "trace.h"
58 
59 #include <libfdt.h>
60 
61 /* SLOF memory layout:
62  *
63  * SLOF raw image loaded at 0, copies its romfs right below the flat
64  * device-tree, then position SLOF itself 31M below that
65  *
66  * So we set FW_OVERHEAD to 40MB which should account for all of that
67  * and more
68  *
69  * We load our kernel at 4M, leaving space for SLOF initial image
70  */
71 #define FDT_MAX_SIZE            0x40000
72 #define RTAS_MAX_SIZE           0x10000
73 #define FW_MAX_SIZE             0x400000
74 #define FW_FILE_NAME            "slof.bin"
75 #define FW_OVERHEAD             0x2800000
76 #define KERNEL_LOAD_ADDR        FW_MAX_SIZE
77 
78 #define MIN_RMA_SLOF            128UL
79 
80 #define TIMEBASE_FREQ           512000000ULL
81 
82 #define MAX_CPUS                256
83 
84 #define PHANDLE_XICP            0x00001111
85 
86 #define HTAB_SIZE(spapr)        (1ULL << ((spapr)->htab_shift))
87 
88 
89 typedef struct SPAPRMachine SPAPRMachine;
90 #define TYPE_SPAPR_MACHINE      "spapr-machine"
91 #define SPAPR_MACHINE(obj) \
92     OBJECT_CHECK(SPAPRMachine, (obj), TYPE_SPAPR_MACHINE)
93 
94 /**
95  * SPAPRMachine:
96  */
97 struct SPAPRMachine {
98     /*< private >*/
99     MachineState parent_obj;
100 
101     /*< public >*/
102     char *kvm_type;
103 };
104 
105 
106 sPAPREnvironment *spapr;
107 
108 int spapr_allocate_irq(int hint, bool lsi)
109 {
110     int irq;
111 
112     if (hint) {
113         irq = hint;
114         if (hint >= spapr->next_irq) {
115             spapr->next_irq = hint + 1;
116         }
117         /* FIXME: we should probably check for collisions somehow */
118     } else {
119         irq = spapr->next_irq++;
120     }
121 
122     /* Configure irq type */
123     if (!xics_get_qirq(spapr->icp, irq)) {
124         return 0;
125     }
126 
127     xics_set_irq_type(spapr->icp, irq, lsi);
128 
129     return irq;
130 }
131 
132 /*
133  * Allocate block of consequtive IRQs, returns a number of the first.
134  * If msi==true, aligns the first IRQ number to num.
135  */
136 int spapr_allocate_irq_block(int num, bool lsi, bool msi)
137 {
138     int first = -1;
139     int i, hint = 0;
140 
141     /*
142      * MSIMesage::data is used for storing VIRQ so
143      * it has to be aligned to num to support multiple
144      * MSI vectors. MSI-X is not affected by this.
145      * The hint is used for the first IRQ, the rest should
146      * be allocated continuously.
147      */
148     if (msi) {
149         assert((num == 1) || (num == 2) || (num == 4) ||
150                (num == 8) || (num == 16) || (num == 32));
151         hint = (spapr->next_irq + num - 1) & ~(num - 1);
152     }
153 
154     for (i = 0; i < num; ++i) {
155         int irq;
156 
157         irq = spapr_allocate_irq(hint, lsi);
158         if (!irq) {
159             return -1;
160         }
161 
162         if (0 == i) {
163             first = irq;
164             hint = 0;
165         }
166 
167         /* If the above doesn't create a consecutive block then that's
168          * an internal bug */
169         assert(irq == (first + i));
170     }
171 
172     return first;
173 }
174 
175 static XICSState *try_create_xics(const char *type, int nr_servers,
176                                   int nr_irqs)
177 {
178     DeviceState *dev;
179 
180     dev = qdev_create(NULL, type);
181     qdev_prop_set_uint32(dev, "nr_servers", nr_servers);
182     qdev_prop_set_uint32(dev, "nr_irqs", nr_irqs);
183     if (qdev_init(dev) < 0) {
184         return NULL;
185     }
186 
187     return XICS_COMMON(dev);
188 }
189 
190 static XICSState *xics_system_init(int nr_servers, int nr_irqs)
191 {
192     XICSState *icp = NULL;
193 
194     if (kvm_enabled()) {
195         QemuOpts *machine_opts = qemu_get_machine_opts();
196         bool irqchip_allowed = qemu_opt_get_bool(machine_opts,
197                                                 "kernel_irqchip", true);
198         bool irqchip_required = qemu_opt_get_bool(machine_opts,
199                                                   "kernel_irqchip", false);
200         if (irqchip_allowed) {
201             icp = try_create_xics(TYPE_KVM_XICS, nr_servers, nr_irqs);
202         }
203 
204         if (irqchip_required && !icp) {
205             perror("Failed to create in-kernel XICS\n");
206             abort();
207         }
208     }
209 
210     if (!icp) {
211         icp = try_create_xics(TYPE_XICS, nr_servers, nr_irqs);
212     }
213 
214     if (!icp) {
215         perror("Failed to create XICS\n");
216         abort();
217     }
218 
219     return icp;
220 }
221 
222 static int spapr_fixup_cpu_smt_dt(void *fdt, int offset, PowerPCCPU *cpu,
223                                   int smt_threads)
224 {
225     int i, ret = 0;
226     uint32_t servers_prop[smt_threads];
227     uint32_t gservers_prop[smt_threads * 2];
228     int index = ppc_get_vcpu_dt_id(cpu);
229 
230     if (cpu->cpu_version) {
231         ret = fdt_setprop(fdt, offset, "cpu-version",
232                           &cpu->cpu_version, sizeof(cpu->cpu_version));
233         if (ret < 0) {
234             return ret;
235         }
236     }
237 
238     /* Build interrupt servers and gservers properties */
239     for (i = 0; i < smt_threads; i++) {
240         servers_prop[i] = cpu_to_be32(index + i);
241         /* Hack, direct the group queues back to cpu 0 */
242         gservers_prop[i*2] = cpu_to_be32(index + i);
243         gservers_prop[i*2 + 1] = 0;
244     }
245     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-server#s",
246                       servers_prop, sizeof(servers_prop));
247     if (ret < 0) {
248         return ret;
249     }
250     ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-gserver#s",
251                       gservers_prop, sizeof(gservers_prop));
252 
253     return ret;
254 }
255 
256 static int spapr_fixup_cpu_dt(void *fdt, sPAPREnvironment *spapr)
257 {
258     int ret = 0, offset, cpus_offset;
259     CPUState *cs;
260     char cpu_model[32];
261     int smt = kvmppc_smt_threads();
262     uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};
263 
264     CPU_FOREACH(cs) {
265         PowerPCCPU *cpu = POWERPC_CPU(cs);
266         DeviceClass *dc = DEVICE_GET_CLASS(cs);
267         int index = ppc_get_vcpu_dt_id(cpu);
268         uint32_t associativity[] = {cpu_to_be32(0x5),
269                                     cpu_to_be32(0x0),
270                                     cpu_to_be32(0x0),
271                                     cpu_to_be32(0x0),
272                                     cpu_to_be32(cs->numa_node),
273                                     cpu_to_be32(index)};
274 
275         if ((index % smt) != 0) {
276             continue;
277         }
278 
279         snprintf(cpu_model, 32, "%s@%x", dc->fw_name, index);
280 
281         cpus_offset = fdt_path_offset(fdt, "/cpus");
282         if (cpus_offset < 0) {
283             cpus_offset = fdt_add_subnode(fdt, fdt_path_offset(fdt, "/"),
284                                           "cpus");
285             if (cpus_offset < 0) {
286                 return cpus_offset;
287             }
288         }
289         offset = fdt_subnode_offset(fdt, cpus_offset, cpu_model);
290         if (offset < 0) {
291             offset = fdt_add_subnode(fdt, cpus_offset, cpu_model);
292             if (offset < 0) {
293                 return offset;
294             }
295         }
296 
297         if (nb_numa_nodes > 1) {
298             ret = fdt_setprop(fdt, offset, "ibm,associativity", associativity,
299                               sizeof(associativity));
300             if (ret < 0) {
301                 return ret;
302             }
303         }
304 
305         ret = fdt_setprop(fdt, offset, "ibm,pft-size",
306                           pft_size_prop, sizeof(pft_size_prop));
307         if (ret < 0) {
308             return ret;
309         }
310 
311         ret = spapr_fixup_cpu_smt_dt(fdt, offset, cpu,
312                                      ppc_get_compat_smt_threads(cpu));
313         if (ret < 0) {
314             return ret;
315         }
316     }
317     return ret;
318 }
319 
320 
321 static size_t create_page_sizes_prop(CPUPPCState *env, uint32_t *prop,
322                                      size_t maxsize)
323 {
324     size_t maxcells = maxsize / sizeof(uint32_t);
325     int i, j, count;
326     uint32_t *p = prop;
327 
328     for (i = 0; i < PPC_PAGE_SIZES_MAX_SZ; i++) {
329         struct ppc_one_seg_page_size *sps = &env->sps.sps[i];
330 
331         if (!sps->page_shift) {
332             break;
333         }
334         for (count = 0; count < PPC_PAGE_SIZES_MAX_SZ; count++) {
335             if (sps->enc[count].page_shift == 0) {
336                 break;
337             }
338         }
339         if ((p - prop) >= (maxcells - 3 - count * 2)) {
340             break;
341         }
342         *(p++) = cpu_to_be32(sps->page_shift);
343         *(p++) = cpu_to_be32(sps->slb_enc);
344         *(p++) = cpu_to_be32(count);
345         for (j = 0; j < count; j++) {
346             *(p++) = cpu_to_be32(sps->enc[j].page_shift);
347             *(p++) = cpu_to_be32(sps->enc[j].pte_enc);
348         }
349     }
350 
351     return (p - prop) * sizeof(uint32_t);
352 }
353 
354 #define _FDT(exp) \
355     do { \
356         int ret = (exp);                                           \
357         if (ret < 0) {                                             \
358             fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \
359                     #exp, fdt_strerror(ret));                      \
360             exit(1);                                               \
361         }                                                          \
362     } while (0)
363 
364 static void add_str(GString *s, const gchar *s1)
365 {
366     g_string_append_len(s, s1, strlen(s1) + 1);
367 }
368 
369 static void *spapr_create_fdt_skel(hwaddr initrd_base,
370                                    hwaddr initrd_size,
371                                    hwaddr kernel_size,
372                                    bool little_endian,
373                                    const char *boot_device,
374                                    const char *kernel_cmdline,
375                                    uint32_t epow_irq)
376 {
377     void *fdt;
378     CPUState *cs;
379     uint32_t start_prop = cpu_to_be32(initrd_base);
380     uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);
381     GString *hypertas = g_string_sized_new(256);
382     GString *qemu_hypertas = g_string_sized_new(256);
383     uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};
384     uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};
385     int smt = kvmppc_smt_threads();
386     unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};
387     QemuOpts *opts = qemu_opts_find(qemu_find_opts("smp-opts"), NULL);
388     unsigned sockets = opts ? qemu_opt_get_number(opts, "sockets", 0) : 0;
389     uint32_t cpus_per_socket = sockets ? (smp_cpus / sockets) : 1;
390 
391     add_str(hypertas, "hcall-pft");
392     add_str(hypertas, "hcall-term");
393     add_str(hypertas, "hcall-dabr");
394     add_str(hypertas, "hcall-interrupt");
395     add_str(hypertas, "hcall-tce");
396     add_str(hypertas, "hcall-vio");
397     add_str(hypertas, "hcall-splpar");
398     add_str(hypertas, "hcall-bulk");
399     add_str(hypertas, "hcall-set-mode");
400     add_str(qemu_hypertas, "hcall-memop1");
401 
402     fdt = g_malloc0(FDT_MAX_SIZE);
403     _FDT((fdt_create(fdt, FDT_MAX_SIZE)));
404 
405     if (kernel_size) {
406         _FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));
407     }
408     if (initrd_size) {
409         _FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));
410     }
411     _FDT((fdt_finish_reservemap(fdt)));
412 
413     /* Root node */
414     _FDT((fdt_begin_node(fdt, "")));
415     _FDT((fdt_property_string(fdt, "device_type", "chrp")));
416     _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));
417     _FDT((fdt_property_string(fdt, "compatible", "qemu,pseries")));
418 
419     _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));
420     _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));
421 
422     /* /chosen */
423     _FDT((fdt_begin_node(fdt, "chosen")));
424 
425     /* Set Form1_affinity */
426     _FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));
427 
428     _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));
429     _FDT((fdt_property(fdt, "linux,initrd-start",
430                        &start_prop, sizeof(start_prop))));
431     _FDT((fdt_property(fdt, "linux,initrd-end",
432                        &end_prop, sizeof(end_prop))));
433     if (kernel_size) {
434         uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
435                               cpu_to_be64(kernel_size) };
436 
437         _FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
438         if (little_endian) {
439             _FDT((fdt_property(fdt, "qemu,boot-kernel-le", NULL, 0)));
440         }
441     }
442     if (boot_device) {
443         _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));
444     }
445     _FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));
446     _FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));
447     _FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));
448 
449     _FDT((fdt_end_node(fdt)));
450 
451     /* cpus */
452     _FDT((fdt_begin_node(fdt, "cpus")));
453 
454     _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
455     _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
456 
457     CPU_FOREACH(cs) {
458         PowerPCCPU *cpu = POWERPC_CPU(cs);
459         CPUPPCState *env = &cpu->env;
460         DeviceClass *dc = DEVICE_GET_CLASS(cs);
461         PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
462         int index = ppc_get_vcpu_dt_id(cpu);
463         char *nodename;
464         uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
465                            0xffffffff, 0xffffffff};
466         uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;
467         uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
468         uint32_t page_sizes_prop[64];
469         size_t page_sizes_prop_size;
470 
471         if ((index % smt) != 0) {
472             continue;
473         }
474 
475         nodename = g_strdup_printf("%s@%x", dc->fw_name, index);
476 
477         _FDT((fdt_begin_node(fdt, nodename)));
478 
479         g_free(nodename);
480 
481         _FDT((fdt_property_cell(fdt, "reg", index)));
482         _FDT((fdt_property_string(fdt, "device_type", "cpu")));
483 
484         _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));
485         _FDT((fdt_property_cell(fdt, "d-cache-block-size",
486                                 env->dcache_line_size)));
487         _FDT((fdt_property_cell(fdt, "d-cache-line-size",
488                                 env->dcache_line_size)));
489         _FDT((fdt_property_cell(fdt, "i-cache-block-size",
490                                 env->icache_line_size)));
491         _FDT((fdt_property_cell(fdt, "i-cache-line-size",
492                                 env->icache_line_size)));
493 
494         if (pcc->l1_dcache_size) {
495             _FDT((fdt_property_cell(fdt, "d-cache-size", pcc->l1_dcache_size)));
496         } else {
497             fprintf(stderr, "Warning: Unknown L1 dcache size for cpu\n");
498         }
499         if (pcc->l1_icache_size) {
500             _FDT((fdt_property_cell(fdt, "i-cache-size", pcc->l1_icache_size)));
501         } else {
502             fprintf(stderr, "Warning: Unknown L1 icache size for cpu\n");
503         }
504 
505         _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));
506         _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));
507         _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));
508         _FDT((fdt_property_string(fdt, "status", "okay")));
509         _FDT((fdt_property(fdt, "64-bit", NULL, 0)));
510 
511         if (env->spr_cb[SPR_PURR].oea_read) {
512             _FDT((fdt_property(fdt, "ibm,purr", NULL, 0)));
513         }
514 
515         if (env->mmu_model & POWERPC_MMU_1TSEG) {
516             _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",
517                                segs, sizeof(segs))));
518         }
519 
520         /* Advertise VMX/VSX (vector extensions) if available
521          *   0 / no property == no vector extensions
522          *   1               == VMX / Altivec available
523          *   2               == VSX available */
524         if (env->insns_flags & PPC_ALTIVEC) {
525             uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;
526 
527             _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));
528         }
529 
530         /* Advertise DFP (Decimal Floating Point) if available
531          *   0 / no property == no DFP
532          *   1               == DFP available */
533         if (env->insns_flags2 & PPC2_DFP) {
534             _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));
535         }
536 
537         page_sizes_prop_size = create_page_sizes_prop(env, page_sizes_prop,
538                                                       sizeof(page_sizes_prop));
539         if (page_sizes_prop_size) {
540             _FDT((fdt_property(fdt, "ibm,segment-page-sizes",
541                                page_sizes_prop, page_sizes_prop_size)));
542         }
543 
544         _FDT((fdt_property_cell(fdt, "ibm,chip-id",
545                                 cs->cpu_index / cpus_per_socket)));
546 
547         _FDT((fdt_end_node(fdt)));
548     }
549 
550     _FDT((fdt_end_node(fdt)));
551 
552     /* RTAS */
553     _FDT((fdt_begin_node(fdt, "rtas")));
554 
555     if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {
556         add_str(hypertas, "hcall-multi-tce");
557     }
558     _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas->str,
559                        hypertas->len)));
560     g_string_free(hypertas, TRUE);
561     _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas->str,
562                        qemu_hypertas->len)));
563     g_string_free(qemu_hypertas, TRUE);
564 
565     _FDT((fdt_property(fdt, "ibm,associativity-reference-points",
566         refpoints, sizeof(refpoints))));
567 
568     _FDT((fdt_property_cell(fdt, "rtas-error-log-max", RTAS_ERROR_LOG_MAX)));
569 
570     _FDT((fdt_end_node(fdt)));
571 
572     /* interrupt controller */
573     _FDT((fdt_begin_node(fdt, "interrupt-controller")));
574 
575     _FDT((fdt_property_string(fdt, "device_type",
576                               "PowerPC-External-Interrupt-Presentation")));
577     _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));
578     _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
579     _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",
580                        interrupt_server_ranges_prop,
581                        sizeof(interrupt_server_ranges_prop))));
582     _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));
583     _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));
584     _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));
585 
586     _FDT((fdt_end_node(fdt)));
587 
588     /* vdevice */
589     _FDT((fdt_begin_node(fdt, "vdevice")));
590 
591     _FDT((fdt_property_string(fdt, "device_type", "vdevice")));
592     _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));
593     _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
594     _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
595     _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));
596     _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
597 
598     _FDT((fdt_end_node(fdt)));
599 
600     /* event-sources */
601     spapr_events_fdt_skel(fdt, epow_irq);
602 
603     /* /hypervisor node */
604     if (kvm_enabled()) {
605         uint8_t hypercall[16];
606 
607         /* indicate KVM hypercall interface */
608         _FDT((fdt_begin_node(fdt, "hypervisor")));
609         _FDT((fdt_property_string(fdt, "compatible", "linux,kvm")));
610         if (kvmppc_has_cap_fixup_hcalls()) {
611             /*
612              * Older KVM versions with older guest kernels were broken with the
613              * magic page, don't allow the guest to map it.
614              */
615             kvmppc_get_hypercall(first_cpu->env_ptr, hypercall,
616                                  sizeof(hypercall));
617             _FDT((fdt_property(fdt, "hcall-instructions", hypercall,
618                               sizeof(hypercall))));
619         }
620         _FDT((fdt_end_node(fdt)));
621     }
622 
623     _FDT((fdt_end_node(fdt))); /* close root node */
624     _FDT((fdt_finish(fdt)));
625 
626     return fdt;
627 }
628 
629 int spapr_h_cas_compose_response(target_ulong addr, target_ulong size)
630 {
631     void *fdt, *fdt_skel;
632     sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };
633 
634     size -= sizeof(hdr);
635 
636     /* Create sceleton */
637     fdt_skel = g_malloc0(size);
638     _FDT((fdt_create(fdt_skel, size)));
639     _FDT((fdt_begin_node(fdt_skel, "")));
640     _FDT((fdt_end_node(fdt_skel)));
641     _FDT((fdt_finish(fdt_skel)));
642     fdt = g_malloc0(size);
643     _FDT((fdt_open_into(fdt_skel, fdt, size)));
644     g_free(fdt_skel);
645 
646     /* Fix skeleton up */
647     _FDT((spapr_fixup_cpu_dt(fdt, spapr)));
648 
649     /* Pack resulting tree */
650     _FDT((fdt_pack(fdt)));
651 
652     if (fdt_totalsize(fdt) + sizeof(hdr) > size) {
653         trace_spapr_cas_failed(size);
654         return -1;
655     }
656 
657     cpu_physical_memory_write(addr, &hdr, sizeof(hdr));
658     cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));
659     trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));
660     g_free(fdt);
661 
662     return 0;
663 }
664 
665 static int spapr_populate_memory(sPAPREnvironment *spapr, void *fdt)
666 {
667     uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0),
668                                 cpu_to_be32(0x0), cpu_to_be32(0x0),
669                                 cpu_to_be32(0x0)};
670     char mem_name[32];
671     hwaddr node0_size, mem_start, node_size;
672     uint64_t mem_reg_property[2];
673     int i, off;
674 
675     /* memory node(s) */
676     if (nb_numa_nodes > 1 && numa_info[0].node_mem < ram_size) {
677         node0_size = numa_info[0].node_mem;
678     } else {
679         node0_size = ram_size;
680     }
681 
682     /* RMA */
683     mem_reg_property[0] = 0;
684     mem_reg_property[1] = cpu_to_be64(spapr->rma_size);
685     off = fdt_add_subnode(fdt, 0, "memory@0");
686     _FDT(off);
687     _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
688     _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property,
689                       sizeof(mem_reg_property))));
690     _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity,
691                       sizeof(associativity))));
692 
693     /* RAM: Node 0 */
694     if (node0_size > spapr->rma_size) {
695         mem_reg_property[0] = cpu_to_be64(spapr->rma_size);
696         mem_reg_property[1] = cpu_to_be64(node0_size - spapr->rma_size);
697 
698         sprintf(mem_name, "memory@" TARGET_FMT_lx, spapr->rma_size);
699         off = fdt_add_subnode(fdt, 0, mem_name);
700         _FDT(off);
701         _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
702         _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property,
703                           sizeof(mem_reg_property))));
704         _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity,
705                           sizeof(associativity))));
706     }
707 
708     /* RAM: Node 1 and beyond */
709     mem_start = node0_size;
710     for (i = 1; i < nb_numa_nodes; i++) {
711         mem_reg_property[0] = cpu_to_be64(mem_start);
712         if (mem_start >= ram_size) {
713             node_size = 0;
714         } else {
715             node_size = numa_info[i].node_mem;
716             if (node_size > ram_size - mem_start) {
717                 node_size = ram_size - mem_start;
718             }
719         }
720         mem_reg_property[1] = cpu_to_be64(node_size);
721         associativity[3] = associativity[4] = cpu_to_be32(i);
722         sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start);
723         off = fdt_add_subnode(fdt, 0, mem_name);
724         _FDT(off);
725         _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
726         _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property,
727                           sizeof(mem_reg_property))));
728         _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity,
729                           sizeof(associativity))));
730         mem_start += node_size;
731     }
732 
733     return 0;
734 }
735 
736 static void spapr_finalize_fdt(sPAPREnvironment *spapr,
737                                hwaddr fdt_addr,
738                                hwaddr rtas_addr,
739                                hwaddr rtas_size)
740 {
741     int ret, i;
742     size_t cb = 0;
743     char *bootlist;
744     void *fdt;
745     sPAPRPHBState *phb;
746 
747     fdt = g_malloc(FDT_MAX_SIZE);
748 
749     /* open out the base tree into a temp buffer for the final tweaks */
750     _FDT((fdt_open_into(spapr->fdt_skel, fdt, FDT_MAX_SIZE)));
751 
752     ret = spapr_populate_memory(spapr, fdt);
753     if (ret < 0) {
754         fprintf(stderr, "couldn't setup memory nodes in fdt\n");
755         exit(1);
756     }
757 
758     ret = spapr_populate_vdevice(spapr->vio_bus, fdt);
759     if (ret < 0) {
760         fprintf(stderr, "couldn't setup vio devices in fdt\n");
761         exit(1);
762     }
763 
764     QLIST_FOREACH(phb, &spapr->phbs, list) {
765         ret = spapr_populate_pci_dt(phb, PHANDLE_XICP, fdt);
766     }
767 
768     if (ret < 0) {
769         fprintf(stderr, "couldn't setup PCI devices in fdt\n");
770         exit(1);
771     }
772 
773     /* RTAS */
774     ret = spapr_rtas_device_tree_setup(fdt, rtas_addr, rtas_size);
775     if (ret < 0) {
776         fprintf(stderr, "Couldn't set up RTAS device tree properties\n");
777     }
778 
779     /* Advertise NUMA via ibm,associativity */
780     ret = spapr_fixup_cpu_dt(fdt, spapr);
781     if (ret < 0) {
782         fprintf(stderr, "Couldn't finalize CPU device tree properties\n");
783     }
784 
785     bootlist = get_boot_devices_list(&cb, true);
786     if (cb && bootlist) {
787         int offset = fdt_path_offset(fdt, "/chosen");
788         if (offset < 0) {
789             exit(1);
790         }
791         for (i = 0; i < cb; i++) {
792             if (bootlist[i] == '\n') {
793                 bootlist[i] = ' ';
794             }
795 
796         }
797         ret = fdt_setprop_string(fdt, offset, "qemu,boot-list", bootlist);
798     }
799 
800     if (!spapr->has_graphics) {
801         spapr_populate_chosen_stdout(fdt, spapr->vio_bus);
802     }
803 
804     _FDT((fdt_pack(fdt)));
805 
806     if (fdt_totalsize(fdt) > FDT_MAX_SIZE) {
807         hw_error("FDT too big ! 0x%x bytes (max is 0x%x)\n",
808                  fdt_totalsize(fdt), FDT_MAX_SIZE);
809         exit(1);
810     }
811 
812     cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt));
813 
814     g_free(fdt);
815 }
816 
817 static uint64_t translate_kernel_address(void *opaque, uint64_t addr)
818 {
819     return (addr & 0x0fffffff) + KERNEL_LOAD_ADDR;
820 }
821 
822 static void emulate_spapr_hypercall(PowerPCCPU *cpu)
823 {
824     CPUPPCState *env = &cpu->env;
825 
826     if (msr_pr) {
827         hcall_dprintf("Hypercall made with MSR[PR]=1\n");
828         env->gpr[3] = H_PRIVILEGE;
829     } else {
830         env->gpr[3] = spapr_hypercall(cpu, env->gpr[3], &env->gpr[4]);
831     }
832 }
833 
834 static void spapr_reset_htab(sPAPREnvironment *spapr)
835 {
836     long shift;
837 
838     /* allocate hash page table.  For now we always make this 16mb,
839      * later we should probably make it scale to the size of guest
840      * RAM */
841 
842     shift = kvmppc_reset_htab(spapr->htab_shift);
843 
844     if (shift > 0) {
845         /* Kernel handles htab, we don't need to allocate one */
846         spapr->htab_shift = shift;
847         kvmppc_kern_htab = true;
848     } else {
849         if (!spapr->htab) {
850             /* Allocate an htab if we don't yet have one */
851             spapr->htab = qemu_memalign(HTAB_SIZE(spapr), HTAB_SIZE(spapr));
852         }
853 
854         /* And clear it */
855         memset(spapr->htab, 0, HTAB_SIZE(spapr));
856     }
857 
858     /* Update the RMA size if necessary */
859     if (spapr->vrma_adjust) {
860         hwaddr node0_size = (nb_numa_nodes > 1) ?
861             numa_info[0].node_mem : ram_size;
862         spapr->rma_size = kvmppc_rma_size(node0_size, spapr->htab_shift);
863     }
864 }
865 
866 static void ppc_spapr_reset(void)
867 {
868     PowerPCCPU *first_ppc_cpu;
869 
870     /* Reset the hash table & recalc the RMA */
871     spapr_reset_htab(spapr);
872 
873     qemu_devices_reset();
874 
875     /* Load the fdt */
876     spapr_finalize_fdt(spapr, spapr->fdt_addr, spapr->rtas_addr,
877                        spapr->rtas_size);
878 
879     /* Set up the entry state */
880     first_ppc_cpu = POWERPC_CPU(first_cpu);
881     first_ppc_cpu->env.gpr[3] = spapr->fdt_addr;
882     first_ppc_cpu->env.gpr[5] = 0;
883     first_cpu->halted = 0;
884     first_ppc_cpu->env.nip = spapr->entry_point;
885 
886 }
887 
888 static void spapr_cpu_reset(void *opaque)
889 {
890     PowerPCCPU *cpu = opaque;
891     CPUState *cs = CPU(cpu);
892     CPUPPCState *env = &cpu->env;
893 
894     cpu_reset(cs);
895 
896     /* All CPUs start halted.  CPU0 is unhalted from the machine level
897      * reset code and the rest are explicitly started up by the guest
898      * using an RTAS call */
899     cs->halted = 1;
900 
901     env->spr[SPR_HIOR] = 0;
902 
903     env->external_htab = (uint8_t *)spapr->htab;
904     if (kvm_enabled() && !env->external_htab) {
905         /*
906          * HV KVM, set external_htab to 1 so our ppc_hash64_load_hpte*
907          * functions do the right thing.
908          */
909         env->external_htab = (void *)1;
910     }
911     env->htab_base = -1;
912     /*
913      * htab_mask is the mask used to normalize hash value to PTEG index.
914      * htab_shift is log2 of hash table size.
915      * We have 8 hpte per group, and each hpte is 16 bytes.
916      * ie have 128 bytes per hpte entry.
917      */
918     env->htab_mask = (1ULL << ((spapr)->htab_shift - 7)) - 1;
919     env->spr[SPR_SDR1] = (target_ulong)(uintptr_t)spapr->htab |
920         (spapr->htab_shift - 18);
921 }
922 
923 static void spapr_create_nvram(sPAPREnvironment *spapr)
924 {
925     DeviceState *dev = qdev_create(&spapr->vio_bus->bus, "spapr-nvram");
926     DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);
927 
928     if (dinfo) {
929         qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);
930     }
931 
932     qdev_init_nofail(dev);
933 
934     spapr->nvram = (struct sPAPRNVRAM *)dev;
935 }
936 
937 /* Returns whether we want to use VGA or not */
938 static int spapr_vga_init(PCIBus *pci_bus)
939 {
940     switch (vga_interface_type) {
941     case VGA_NONE:
942         return false;
943     case VGA_DEVICE:
944         return true;
945     case VGA_STD:
946         return pci_vga_init(pci_bus) != NULL;
947     default:
948         fprintf(stderr, "This vga model is not supported,"
949                 "currently it only supports -vga std\n");
950         exit(0);
951     }
952 }
953 
954 static const VMStateDescription vmstate_spapr = {
955     .name = "spapr",
956     .version_id = 2,
957     .minimum_version_id = 1,
958     .fields = (VMStateField[]) {
959         VMSTATE_UINT32(next_irq, sPAPREnvironment),
960 
961         /* RTC offset */
962         VMSTATE_UINT64(rtc_offset, sPAPREnvironment),
963         VMSTATE_PPC_TIMEBASE_V(tb, sPAPREnvironment, 2),
964         VMSTATE_END_OF_LIST()
965     },
966 };
967 
968 #define HPTE(_table, _i)   (void *)(((uint64_t *)(_table)) + ((_i) * 2))
969 #define HPTE_VALID(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_VALID)
970 #define HPTE_DIRTY(_hpte)  (tswap64(*((uint64_t *)(_hpte))) & HPTE64_V_HPTE_DIRTY)
971 #define CLEAN_HPTE(_hpte)  ((*(uint64_t *)(_hpte)) &= tswap64(~HPTE64_V_HPTE_DIRTY))
972 
973 static int htab_save_setup(QEMUFile *f, void *opaque)
974 {
975     sPAPREnvironment *spapr = opaque;
976 
977     /* "Iteration" header */
978     qemu_put_be32(f, spapr->htab_shift);
979 
980     if (spapr->htab) {
981         spapr->htab_save_index = 0;
982         spapr->htab_first_pass = true;
983     } else {
984         assert(kvm_enabled());
985 
986         spapr->htab_fd = kvmppc_get_htab_fd(false);
987         if (spapr->htab_fd < 0) {
988             fprintf(stderr, "Unable to open fd for reading hash table from KVM: %s\n",
989                     strerror(errno));
990             return -1;
991         }
992     }
993 
994 
995     return 0;
996 }
997 
998 static void htab_save_first_pass(QEMUFile *f, sPAPREnvironment *spapr,
999                                  int64_t max_ns)
1000 {
1001     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
1002     int index = spapr->htab_save_index;
1003     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1004 
1005     assert(spapr->htab_first_pass);
1006 
1007     do {
1008         int chunkstart;
1009 
1010         /* Consume invalid HPTEs */
1011         while ((index < htabslots)
1012                && !HPTE_VALID(HPTE(spapr->htab, index))) {
1013             index++;
1014             CLEAN_HPTE(HPTE(spapr->htab, index));
1015         }
1016 
1017         /* Consume valid HPTEs */
1018         chunkstart = index;
1019         while ((index < htabslots)
1020                && HPTE_VALID(HPTE(spapr->htab, index))) {
1021             index++;
1022             CLEAN_HPTE(HPTE(spapr->htab, index));
1023         }
1024 
1025         if (index > chunkstart) {
1026             int n_valid = index - chunkstart;
1027 
1028             qemu_put_be32(f, chunkstart);
1029             qemu_put_be16(f, n_valid);
1030             qemu_put_be16(f, 0);
1031             qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),
1032                             HASH_PTE_SIZE_64 * n_valid);
1033 
1034             if ((qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
1035                 break;
1036             }
1037         }
1038     } while ((index < htabslots) && !qemu_file_rate_limit(f));
1039 
1040     if (index >= htabslots) {
1041         assert(index == htabslots);
1042         index = 0;
1043         spapr->htab_first_pass = false;
1044     }
1045     spapr->htab_save_index = index;
1046 }
1047 
1048 static int htab_save_later_pass(QEMUFile *f, sPAPREnvironment *spapr,
1049                                 int64_t max_ns)
1050 {
1051     bool final = max_ns < 0;
1052     int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;
1053     int examined = 0, sent = 0;
1054     int index = spapr->htab_save_index;
1055     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1056 
1057     assert(!spapr->htab_first_pass);
1058 
1059     do {
1060         int chunkstart, invalidstart;
1061 
1062         /* Consume non-dirty HPTEs */
1063         while ((index < htabslots)
1064                && !HPTE_DIRTY(HPTE(spapr->htab, index))) {
1065             index++;
1066             examined++;
1067         }
1068 
1069         chunkstart = index;
1070         /* Consume valid dirty HPTEs */
1071         while ((index < htabslots)
1072                && HPTE_DIRTY(HPTE(spapr->htab, index))
1073                && HPTE_VALID(HPTE(spapr->htab, index))) {
1074             CLEAN_HPTE(HPTE(spapr->htab, index));
1075             index++;
1076             examined++;
1077         }
1078 
1079         invalidstart = index;
1080         /* Consume invalid dirty HPTEs */
1081         while ((index < htabslots)
1082                && HPTE_DIRTY(HPTE(spapr->htab, index))
1083                && !HPTE_VALID(HPTE(spapr->htab, index))) {
1084             CLEAN_HPTE(HPTE(spapr->htab, index));
1085             index++;
1086             examined++;
1087         }
1088 
1089         if (index > chunkstart) {
1090             int n_valid = invalidstart - chunkstart;
1091             int n_invalid = index - invalidstart;
1092 
1093             qemu_put_be32(f, chunkstart);
1094             qemu_put_be16(f, n_valid);
1095             qemu_put_be16(f, n_invalid);
1096             qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),
1097                             HASH_PTE_SIZE_64 * n_valid);
1098             sent += index - chunkstart;
1099 
1100             if (!final && (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {
1101                 break;
1102             }
1103         }
1104 
1105         if (examined >= htabslots) {
1106             break;
1107         }
1108 
1109         if (index >= htabslots) {
1110             assert(index == htabslots);
1111             index = 0;
1112         }
1113     } while ((examined < htabslots) && (!qemu_file_rate_limit(f) || final));
1114 
1115     if (index >= htabslots) {
1116         assert(index == htabslots);
1117         index = 0;
1118     }
1119 
1120     spapr->htab_save_index = index;
1121 
1122     return (examined >= htabslots) && (sent == 0) ? 1 : 0;
1123 }
1124 
1125 #define MAX_ITERATION_NS    5000000 /* 5 ms */
1126 #define MAX_KVM_BUF_SIZE    2048
1127 
1128 static int htab_save_iterate(QEMUFile *f, void *opaque)
1129 {
1130     sPAPREnvironment *spapr = opaque;
1131     int rc = 0;
1132 
1133     /* Iteration header */
1134     qemu_put_be32(f, 0);
1135 
1136     if (!spapr->htab) {
1137         assert(kvm_enabled());
1138 
1139         rc = kvmppc_save_htab(f, spapr->htab_fd,
1140                               MAX_KVM_BUF_SIZE, MAX_ITERATION_NS);
1141         if (rc < 0) {
1142             return rc;
1143         }
1144     } else  if (spapr->htab_first_pass) {
1145         htab_save_first_pass(f, spapr, MAX_ITERATION_NS);
1146     } else {
1147         rc = htab_save_later_pass(f, spapr, MAX_ITERATION_NS);
1148     }
1149 
1150     /* End marker */
1151     qemu_put_be32(f, 0);
1152     qemu_put_be16(f, 0);
1153     qemu_put_be16(f, 0);
1154 
1155     return rc;
1156 }
1157 
1158 static int htab_save_complete(QEMUFile *f, void *opaque)
1159 {
1160     sPAPREnvironment *spapr = opaque;
1161 
1162     /* Iteration header */
1163     qemu_put_be32(f, 0);
1164 
1165     if (!spapr->htab) {
1166         int rc;
1167 
1168         assert(kvm_enabled());
1169 
1170         rc = kvmppc_save_htab(f, spapr->htab_fd, MAX_KVM_BUF_SIZE, -1);
1171         if (rc < 0) {
1172             return rc;
1173         }
1174         close(spapr->htab_fd);
1175         spapr->htab_fd = -1;
1176     } else {
1177         htab_save_later_pass(f, spapr, -1);
1178     }
1179 
1180     /* End marker */
1181     qemu_put_be32(f, 0);
1182     qemu_put_be16(f, 0);
1183     qemu_put_be16(f, 0);
1184 
1185     return 0;
1186 }
1187 
1188 static int htab_load(QEMUFile *f, void *opaque, int version_id)
1189 {
1190     sPAPREnvironment *spapr = opaque;
1191     uint32_t section_hdr;
1192     int fd = -1;
1193 
1194     if (version_id < 1 || version_id > 1) {
1195         fprintf(stderr, "htab_load() bad version\n");
1196         return -EINVAL;
1197     }
1198 
1199     section_hdr = qemu_get_be32(f);
1200 
1201     if (section_hdr) {
1202         /* First section, just the hash shift */
1203         if (spapr->htab_shift != section_hdr) {
1204             return -EINVAL;
1205         }
1206         return 0;
1207     }
1208 
1209     if (!spapr->htab) {
1210         assert(kvm_enabled());
1211 
1212         fd = kvmppc_get_htab_fd(true);
1213         if (fd < 0) {
1214             fprintf(stderr, "Unable to open fd to restore KVM hash table: %s\n",
1215                     strerror(errno));
1216         }
1217     }
1218 
1219     while (true) {
1220         uint32_t index;
1221         uint16_t n_valid, n_invalid;
1222 
1223         index = qemu_get_be32(f);
1224         n_valid = qemu_get_be16(f);
1225         n_invalid = qemu_get_be16(f);
1226 
1227         if ((index == 0) && (n_valid == 0) && (n_invalid == 0)) {
1228             /* End of Stream */
1229             break;
1230         }
1231 
1232         if ((index + n_valid + n_invalid) >
1233             (HTAB_SIZE(spapr) / HASH_PTE_SIZE_64)) {
1234             /* Bad index in stream */
1235             fprintf(stderr, "htab_load() bad index %d (%hd+%hd entries) "
1236                     "in htab stream (htab_shift=%d)\n", index, n_valid, n_invalid,
1237                     spapr->htab_shift);
1238             return -EINVAL;
1239         }
1240 
1241         if (spapr->htab) {
1242             if (n_valid) {
1243                 qemu_get_buffer(f, HPTE(spapr->htab, index),
1244                                 HASH_PTE_SIZE_64 * n_valid);
1245             }
1246             if (n_invalid) {
1247                 memset(HPTE(spapr->htab, index + n_valid), 0,
1248                        HASH_PTE_SIZE_64 * n_invalid);
1249             }
1250         } else {
1251             int rc;
1252 
1253             assert(fd >= 0);
1254 
1255             rc = kvmppc_load_htab_chunk(f, fd, index, n_valid, n_invalid);
1256             if (rc < 0) {
1257                 return rc;
1258             }
1259         }
1260     }
1261 
1262     if (!spapr->htab) {
1263         assert(fd >= 0);
1264         close(fd);
1265     }
1266 
1267     return 0;
1268 }
1269 
1270 static SaveVMHandlers savevm_htab_handlers = {
1271     .save_live_setup = htab_save_setup,
1272     .save_live_iterate = htab_save_iterate,
1273     .save_live_complete = htab_save_complete,
1274     .load_state = htab_load,
1275 };
1276 
1277 /* pSeries LPAR / sPAPR hardware init */
1278 static void ppc_spapr_init(MachineState *machine)
1279 {
1280     ram_addr_t ram_size = machine->ram_size;
1281     const char *cpu_model = machine->cpu_model;
1282     const char *kernel_filename = machine->kernel_filename;
1283     const char *kernel_cmdline = machine->kernel_cmdline;
1284     const char *initrd_filename = machine->initrd_filename;
1285     const char *boot_device = machine->boot_order;
1286     PowerPCCPU *cpu;
1287     CPUPPCState *env;
1288     PCIHostState *phb;
1289     int i;
1290     MemoryRegion *sysmem = get_system_memory();
1291     MemoryRegion *ram = g_new(MemoryRegion, 1);
1292     hwaddr rma_alloc_size;
1293     hwaddr node0_size = (nb_numa_nodes > 1) ? numa_info[0].node_mem : ram_size;
1294     uint32_t initrd_base = 0;
1295     long kernel_size = 0, initrd_size = 0;
1296     long load_limit, rtas_limit, fw_size;
1297     bool kernel_le = false;
1298     char *filename;
1299 
1300     msi_supported = true;
1301 
1302     spapr = g_malloc0(sizeof(*spapr));
1303     QLIST_INIT(&spapr->phbs);
1304 
1305     cpu_ppc_hypercall = emulate_spapr_hypercall;
1306 
1307     /* Allocate RMA if necessary */
1308     rma_alloc_size = kvmppc_alloc_rma("ppc_spapr.rma", sysmem);
1309 
1310     if (rma_alloc_size == -1) {
1311         hw_error("qemu: Unable to create RMA\n");
1312         exit(1);
1313     }
1314 
1315     if (rma_alloc_size && (rma_alloc_size < node0_size)) {
1316         spapr->rma_size = rma_alloc_size;
1317     } else {
1318         spapr->rma_size = node0_size;
1319 
1320         /* With KVM, we don't actually know whether KVM supports an
1321          * unbounded RMA (PR KVM) or is limited by the hash table size
1322          * (HV KVM using VRMA), so we always assume the latter
1323          *
1324          * In that case, we also limit the initial allocations for RTAS
1325          * etc... to 256M since we have no way to know what the VRMA size
1326          * is going to be as it depends on the size of the hash table
1327          * isn't determined yet.
1328          */
1329         if (kvm_enabled()) {
1330             spapr->vrma_adjust = 1;
1331             spapr->rma_size = MIN(spapr->rma_size, 0x10000000);
1332         }
1333     }
1334 
1335     if (spapr->rma_size > node0_size) {
1336         fprintf(stderr, "Error: Numa node 0 has to span the RMA (%#08"HWADDR_PRIx")\n",
1337                 spapr->rma_size);
1338         exit(1);
1339     }
1340 
1341     /* We place the device tree and RTAS just below either the top of the RMA,
1342      * or just below 2GB, whichever is lowere, so that it can be
1343      * processed with 32-bit real mode code if necessary */
1344     rtas_limit = MIN(spapr->rma_size, 0x80000000);
1345     spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE;
1346     spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE;
1347     load_limit = spapr->fdt_addr - FW_OVERHEAD;
1348 
1349     /* We aim for a hash table of size 1/128 the size of RAM.  The
1350      * normal rule of thumb is 1/64 the size of RAM, but that's much
1351      * more than needed for the Linux guests we support. */
1352     spapr->htab_shift = 18; /* Minimum architected size */
1353     while (spapr->htab_shift <= 46) {
1354         if ((1ULL << (spapr->htab_shift + 7)) >= ram_size) {
1355             break;
1356         }
1357         spapr->htab_shift++;
1358     }
1359 
1360     /* Set up Interrupt Controller before we create the VCPUs */
1361     spapr->icp = xics_system_init(smp_cpus * kvmppc_smt_threads() / smp_threads,
1362                                   XICS_IRQS);
1363     spapr->next_irq = XICS_IRQ_BASE;
1364 
1365     /* init CPUs */
1366     if (cpu_model == NULL) {
1367         cpu_model = kvm_enabled() ? "host" : "POWER7";
1368     }
1369     for (i = 0; i < smp_cpus; i++) {
1370         cpu = cpu_ppc_init(cpu_model);
1371         if (cpu == NULL) {
1372             fprintf(stderr, "Unable to find PowerPC CPU definition\n");
1373             exit(1);
1374         }
1375         env = &cpu->env;
1376 
1377         /* Set time-base frequency to 512 MHz */
1378         cpu_ppc_tb_init(env, TIMEBASE_FREQ);
1379 
1380         /* PAPR always has exception vectors in RAM not ROM. To ensure this,
1381          * MSR[IP] should never be set.
1382          */
1383         env->msr_mask &= ~(1 << 6);
1384 
1385         /* Tell KVM that we're in PAPR mode */
1386         if (kvm_enabled()) {
1387             kvmppc_set_papr(cpu);
1388         }
1389 
1390         if (cpu->max_compat) {
1391             if (ppc_set_compat(cpu, cpu->max_compat) < 0) {
1392                 exit(1);
1393             }
1394         }
1395 
1396         xics_cpu_setup(spapr->icp, cpu);
1397 
1398         qemu_register_reset(spapr_cpu_reset, cpu);
1399     }
1400 
1401     /* allocate RAM */
1402     spapr->ram_limit = ram_size;
1403     if (spapr->ram_limit > rma_alloc_size) {
1404         ram_addr_t nonrma_base = rma_alloc_size;
1405         ram_addr_t nonrma_size = spapr->ram_limit - rma_alloc_size;
1406 
1407         memory_region_init_ram(ram, NULL, "ppc_spapr.ram", nonrma_size);
1408         vmstate_register_ram_global(ram);
1409         memory_region_add_subregion(sysmem, nonrma_base, ram);
1410     }
1411 
1412     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin");
1413     spapr->rtas_size = load_image_targphys(filename, spapr->rtas_addr,
1414                                            rtas_limit - spapr->rtas_addr);
1415     if (spapr->rtas_size < 0) {
1416         hw_error("qemu: could not load LPAR rtas '%s'\n", filename);
1417         exit(1);
1418     }
1419     if (spapr->rtas_size > RTAS_MAX_SIZE) {
1420         hw_error("RTAS too big ! 0x%lx bytes (max is 0x%x)\n",
1421                  spapr->rtas_size, RTAS_MAX_SIZE);
1422         exit(1);
1423     }
1424     g_free(filename);
1425 
1426     /* Set up EPOW events infrastructure */
1427     spapr_events_init(spapr);
1428 
1429     /* Set up VIO bus */
1430     spapr->vio_bus = spapr_vio_bus_init();
1431 
1432     for (i = 0; i < MAX_SERIAL_PORTS; i++) {
1433         if (serial_hds[i]) {
1434             spapr_vty_create(spapr->vio_bus, serial_hds[i]);
1435         }
1436     }
1437 
1438     /* We always have at least the nvram device on VIO */
1439     spapr_create_nvram(spapr);
1440 
1441     /* Set up PCI */
1442     spapr_pci_msi_init(spapr, SPAPR_PCI_MSI_WINDOW);
1443     spapr_pci_rtas_init();
1444 
1445     phb = spapr_create_phb(spapr, 0);
1446 
1447     for (i = 0; i < nb_nics; i++) {
1448         NICInfo *nd = &nd_table[i];
1449 
1450         if (!nd->model) {
1451             nd->model = g_strdup("ibmveth");
1452         }
1453 
1454         if (strcmp(nd->model, "ibmveth") == 0) {
1455             spapr_vlan_create(spapr->vio_bus, nd);
1456         } else {
1457             pci_nic_init_nofail(&nd_table[i], phb->bus, nd->model, NULL);
1458         }
1459     }
1460 
1461     for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
1462         spapr_vscsi_create(spapr->vio_bus);
1463     }
1464 
1465     /* Graphics */
1466     if (spapr_vga_init(phb->bus)) {
1467         spapr->has_graphics = true;
1468     }
1469 
1470     if (usb_enabled(spapr->has_graphics)) {
1471         pci_create_simple(phb->bus, -1, "pci-ohci");
1472         if (spapr->has_graphics) {
1473             usbdevice_create("keyboard");
1474             usbdevice_create("mouse");
1475         }
1476     }
1477 
1478     if (spapr->rma_size < (MIN_RMA_SLOF << 20)) {
1479         fprintf(stderr, "qemu: pSeries SLOF firmware requires >= "
1480                 "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF);
1481         exit(1);
1482     }
1483 
1484     if (kernel_filename) {
1485         uint64_t lowaddr = 0;
1486 
1487         kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,
1488                                NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);
1489         if (kernel_size == ELF_LOAD_WRONG_ENDIAN) {
1490             kernel_size = load_elf(kernel_filename,
1491                                    translate_kernel_address, NULL,
1492                                    NULL, &lowaddr, NULL, 0, ELF_MACHINE, 0);
1493             kernel_le = kernel_size > 0;
1494         }
1495         if (kernel_size < 0) {
1496             fprintf(stderr, "qemu: error loading %s: %s\n",
1497                     kernel_filename, load_elf_strerror(kernel_size));
1498             exit(1);
1499         }
1500 
1501         /* load initrd */
1502         if (initrd_filename) {
1503             /* Try to locate the initrd in the gap between the kernel
1504              * and the firmware. Add a bit of space just in case
1505              */
1506             initrd_base = (KERNEL_LOAD_ADDR + kernel_size + 0x1ffff) & ~0xffff;
1507             initrd_size = load_image_targphys(initrd_filename, initrd_base,
1508                                               load_limit - initrd_base);
1509             if (initrd_size < 0) {
1510                 fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
1511                         initrd_filename);
1512                 exit(1);
1513             }
1514         } else {
1515             initrd_base = 0;
1516             initrd_size = 0;
1517         }
1518     }
1519 
1520     if (bios_name == NULL) {
1521         bios_name = FW_FILE_NAME;
1522     }
1523     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
1524     fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);
1525     if (fw_size < 0) {
1526         hw_error("qemu: could not load LPAR rtas '%s'\n", filename);
1527         exit(1);
1528     }
1529     g_free(filename);
1530 
1531     spapr->entry_point = 0x100;
1532 
1533     vmstate_register(NULL, 0, &vmstate_spapr, spapr);
1534     register_savevm_live(NULL, "spapr/htab", -1, 1,
1535                          &savevm_htab_handlers, spapr);
1536 
1537     /* Prepare the device tree */
1538     spapr->fdt_skel = spapr_create_fdt_skel(initrd_base, initrd_size,
1539                                             kernel_size, kernel_le,
1540                                             boot_device, kernel_cmdline,
1541                                             spapr->epow_irq);
1542     assert(spapr->fdt_skel != NULL);
1543 }
1544 
1545 static int spapr_kvm_type(const char *vm_type)
1546 {
1547     if (!vm_type) {
1548         return 0;
1549     }
1550 
1551     if (!strcmp(vm_type, "HV")) {
1552         return 1;
1553     }
1554 
1555     if (!strcmp(vm_type, "PR")) {
1556         return 2;
1557     }
1558 
1559     error_report("Unknown kvm-type specified '%s'", vm_type);
1560     exit(1);
1561 }
1562 
1563 /*
1564  * Implementation of an interface to adjust firmware patch
1565  * for the bootindex property handling.
1566  */
1567 static char *spapr_get_fw_dev_path(FWPathProvider *p, BusState *bus,
1568                                    DeviceState *dev)
1569 {
1570 #define CAST(type, obj, name) \
1571     ((type *)object_dynamic_cast(OBJECT(obj), (name)))
1572     SCSIDevice *d = CAST(SCSIDevice,  dev, TYPE_SCSI_DEVICE);
1573     sPAPRPHBState *phb = CAST(sPAPRPHBState, dev, TYPE_SPAPR_PCI_HOST_BRIDGE);
1574 
1575     if (d) {
1576         void *spapr = CAST(void, bus->parent, "spapr-vscsi");
1577         VirtIOSCSI *virtio = CAST(VirtIOSCSI, bus->parent, TYPE_VIRTIO_SCSI);
1578         USBDevice *usb = CAST(USBDevice, bus->parent, TYPE_USB_DEVICE);
1579 
1580         if (spapr) {
1581             /*
1582              * Replace "channel@0/disk@0,0" with "disk@8000000000000000":
1583              * We use SRP luns of the form 8000 | (bus << 8) | (id << 5) | lun
1584              * in the top 16 bits of the 64-bit LUN
1585              */
1586             unsigned id = 0x8000 | (d->id << 8) | d->lun;
1587             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
1588                                    (uint64_t)id << 48);
1589         } else if (virtio) {
1590             /*
1591              * We use SRP luns of the form 01000000 | (target << 8) | lun
1592              * in the top 32 bits of the 64-bit LUN
1593              * Note: the quote above is from SLOF and it is wrong,
1594              * the actual binding is:
1595              * swap 0100 or 10 << or 20 << ( target lun-id -- srplun )
1596              */
1597             unsigned id = 0x1000000 | (d->id << 16) | d->lun;
1598             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
1599                                    (uint64_t)id << 32);
1600         } else if (usb) {
1601             /*
1602              * We use SRP luns of the form 01000000 | (usb-port << 16) | lun
1603              * in the top 32 bits of the 64-bit LUN
1604              */
1605             unsigned usb_port = atoi(usb->port->path);
1606             unsigned id = 0x1000000 | (usb_port << 16) | d->lun;
1607             return g_strdup_printf("%s@%"PRIX64, qdev_fw_name(dev),
1608                                    (uint64_t)id << 32);
1609         }
1610     }
1611 
1612     if (phb) {
1613         /* Replace "pci" with "pci@800000020000000" */
1614         return g_strdup_printf("pci@%"PRIX64, phb->buid);
1615     }
1616 
1617     return NULL;
1618 }
1619 
1620 static char *spapr_get_kvm_type(Object *obj, Error **errp)
1621 {
1622     SPAPRMachine *sm = SPAPR_MACHINE(obj);
1623 
1624     return g_strdup(sm->kvm_type);
1625 }
1626 
1627 static void spapr_set_kvm_type(Object *obj, const char *value, Error **errp)
1628 {
1629     SPAPRMachine *sm = SPAPR_MACHINE(obj);
1630 
1631     g_free(sm->kvm_type);
1632     sm->kvm_type = g_strdup(value);
1633 }
1634 
1635 static void spapr_machine_initfn(Object *obj)
1636 {
1637     object_property_add_str(obj, "kvm-type",
1638                             spapr_get_kvm_type, spapr_set_kvm_type, NULL);
1639 }
1640 
1641 static void spapr_machine_class_init(ObjectClass *oc, void *data)
1642 {
1643     MachineClass *mc = MACHINE_CLASS(oc);
1644     FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc);
1645 
1646     mc->name = "pseries";
1647     mc->desc = "pSeries Logical Partition (PAPR compliant)";
1648     mc->is_default = 1;
1649     mc->init = ppc_spapr_init;
1650     mc->reset = ppc_spapr_reset;
1651     mc->block_default_type = IF_SCSI;
1652     mc->max_cpus = MAX_CPUS;
1653     mc->no_parallel = 1;
1654     mc->default_boot_order = NULL;
1655     mc->kvm_type = spapr_kvm_type;
1656 
1657     fwc->get_dev_path = spapr_get_fw_dev_path;
1658 }
1659 
1660 static const TypeInfo spapr_machine_info = {
1661     .name          = TYPE_SPAPR_MACHINE,
1662     .parent        = TYPE_MACHINE,
1663     .instance_size = sizeof(SPAPRMachine),
1664     .instance_init = spapr_machine_initfn,
1665     .class_init    = spapr_machine_class_init,
1666     .interfaces = (InterfaceInfo[]) {
1667         { TYPE_FW_PATH_PROVIDER },
1668         { }
1669     },
1670 };
1671 
1672 static void spapr_machine_register_types(void)
1673 {
1674     type_register_static(&spapr_machine_info);
1675 }
1676 
1677 type_init(spapr_machine_register_types)
1678