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