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