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