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