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