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