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