xref: /qemu/hw/ppc/spapr_pci.c (revision 99372e785efe9fe6a4e30cab4e33b79b227dc28d)
1 /*
2  * QEMU sPAPR PCI host originated from Uninorth PCI host
3  *
4  * Copyright (c) 2011 Alexey Kardashevskiy, IBM Corporation.
5  * Copyright (C) 2011 David Gibson, IBM Corporation.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu-common.h"
28 #include "cpu.h"
29 #include "hw/hw.h"
30 #include "hw/sysbus.h"
31 #include "hw/pci/pci.h"
32 #include "hw/pci/msi.h"
33 #include "hw/pci/msix.h"
34 #include "hw/pci/pci_host.h"
35 #include "hw/ppc/spapr.h"
36 #include "hw/pci-host/spapr.h"
37 #include "exec/address-spaces.h"
38 #include "exec/ram_addr.h"
39 #include <libfdt.h>
40 #include "trace.h"
41 #include "qemu/error-report.h"
42 #include "qapi/qmp/qerror.h"
43 #include "hw/ppc/fdt.h"
44 #include "hw/pci/pci_bridge.h"
45 #include "hw/pci/pci_bus.h"
46 #include "hw/pci/pci_ids.h"
47 #include "hw/ppc/spapr_drc.h"
48 #include "sysemu/device_tree.h"
49 #include "sysemu/kvm.h"
50 #include "sysemu/hostmem.h"
51 #include "sysemu/numa.h"
52 
53 /* Copied from the kernel arch/powerpc/platforms/pseries/msi.c */
54 #define RTAS_QUERY_FN           0
55 #define RTAS_CHANGE_FN          1
56 #define RTAS_RESET_FN           2
57 #define RTAS_CHANGE_MSI_FN      3
58 #define RTAS_CHANGE_MSIX_FN     4
59 
60 /* Interrupt types to return on RTAS_CHANGE_* */
61 #define RTAS_TYPE_MSI           1
62 #define RTAS_TYPE_MSIX          2
63 
64 sPAPRPHBState *spapr_pci_find_phb(sPAPRMachineState *spapr, uint64_t buid)
65 {
66     sPAPRPHBState *sphb;
67 
68     QLIST_FOREACH(sphb, &spapr->phbs, list) {
69         if (sphb->buid != buid) {
70             continue;
71         }
72         return sphb;
73     }
74 
75     return NULL;
76 }
77 
78 PCIDevice *spapr_pci_find_dev(sPAPRMachineState *spapr, uint64_t buid,
79                               uint32_t config_addr)
80 {
81     sPAPRPHBState *sphb = spapr_pci_find_phb(spapr, buid);
82     PCIHostState *phb = PCI_HOST_BRIDGE(sphb);
83     int bus_num = (config_addr >> 16) & 0xFF;
84     int devfn = (config_addr >> 8) & 0xFF;
85 
86     if (!phb) {
87         return NULL;
88     }
89 
90     return pci_find_device(phb->bus, bus_num, devfn);
91 }
92 
93 static uint32_t rtas_pci_cfgaddr(uint32_t arg)
94 {
95     /* This handles the encoding of extended config space addresses */
96     return ((arg >> 20) & 0xf00) | (arg & 0xff);
97 }
98 
99 static void finish_read_pci_config(sPAPRMachineState *spapr, uint64_t buid,
100                                    uint32_t addr, uint32_t size,
101                                    target_ulong rets)
102 {
103     PCIDevice *pci_dev;
104     uint32_t val;
105 
106     if ((size != 1) && (size != 2) && (size != 4)) {
107         /* access must be 1, 2 or 4 bytes */
108         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
109         return;
110     }
111 
112     pci_dev = spapr_pci_find_dev(spapr, buid, addr);
113     addr = rtas_pci_cfgaddr(addr);
114 
115     if (!pci_dev || (addr % size) || (addr >= pci_config_size(pci_dev))) {
116         /* Access must be to a valid device, within bounds and
117          * naturally aligned */
118         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
119         return;
120     }
121 
122     val = pci_host_config_read_common(pci_dev, addr,
123                                       pci_config_size(pci_dev), size);
124 
125     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
126     rtas_st(rets, 1, val);
127 }
128 
129 static void rtas_ibm_read_pci_config(PowerPCCPU *cpu, sPAPRMachineState *spapr,
130                                      uint32_t token, uint32_t nargs,
131                                      target_ulong args,
132                                      uint32_t nret, target_ulong rets)
133 {
134     uint64_t buid;
135     uint32_t size, addr;
136 
137     if ((nargs != 4) || (nret != 2)) {
138         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
139         return;
140     }
141 
142     buid = rtas_ldq(args, 1);
143     size = rtas_ld(args, 3);
144     addr = rtas_ld(args, 0);
145 
146     finish_read_pci_config(spapr, buid, addr, size, rets);
147 }
148 
149 static void rtas_read_pci_config(PowerPCCPU *cpu, sPAPRMachineState *spapr,
150                                  uint32_t token, uint32_t nargs,
151                                  target_ulong args,
152                                  uint32_t nret, target_ulong rets)
153 {
154     uint32_t size, addr;
155 
156     if ((nargs != 2) || (nret != 2)) {
157         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
158         return;
159     }
160 
161     size = rtas_ld(args, 1);
162     addr = rtas_ld(args, 0);
163 
164     finish_read_pci_config(spapr, 0, addr, size, rets);
165 }
166 
167 static void finish_write_pci_config(sPAPRMachineState *spapr, uint64_t buid,
168                                     uint32_t addr, uint32_t size,
169                                     uint32_t val, target_ulong rets)
170 {
171     PCIDevice *pci_dev;
172 
173     if ((size != 1) && (size != 2) && (size != 4)) {
174         /* access must be 1, 2 or 4 bytes */
175         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
176         return;
177     }
178 
179     pci_dev = spapr_pci_find_dev(spapr, buid, addr);
180     addr = rtas_pci_cfgaddr(addr);
181 
182     if (!pci_dev || (addr % size) || (addr >= pci_config_size(pci_dev))) {
183         /* Access must be to a valid device, within bounds and
184          * naturally aligned */
185         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
186         return;
187     }
188 
189     pci_host_config_write_common(pci_dev, addr, pci_config_size(pci_dev),
190                                  val, size);
191 
192     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
193 }
194 
195 static void rtas_ibm_write_pci_config(PowerPCCPU *cpu, sPAPRMachineState *spapr,
196                                       uint32_t token, uint32_t nargs,
197                                       target_ulong args,
198                                       uint32_t nret, target_ulong rets)
199 {
200     uint64_t buid;
201     uint32_t val, size, addr;
202 
203     if ((nargs != 5) || (nret != 1)) {
204         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
205         return;
206     }
207 
208     buid = rtas_ldq(args, 1);
209     val = rtas_ld(args, 4);
210     size = rtas_ld(args, 3);
211     addr = rtas_ld(args, 0);
212 
213     finish_write_pci_config(spapr, buid, addr, size, val, rets);
214 }
215 
216 static void rtas_write_pci_config(PowerPCCPU *cpu, sPAPRMachineState *spapr,
217                                   uint32_t token, uint32_t nargs,
218                                   target_ulong args,
219                                   uint32_t nret, target_ulong rets)
220 {
221     uint32_t val, size, addr;
222 
223     if ((nargs != 3) || (nret != 1)) {
224         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
225         return;
226     }
227 
228 
229     val = rtas_ld(args, 2);
230     size = rtas_ld(args, 1);
231     addr = rtas_ld(args, 0);
232 
233     finish_write_pci_config(spapr, 0, addr, size, val, rets);
234 }
235 
236 /*
237  * Set MSI/MSIX message data.
238  * This is required for msi_notify()/msix_notify() which
239  * will write at the addresses via spapr_msi_write().
240  *
241  * If hwaddr == 0, all entries will have .data == first_irq i.e.
242  * table will be reset.
243  */
244 static void spapr_msi_setmsg(PCIDevice *pdev, hwaddr addr, bool msix,
245                              unsigned first_irq, unsigned req_num)
246 {
247     unsigned i;
248     MSIMessage msg = { .address = addr, .data = first_irq };
249 
250     if (!msix) {
251         msi_set_message(pdev, msg);
252         trace_spapr_pci_msi_setup(pdev->name, 0, msg.address);
253         return;
254     }
255 
256     for (i = 0; i < req_num; ++i) {
257         msix_set_message(pdev, i, msg);
258         trace_spapr_pci_msi_setup(pdev->name, i, msg.address);
259         if (addr) {
260             ++msg.data;
261         }
262     }
263 }
264 
265 static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPRMachineState *spapr,
266                                 uint32_t token, uint32_t nargs,
267                                 target_ulong args, uint32_t nret,
268                                 target_ulong rets)
269 {
270     uint32_t config_addr = rtas_ld(args, 0);
271     uint64_t buid = rtas_ldq(args, 1);
272     unsigned int func = rtas_ld(args, 3);
273     unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */
274     unsigned int seq_num = rtas_ld(args, 5);
275     unsigned int ret_intr_type;
276     unsigned int irq, max_irqs = 0;
277     sPAPRPHBState *phb = NULL;
278     PCIDevice *pdev = NULL;
279     spapr_pci_msi *msi;
280     int *config_addr_key;
281     Error *err = NULL;
282 
283     switch (func) {
284     case RTAS_CHANGE_MSI_FN:
285     case RTAS_CHANGE_FN:
286         ret_intr_type = RTAS_TYPE_MSI;
287         break;
288     case RTAS_CHANGE_MSIX_FN:
289         ret_intr_type = RTAS_TYPE_MSIX;
290         break;
291     default:
292         error_report("rtas_ibm_change_msi(%u) is not implemented", func);
293         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
294         return;
295     }
296 
297     /* Fins sPAPRPHBState */
298     phb = spapr_pci_find_phb(spapr, buid);
299     if (phb) {
300         pdev = spapr_pci_find_dev(spapr, buid, config_addr);
301     }
302     if (!phb || !pdev) {
303         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
304         return;
305     }
306 
307     msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr);
308 
309     /* Releasing MSIs */
310     if (!req_num) {
311         if (!msi) {
312             trace_spapr_pci_msi("Releasing wrong config", config_addr);
313             rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
314             return;
315         }
316 
317         spapr_ics_free(spapr->ics, msi->first_irq, msi->num);
318         if (msi_present(pdev)) {
319             spapr_msi_setmsg(pdev, 0, false, 0, 0);
320         }
321         if (msix_present(pdev)) {
322             spapr_msi_setmsg(pdev, 0, true, 0, 0);
323         }
324         g_hash_table_remove(phb->msi, &config_addr);
325 
326         trace_spapr_pci_msi("Released MSIs", config_addr);
327         rtas_st(rets, 0, RTAS_OUT_SUCCESS);
328         rtas_st(rets, 1, 0);
329         return;
330     }
331 
332     /* Enabling MSI */
333 
334     /* Check if the device supports as many IRQs as requested */
335     if (ret_intr_type == RTAS_TYPE_MSI) {
336         max_irqs = msi_nr_vectors_allocated(pdev);
337     } else if (ret_intr_type == RTAS_TYPE_MSIX) {
338         max_irqs = pdev->msix_entries_nr;
339     }
340     if (!max_irqs) {
341         error_report("Requested interrupt type %d is not enabled for device %x",
342                      ret_intr_type, config_addr);
343         rtas_st(rets, 0, -1); /* Hardware error */
344         return;
345     }
346     /* Correct the number if the guest asked for too many */
347     if (req_num > max_irqs) {
348         trace_spapr_pci_msi_retry(config_addr, req_num, max_irqs);
349         req_num = max_irqs;
350         irq = 0; /* to avoid misleading trace */
351         goto out;
352     }
353 
354     /* Allocate MSIs */
355     irq = spapr_ics_alloc_block(spapr->ics, req_num, false,
356                            ret_intr_type == RTAS_TYPE_MSI, &err);
357     if (err) {
358         error_reportf_err(err, "Can't allocate MSIs for device %x: ",
359                           config_addr);
360         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
361         return;
362     }
363 
364     /* Release previous MSIs */
365     if (msi) {
366         spapr_ics_free(spapr->ics, msi->first_irq, msi->num);
367         g_hash_table_remove(phb->msi, &config_addr);
368     }
369 
370     /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */
371     spapr_msi_setmsg(pdev, SPAPR_PCI_MSI_WINDOW, ret_intr_type == RTAS_TYPE_MSIX,
372                      irq, req_num);
373 
374     /* Add MSI device to cache */
375     msi = g_new(spapr_pci_msi, 1);
376     msi->first_irq = irq;
377     msi->num = req_num;
378     config_addr_key = g_new(int, 1);
379     *config_addr_key = config_addr;
380     g_hash_table_insert(phb->msi, config_addr_key, msi);
381 
382 out:
383     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
384     rtas_st(rets, 1, req_num);
385     rtas_st(rets, 2, ++seq_num);
386     if (nret > 3) {
387         rtas_st(rets, 3, ret_intr_type);
388     }
389 
390     trace_spapr_pci_rtas_ibm_change_msi(config_addr, func, req_num, irq);
391 }
392 
393 static void rtas_ibm_query_interrupt_source_number(PowerPCCPU *cpu,
394                                                    sPAPRMachineState *spapr,
395                                                    uint32_t token,
396                                                    uint32_t nargs,
397                                                    target_ulong args,
398                                                    uint32_t nret,
399                                                    target_ulong rets)
400 {
401     uint32_t config_addr = rtas_ld(args, 0);
402     uint64_t buid = rtas_ldq(args, 1);
403     unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3);
404     sPAPRPHBState *phb = NULL;
405     PCIDevice *pdev = NULL;
406     spapr_pci_msi *msi;
407 
408     /* Find sPAPRPHBState */
409     phb = spapr_pci_find_phb(spapr, buid);
410     if (phb) {
411         pdev = spapr_pci_find_dev(spapr, buid, config_addr);
412     }
413     if (!phb || !pdev) {
414         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
415         return;
416     }
417 
418     /* Find device descriptor and start IRQ */
419     msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr);
420     if (!msi || !msi->first_irq || !msi->num || (ioa_intr_num >= msi->num)) {
421         trace_spapr_pci_msi("Failed to return vector", config_addr);
422         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
423         return;
424     }
425     intr_src_num = msi->first_irq + ioa_intr_num;
426     trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num,
427                                                            intr_src_num);
428 
429     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
430     rtas_st(rets, 1, intr_src_num);
431     rtas_st(rets, 2, 1);/* 0 == level; 1 == edge */
432 }
433 
434 static void rtas_ibm_set_eeh_option(PowerPCCPU *cpu,
435                                     sPAPRMachineState *spapr,
436                                     uint32_t token, uint32_t nargs,
437                                     target_ulong args, uint32_t nret,
438                                     target_ulong rets)
439 {
440     sPAPRPHBState *sphb;
441     uint32_t addr, option;
442     uint64_t buid;
443     int ret;
444 
445     if ((nargs != 4) || (nret != 1)) {
446         goto param_error_exit;
447     }
448 
449     buid = rtas_ldq(args, 1);
450     addr = rtas_ld(args, 0);
451     option = rtas_ld(args, 3);
452 
453     sphb = spapr_pci_find_phb(spapr, buid);
454     if (!sphb) {
455         goto param_error_exit;
456     }
457 
458     if (!spapr_phb_eeh_available(sphb)) {
459         goto param_error_exit;
460     }
461 
462     ret = spapr_phb_vfio_eeh_set_option(sphb, addr, option);
463     rtas_st(rets, 0, ret);
464     return;
465 
466 param_error_exit:
467     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
468 }
469 
470 static void rtas_ibm_get_config_addr_info2(PowerPCCPU *cpu,
471                                            sPAPRMachineState *spapr,
472                                            uint32_t token, uint32_t nargs,
473                                            target_ulong args, uint32_t nret,
474                                            target_ulong rets)
475 {
476     sPAPRPHBState *sphb;
477     PCIDevice *pdev;
478     uint32_t addr, option;
479     uint64_t buid;
480 
481     if ((nargs != 4) || (nret != 2)) {
482         goto param_error_exit;
483     }
484 
485     buid = rtas_ldq(args, 1);
486     sphb = spapr_pci_find_phb(spapr, buid);
487     if (!sphb) {
488         goto param_error_exit;
489     }
490 
491     if (!spapr_phb_eeh_available(sphb)) {
492         goto param_error_exit;
493     }
494 
495     /*
496      * We always have PE address of form "00BB0001". "BB"
497      * represents the bus number of PE's primary bus.
498      */
499     option = rtas_ld(args, 3);
500     switch (option) {
501     case RTAS_GET_PE_ADDR:
502         addr = rtas_ld(args, 0);
503         pdev = spapr_pci_find_dev(spapr, buid, addr);
504         if (!pdev) {
505             goto param_error_exit;
506         }
507 
508         rtas_st(rets, 1, (pci_bus_num(pdev->bus) << 16) + 1);
509         break;
510     case RTAS_GET_PE_MODE:
511         rtas_st(rets, 1, RTAS_PE_MODE_SHARED);
512         break;
513     default:
514         goto param_error_exit;
515     }
516 
517     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
518     return;
519 
520 param_error_exit:
521     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
522 }
523 
524 static void rtas_ibm_read_slot_reset_state2(PowerPCCPU *cpu,
525                                             sPAPRMachineState *spapr,
526                                             uint32_t token, uint32_t nargs,
527                                             target_ulong args, uint32_t nret,
528                                             target_ulong rets)
529 {
530     sPAPRPHBState *sphb;
531     uint64_t buid;
532     int state, ret;
533 
534     if ((nargs != 3) || (nret != 4 && nret != 5)) {
535         goto param_error_exit;
536     }
537 
538     buid = rtas_ldq(args, 1);
539     sphb = spapr_pci_find_phb(spapr, buid);
540     if (!sphb) {
541         goto param_error_exit;
542     }
543 
544     if (!spapr_phb_eeh_available(sphb)) {
545         goto param_error_exit;
546     }
547 
548     ret = spapr_phb_vfio_eeh_get_state(sphb, &state);
549     rtas_st(rets, 0, ret);
550     if (ret != RTAS_OUT_SUCCESS) {
551         return;
552     }
553 
554     rtas_st(rets, 1, state);
555     rtas_st(rets, 2, RTAS_EEH_SUPPORT);
556     rtas_st(rets, 3, RTAS_EEH_PE_UNAVAIL_INFO);
557     if (nret >= 5) {
558         rtas_st(rets, 4, RTAS_EEH_PE_RECOVER_INFO);
559     }
560     return;
561 
562 param_error_exit:
563     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
564 }
565 
566 static void rtas_ibm_set_slot_reset(PowerPCCPU *cpu,
567                                     sPAPRMachineState *spapr,
568                                     uint32_t token, uint32_t nargs,
569                                     target_ulong args, uint32_t nret,
570                                     target_ulong rets)
571 {
572     sPAPRPHBState *sphb;
573     uint32_t option;
574     uint64_t buid;
575     int ret;
576 
577     if ((nargs != 4) || (nret != 1)) {
578         goto param_error_exit;
579     }
580 
581     buid = rtas_ldq(args, 1);
582     option = rtas_ld(args, 3);
583     sphb = spapr_pci_find_phb(spapr, buid);
584     if (!sphb) {
585         goto param_error_exit;
586     }
587 
588     if (!spapr_phb_eeh_available(sphb)) {
589         goto param_error_exit;
590     }
591 
592     ret = spapr_phb_vfio_eeh_reset(sphb, option);
593     rtas_st(rets, 0, ret);
594     return;
595 
596 param_error_exit:
597     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
598 }
599 
600 static void rtas_ibm_configure_pe(PowerPCCPU *cpu,
601                                   sPAPRMachineState *spapr,
602                                   uint32_t token, uint32_t nargs,
603                                   target_ulong args, uint32_t nret,
604                                   target_ulong rets)
605 {
606     sPAPRPHBState *sphb;
607     uint64_t buid;
608     int ret;
609 
610     if ((nargs != 3) || (nret != 1)) {
611         goto param_error_exit;
612     }
613 
614     buid = rtas_ldq(args, 1);
615     sphb = spapr_pci_find_phb(spapr, buid);
616     if (!sphb) {
617         goto param_error_exit;
618     }
619 
620     if (!spapr_phb_eeh_available(sphb)) {
621         goto param_error_exit;
622     }
623 
624     ret = spapr_phb_vfio_eeh_configure(sphb);
625     rtas_st(rets, 0, ret);
626     return;
627 
628 param_error_exit:
629     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
630 }
631 
632 /* To support it later */
633 static void rtas_ibm_slot_error_detail(PowerPCCPU *cpu,
634                                        sPAPRMachineState *spapr,
635                                        uint32_t token, uint32_t nargs,
636                                        target_ulong args, uint32_t nret,
637                                        target_ulong rets)
638 {
639     sPAPRPHBState *sphb;
640     int option;
641     uint64_t buid;
642 
643     if ((nargs != 8) || (nret != 1)) {
644         goto param_error_exit;
645     }
646 
647     buid = rtas_ldq(args, 1);
648     sphb = spapr_pci_find_phb(spapr, buid);
649     if (!sphb) {
650         goto param_error_exit;
651     }
652 
653     if (!spapr_phb_eeh_available(sphb)) {
654         goto param_error_exit;
655     }
656 
657     option = rtas_ld(args, 7);
658     switch (option) {
659     case RTAS_SLOT_TEMP_ERR_LOG:
660     case RTAS_SLOT_PERM_ERR_LOG:
661         break;
662     default:
663         goto param_error_exit;
664     }
665 
666     /* We don't have error log yet */
667     rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);
668     return;
669 
670 param_error_exit:
671     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
672 }
673 
674 static int pci_spapr_swizzle(int slot, int pin)
675 {
676     return (slot + pin) % PCI_NUM_PINS;
677 }
678 
679 static int pci_spapr_map_irq(PCIDevice *pci_dev, int irq_num)
680 {
681     /*
682      * Here we need to convert pci_dev + irq_num to some unique value
683      * which is less than number of IRQs on the specific bus (4).  We
684      * use standard PCI swizzling, that is (slot number + pin number)
685      * % 4.
686      */
687     return pci_spapr_swizzle(PCI_SLOT(pci_dev->devfn), irq_num);
688 }
689 
690 static void pci_spapr_set_irq(void *opaque, int irq_num, int level)
691 {
692     /*
693      * Here we use the number returned by pci_spapr_map_irq to find a
694      * corresponding qemu_irq.
695      */
696     sPAPRPHBState *phb = opaque;
697 
698     trace_spapr_pci_lsi_set(phb->dtbusname, irq_num, phb->lsi_table[irq_num].irq);
699     qemu_set_irq(spapr_phb_lsi_qirq(phb, irq_num), level);
700 }
701 
702 static PCIINTxRoute spapr_route_intx_pin_to_irq(void *opaque, int pin)
703 {
704     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(opaque);
705     PCIINTxRoute route;
706 
707     route.mode = PCI_INTX_ENABLED;
708     route.irq = sphb->lsi_table[pin].irq;
709 
710     return route;
711 }
712 
713 /*
714  * MSI/MSIX memory region implementation.
715  * The handler handles both MSI and MSIX.
716  * The vector number is encoded in least bits in data.
717  */
718 static void spapr_msi_write(void *opaque, hwaddr addr,
719                             uint64_t data, unsigned size)
720 {
721     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
722     uint32_t irq = data;
723 
724     trace_spapr_pci_msi_write(addr, data, irq);
725 
726     qemu_irq_pulse(xics_get_qirq(XICS_FABRIC(spapr), irq));
727 }
728 
729 static const MemoryRegionOps spapr_msi_ops = {
730     /* There is no .read as the read result is undefined by PCI spec */
731     .read = NULL,
732     .write = spapr_msi_write,
733     .endianness = DEVICE_LITTLE_ENDIAN
734 };
735 
736 /*
737  * PHB PCI device
738  */
739 static AddressSpace *spapr_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn)
740 {
741     sPAPRPHBState *phb = opaque;
742 
743     return &phb->iommu_as;
744 }
745 
746 static char *spapr_phb_vfio_get_loc_code(sPAPRPHBState *sphb,  PCIDevice *pdev)
747 {
748     char *path = NULL, *buf = NULL, *host = NULL;
749 
750     /* Get the PCI VFIO host id */
751     host = object_property_get_str(OBJECT(pdev), "host", NULL);
752     if (!host) {
753         goto err_out;
754     }
755 
756     /* Construct the path of the file that will give us the DT location */
757     path = g_strdup_printf("/sys/bus/pci/devices/%s/devspec", host);
758     g_free(host);
759     if (!g_file_get_contents(path, &buf, NULL, NULL)) {
760         goto err_out;
761     }
762     g_free(path);
763 
764     /* Construct and read from host device tree the loc-code */
765     path = g_strdup_printf("/proc/device-tree%s/ibm,loc-code", buf);
766     g_free(buf);
767     if (!g_file_get_contents(path, &buf, NULL, NULL)) {
768         goto err_out;
769     }
770     return buf;
771 
772 err_out:
773     g_free(path);
774     return NULL;
775 }
776 
777 static char *spapr_phb_get_loc_code(sPAPRPHBState *sphb, PCIDevice *pdev)
778 {
779     char *buf;
780     const char *devtype = "qemu";
781     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
782 
783     if (object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {
784         buf = spapr_phb_vfio_get_loc_code(sphb, pdev);
785         if (buf) {
786             return buf;
787         }
788         devtype = "vfio";
789     }
790     /*
791      * For emulated devices and VFIO-failure case, make up
792      * the loc-code.
793      */
794     buf = g_strdup_printf("%s_%s:%04x:%02x:%02x.%x",
795                           devtype, pdev->name, sphb->index, busnr,
796                           PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
797     return buf;
798 }
799 
800 /* Macros to operate with address in OF binding to PCI */
801 #define b_x(x, p, l)    (((x) & ((1<<(l))-1)) << (p))
802 #define b_n(x)          b_x((x), 31, 1) /* 0 if relocatable */
803 #define b_p(x)          b_x((x), 30, 1) /* 1 if prefetchable */
804 #define b_t(x)          b_x((x), 29, 1) /* 1 if the address is aliased */
805 #define b_ss(x)         b_x((x), 24, 2) /* the space code */
806 #define b_bbbbbbbb(x)   b_x((x), 16, 8) /* bus number */
807 #define b_ddddd(x)      b_x((x), 11, 5) /* device number */
808 #define b_fff(x)        b_x((x), 8, 3)  /* function number */
809 #define b_rrrrrrrr(x)   b_x((x), 0, 8)  /* register number */
810 
811 /* for 'reg'/'assigned-addresses' OF properties */
812 #define RESOURCE_CELLS_SIZE 2
813 #define RESOURCE_CELLS_ADDRESS 3
814 
815 typedef struct ResourceFields {
816     uint32_t phys_hi;
817     uint32_t phys_mid;
818     uint32_t phys_lo;
819     uint32_t size_hi;
820     uint32_t size_lo;
821 } QEMU_PACKED ResourceFields;
822 
823 typedef struct ResourceProps {
824     ResourceFields reg[8];
825     ResourceFields assigned[7];
826     uint32_t reg_len;
827     uint32_t assigned_len;
828 } ResourceProps;
829 
830 /* fill in the 'reg'/'assigned-resources' OF properties for
831  * a PCI device. 'reg' describes resource requirements for a
832  * device's IO/MEM regions, 'assigned-addresses' describes the
833  * actual resource assignments.
834  *
835  * the properties are arrays of ('phys-addr', 'size') pairs describing
836  * the addressable regions of the PCI device, where 'phys-addr' is a
837  * RESOURCE_CELLS_ADDRESS-tuple of 32-bit integers corresponding to
838  * (phys.hi, phys.mid, phys.lo), and 'size' is a
839  * RESOURCE_CELLS_SIZE-tuple corresponding to (size.hi, size.lo).
840  *
841  * phys.hi = 0xYYXXXXZZ, where:
842  *   0xYY = npt000ss
843  *          |||   |
844  *          |||   +-- space code
845  *          |||               |
846  *          |||               +  00 if configuration space
847  *          |||               +  01 if IO region,
848  *          |||               +  10 if 32-bit MEM region
849  *          |||               +  11 if 64-bit MEM region
850  *          |||
851  *          ||+------ for non-relocatable IO: 1 if aliased
852  *          ||        for relocatable IO: 1 if below 64KB
853  *          ||        for MEM: 1 if below 1MB
854  *          |+------- 1 if region is prefetchable
855  *          +-------- 1 if region is non-relocatable
856  *   0xXXXX = bbbbbbbb dddddfff, encoding bus, slot, and function
857  *            bits respectively
858  *   0xZZ = rrrrrrrr, the register number of the BAR corresponding
859  *          to the region
860  *
861  * phys.mid and phys.lo correspond respectively to the hi/lo portions
862  * of the actual address of the region.
863  *
864  * how the phys-addr/size values are used differ slightly between
865  * 'reg' and 'assigned-addresses' properties. namely, 'reg' has
866  * an additional description for the config space region of the
867  * device, and in the case of QEMU has n=0 and phys.mid=phys.lo=0
868  * to describe the region as relocatable, with an address-mapping
869  * that corresponds directly to the PHB's address space for the
870  * resource. 'assigned-addresses' always has n=1 set with an absolute
871  * address assigned for the resource. in general, 'assigned-addresses'
872  * won't be populated, since addresses for PCI devices are generally
873  * unmapped initially and left to the guest to assign.
874  *
875  * note also that addresses defined in these properties are, at least
876  * for PAPR guests, relative to the PHBs IO/MEM windows, and
877  * correspond directly to the addresses in the BARs.
878  *
879  * in accordance with PCI Bus Binding to Open Firmware,
880  * IEEE Std 1275-1994, section 4.1.1, as implemented by PAPR+ v2.7,
881  * Appendix C.
882  */
883 static void populate_resource_props(PCIDevice *d, ResourceProps *rp)
884 {
885     int bus_num = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(d))));
886     uint32_t dev_id = (b_bbbbbbbb(bus_num) |
887                        b_ddddd(PCI_SLOT(d->devfn)) |
888                        b_fff(PCI_FUNC(d->devfn)));
889     ResourceFields *reg, *assigned;
890     int i, reg_idx = 0, assigned_idx = 0;
891 
892     /* config space region */
893     reg = &rp->reg[reg_idx++];
894     reg->phys_hi = cpu_to_be32(dev_id);
895     reg->phys_mid = 0;
896     reg->phys_lo = 0;
897     reg->size_hi = 0;
898     reg->size_lo = 0;
899 
900     for (i = 0; i < PCI_NUM_REGIONS; i++) {
901         if (!d->io_regions[i].size) {
902             continue;
903         }
904 
905         reg = &rp->reg[reg_idx++];
906 
907         reg->phys_hi = cpu_to_be32(dev_id | b_rrrrrrrr(pci_bar(d, i)));
908         if (d->io_regions[i].type & PCI_BASE_ADDRESS_SPACE_IO) {
909             reg->phys_hi |= cpu_to_be32(b_ss(1));
910         } else if (d->io_regions[i].type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
911             reg->phys_hi |= cpu_to_be32(b_ss(3));
912         } else {
913             reg->phys_hi |= cpu_to_be32(b_ss(2));
914         }
915         reg->phys_mid = 0;
916         reg->phys_lo = 0;
917         reg->size_hi = cpu_to_be32(d->io_regions[i].size >> 32);
918         reg->size_lo = cpu_to_be32(d->io_regions[i].size);
919 
920         if (d->io_regions[i].addr == PCI_BAR_UNMAPPED) {
921             continue;
922         }
923 
924         assigned = &rp->assigned[assigned_idx++];
925         assigned->phys_hi = cpu_to_be32(reg->phys_hi | b_n(1));
926         assigned->phys_mid = cpu_to_be32(d->io_regions[i].addr >> 32);
927         assigned->phys_lo = cpu_to_be32(d->io_regions[i].addr);
928         assigned->size_hi = reg->size_hi;
929         assigned->size_lo = reg->size_lo;
930     }
931 
932     rp->reg_len = reg_idx * sizeof(ResourceFields);
933     rp->assigned_len = assigned_idx * sizeof(ResourceFields);
934 }
935 
936 typedef struct PCIClass PCIClass;
937 typedef struct PCISubClass PCISubClass;
938 typedef struct PCIIFace PCIIFace;
939 
940 struct PCIIFace {
941     int iface;
942     const char *name;
943 };
944 
945 struct PCISubClass {
946     int subclass;
947     const char *name;
948     const PCIIFace *iface;
949 };
950 
951 struct PCIClass {
952     const char *name;
953     const PCISubClass *subc;
954 };
955 
956 static const PCISubClass undef_subclass[] = {
957     { PCI_CLASS_NOT_DEFINED_VGA, "display", NULL },
958     { 0xFF, NULL, NULL },
959 };
960 
961 static const PCISubClass mass_subclass[] = {
962     { PCI_CLASS_STORAGE_SCSI, "scsi", NULL },
963     { PCI_CLASS_STORAGE_IDE, "ide", NULL },
964     { PCI_CLASS_STORAGE_FLOPPY, "fdc", NULL },
965     { PCI_CLASS_STORAGE_IPI, "ipi", NULL },
966     { PCI_CLASS_STORAGE_RAID, "raid", NULL },
967     { PCI_CLASS_STORAGE_ATA, "ata", NULL },
968     { PCI_CLASS_STORAGE_SATA, "sata", NULL },
969     { PCI_CLASS_STORAGE_SAS, "sas", NULL },
970     { 0xFF, NULL, NULL },
971 };
972 
973 static const PCISubClass net_subclass[] = {
974     { PCI_CLASS_NETWORK_ETHERNET, "ethernet", NULL },
975     { PCI_CLASS_NETWORK_TOKEN_RING, "token-ring", NULL },
976     { PCI_CLASS_NETWORK_FDDI, "fddi", NULL },
977     { PCI_CLASS_NETWORK_ATM, "atm", NULL },
978     { PCI_CLASS_NETWORK_ISDN, "isdn", NULL },
979     { PCI_CLASS_NETWORK_WORLDFIP, "worldfip", NULL },
980     { PCI_CLASS_NETWORK_PICMG214, "picmg", NULL },
981     { 0xFF, NULL, NULL },
982 };
983 
984 static const PCISubClass displ_subclass[] = {
985     { PCI_CLASS_DISPLAY_VGA, "vga", NULL },
986     { PCI_CLASS_DISPLAY_XGA, "xga", NULL },
987     { PCI_CLASS_DISPLAY_3D, "3d-controller", NULL },
988     { 0xFF, NULL, NULL },
989 };
990 
991 static const PCISubClass media_subclass[] = {
992     { PCI_CLASS_MULTIMEDIA_VIDEO, "video", NULL },
993     { PCI_CLASS_MULTIMEDIA_AUDIO, "sound", NULL },
994     { PCI_CLASS_MULTIMEDIA_PHONE, "telephony", NULL },
995     { 0xFF, NULL, NULL },
996 };
997 
998 static const PCISubClass mem_subclass[] = {
999     { PCI_CLASS_MEMORY_RAM, "memory", NULL },
1000     { PCI_CLASS_MEMORY_FLASH, "flash", NULL },
1001     { 0xFF, NULL, NULL },
1002 };
1003 
1004 static const PCISubClass bridg_subclass[] = {
1005     { PCI_CLASS_BRIDGE_HOST, "host", NULL },
1006     { PCI_CLASS_BRIDGE_ISA, "isa", NULL },
1007     { PCI_CLASS_BRIDGE_EISA, "eisa", NULL },
1008     { PCI_CLASS_BRIDGE_MC, "mca", NULL },
1009     { PCI_CLASS_BRIDGE_PCI, "pci", NULL },
1010     { PCI_CLASS_BRIDGE_PCMCIA, "pcmcia", NULL },
1011     { PCI_CLASS_BRIDGE_NUBUS, "nubus", NULL },
1012     { PCI_CLASS_BRIDGE_CARDBUS, "cardbus", NULL },
1013     { PCI_CLASS_BRIDGE_RACEWAY, "raceway", NULL },
1014     { PCI_CLASS_BRIDGE_PCI_SEMITP, "semi-transparent-pci", NULL },
1015     { PCI_CLASS_BRIDGE_IB_PCI, "infiniband", NULL },
1016     { 0xFF, NULL, NULL },
1017 };
1018 
1019 static const PCISubClass comm_subclass[] = {
1020     { PCI_CLASS_COMMUNICATION_SERIAL, "serial", NULL },
1021     { PCI_CLASS_COMMUNICATION_PARALLEL, "parallel", NULL },
1022     { PCI_CLASS_COMMUNICATION_MULTISERIAL, "multiport-serial", NULL },
1023     { PCI_CLASS_COMMUNICATION_MODEM, "modem", NULL },
1024     { PCI_CLASS_COMMUNICATION_GPIB, "gpib", NULL },
1025     { PCI_CLASS_COMMUNICATION_SC, "smart-card", NULL },
1026     { 0xFF, NULL, NULL, },
1027 };
1028 
1029 static const PCIIFace pic_iface[] = {
1030     { PCI_CLASS_SYSTEM_PIC_IOAPIC, "io-apic" },
1031     { PCI_CLASS_SYSTEM_PIC_IOXAPIC, "io-xapic" },
1032     { 0xFF, NULL },
1033 };
1034 
1035 static const PCISubClass sys_subclass[] = {
1036     { PCI_CLASS_SYSTEM_PIC, "interrupt-controller", pic_iface },
1037     { PCI_CLASS_SYSTEM_DMA, "dma-controller", NULL },
1038     { PCI_CLASS_SYSTEM_TIMER, "timer", NULL },
1039     { PCI_CLASS_SYSTEM_RTC, "rtc", NULL },
1040     { PCI_CLASS_SYSTEM_PCI_HOTPLUG, "hot-plug-controller", NULL },
1041     { PCI_CLASS_SYSTEM_SDHCI, "sd-host-controller", NULL },
1042     { 0xFF, NULL, NULL },
1043 };
1044 
1045 static const PCISubClass inp_subclass[] = {
1046     { PCI_CLASS_INPUT_KEYBOARD, "keyboard", NULL },
1047     { PCI_CLASS_INPUT_PEN, "pen", NULL },
1048     { PCI_CLASS_INPUT_MOUSE, "mouse", NULL },
1049     { PCI_CLASS_INPUT_SCANNER, "scanner", NULL },
1050     { PCI_CLASS_INPUT_GAMEPORT, "gameport", NULL },
1051     { 0xFF, NULL, NULL },
1052 };
1053 
1054 static const PCISubClass dock_subclass[] = {
1055     { PCI_CLASS_DOCKING_GENERIC, "dock", NULL },
1056     { 0xFF, NULL, NULL },
1057 };
1058 
1059 static const PCISubClass cpu_subclass[] = {
1060     { PCI_CLASS_PROCESSOR_PENTIUM, "pentium", NULL },
1061     { PCI_CLASS_PROCESSOR_POWERPC, "powerpc", NULL },
1062     { PCI_CLASS_PROCESSOR_MIPS, "mips", NULL },
1063     { PCI_CLASS_PROCESSOR_CO, "co-processor", NULL },
1064     { 0xFF, NULL, NULL },
1065 };
1066 
1067 static const PCIIFace usb_iface[] = {
1068     { PCI_CLASS_SERIAL_USB_UHCI, "usb-uhci" },
1069     { PCI_CLASS_SERIAL_USB_OHCI, "usb-ohci", },
1070     { PCI_CLASS_SERIAL_USB_EHCI, "usb-ehci" },
1071     { PCI_CLASS_SERIAL_USB_XHCI, "usb-xhci" },
1072     { PCI_CLASS_SERIAL_USB_UNKNOWN, "usb-unknown" },
1073     { PCI_CLASS_SERIAL_USB_DEVICE, "usb-device" },
1074     { 0xFF, NULL },
1075 };
1076 
1077 static const PCISubClass ser_subclass[] = {
1078     { PCI_CLASS_SERIAL_FIREWIRE, "firewire", NULL },
1079     { PCI_CLASS_SERIAL_ACCESS, "access-bus", NULL },
1080     { PCI_CLASS_SERIAL_SSA, "ssa", NULL },
1081     { PCI_CLASS_SERIAL_USB, "usb", usb_iface },
1082     { PCI_CLASS_SERIAL_FIBER, "fibre-channel", NULL },
1083     { PCI_CLASS_SERIAL_SMBUS, "smb", NULL },
1084     { PCI_CLASS_SERIAL_IB, "infiniband", NULL },
1085     { PCI_CLASS_SERIAL_IPMI, "ipmi", NULL },
1086     { PCI_CLASS_SERIAL_SERCOS, "sercos", NULL },
1087     { PCI_CLASS_SERIAL_CANBUS, "canbus", NULL },
1088     { 0xFF, NULL, NULL },
1089 };
1090 
1091 static const PCISubClass wrl_subclass[] = {
1092     { PCI_CLASS_WIRELESS_IRDA, "irda", NULL },
1093     { PCI_CLASS_WIRELESS_CIR, "consumer-ir", NULL },
1094     { PCI_CLASS_WIRELESS_RF_CONTROLLER, "rf-controller", NULL },
1095     { PCI_CLASS_WIRELESS_BLUETOOTH, "bluetooth", NULL },
1096     { PCI_CLASS_WIRELESS_BROADBAND, "broadband", NULL },
1097     { 0xFF, NULL, NULL },
1098 };
1099 
1100 static const PCISubClass sat_subclass[] = {
1101     { PCI_CLASS_SATELLITE_TV, "satellite-tv", NULL },
1102     { PCI_CLASS_SATELLITE_AUDIO, "satellite-audio", NULL },
1103     { PCI_CLASS_SATELLITE_VOICE, "satellite-voice", NULL },
1104     { PCI_CLASS_SATELLITE_DATA, "satellite-data", NULL },
1105     { 0xFF, NULL, NULL },
1106 };
1107 
1108 static const PCISubClass crypt_subclass[] = {
1109     { PCI_CLASS_CRYPT_NETWORK, "network-encryption", NULL },
1110     { PCI_CLASS_CRYPT_ENTERTAINMENT,
1111       "entertainment-encryption", NULL },
1112     { 0xFF, NULL, NULL },
1113 };
1114 
1115 static const PCISubClass spc_subclass[] = {
1116     { PCI_CLASS_SP_DPIO, "dpio", NULL },
1117     { PCI_CLASS_SP_PERF, "counter", NULL },
1118     { PCI_CLASS_SP_SYNCH, "measurement", NULL },
1119     { PCI_CLASS_SP_MANAGEMENT, "management-card", NULL },
1120     { 0xFF, NULL, NULL },
1121 };
1122 
1123 static const PCIClass pci_classes[] = {
1124     { "legacy-device", undef_subclass },
1125     { "mass-storage",  mass_subclass },
1126     { "network", net_subclass },
1127     { "display", displ_subclass, },
1128     { "multimedia-device", media_subclass },
1129     { "memory-controller", mem_subclass },
1130     { "unknown-bridge", bridg_subclass },
1131     { "communication-controller", comm_subclass},
1132     { "system-peripheral", sys_subclass },
1133     { "input-controller", inp_subclass },
1134     { "docking-station", dock_subclass },
1135     { "cpu", cpu_subclass },
1136     { "serial-bus", ser_subclass },
1137     { "wireless-controller", wrl_subclass },
1138     { "intelligent-io", NULL },
1139     { "satellite-device", sat_subclass },
1140     { "encryption", crypt_subclass },
1141     { "data-processing-controller", spc_subclass },
1142 };
1143 
1144 static const char *pci_find_device_name(uint8_t class, uint8_t subclass,
1145                                         uint8_t iface)
1146 {
1147     const PCIClass *pclass;
1148     const PCISubClass *psubclass;
1149     const PCIIFace *piface;
1150     const char *name;
1151 
1152     if (class >= ARRAY_SIZE(pci_classes)) {
1153         return "pci";
1154     }
1155 
1156     pclass = pci_classes + class;
1157     name = pclass->name;
1158 
1159     if (pclass->subc == NULL) {
1160         return name;
1161     }
1162 
1163     psubclass = pclass->subc;
1164     while ((psubclass->subclass & 0xff) != 0xff) {
1165         if ((psubclass->subclass & 0xff) == subclass) {
1166             name = psubclass->name;
1167             break;
1168         }
1169         psubclass++;
1170     }
1171 
1172     piface = psubclass->iface;
1173     if (piface == NULL) {
1174         return name;
1175     }
1176     while ((piface->iface & 0xff) != 0xff) {
1177         if ((piface->iface & 0xff) == iface) {
1178             name = piface->name;
1179             break;
1180         }
1181         piface++;
1182     }
1183 
1184     return name;
1185 }
1186 
1187 static gchar *pci_get_node_name(PCIDevice *dev)
1188 {
1189     int slot = PCI_SLOT(dev->devfn);
1190     int func = PCI_FUNC(dev->devfn);
1191     uint32_t ccode = pci_default_read_config(dev, PCI_CLASS_PROG, 3);
1192     const char *name;
1193 
1194     name = pci_find_device_name((ccode >> 16) & 0xff, (ccode >> 8) & 0xff,
1195                                 ccode & 0xff);
1196 
1197     if (func != 0) {
1198         return g_strdup_printf("%s@%x,%x", name, slot, func);
1199     } else {
1200         return g_strdup_printf("%s@%x", name, slot);
1201     }
1202 }
1203 
1204 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
1205                                             PCIDevice *pdev);
1206 
1207 static int spapr_populate_pci_child_dt(PCIDevice *dev, void *fdt, int offset,
1208                                        sPAPRPHBState *sphb)
1209 {
1210     ResourceProps rp;
1211     bool is_bridge = false;
1212     int pci_status, err;
1213     char *buf = NULL;
1214     uint32_t drc_index = spapr_phb_get_pci_drc_index(sphb, dev);
1215     uint32_t ccode = pci_default_read_config(dev, PCI_CLASS_PROG, 3);
1216     uint32_t max_msi, max_msix;
1217 
1218     if (pci_default_read_config(dev, PCI_HEADER_TYPE, 1) ==
1219         PCI_HEADER_TYPE_BRIDGE) {
1220         is_bridge = true;
1221     }
1222 
1223     /* in accordance with PAPR+ v2.7 13.6.3, Table 181 */
1224     _FDT(fdt_setprop_cell(fdt, offset, "vendor-id",
1225                           pci_default_read_config(dev, PCI_VENDOR_ID, 2)));
1226     _FDT(fdt_setprop_cell(fdt, offset, "device-id",
1227                           pci_default_read_config(dev, PCI_DEVICE_ID, 2)));
1228     _FDT(fdt_setprop_cell(fdt, offset, "revision-id",
1229                           pci_default_read_config(dev, PCI_REVISION_ID, 1)));
1230     _FDT(fdt_setprop_cell(fdt, offset, "class-code", ccode));
1231     if (pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)) {
1232         _FDT(fdt_setprop_cell(fdt, offset, "interrupts",
1233                  pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)));
1234     }
1235 
1236     if (!is_bridge) {
1237         _FDT(fdt_setprop_cell(fdt, offset, "min-grant",
1238             pci_default_read_config(dev, PCI_MIN_GNT, 1)));
1239         _FDT(fdt_setprop_cell(fdt, offset, "max-latency",
1240             pci_default_read_config(dev, PCI_MAX_LAT, 1)));
1241     }
1242 
1243     if (pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)) {
1244         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-id",
1245                  pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)));
1246     }
1247 
1248     if (pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)) {
1249         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-vendor-id",
1250                  pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)));
1251     }
1252 
1253     _FDT(fdt_setprop_cell(fdt, offset, "cache-line-size",
1254         pci_default_read_config(dev, PCI_CACHE_LINE_SIZE, 1)));
1255 
1256     /* the following fdt cells are masked off the pci status register */
1257     pci_status = pci_default_read_config(dev, PCI_STATUS, 2);
1258     _FDT(fdt_setprop_cell(fdt, offset, "devsel-speed",
1259                           PCI_STATUS_DEVSEL_MASK & pci_status));
1260 
1261     if (pci_status & PCI_STATUS_FAST_BACK) {
1262         _FDT(fdt_setprop(fdt, offset, "fast-back-to-back", NULL, 0));
1263     }
1264     if (pci_status & PCI_STATUS_66MHZ) {
1265         _FDT(fdt_setprop(fdt, offset, "66mhz-capable", NULL, 0));
1266     }
1267     if (pci_status & PCI_STATUS_UDF) {
1268         _FDT(fdt_setprop(fdt, offset, "udf-supported", NULL, 0));
1269     }
1270 
1271     _FDT(fdt_setprop_string(fdt, offset, "name",
1272                             pci_find_device_name((ccode >> 16) & 0xff,
1273                                                  (ccode >> 8) & 0xff,
1274                                                  ccode & 0xff)));
1275 
1276     buf = spapr_phb_get_loc_code(sphb, dev);
1277     err = fdt_setprop_string(fdt, offset, "ibm,loc-code", buf);
1278     g_free(buf);
1279     if (err < 0) {
1280         return err;
1281     }
1282 
1283     if (drc_index) {
1284         _FDT(fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index));
1285     }
1286 
1287     _FDT(fdt_setprop_cell(fdt, offset, "#address-cells",
1288                           RESOURCE_CELLS_ADDRESS));
1289     _FDT(fdt_setprop_cell(fdt, offset, "#size-cells",
1290                           RESOURCE_CELLS_SIZE));
1291 
1292     max_msi = msi_nr_vectors_allocated(dev);
1293     if (max_msi) {
1294         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi", max_msi));
1295     }
1296     max_msix = dev->msix_entries_nr;
1297     if (max_msix) {
1298         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi-x", max_msix));
1299     }
1300 
1301     populate_resource_props(dev, &rp);
1302     _FDT(fdt_setprop(fdt, offset, "reg", (uint8_t *)rp.reg, rp.reg_len));
1303     _FDT(fdt_setprop(fdt, offset, "assigned-addresses",
1304                      (uint8_t *)rp.assigned, rp.assigned_len));
1305 
1306     if (sphb->pcie_ecs && pci_is_express(dev)) {
1307         _FDT(fdt_setprop_cell(fdt, offset, "ibm,pci-config-space-type", 0x1));
1308     }
1309 
1310     return 0;
1311 }
1312 
1313 /* create OF node for pci device and required OF DT properties */
1314 static int spapr_create_pci_child_dt(sPAPRPHBState *phb, PCIDevice *dev,
1315                                      void *fdt, int node_offset)
1316 {
1317     int offset, ret;
1318     gchar *nodename;
1319 
1320     nodename = pci_get_node_name(dev);
1321     offset = fdt_add_subnode(fdt, node_offset, nodename);
1322     g_free(nodename);
1323 
1324     ret = spapr_populate_pci_child_dt(dev, fdt, offset, phb);
1325 
1326     g_assert(!ret);
1327     if (ret) {
1328         return 0;
1329     }
1330     return offset;
1331 }
1332 
1333 /* Callback to be called during DRC release. */
1334 void spapr_phb_remove_pci_device_cb(DeviceState *dev)
1335 {
1336     /* some version guests do not wait for completion of a device
1337      * cleanup (generally done asynchronously by the kernel) before
1338      * signaling to QEMU that the device is safe, but instead sleep
1339      * for some 'safe' period of time. unfortunately on a busy host
1340      * this sleep isn't guaranteed to be long enough, resulting in
1341      * bad things like IRQ lines being left asserted during final
1342      * device removal. to deal with this we call reset just prior
1343      * to finalizing the device, which will put the device back into
1344      * an 'idle' state, as the device cleanup code expects.
1345      */
1346     pci_device_reset(PCI_DEVICE(dev));
1347     object_unparent(OBJECT(dev));
1348 }
1349 
1350 static sPAPRDRConnector *spapr_phb_get_pci_func_drc(sPAPRPHBState *phb,
1351                                                     uint32_t busnr,
1352                                                     int32_t devfn)
1353 {
1354     return spapr_drc_by_id(TYPE_SPAPR_DRC_PCI,
1355                            (phb->index << 16) | (busnr << 8) | devfn);
1356 }
1357 
1358 static sPAPRDRConnector *spapr_phb_get_pci_drc(sPAPRPHBState *phb,
1359                                                PCIDevice *pdev)
1360 {
1361     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
1362     return spapr_phb_get_pci_func_drc(phb, busnr, pdev->devfn);
1363 }
1364 
1365 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
1366                                             PCIDevice *pdev)
1367 {
1368     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1369 
1370     if (!drc) {
1371         return 0;
1372     }
1373 
1374     return spapr_drc_index(drc);
1375 }
1376 
1377 static void spapr_pci_plug(HotplugHandler *plug_handler,
1378                            DeviceState *plugged_dev, Error **errp)
1379 {
1380     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1381     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1382     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1383     Error *local_err = NULL;
1384     PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1385     uint32_t slotnr = PCI_SLOT(pdev->devfn);
1386     void *fdt = NULL;
1387     int fdt_start_offset, fdt_size;
1388 
1389     /* if DR is disabled we don't need to do anything in the case of
1390      * hotplug or coldplug callbacks
1391      */
1392     if (!phb->dr_enabled) {
1393         /* if this is a hotplug operation initiated by the user
1394          * we need to let them know it's not enabled
1395          */
1396         if (plugged_dev->hotplugged) {
1397             error_setg(&local_err, QERR_BUS_NO_HOTPLUG,
1398                        object_get_typename(OBJECT(phb)));
1399         }
1400         goto out;
1401     }
1402 
1403     g_assert(drc);
1404 
1405     /* Following the QEMU convention used for PCIe multifunction
1406      * hotplug, we do not allow functions to be hotplugged to a
1407      * slot that already has function 0 present
1408      */
1409     if (plugged_dev->hotplugged && bus->devices[PCI_DEVFN(slotnr, 0)] &&
1410         PCI_FUNC(pdev->devfn) != 0) {
1411         error_setg(&local_err, "PCI: slot %d function 0 already ocuppied by %s,"
1412                    " additional functions can no longer be exposed to guest.",
1413                    slotnr, bus->devices[PCI_DEVFN(slotnr, 0)]->name);
1414         goto out;
1415     }
1416 
1417     fdt = create_device_tree(&fdt_size);
1418     fdt_start_offset = spapr_create_pci_child_dt(phb, pdev, fdt, 0);
1419     if (!fdt_start_offset) {
1420         error_setg(&local_err, "Failed to create pci child device tree node");
1421         goto out;
1422     }
1423 
1424     spapr_drc_attach(drc, DEVICE(pdev), fdt, fdt_start_offset, &local_err);
1425     if (local_err) {
1426         goto out;
1427     }
1428 
1429     /* If this is function 0, signal hotplug for all the device functions.
1430      * Otherwise defer sending the hotplug event.
1431      */
1432     if (!spapr_drc_hotplugged(plugged_dev)) {
1433         spapr_drc_reset(drc);
1434     } else if (PCI_FUNC(pdev->devfn) == 0) {
1435         int i;
1436 
1437         for (i = 0; i < 8; i++) {
1438             sPAPRDRConnector *func_drc;
1439             sPAPRDRConnectorClass *func_drck;
1440             sPAPRDREntitySense state;
1441 
1442             func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1443                                                   PCI_DEVFN(slotnr, i));
1444             func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1445             state = func_drck->dr_entity_sense(func_drc);
1446 
1447             if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1448                 spapr_hotplug_req_add_by_index(func_drc);
1449             }
1450         }
1451     }
1452 
1453 out:
1454     if (local_err) {
1455         error_propagate(errp, local_err);
1456         g_free(fdt);
1457     }
1458 }
1459 
1460 static void spapr_pci_unplug_request(HotplugHandler *plug_handler,
1461                                      DeviceState *plugged_dev, Error **errp)
1462 {
1463     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1464     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1465     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1466 
1467     if (!phb->dr_enabled) {
1468         error_setg(errp, QERR_BUS_NO_HOTPLUG,
1469                    object_get_typename(OBJECT(phb)));
1470         return;
1471     }
1472 
1473     g_assert(drc);
1474     g_assert(drc->dev == plugged_dev);
1475 
1476     if (!spapr_drc_unplug_requested(drc)) {
1477         PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1478         uint32_t slotnr = PCI_SLOT(pdev->devfn);
1479         sPAPRDRConnector *func_drc;
1480         sPAPRDRConnectorClass *func_drck;
1481         sPAPRDREntitySense state;
1482         int i;
1483 
1484         /* ensure any other present functions are pending unplug */
1485         if (PCI_FUNC(pdev->devfn) == 0) {
1486             for (i = 1; i < 8; i++) {
1487                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1488                                                       PCI_DEVFN(slotnr, i));
1489                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1490                 state = func_drck->dr_entity_sense(func_drc);
1491                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT
1492                     && !spapr_drc_unplug_requested(func_drc)) {
1493                     error_setg(errp,
1494                                "PCI: slot %d, function %d still present. "
1495                                "Must unplug all non-0 functions first.",
1496                                slotnr, i);
1497                     return;
1498                 }
1499             }
1500         }
1501 
1502         spapr_drc_detach(drc);
1503 
1504         /* if this isn't func 0, defer unplug event. otherwise signal removal
1505          * for all present functions
1506          */
1507         if (PCI_FUNC(pdev->devfn) == 0) {
1508             for (i = 7; i >= 0; i--) {
1509                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1510                                                       PCI_DEVFN(slotnr, i));
1511                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1512                 state = func_drck->dr_entity_sense(func_drc);
1513                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1514                     spapr_hotplug_req_remove_by_index(func_drc);
1515                 }
1516             }
1517         }
1518     }
1519 }
1520 
1521 static void spapr_phb_realize(DeviceState *dev, Error **errp)
1522 {
1523     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1524     SysBusDevice *s = SYS_BUS_DEVICE(dev);
1525     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
1526     PCIHostState *phb = PCI_HOST_BRIDGE(s);
1527     char *namebuf;
1528     int i;
1529     PCIBus *bus;
1530     uint64_t msi_window_size = 4096;
1531     sPAPRTCETable *tcet;
1532     const unsigned windows_supported =
1533         sphb->ddw_enabled ? SPAPR_PCI_DMA_MAX_WINDOWS : 1;
1534 
1535     if (sphb->index != (uint32_t)-1) {
1536         sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(spapr);
1537         Error *local_err = NULL;
1538 
1539         if ((sphb->buid != (uint64_t)-1) || (sphb->dma_liobn[0] != (uint32_t)-1)
1540             || (sphb->dma_liobn[1] != (uint32_t)-1 && windows_supported == 2)
1541             || (sphb->mem_win_addr != (hwaddr)-1)
1542             || (sphb->mem64_win_addr != (hwaddr)-1)
1543             || (sphb->io_win_addr != (hwaddr)-1)) {
1544             error_setg(errp, "Either \"index\" or other parameters must"
1545                        " be specified for PAPR PHB, not both");
1546             return;
1547         }
1548 
1549         smc->phb_placement(spapr, sphb->index,
1550                            &sphb->buid, &sphb->io_win_addr,
1551                            &sphb->mem_win_addr, &sphb->mem64_win_addr,
1552                            windows_supported, sphb->dma_liobn, &local_err);
1553         if (local_err) {
1554             error_propagate(errp, local_err);
1555             return;
1556         }
1557     }
1558 
1559     if (sphb->buid == (uint64_t)-1) {
1560         error_setg(errp, "BUID not specified for PHB");
1561         return;
1562     }
1563 
1564     if ((sphb->dma_liobn[0] == (uint32_t)-1) ||
1565         ((sphb->dma_liobn[1] == (uint32_t)-1) && (windows_supported > 1))) {
1566         error_setg(errp, "LIOBN(s) not specified for PHB");
1567         return;
1568     }
1569 
1570     if (sphb->mem_win_addr == (hwaddr)-1) {
1571         error_setg(errp, "Memory window address not specified for PHB");
1572         return;
1573     }
1574 
1575     if (sphb->io_win_addr == (hwaddr)-1) {
1576         error_setg(errp, "IO window address not specified for PHB");
1577         return;
1578     }
1579 
1580     if (sphb->mem64_win_size != 0) {
1581         if (sphb->mem64_win_addr == (hwaddr)-1) {
1582             error_setg(errp,
1583                        "64-bit memory window address not specified for PHB");
1584             return;
1585         }
1586 
1587         if (sphb->mem_win_size > SPAPR_PCI_MEM32_WIN_SIZE) {
1588             error_setg(errp, "32-bit memory window of size 0x%"HWADDR_PRIx
1589                        " (max 2 GiB)", sphb->mem_win_size);
1590             return;
1591         }
1592 
1593         if (sphb->mem64_win_pciaddr == (hwaddr)-1) {
1594             /* 64-bit window defaults to identity mapping */
1595             sphb->mem64_win_pciaddr = sphb->mem64_win_addr;
1596         }
1597     } else if (sphb->mem_win_size > SPAPR_PCI_MEM32_WIN_SIZE) {
1598         /*
1599          * For compatibility with old configuration, if no 64-bit MMIO
1600          * window is specified, but the ordinary (32-bit) memory
1601          * window is specified as > 2GiB, we treat it as a 2GiB 32-bit
1602          * window, with a 64-bit MMIO window following on immediately
1603          * afterwards
1604          */
1605         sphb->mem64_win_size = sphb->mem_win_size - SPAPR_PCI_MEM32_WIN_SIZE;
1606         sphb->mem64_win_addr = sphb->mem_win_addr + SPAPR_PCI_MEM32_WIN_SIZE;
1607         sphb->mem64_win_pciaddr =
1608             SPAPR_PCI_MEM_WIN_BUS_OFFSET + SPAPR_PCI_MEM32_WIN_SIZE;
1609         sphb->mem_win_size = SPAPR_PCI_MEM32_WIN_SIZE;
1610     }
1611 
1612     if (spapr_pci_find_phb(spapr, sphb->buid)) {
1613         error_setg(errp, "PCI host bridges must have unique BUIDs");
1614         return;
1615     }
1616 
1617     if (sphb->numa_node != -1 &&
1618         (sphb->numa_node >= MAX_NODES || !numa_info[sphb->numa_node].present)) {
1619         error_setg(errp, "Invalid NUMA node ID for PCI host bridge");
1620         return;
1621     }
1622 
1623     sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);
1624 
1625     namebuf = alloca(strlen(sphb->dtbusname) + 32);
1626 
1627     /* Initialize memory regions */
1628     sprintf(namebuf, "%s.mmio", sphb->dtbusname);
1629     memory_region_init(&sphb->memspace, OBJECT(sphb), namebuf, UINT64_MAX);
1630 
1631     sprintf(namebuf, "%s.mmio32-alias", sphb->dtbusname);
1632     memory_region_init_alias(&sphb->mem32window, OBJECT(sphb),
1633                              namebuf, &sphb->memspace,
1634                              SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);
1635     memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,
1636                                 &sphb->mem32window);
1637 
1638     sprintf(namebuf, "%s.mmio64-alias", sphb->dtbusname);
1639     memory_region_init_alias(&sphb->mem64window, OBJECT(sphb),
1640                              namebuf, &sphb->memspace,
1641                              sphb->mem64_win_pciaddr, sphb->mem64_win_size);
1642     memory_region_add_subregion(get_system_memory(), sphb->mem64_win_addr,
1643                                 &sphb->mem64window);
1644 
1645     /* Initialize IO regions */
1646     sprintf(namebuf, "%s.io", sphb->dtbusname);
1647     memory_region_init(&sphb->iospace, OBJECT(sphb),
1648                        namebuf, SPAPR_PCI_IO_WIN_SIZE);
1649 
1650     sprintf(namebuf, "%s.io-alias", sphb->dtbusname);
1651     memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf,
1652                              &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE);
1653     memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,
1654                                 &sphb->iowindow);
1655 
1656     bus = pci_register_bus(dev, NULL,
1657                            pci_spapr_set_irq, pci_spapr_map_irq, sphb,
1658                            &sphb->memspace, &sphb->iospace,
1659                            PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS);
1660     phb->bus = bus;
1661     qbus_set_hotplug_handler(BUS(phb->bus), DEVICE(sphb), NULL);
1662 
1663     /*
1664      * Initialize PHB address space.
1665      * By default there will be at least one subregion for default
1666      * 32bit DMA window.
1667      * Later the guest might want to create another DMA window
1668      * which will become another memory subregion.
1669      */
1670     sprintf(namebuf, "%s.iommu-root", sphb->dtbusname);
1671 
1672     memory_region_init(&sphb->iommu_root, OBJECT(sphb),
1673                        namebuf, UINT64_MAX);
1674     address_space_init(&sphb->iommu_as, &sphb->iommu_root,
1675                        sphb->dtbusname);
1676 
1677     /*
1678      * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,
1679      * we need to allocate some memory to catch those writes coming
1680      * from msi_notify()/msix_notify().
1681      * As MSIMessage:addr is going to be the same and MSIMessage:data
1682      * is going to be a VIRQ number, 4 bytes of the MSI MR will only
1683      * be used.
1684      *
1685      * For KVM we want to ensure that this memory is a full page so that
1686      * our memory slot is of page size granularity.
1687      */
1688 #ifdef CONFIG_KVM
1689     if (kvm_enabled()) {
1690         msi_window_size = getpagesize();
1691     }
1692 #endif
1693 
1694     memory_region_init_io(&sphb->msiwindow, OBJECT(sphb), &spapr_msi_ops, spapr,
1695                           "msi", msi_window_size);
1696     memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW,
1697                                 &sphb->msiwindow);
1698 
1699     pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb);
1700 
1701     pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq);
1702 
1703     QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);
1704 
1705     /* Initialize the LSI table */
1706     for (i = 0; i < PCI_NUM_PINS; i++) {
1707         uint32_t irq;
1708         Error *local_err = NULL;
1709 
1710         irq = spapr_ics_alloc_block(spapr->ics, 1, true, false, &local_err);
1711         if (local_err) {
1712             error_propagate(errp, local_err);
1713             error_prepend(errp, "can't allocate LSIs: ");
1714             return;
1715         }
1716 
1717         sphb->lsi_table[i].irq = irq;
1718     }
1719 
1720     /* allocate connectors for child PCI devices */
1721     if (sphb->dr_enabled) {
1722         for (i = 0; i < PCI_SLOT_MAX * 8; i++) {
1723             spapr_dr_connector_new(OBJECT(phb), TYPE_SPAPR_DRC_PCI,
1724                                    (sphb->index << 16) | i);
1725         }
1726     }
1727 
1728     /* DMA setup */
1729     if (((sphb->page_size_mask & qemu_getrampagesize()) == 0)
1730         && kvm_enabled()) {
1731         error_report("System page size 0x%lx is not enabled in page_size_mask "
1732                      "(0x%"PRIx64"). Performance may be slow",
1733                      qemu_getrampagesize(), sphb->page_size_mask);
1734     }
1735 
1736     for (i = 0; i < windows_supported; ++i) {
1737         tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn[i]);
1738         if (!tcet) {
1739             error_setg(errp, "Creating window#%d failed for %s",
1740                        i, sphb->dtbusname);
1741             return;
1742         }
1743         memory_region_add_subregion(&sphb->iommu_root, 0,
1744                                     spapr_tce_get_iommu(tcet));
1745     }
1746 
1747     sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);
1748 }
1749 
1750 static int spapr_phb_children_reset(Object *child, void *opaque)
1751 {
1752     DeviceState *dev = (DeviceState *) object_dynamic_cast(child, TYPE_DEVICE);
1753 
1754     if (dev) {
1755         device_reset(dev);
1756     }
1757 
1758     return 0;
1759 }
1760 
1761 void spapr_phb_dma_reset(sPAPRPHBState *sphb)
1762 {
1763     int i;
1764     sPAPRTCETable *tcet;
1765 
1766     for (i = 0; i < SPAPR_PCI_DMA_MAX_WINDOWS; ++i) {
1767         tcet = spapr_tce_find_by_liobn(sphb->dma_liobn[i]);
1768 
1769         if (tcet && tcet->nb_table) {
1770             spapr_tce_table_disable(tcet);
1771         }
1772     }
1773 
1774     /* Register default 32bit DMA window */
1775     tcet = spapr_tce_find_by_liobn(sphb->dma_liobn[0]);
1776     spapr_tce_table_enable(tcet, SPAPR_TCE_PAGE_SHIFT, sphb->dma_win_addr,
1777                            sphb->dma_win_size >> SPAPR_TCE_PAGE_SHIFT);
1778 }
1779 
1780 static void spapr_phb_reset(DeviceState *qdev)
1781 {
1782     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(qdev);
1783 
1784     spapr_phb_dma_reset(sphb);
1785 
1786     /* Reset the IOMMU state */
1787     object_child_foreach(OBJECT(qdev), spapr_phb_children_reset, NULL);
1788 
1789     if (spapr_phb_eeh_available(SPAPR_PCI_HOST_BRIDGE(qdev))) {
1790         spapr_phb_vfio_reset(qdev);
1791     }
1792 }
1793 
1794 static Property spapr_phb_properties[] = {
1795     DEFINE_PROP_UINT32("index", sPAPRPHBState, index, -1),
1796     DEFINE_PROP_UINT64("buid", sPAPRPHBState, buid, -1),
1797     DEFINE_PROP_UINT32("liobn", sPAPRPHBState, dma_liobn[0], -1),
1798     DEFINE_PROP_UINT32("liobn64", sPAPRPHBState, dma_liobn[1], -1),
1799     DEFINE_PROP_UINT64("mem_win_addr", sPAPRPHBState, mem_win_addr, -1),
1800     DEFINE_PROP_UINT64("mem_win_size", sPAPRPHBState, mem_win_size,
1801                        SPAPR_PCI_MEM32_WIN_SIZE),
1802     DEFINE_PROP_UINT64("mem64_win_addr", sPAPRPHBState, mem64_win_addr, -1),
1803     DEFINE_PROP_UINT64("mem64_win_size", sPAPRPHBState, mem64_win_size,
1804                        SPAPR_PCI_MEM64_WIN_SIZE),
1805     DEFINE_PROP_UINT64("mem64_win_pciaddr", sPAPRPHBState, mem64_win_pciaddr,
1806                        -1),
1807     DEFINE_PROP_UINT64("io_win_addr", sPAPRPHBState, io_win_addr, -1),
1808     DEFINE_PROP_UINT64("io_win_size", sPAPRPHBState, io_win_size,
1809                        SPAPR_PCI_IO_WIN_SIZE),
1810     DEFINE_PROP_BOOL("dynamic-reconfiguration", sPAPRPHBState, dr_enabled,
1811                      true),
1812     /* Default DMA window is 0..1GB */
1813     DEFINE_PROP_UINT64("dma_win_addr", sPAPRPHBState, dma_win_addr, 0),
1814     DEFINE_PROP_UINT64("dma_win_size", sPAPRPHBState, dma_win_size, 0x40000000),
1815     DEFINE_PROP_UINT64("dma64_win_addr", sPAPRPHBState, dma64_win_addr,
1816                        0x800000000000000ULL),
1817     DEFINE_PROP_BOOL("ddw", sPAPRPHBState, ddw_enabled, true),
1818     DEFINE_PROP_UINT64("pgsz", sPAPRPHBState, page_size_mask,
1819                        (1ULL << 12) | (1ULL << 16)),
1820     DEFINE_PROP_UINT32("numa_node", sPAPRPHBState, numa_node, -1),
1821     DEFINE_PROP_BOOL("pre-2.8-migration", sPAPRPHBState,
1822                      pre_2_8_migration, false),
1823     DEFINE_PROP_BOOL("pcie-extended-configuration-space", sPAPRPHBState,
1824                      pcie_ecs, true),
1825     DEFINE_PROP_END_OF_LIST(),
1826 };
1827 
1828 static const VMStateDescription vmstate_spapr_pci_lsi = {
1829     .name = "spapr_pci/lsi",
1830     .version_id = 1,
1831     .minimum_version_id = 1,
1832     .fields = (VMStateField[]) {
1833         VMSTATE_UINT32_EQUAL(irq, struct spapr_pci_lsi, NULL),
1834 
1835         VMSTATE_END_OF_LIST()
1836     },
1837 };
1838 
1839 static const VMStateDescription vmstate_spapr_pci_msi = {
1840     .name = "spapr_pci/msi",
1841     .version_id = 1,
1842     .minimum_version_id = 1,
1843     .fields = (VMStateField []) {
1844         VMSTATE_UINT32(key, spapr_pci_msi_mig),
1845         VMSTATE_UINT32(value.first_irq, spapr_pci_msi_mig),
1846         VMSTATE_UINT32(value.num, spapr_pci_msi_mig),
1847         VMSTATE_END_OF_LIST()
1848     },
1849 };
1850 
1851 static void spapr_pci_pre_save(void *opaque)
1852 {
1853     sPAPRPHBState *sphb = opaque;
1854     GHashTableIter iter;
1855     gpointer key, value;
1856     int i;
1857 
1858     if (sphb->pre_2_8_migration) {
1859         sphb->mig_liobn = sphb->dma_liobn[0];
1860         sphb->mig_mem_win_addr = sphb->mem_win_addr;
1861         sphb->mig_mem_win_size = sphb->mem_win_size;
1862         sphb->mig_io_win_addr = sphb->io_win_addr;
1863         sphb->mig_io_win_size = sphb->io_win_size;
1864 
1865         if ((sphb->mem64_win_size != 0)
1866             && (sphb->mem64_win_addr
1867                 == (sphb->mem_win_addr + sphb->mem_win_size))) {
1868             sphb->mig_mem_win_size += sphb->mem64_win_size;
1869         }
1870     }
1871 
1872     g_free(sphb->msi_devs);
1873     sphb->msi_devs = NULL;
1874     sphb->msi_devs_num = g_hash_table_size(sphb->msi);
1875     if (!sphb->msi_devs_num) {
1876         return;
1877     }
1878     sphb->msi_devs = g_malloc(sphb->msi_devs_num * sizeof(spapr_pci_msi_mig));
1879 
1880     g_hash_table_iter_init(&iter, sphb->msi);
1881     for (i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
1882         sphb->msi_devs[i].key = *(uint32_t *) key;
1883         sphb->msi_devs[i].value = *(spapr_pci_msi *) value;
1884     }
1885 }
1886 
1887 static int spapr_pci_post_load(void *opaque, int version_id)
1888 {
1889     sPAPRPHBState *sphb = opaque;
1890     gpointer key, value;
1891     int i;
1892 
1893     for (i = 0; i < sphb->msi_devs_num; ++i) {
1894         key = g_memdup(&sphb->msi_devs[i].key,
1895                        sizeof(sphb->msi_devs[i].key));
1896         value = g_memdup(&sphb->msi_devs[i].value,
1897                          sizeof(sphb->msi_devs[i].value));
1898         g_hash_table_insert(sphb->msi, key, value);
1899     }
1900     g_free(sphb->msi_devs);
1901     sphb->msi_devs = NULL;
1902     sphb->msi_devs_num = 0;
1903 
1904     return 0;
1905 }
1906 
1907 static bool pre_2_8_migration(void *opaque, int version_id)
1908 {
1909     sPAPRPHBState *sphb = opaque;
1910 
1911     return sphb->pre_2_8_migration;
1912 }
1913 
1914 static const VMStateDescription vmstate_spapr_pci = {
1915     .name = "spapr_pci",
1916     .version_id = 2,
1917     .minimum_version_id = 2,
1918     .pre_save = spapr_pci_pre_save,
1919     .post_load = spapr_pci_post_load,
1920     .fields = (VMStateField[]) {
1921         VMSTATE_UINT64_EQUAL(buid, sPAPRPHBState, NULL),
1922         VMSTATE_UINT32_TEST(mig_liobn, sPAPRPHBState, pre_2_8_migration),
1923         VMSTATE_UINT64_TEST(mig_mem_win_addr, sPAPRPHBState, pre_2_8_migration),
1924         VMSTATE_UINT64_TEST(mig_mem_win_size, sPAPRPHBState, pre_2_8_migration),
1925         VMSTATE_UINT64_TEST(mig_io_win_addr, sPAPRPHBState, pre_2_8_migration),
1926         VMSTATE_UINT64_TEST(mig_io_win_size, sPAPRPHBState, pre_2_8_migration),
1927         VMSTATE_STRUCT_ARRAY(lsi_table, sPAPRPHBState, PCI_NUM_PINS, 0,
1928                              vmstate_spapr_pci_lsi, struct spapr_pci_lsi),
1929         VMSTATE_INT32(msi_devs_num, sPAPRPHBState),
1930         VMSTATE_STRUCT_VARRAY_ALLOC(msi_devs, sPAPRPHBState, msi_devs_num, 0,
1931                                     vmstate_spapr_pci_msi, spapr_pci_msi_mig),
1932         VMSTATE_END_OF_LIST()
1933     },
1934 };
1935 
1936 static const char *spapr_phb_root_bus_path(PCIHostState *host_bridge,
1937                                            PCIBus *rootbus)
1938 {
1939     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(host_bridge);
1940 
1941     return sphb->dtbusname;
1942 }
1943 
1944 static void spapr_phb_class_init(ObjectClass *klass, void *data)
1945 {
1946     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);
1947     DeviceClass *dc = DEVICE_CLASS(klass);
1948     HotplugHandlerClass *hp = HOTPLUG_HANDLER_CLASS(klass);
1949 
1950     hc->root_bus_path = spapr_phb_root_bus_path;
1951     dc->realize = spapr_phb_realize;
1952     dc->props = spapr_phb_properties;
1953     dc->reset = spapr_phb_reset;
1954     dc->vmsd = &vmstate_spapr_pci;
1955     /* Supported by TYPE_SPAPR_MACHINE */
1956     dc->user_creatable = true;
1957     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1958     hp->plug = spapr_pci_plug;
1959     hp->unplug_request = spapr_pci_unplug_request;
1960 }
1961 
1962 static const TypeInfo spapr_phb_info = {
1963     .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
1964     .parent        = TYPE_PCI_HOST_BRIDGE,
1965     .instance_size = sizeof(sPAPRPHBState),
1966     .class_init    = spapr_phb_class_init,
1967     .interfaces    = (InterfaceInfo[]) {
1968         { TYPE_HOTPLUG_HANDLER },
1969         { }
1970     }
1971 };
1972 
1973 PCIHostState *spapr_create_phb(sPAPRMachineState *spapr, int index)
1974 {
1975     DeviceState *dev;
1976 
1977     dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
1978     qdev_prop_set_uint32(dev, "index", index);
1979     qdev_init_nofail(dev);
1980 
1981     return PCI_HOST_BRIDGE(dev);
1982 }
1983 
1984 typedef struct sPAPRFDT {
1985     void *fdt;
1986     int node_off;
1987     sPAPRPHBState *sphb;
1988 } sPAPRFDT;
1989 
1990 static void spapr_populate_pci_devices_dt(PCIBus *bus, PCIDevice *pdev,
1991                                           void *opaque)
1992 {
1993     PCIBus *sec_bus;
1994     sPAPRFDT *p = opaque;
1995     int offset;
1996     sPAPRFDT s_fdt;
1997 
1998     offset = spapr_create_pci_child_dt(p->sphb, pdev, p->fdt, p->node_off);
1999     if (!offset) {
2000         error_report("Failed to create pci child device tree node");
2001         return;
2002     }
2003 
2004     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
2005          PCI_HEADER_TYPE_BRIDGE)) {
2006         return;
2007     }
2008 
2009     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
2010     if (!sec_bus) {
2011         return;
2012     }
2013 
2014     s_fdt.fdt = p->fdt;
2015     s_fdt.node_off = offset;
2016     s_fdt.sphb = p->sphb;
2017     pci_for_each_device_reverse(sec_bus, pci_bus_num(sec_bus),
2018                                 spapr_populate_pci_devices_dt,
2019                                 &s_fdt);
2020 }
2021 
2022 static void spapr_phb_pci_enumerate_bridge(PCIBus *bus, PCIDevice *pdev,
2023                                            void *opaque)
2024 {
2025     unsigned int *bus_no = opaque;
2026     unsigned int primary = *bus_no;
2027     unsigned int subordinate = 0xff;
2028     PCIBus *sec_bus = NULL;
2029 
2030     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
2031          PCI_HEADER_TYPE_BRIDGE)) {
2032         return;
2033     }
2034 
2035     (*bus_no)++;
2036     pci_default_write_config(pdev, PCI_PRIMARY_BUS, primary, 1);
2037     pci_default_write_config(pdev, PCI_SECONDARY_BUS, *bus_no, 1);
2038     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
2039 
2040     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
2041     if (!sec_bus) {
2042         return;
2043     }
2044 
2045     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, subordinate, 1);
2046     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
2047                         spapr_phb_pci_enumerate_bridge, bus_no);
2048     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
2049 }
2050 
2051 static void spapr_phb_pci_enumerate(sPAPRPHBState *phb)
2052 {
2053     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
2054     unsigned int bus_no = 0;
2055 
2056     pci_for_each_device(bus, pci_bus_num(bus),
2057                         spapr_phb_pci_enumerate_bridge,
2058                         &bus_no);
2059 
2060 }
2061 
2062 int spapr_populate_pci_dt(sPAPRPHBState *phb,
2063                           uint32_t xics_phandle,
2064                           void *fdt)
2065 {
2066     int bus_off, i, j, ret;
2067     gchar *nodename;
2068     uint32_t bus_range[] = { cpu_to_be32(0), cpu_to_be32(0xff) };
2069     struct {
2070         uint32_t hi;
2071         uint64_t child;
2072         uint64_t parent;
2073         uint64_t size;
2074     } QEMU_PACKED ranges[] = {
2075         {
2076             cpu_to_be32(b_ss(1)), cpu_to_be64(0),
2077             cpu_to_be64(phb->io_win_addr),
2078             cpu_to_be64(memory_region_size(&phb->iospace)),
2079         },
2080         {
2081             cpu_to_be32(b_ss(2)), cpu_to_be64(SPAPR_PCI_MEM_WIN_BUS_OFFSET),
2082             cpu_to_be64(phb->mem_win_addr),
2083             cpu_to_be64(phb->mem_win_size),
2084         },
2085         {
2086             cpu_to_be32(b_ss(3)), cpu_to_be64(phb->mem64_win_pciaddr),
2087             cpu_to_be64(phb->mem64_win_addr),
2088             cpu_to_be64(phb->mem64_win_size),
2089         },
2090     };
2091     const unsigned sizeof_ranges =
2092         (phb->mem64_win_size ? 3 : 2) * sizeof(ranges[0]);
2093     uint64_t bus_reg[] = { cpu_to_be64(phb->buid), 0 };
2094     uint32_t interrupt_map_mask[] = {
2095         cpu_to_be32(b_ddddd(-1)|b_fff(0)), 0x0, 0x0, cpu_to_be32(-1)};
2096     uint32_t interrupt_map[PCI_SLOT_MAX * PCI_NUM_PINS][7];
2097     uint32_t ddw_applicable[] = {
2098         cpu_to_be32(RTAS_IBM_QUERY_PE_DMA_WINDOW),
2099         cpu_to_be32(RTAS_IBM_CREATE_PE_DMA_WINDOW),
2100         cpu_to_be32(RTAS_IBM_REMOVE_PE_DMA_WINDOW)
2101     };
2102     uint32_t ddw_extensions[] = {
2103         cpu_to_be32(1),
2104         cpu_to_be32(RTAS_IBM_RESET_PE_DMA_WINDOW)
2105     };
2106     uint32_t associativity[] = {cpu_to_be32(0x4),
2107                                 cpu_to_be32(0x0),
2108                                 cpu_to_be32(0x0),
2109                                 cpu_to_be32(0x0),
2110                                 cpu_to_be32(phb->numa_node)};
2111     sPAPRTCETable *tcet;
2112     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
2113     sPAPRFDT s_fdt;
2114 
2115     /* Start populating the FDT */
2116     nodename = g_strdup_printf("pci@%" PRIx64, phb->buid);
2117     bus_off = fdt_add_subnode(fdt, 0, nodename);
2118     g_free(nodename);
2119     if (bus_off < 0) {
2120         return bus_off;
2121     }
2122 
2123     /* Write PHB properties */
2124     _FDT(fdt_setprop_string(fdt, bus_off, "device_type", "pci"));
2125     _FDT(fdt_setprop_string(fdt, bus_off, "compatible", "IBM,Logical_PHB"));
2126     _FDT(fdt_setprop_cell(fdt, bus_off, "#address-cells", 0x3));
2127     _FDT(fdt_setprop_cell(fdt, bus_off, "#size-cells", 0x2));
2128     _FDT(fdt_setprop_cell(fdt, bus_off, "#interrupt-cells", 0x1));
2129     _FDT(fdt_setprop(fdt, bus_off, "used-by-rtas", NULL, 0));
2130     _FDT(fdt_setprop(fdt, bus_off, "bus-range", &bus_range, sizeof(bus_range)));
2131     _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof_ranges));
2132     _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg)));
2133     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1));
2134     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS_SPAPR));
2135 
2136     /* Dynamic DMA window */
2137     if (phb->ddw_enabled) {
2138         _FDT(fdt_setprop(fdt, bus_off, "ibm,ddw-applicable", &ddw_applicable,
2139                          sizeof(ddw_applicable)));
2140         _FDT(fdt_setprop(fdt, bus_off, "ibm,ddw-extensions",
2141                          &ddw_extensions, sizeof(ddw_extensions)));
2142     }
2143 
2144     /* Advertise NUMA via ibm,associativity */
2145     if (phb->numa_node != -1) {
2146         _FDT(fdt_setprop(fdt, bus_off, "ibm,associativity", associativity,
2147                          sizeof(associativity)));
2148     }
2149 
2150     /* Build the interrupt-map, this must matches what is done
2151      * in pci_spapr_map_irq
2152      */
2153     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map-mask",
2154                      &interrupt_map_mask, sizeof(interrupt_map_mask)));
2155     for (i = 0; i < PCI_SLOT_MAX; i++) {
2156         for (j = 0; j < PCI_NUM_PINS; j++) {
2157             uint32_t *irqmap = interrupt_map[i*PCI_NUM_PINS + j];
2158             int lsi_num = pci_spapr_swizzle(i, j);
2159 
2160             irqmap[0] = cpu_to_be32(b_ddddd(i)|b_fff(0));
2161             irqmap[1] = 0;
2162             irqmap[2] = 0;
2163             irqmap[3] = cpu_to_be32(j+1);
2164             irqmap[4] = cpu_to_be32(xics_phandle);
2165             irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);
2166             irqmap[6] = cpu_to_be32(0x8);
2167         }
2168     }
2169     /* Write interrupt map */
2170     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
2171                      sizeof(interrupt_map)));
2172 
2173     tcet = spapr_tce_find_by_liobn(phb->dma_liobn[0]);
2174     if (!tcet) {
2175         return -1;
2176     }
2177     spapr_dma_dt(fdt, bus_off, "ibm,dma-window",
2178                  tcet->liobn, tcet->bus_offset,
2179                  tcet->nb_table << tcet->page_shift);
2180 
2181     /* Walk the bridges and program the bus numbers*/
2182     spapr_phb_pci_enumerate(phb);
2183     _FDT(fdt_setprop_cell(fdt, bus_off, "qemu,phb-enumerated", 0x1));
2184 
2185     /* Populate tree nodes with PCI devices attached */
2186     s_fdt.fdt = fdt;
2187     s_fdt.node_off = bus_off;
2188     s_fdt.sphb = phb;
2189     pci_for_each_device_reverse(bus, pci_bus_num(bus),
2190                                 spapr_populate_pci_devices_dt,
2191                                 &s_fdt);
2192 
2193     ret = spapr_drc_populate_dt(fdt, bus_off, OBJECT(phb),
2194                                 SPAPR_DR_CONNECTOR_TYPE_PCI);
2195     if (ret) {
2196         return ret;
2197     }
2198 
2199     return 0;
2200 }
2201 
2202 void spapr_pci_rtas_init(void)
2203 {
2204     spapr_rtas_register(RTAS_READ_PCI_CONFIG, "read-pci-config",
2205                         rtas_read_pci_config);
2206     spapr_rtas_register(RTAS_WRITE_PCI_CONFIG, "write-pci-config",
2207                         rtas_write_pci_config);
2208     spapr_rtas_register(RTAS_IBM_READ_PCI_CONFIG, "ibm,read-pci-config",
2209                         rtas_ibm_read_pci_config);
2210     spapr_rtas_register(RTAS_IBM_WRITE_PCI_CONFIG, "ibm,write-pci-config",
2211                         rtas_ibm_write_pci_config);
2212     if (msi_nonbroken) {
2213         spapr_rtas_register(RTAS_IBM_QUERY_INTERRUPT_SOURCE_NUMBER,
2214                             "ibm,query-interrupt-source-number",
2215                             rtas_ibm_query_interrupt_source_number);
2216         spapr_rtas_register(RTAS_IBM_CHANGE_MSI, "ibm,change-msi",
2217                             rtas_ibm_change_msi);
2218     }
2219 
2220     spapr_rtas_register(RTAS_IBM_SET_EEH_OPTION,
2221                         "ibm,set-eeh-option",
2222                         rtas_ibm_set_eeh_option);
2223     spapr_rtas_register(RTAS_IBM_GET_CONFIG_ADDR_INFO2,
2224                         "ibm,get-config-addr-info2",
2225                         rtas_ibm_get_config_addr_info2);
2226     spapr_rtas_register(RTAS_IBM_READ_SLOT_RESET_STATE2,
2227                         "ibm,read-slot-reset-state2",
2228                         rtas_ibm_read_slot_reset_state2);
2229     spapr_rtas_register(RTAS_IBM_SET_SLOT_RESET,
2230                         "ibm,set-slot-reset",
2231                         rtas_ibm_set_slot_reset);
2232     spapr_rtas_register(RTAS_IBM_CONFIGURE_PE,
2233                         "ibm,configure-pe",
2234                         rtas_ibm_configure_pe);
2235     spapr_rtas_register(RTAS_IBM_SLOT_ERROR_DETAIL,
2236                         "ibm,slot-error-detail",
2237                         rtas_ibm_slot_error_detail);
2238 }
2239 
2240 static void spapr_pci_register_types(void)
2241 {
2242     type_register_static(&spapr_phb_info);
2243 }
2244 
2245 type_init(spapr_pci_register_types)
2246 
2247 static int spapr_switch_one_vga(DeviceState *dev, void *opaque)
2248 {
2249     bool be = *(bool *)opaque;
2250 
2251     if (object_dynamic_cast(OBJECT(dev), "VGA")
2252         || object_dynamic_cast(OBJECT(dev), "secondary-vga")) {
2253         object_property_set_bool(OBJECT(dev), be, "big-endian-framebuffer",
2254                                  &error_abort);
2255     }
2256     return 0;
2257 }
2258 
2259 void spapr_pci_switch_vga(bool big_endian)
2260 {
2261     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
2262     sPAPRPHBState *sphb;
2263 
2264     /*
2265      * For backward compatibility with existing guests, we switch
2266      * the endianness of the VGA controller when changing the guest
2267      * interrupt mode
2268      */
2269     QLIST_FOREACH(sphb, &spapr->phbs, list) {
2270         BusState *bus = &PCI_HOST_BRIDGE(sphb)->bus->qbus;
2271         qbus_walk_children(bus, spapr_switch_one_vga, NULL, NULL, NULL,
2272                            &big_endian);
2273     }
2274 }
2275