xref: /qemu/hw/ppc/spapr_pci.c (revision 788d2599def0e26d92802593b07ec76e8701ccce)
1 /*
2  * QEMU sPAPR PCI host originated from Uninorth PCI host
3  *
4  * Copyright (c) 2011 Alexey Kardashevskiy, IBM Corporation.
5  * Copyright (C) 2011 David Gibson, IBM Corporation.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 #include "qemu/osdep.h"
26 #include "hw/hw.h"
27 #include "hw/sysbus.h"
28 #include "hw/pci/pci.h"
29 #include "hw/pci/msi.h"
30 #include "hw/pci/msix.h"
31 #include "hw/pci/pci_host.h"
32 #include "hw/ppc/spapr.h"
33 #include "hw/pci-host/spapr.h"
34 #include "exec/address-spaces.h"
35 #include <libfdt.h>
36 #include "trace.h"
37 #include "qemu/error-report.h"
38 #include "qapi/qmp/qerror.h"
39 
40 #include "hw/pci/pci_bridge.h"
41 #include "hw/pci/pci_bus.h"
42 #include "hw/ppc/spapr_drc.h"
43 #include "sysemu/device_tree.h"
44 
45 /* Copied from the kernel arch/powerpc/platforms/pseries/msi.c */
46 #define RTAS_QUERY_FN           0
47 #define RTAS_CHANGE_FN          1
48 #define RTAS_RESET_FN           2
49 #define RTAS_CHANGE_MSI_FN      3
50 #define RTAS_CHANGE_MSIX_FN     4
51 
52 /* Interrupt types to return on RTAS_CHANGE_* */
53 #define RTAS_TYPE_MSI           1
54 #define RTAS_TYPE_MSIX          2
55 
56 #define FDT_NAME_MAX          128
57 
58 #define _FDT(exp) \
59     do { \
60         int ret = (exp);                                           \
61         if (ret < 0) {                                             \
62             return ret;                                            \
63         }                                                          \
64     } while (0)
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     uint32_t config_addr = rtas_ld(args, 0);
273     uint64_t buid = rtas_ldq(args, 1);
274     unsigned int func = rtas_ld(args, 3);
275     unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */
276     unsigned int seq_num = rtas_ld(args, 5);
277     unsigned int ret_intr_type;
278     unsigned int irq, max_irqs = 0;
279     sPAPRPHBState *phb = NULL;
280     PCIDevice *pdev = NULL;
281     spapr_pci_msi *msi;
282     int *config_addr_key;
283     Error *err = NULL;
284 
285     switch (func) {
286     case RTAS_CHANGE_MSI_FN:
287     case RTAS_CHANGE_FN:
288         ret_intr_type = RTAS_TYPE_MSI;
289         break;
290     case RTAS_CHANGE_MSIX_FN:
291         ret_intr_type = RTAS_TYPE_MSIX;
292         break;
293     default:
294         error_report("rtas_ibm_change_msi(%u) is not implemented", func);
295         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
296         return;
297     }
298 
299     /* Fins sPAPRPHBState */
300     phb = spapr_pci_find_phb(spapr, buid);
301     if (phb) {
302         pdev = spapr_pci_find_dev(spapr, buid, config_addr);
303     }
304     if (!phb || !pdev) {
305         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
306         return;
307     }
308 
309     msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr);
310 
311     /* Releasing MSIs */
312     if (!req_num) {
313         if (!msi) {
314             trace_spapr_pci_msi("Releasing wrong config", config_addr);
315             rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
316             return;
317         }
318 
319         xics_free(spapr->icp, msi->first_irq, msi->num);
320         if (msi_present(pdev)) {
321             spapr_msi_setmsg(pdev, 0, false, 0, 0);
322         }
323         if (msix_present(pdev)) {
324             spapr_msi_setmsg(pdev, 0, true, 0, 0);
325         }
326         g_hash_table_remove(phb->msi, &config_addr);
327 
328         trace_spapr_pci_msi("Released MSIs", config_addr);
329         rtas_st(rets, 0, RTAS_OUT_SUCCESS);
330         rtas_st(rets, 1, 0);
331         return;
332     }
333 
334     /* Enabling MSI */
335 
336     /* Check if the device supports as many IRQs as requested */
337     if (ret_intr_type == RTAS_TYPE_MSI) {
338         max_irqs = msi_nr_vectors_allocated(pdev);
339     } else if (ret_intr_type == RTAS_TYPE_MSIX) {
340         max_irqs = pdev->msix_entries_nr;
341     }
342     if (!max_irqs) {
343         error_report("Requested interrupt type %d is not enabled for device %x",
344                      ret_intr_type, config_addr);
345         rtas_st(rets, 0, -1); /* Hardware error */
346         return;
347     }
348     /* Correct the number if the guest asked for too many */
349     if (req_num > max_irqs) {
350         trace_spapr_pci_msi_retry(config_addr, req_num, max_irqs);
351         req_num = max_irqs;
352         irq = 0; /* to avoid misleading trace */
353         goto out;
354     }
355 
356     /* Allocate MSIs */
357     irq = xics_alloc_block(spapr->icp, 0, req_num, false,
358                            ret_intr_type == RTAS_TYPE_MSI, &err);
359     if (err) {
360         error_reportf_err(err, "Can't allocate MSIs for device %x: ",
361                           config_addr);
362         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
363         return;
364     }
365 
366     /* Release previous MSIs */
367     if (msi) {
368         xics_free(spapr->icp, msi->first_irq, msi->num);
369         g_hash_table_remove(phb->msi, &config_addr);
370     }
371 
372     /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */
373     spapr_msi_setmsg(pdev, SPAPR_PCI_MSI_WINDOW, ret_intr_type == RTAS_TYPE_MSIX,
374                      irq, req_num);
375 
376     /* Add MSI device to cache */
377     msi = g_new(spapr_pci_msi, 1);
378     msi->first_irq = irq;
379     msi->num = req_num;
380     config_addr_key = g_new(int, 1);
381     *config_addr_key = config_addr;
382     g_hash_table_insert(phb->msi, config_addr_key, msi);
383 
384 out:
385     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
386     rtas_st(rets, 1, req_num);
387     rtas_st(rets, 2, ++seq_num);
388     if (nret > 3) {
389         rtas_st(rets, 3, ret_intr_type);
390     }
391 
392     trace_spapr_pci_rtas_ibm_change_msi(config_addr, func, req_num, irq);
393 }
394 
395 static void rtas_ibm_query_interrupt_source_number(PowerPCCPU *cpu,
396                                                    sPAPRMachineState *spapr,
397                                                    uint32_t token,
398                                                    uint32_t nargs,
399                                                    target_ulong args,
400                                                    uint32_t nret,
401                                                    target_ulong rets)
402 {
403     uint32_t config_addr = rtas_ld(args, 0);
404     uint64_t buid = rtas_ldq(args, 1);
405     unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3);
406     sPAPRPHBState *phb = NULL;
407     PCIDevice *pdev = NULL;
408     spapr_pci_msi *msi;
409 
410     /* Find sPAPRPHBState */
411     phb = spapr_pci_find_phb(spapr, buid);
412     if (phb) {
413         pdev = spapr_pci_find_dev(spapr, buid, config_addr);
414     }
415     if (!phb || !pdev) {
416         rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
417         return;
418     }
419 
420     /* Find device descriptor and start IRQ */
421     msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr);
422     if (!msi || !msi->first_irq || !msi->num || (ioa_intr_num >= msi->num)) {
423         trace_spapr_pci_msi("Failed to return vector", config_addr);
424         rtas_st(rets, 0, RTAS_OUT_HW_ERROR);
425         return;
426     }
427     intr_src_num = msi->first_irq + ioa_intr_num;
428     trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num,
429                                                            intr_src_num);
430 
431     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
432     rtas_st(rets, 1, intr_src_num);
433     rtas_st(rets, 2, 1);/* 0 == level; 1 == edge */
434 }
435 
436 static void rtas_ibm_set_eeh_option(PowerPCCPU *cpu,
437                                     sPAPRMachineState *spapr,
438                                     uint32_t token, uint32_t nargs,
439                                     target_ulong args, uint32_t nret,
440                                     target_ulong rets)
441 {
442     sPAPRPHBState *sphb;
443     sPAPRPHBClass *spc;
444     uint32_t addr, option;
445     uint64_t buid;
446     int ret;
447 
448     if ((nargs != 4) || (nret != 1)) {
449         goto param_error_exit;
450     }
451 
452     buid = rtas_ldq(args, 1);
453     addr = rtas_ld(args, 0);
454     option = rtas_ld(args, 3);
455 
456     sphb = spapr_pci_find_phb(spapr, buid);
457     if (!sphb) {
458         goto param_error_exit;
459     }
460 
461     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
462     if (!spc->eeh_set_option) {
463         goto param_error_exit;
464     }
465 
466     ret = spc->eeh_set_option(sphb, addr, option);
467     rtas_st(rets, 0, ret);
468     return;
469 
470 param_error_exit:
471     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
472 }
473 
474 static void rtas_ibm_get_config_addr_info2(PowerPCCPU *cpu,
475                                            sPAPRMachineState *spapr,
476                                            uint32_t token, uint32_t nargs,
477                                            target_ulong args, uint32_t nret,
478                                            target_ulong rets)
479 {
480     sPAPRPHBState *sphb;
481     sPAPRPHBClass *spc;
482     PCIDevice *pdev;
483     uint32_t addr, option;
484     uint64_t buid;
485 
486     if ((nargs != 4) || (nret != 2)) {
487         goto param_error_exit;
488     }
489 
490     buid = rtas_ldq(args, 1);
491     sphb = spapr_pci_find_phb(spapr, buid);
492     if (!sphb) {
493         goto param_error_exit;
494     }
495 
496     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
497     if (!spc->eeh_set_option) {
498         goto param_error_exit;
499     }
500 
501     /*
502      * We always have PE address of form "00BB0001". "BB"
503      * represents the bus number of PE's primary bus.
504      */
505     option = rtas_ld(args, 3);
506     switch (option) {
507     case RTAS_GET_PE_ADDR:
508         addr = rtas_ld(args, 0);
509         pdev = spapr_pci_find_dev(spapr, buid, addr);
510         if (!pdev) {
511             goto param_error_exit;
512         }
513 
514         rtas_st(rets, 1, (pci_bus_num(pdev->bus) << 16) + 1);
515         break;
516     case RTAS_GET_PE_MODE:
517         rtas_st(rets, 1, RTAS_PE_MODE_SHARED);
518         break;
519     default:
520         goto param_error_exit;
521     }
522 
523     rtas_st(rets, 0, RTAS_OUT_SUCCESS);
524     return;
525 
526 param_error_exit:
527     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
528 }
529 
530 static void rtas_ibm_read_slot_reset_state2(PowerPCCPU *cpu,
531                                             sPAPRMachineState *spapr,
532                                             uint32_t token, uint32_t nargs,
533                                             target_ulong args, uint32_t nret,
534                                             target_ulong rets)
535 {
536     sPAPRPHBState *sphb;
537     sPAPRPHBClass *spc;
538     uint64_t buid;
539     int state, ret;
540 
541     if ((nargs != 3) || (nret != 4 && nret != 5)) {
542         goto param_error_exit;
543     }
544 
545     buid = rtas_ldq(args, 1);
546     sphb = spapr_pci_find_phb(spapr, buid);
547     if (!sphb) {
548         goto param_error_exit;
549     }
550 
551     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
552     if (!spc->eeh_get_state) {
553         goto param_error_exit;
554     }
555 
556     ret = spc->eeh_get_state(sphb, &state);
557     rtas_st(rets, 0, ret);
558     if (ret != RTAS_OUT_SUCCESS) {
559         return;
560     }
561 
562     rtas_st(rets, 1, state);
563     rtas_st(rets, 2, RTAS_EEH_SUPPORT);
564     rtas_st(rets, 3, RTAS_EEH_PE_UNAVAIL_INFO);
565     if (nret >= 5) {
566         rtas_st(rets, 4, RTAS_EEH_PE_RECOVER_INFO);
567     }
568     return;
569 
570 param_error_exit:
571     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
572 }
573 
574 static void rtas_ibm_set_slot_reset(PowerPCCPU *cpu,
575                                     sPAPRMachineState *spapr,
576                                     uint32_t token, uint32_t nargs,
577                                     target_ulong args, uint32_t nret,
578                                     target_ulong rets)
579 {
580     sPAPRPHBState *sphb;
581     sPAPRPHBClass *spc;
582     uint32_t option;
583     uint64_t buid;
584     int ret;
585 
586     if ((nargs != 4) || (nret != 1)) {
587         goto param_error_exit;
588     }
589 
590     buid = rtas_ldq(args, 1);
591     option = rtas_ld(args, 3);
592     sphb = spapr_pci_find_phb(spapr, buid);
593     if (!sphb) {
594         goto param_error_exit;
595     }
596 
597     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
598     if (!spc->eeh_reset) {
599         goto param_error_exit;
600     }
601 
602     ret = spc->eeh_reset(sphb, option);
603     rtas_st(rets, 0, ret);
604     return;
605 
606 param_error_exit:
607     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
608 }
609 
610 static void rtas_ibm_configure_pe(PowerPCCPU *cpu,
611                                   sPAPRMachineState *spapr,
612                                   uint32_t token, uint32_t nargs,
613                                   target_ulong args, uint32_t nret,
614                                   target_ulong rets)
615 {
616     sPAPRPHBState *sphb;
617     sPAPRPHBClass *spc;
618     uint64_t buid;
619     int ret;
620 
621     if ((nargs != 3) || (nret != 1)) {
622         goto param_error_exit;
623     }
624 
625     buid = rtas_ldq(args, 1);
626     sphb = spapr_pci_find_phb(spapr, buid);
627     if (!sphb) {
628         goto param_error_exit;
629     }
630 
631     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
632     if (!spc->eeh_configure) {
633         goto param_error_exit;
634     }
635 
636     ret = spc->eeh_configure(sphb);
637     rtas_st(rets, 0, ret);
638     return;
639 
640 param_error_exit:
641     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
642 }
643 
644 /* To support it later */
645 static void rtas_ibm_slot_error_detail(PowerPCCPU *cpu,
646                                        sPAPRMachineState *spapr,
647                                        uint32_t token, uint32_t nargs,
648                                        target_ulong args, uint32_t nret,
649                                        target_ulong rets)
650 {
651     sPAPRPHBState *sphb;
652     sPAPRPHBClass *spc;
653     int option;
654     uint64_t buid;
655 
656     if ((nargs != 8) || (nret != 1)) {
657         goto param_error_exit;
658     }
659 
660     buid = rtas_ldq(args, 1);
661     sphb = spapr_pci_find_phb(spapr, buid);
662     if (!sphb) {
663         goto param_error_exit;
664     }
665 
666     spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);
667     if (!spc->eeh_set_option) {
668         goto param_error_exit;
669     }
670 
671     option = rtas_ld(args, 7);
672     switch (option) {
673     case RTAS_SLOT_TEMP_ERR_LOG:
674     case RTAS_SLOT_PERM_ERR_LOG:
675         break;
676     default:
677         goto param_error_exit;
678     }
679 
680     /* We don't have error log yet */
681     rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);
682     return;
683 
684 param_error_exit:
685     rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);
686 }
687 
688 static int pci_spapr_swizzle(int slot, int pin)
689 {
690     return (slot + pin) % PCI_NUM_PINS;
691 }
692 
693 static int pci_spapr_map_irq(PCIDevice *pci_dev, int irq_num)
694 {
695     /*
696      * Here we need to convert pci_dev + irq_num to some unique value
697      * which is less than number of IRQs on the specific bus (4).  We
698      * use standard PCI swizzling, that is (slot number + pin number)
699      * % 4.
700      */
701     return pci_spapr_swizzle(PCI_SLOT(pci_dev->devfn), irq_num);
702 }
703 
704 static void pci_spapr_set_irq(void *opaque, int irq_num, int level)
705 {
706     /*
707      * Here we use the number returned by pci_spapr_map_irq to find a
708      * corresponding qemu_irq.
709      */
710     sPAPRPHBState *phb = opaque;
711 
712     trace_spapr_pci_lsi_set(phb->dtbusname, irq_num, phb->lsi_table[irq_num].irq);
713     qemu_set_irq(spapr_phb_lsi_qirq(phb, irq_num), level);
714 }
715 
716 static PCIINTxRoute spapr_route_intx_pin_to_irq(void *opaque, int pin)
717 {
718     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(opaque);
719     PCIINTxRoute route;
720 
721     route.mode = PCI_INTX_ENABLED;
722     route.irq = sphb->lsi_table[pin].irq;
723 
724     return route;
725 }
726 
727 /*
728  * MSI/MSIX memory region implementation.
729  * The handler handles both MSI and MSIX.
730  * For MSI-X, the vector number is encoded as a part of the address,
731  * data is set to 0.
732  * For MSI, the vector number is encoded in least bits in data.
733  */
734 static void spapr_msi_write(void *opaque, hwaddr addr,
735                             uint64_t data, unsigned size)
736 {
737     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
738     uint32_t irq = data;
739 
740     trace_spapr_pci_msi_write(addr, data, irq);
741 
742     qemu_irq_pulse(xics_get_qirq(spapr->icp, irq));
743 }
744 
745 static const MemoryRegionOps spapr_msi_ops = {
746     /* There is no .read as the read result is undefined by PCI spec */
747     .read = NULL,
748     .write = spapr_msi_write,
749     .endianness = DEVICE_LITTLE_ENDIAN
750 };
751 
752 /*
753  * PHB PCI device
754  */
755 static AddressSpace *spapr_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn)
756 {
757     sPAPRPHBState *phb = opaque;
758 
759     return &phb->iommu_as;
760 }
761 
762 static char *spapr_phb_vfio_get_loc_code(sPAPRPHBState *sphb,  PCIDevice *pdev)
763 {
764     char *path = NULL, *buf = NULL, *host = NULL;
765 
766     /* Get the PCI VFIO host id */
767     host = object_property_get_str(OBJECT(pdev), "host", NULL);
768     if (!host) {
769         goto err_out;
770     }
771 
772     /* Construct the path of the file that will give us the DT location */
773     path = g_strdup_printf("/sys/bus/pci/devices/%s/devspec", host);
774     g_free(host);
775     if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {
776         goto err_out;
777     }
778     g_free(path);
779 
780     /* Construct and read from host device tree the loc-code */
781     path = g_strdup_printf("/proc/device-tree%s/ibm,loc-code", buf);
782     g_free(buf);
783     if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {
784         goto err_out;
785     }
786     return buf;
787 
788 err_out:
789     g_free(path);
790     return NULL;
791 }
792 
793 static char *spapr_phb_get_loc_code(sPAPRPHBState *sphb, PCIDevice *pdev)
794 {
795     char *buf;
796     const char *devtype = "qemu";
797     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
798 
799     if (object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {
800         buf = spapr_phb_vfio_get_loc_code(sphb, pdev);
801         if (buf) {
802             return buf;
803         }
804         devtype = "vfio";
805     }
806     /*
807      * For emulated devices and VFIO-failure case, make up
808      * the loc-code.
809      */
810     buf = g_strdup_printf("%s_%s:%04x:%02x:%02x.%x",
811                           devtype, pdev->name, sphb->index, busnr,
812                           PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
813     return buf;
814 }
815 
816 /* Macros to operate with address in OF binding to PCI */
817 #define b_x(x, p, l)    (((x) & ((1<<(l))-1)) << (p))
818 #define b_n(x)          b_x((x), 31, 1) /* 0 if relocatable */
819 #define b_p(x)          b_x((x), 30, 1) /* 1 if prefetchable */
820 #define b_t(x)          b_x((x), 29, 1) /* 1 if the address is aliased */
821 #define b_ss(x)         b_x((x), 24, 2) /* the space code */
822 #define b_bbbbbbbb(x)   b_x((x), 16, 8) /* bus number */
823 #define b_ddddd(x)      b_x((x), 11, 5) /* device number */
824 #define b_fff(x)        b_x((x), 8, 3)  /* function number */
825 #define b_rrrrrrrr(x)   b_x((x), 0, 8)  /* register number */
826 
827 /* for 'reg'/'assigned-addresses' OF properties */
828 #define RESOURCE_CELLS_SIZE 2
829 #define RESOURCE_CELLS_ADDRESS 3
830 
831 typedef struct ResourceFields {
832     uint32_t phys_hi;
833     uint32_t phys_mid;
834     uint32_t phys_lo;
835     uint32_t size_hi;
836     uint32_t size_lo;
837 } QEMU_PACKED ResourceFields;
838 
839 typedef struct ResourceProps {
840     ResourceFields reg[8];
841     ResourceFields assigned[7];
842     uint32_t reg_len;
843     uint32_t assigned_len;
844 } ResourceProps;
845 
846 /* fill in the 'reg'/'assigned-resources' OF properties for
847  * a PCI device. 'reg' describes resource requirements for a
848  * device's IO/MEM regions, 'assigned-addresses' describes the
849  * actual resource assignments.
850  *
851  * the properties are arrays of ('phys-addr', 'size') pairs describing
852  * the addressable regions of the PCI device, where 'phys-addr' is a
853  * RESOURCE_CELLS_ADDRESS-tuple of 32-bit integers corresponding to
854  * (phys.hi, phys.mid, phys.lo), and 'size' is a
855  * RESOURCE_CELLS_SIZE-tuple corresponding to (size.hi, size.lo).
856  *
857  * phys.hi = 0xYYXXXXZZ, where:
858  *   0xYY = npt000ss
859  *          |||   |
860  *          |||   +-- space code
861  *          |||               |
862  *          |||               +  00 if configuration space
863  *          |||               +  01 if IO region,
864  *          |||               +  10 if 32-bit MEM region
865  *          |||               +  11 if 64-bit MEM region
866  *          |||
867  *          ||+------ for non-relocatable IO: 1 if aliased
868  *          ||        for relocatable IO: 1 if below 64KB
869  *          ||        for MEM: 1 if below 1MB
870  *          |+------- 1 if region is prefetchable
871  *          +-------- 1 if region is non-relocatable
872  *   0xXXXX = bbbbbbbb dddddfff, encoding bus, slot, and function
873  *            bits respectively
874  *   0xZZ = rrrrrrrr, the register number of the BAR corresponding
875  *          to the region
876  *
877  * phys.mid and phys.lo correspond respectively to the hi/lo portions
878  * of the actual address of the region.
879  *
880  * how the phys-addr/size values are used differ slightly between
881  * 'reg' and 'assigned-addresses' properties. namely, 'reg' has
882  * an additional description for the config space region of the
883  * device, and in the case of QEMU has n=0 and phys.mid=phys.lo=0
884  * to describe the region as relocatable, with an address-mapping
885  * that corresponds directly to the PHB's address space for the
886  * resource. 'assigned-addresses' always has n=1 set with an absolute
887  * address assigned for the resource. in general, 'assigned-addresses'
888  * won't be populated, since addresses for PCI devices are generally
889  * unmapped initially and left to the guest to assign.
890  *
891  * note also that addresses defined in these properties are, at least
892  * for PAPR guests, relative to the PHBs IO/MEM windows, and
893  * correspond directly to the addresses in the BARs.
894  *
895  * in accordance with PCI Bus Binding to Open Firmware,
896  * IEEE Std 1275-1994, section 4.1.1, as implemented by PAPR+ v2.7,
897  * Appendix C.
898  */
899 static void populate_resource_props(PCIDevice *d, ResourceProps *rp)
900 {
901     int bus_num = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(d))));
902     uint32_t dev_id = (b_bbbbbbbb(bus_num) |
903                        b_ddddd(PCI_SLOT(d->devfn)) |
904                        b_fff(PCI_FUNC(d->devfn)));
905     ResourceFields *reg, *assigned;
906     int i, reg_idx = 0, assigned_idx = 0;
907 
908     /* config space region */
909     reg = &rp->reg[reg_idx++];
910     reg->phys_hi = cpu_to_be32(dev_id);
911     reg->phys_mid = 0;
912     reg->phys_lo = 0;
913     reg->size_hi = 0;
914     reg->size_lo = 0;
915 
916     for (i = 0; i < PCI_NUM_REGIONS; i++) {
917         if (!d->io_regions[i].size) {
918             continue;
919         }
920 
921         reg = &rp->reg[reg_idx++];
922 
923         reg->phys_hi = cpu_to_be32(dev_id | b_rrrrrrrr(pci_bar(d, i)));
924         if (d->io_regions[i].type & PCI_BASE_ADDRESS_SPACE_IO) {
925             reg->phys_hi |= cpu_to_be32(b_ss(1));
926         } else if (d->io_regions[i].type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
927             reg->phys_hi |= cpu_to_be32(b_ss(3));
928         } else {
929             reg->phys_hi |= cpu_to_be32(b_ss(2));
930         }
931         reg->phys_mid = 0;
932         reg->phys_lo = 0;
933         reg->size_hi = cpu_to_be32(d->io_regions[i].size >> 32);
934         reg->size_lo = cpu_to_be32(d->io_regions[i].size);
935 
936         if (d->io_regions[i].addr == PCI_BAR_UNMAPPED) {
937             continue;
938         }
939 
940         assigned = &rp->assigned[assigned_idx++];
941         assigned->phys_hi = cpu_to_be32(reg->phys_hi | b_n(1));
942         assigned->phys_mid = cpu_to_be32(d->io_regions[i].addr >> 32);
943         assigned->phys_lo = cpu_to_be32(d->io_regions[i].addr);
944         assigned->size_hi = reg->size_hi;
945         assigned->size_lo = reg->size_lo;
946     }
947 
948     rp->reg_len = reg_idx * sizeof(ResourceFields);
949     rp->assigned_len = assigned_idx * sizeof(ResourceFields);
950 }
951 
952 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
953                                             PCIDevice *pdev);
954 
955 static int spapr_populate_pci_child_dt(PCIDevice *dev, void *fdt, int offset,
956                                        sPAPRPHBState *sphb)
957 {
958     ResourceProps rp;
959     bool is_bridge = false;
960     int pci_status, err;
961     char *buf = NULL;
962     uint32_t drc_index = spapr_phb_get_pci_drc_index(sphb, dev);
963     uint32_t max_msi, max_msix;
964 
965     if (pci_default_read_config(dev, PCI_HEADER_TYPE, 1) ==
966         PCI_HEADER_TYPE_BRIDGE) {
967         is_bridge = true;
968     }
969 
970     /* in accordance with PAPR+ v2.7 13.6.3, Table 181 */
971     _FDT(fdt_setprop_cell(fdt, offset, "vendor-id",
972                           pci_default_read_config(dev, PCI_VENDOR_ID, 2)));
973     _FDT(fdt_setprop_cell(fdt, offset, "device-id",
974                           pci_default_read_config(dev, PCI_DEVICE_ID, 2)));
975     _FDT(fdt_setprop_cell(fdt, offset, "revision-id",
976                           pci_default_read_config(dev, PCI_REVISION_ID, 1)));
977     _FDT(fdt_setprop_cell(fdt, offset, "class-code",
978                           pci_default_read_config(dev, PCI_CLASS_PROG, 3)));
979     if (pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)) {
980         _FDT(fdt_setprop_cell(fdt, offset, "interrupts",
981                  pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)));
982     }
983 
984     if (!is_bridge) {
985         _FDT(fdt_setprop_cell(fdt, offset, "min-grant",
986             pci_default_read_config(dev, PCI_MIN_GNT, 1)));
987         _FDT(fdt_setprop_cell(fdt, offset, "max-latency",
988             pci_default_read_config(dev, PCI_MAX_LAT, 1)));
989     }
990 
991     if (pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)) {
992         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-id",
993                  pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)));
994     }
995 
996     if (pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)) {
997         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-vendor-id",
998                  pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)));
999     }
1000 
1001     _FDT(fdt_setprop_cell(fdt, offset, "cache-line-size",
1002         pci_default_read_config(dev, PCI_CACHE_LINE_SIZE, 1)));
1003 
1004     /* the following fdt cells are masked off the pci status register */
1005     pci_status = pci_default_read_config(dev, PCI_STATUS, 2);
1006     _FDT(fdt_setprop_cell(fdt, offset, "devsel-speed",
1007                           PCI_STATUS_DEVSEL_MASK & pci_status));
1008 
1009     if (pci_status & PCI_STATUS_FAST_BACK) {
1010         _FDT(fdt_setprop(fdt, offset, "fast-back-to-back", NULL, 0));
1011     }
1012     if (pci_status & PCI_STATUS_66MHZ) {
1013         _FDT(fdt_setprop(fdt, offset, "66mhz-capable", NULL, 0));
1014     }
1015     if (pci_status & PCI_STATUS_UDF) {
1016         _FDT(fdt_setprop(fdt, offset, "udf-supported", NULL, 0));
1017     }
1018 
1019     /* NOTE: this is normally generated by firmware via path/unit name,
1020      * but in our case we must set it manually since it does not get
1021      * processed by OF beforehand
1022      */
1023     _FDT(fdt_setprop_string(fdt, offset, "name", "pci"));
1024     buf = spapr_phb_get_loc_code(sphb, dev);
1025     if (!buf) {
1026         error_report("Failed setting the ibm,loc-code");
1027         return -1;
1028     }
1029 
1030     err = fdt_setprop_string(fdt, offset, "ibm,loc-code", buf);
1031     g_free(buf);
1032     if (err < 0) {
1033         return err;
1034     }
1035 
1036     if (drc_index) {
1037         _FDT(fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index));
1038     }
1039 
1040     _FDT(fdt_setprop_cell(fdt, offset, "#address-cells",
1041                           RESOURCE_CELLS_ADDRESS));
1042     _FDT(fdt_setprop_cell(fdt, offset, "#size-cells",
1043                           RESOURCE_CELLS_SIZE));
1044 
1045     max_msi = msi_nr_vectors_allocated(dev);
1046     if (max_msi) {
1047         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi", max_msi));
1048     }
1049     max_msix = dev->msix_entries_nr;
1050     if (max_msix) {
1051         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi-x", max_msix));
1052     }
1053 
1054     populate_resource_props(dev, &rp);
1055     _FDT(fdt_setprop(fdt, offset, "reg", (uint8_t *)rp.reg, rp.reg_len));
1056     _FDT(fdt_setprop(fdt, offset, "assigned-addresses",
1057                      (uint8_t *)rp.assigned, rp.assigned_len));
1058 
1059     return 0;
1060 }
1061 
1062 /* create OF node for pci device and required OF DT properties */
1063 static int spapr_create_pci_child_dt(sPAPRPHBState *phb, PCIDevice *dev,
1064                                      void *fdt, int node_offset)
1065 {
1066     int offset, ret;
1067     int slot = PCI_SLOT(dev->devfn);
1068     int func = PCI_FUNC(dev->devfn);
1069     char nodename[FDT_NAME_MAX];
1070 
1071     if (func != 0) {
1072         snprintf(nodename, FDT_NAME_MAX, "pci@%x,%x", slot, func);
1073     } else {
1074         snprintf(nodename, FDT_NAME_MAX, "pci@%x", slot);
1075     }
1076     offset = fdt_add_subnode(fdt, node_offset, nodename);
1077     ret = spapr_populate_pci_child_dt(dev, fdt, offset, phb);
1078 
1079     g_assert(!ret);
1080     if (ret) {
1081         return 0;
1082     }
1083     return offset;
1084 }
1085 
1086 static void spapr_phb_add_pci_device(sPAPRDRConnector *drc,
1087                                      sPAPRPHBState *phb,
1088                                      PCIDevice *pdev,
1089                                      Error **errp)
1090 {
1091     sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1092     DeviceState *dev = DEVICE(pdev);
1093     void *fdt = NULL;
1094     int fdt_start_offset = 0, fdt_size;
1095 
1096     if (object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {
1097         sPAPRTCETable *tcet = spapr_tce_find_by_liobn(phb->dma_liobn);
1098 
1099         spapr_tce_set_need_vfio(tcet, true);
1100     }
1101 
1102     if (dev->hotplugged) {
1103         fdt = create_device_tree(&fdt_size);
1104         fdt_start_offset = spapr_create_pci_child_dt(phb, pdev, fdt, 0);
1105         if (!fdt_start_offset) {
1106             error_setg(errp, "Failed to create pci child device tree node");
1107             goto out;
1108         }
1109     }
1110 
1111     drck->attach(drc, DEVICE(pdev),
1112                  fdt, fdt_start_offset, !dev->hotplugged, errp);
1113 out:
1114     if (*errp) {
1115         g_free(fdt);
1116     }
1117 }
1118 
1119 static void spapr_phb_remove_pci_device_cb(DeviceState *dev, void *opaque)
1120 {
1121     /* some version guests do not wait for completion of a device
1122      * cleanup (generally done asynchronously by the kernel) before
1123      * signaling to QEMU that the device is safe, but instead sleep
1124      * for some 'safe' period of time. unfortunately on a busy host
1125      * this sleep isn't guaranteed to be long enough, resulting in
1126      * bad things like IRQ lines being left asserted during final
1127      * device removal. to deal with this we call reset just prior
1128      * to finalizing the device, which will put the device back into
1129      * an 'idle' state, as the device cleanup code expects.
1130      */
1131     pci_device_reset(PCI_DEVICE(dev));
1132     object_unparent(OBJECT(dev));
1133 }
1134 
1135 static void spapr_phb_remove_pci_device(sPAPRDRConnector *drc,
1136                                         sPAPRPHBState *phb,
1137                                         PCIDevice *pdev,
1138                                         Error **errp)
1139 {
1140     sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1141 
1142     drck->detach(drc, DEVICE(pdev), spapr_phb_remove_pci_device_cb, phb, errp);
1143 }
1144 
1145 static sPAPRDRConnector *spapr_phb_get_pci_func_drc(sPAPRPHBState *phb,
1146                                                     uint32_t busnr,
1147                                                     int32_t devfn)
1148 {
1149     return spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_PCI,
1150                                     (phb->index << 16) |
1151                                     (busnr << 8) |
1152                                     devfn);
1153 }
1154 
1155 static sPAPRDRConnector *spapr_phb_get_pci_drc(sPAPRPHBState *phb,
1156                                                PCIDevice *pdev)
1157 {
1158     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
1159     return spapr_phb_get_pci_func_drc(phb, busnr, pdev->devfn);
1160 }
1161 
1162 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
1163                                             PCIDevice *pdev)
1164 {
1165     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1166     sPAPRDRConnectorClass *drck;
1167 
1168     if (!drc) {
1169         return 0;
1170     }
1171 
1172     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1173     return drck->get_index(drc);
1174 }
1175 
1176 static void spapr_phb_hot_plug_child(HotplugHandler *plug_handler,
1177                                      DeviceState *plugged_dev, Error **errp)
1178 {
1179     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1180     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1181     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1182     Error *local_err = NULL;
1183     PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1184     uint32_t slotnr = PCI_SLOT(pdev->devfn);
1185 
1186     /* if DR is disabled we don't need to do anything in the case of
1187      * hotplug or coldplug callbacks
1188      */
1189     if (!phb->dr_enabled) {
1190         /* if this is a hotplug operation initiated by the user
1191          * we need to let them know it's not enabled
1192          */
1193         if (plugged_dev->hotplugged) {
1194             error_setg(errp, QERR_BUS_NO_HOTPLUG,
1195                        object_get_typename(OBJECT(phb)));
1196         }
1197         return;
1198     }
1199 
1200     g_assert(drc);
1201 
1202     /* Following the QEMU convention used for PCIe multifunction
1203      * hotplug, we do not allow functions to be hotplugged to a
1204      * slot that already has function 0 present
1205      */
1206     if (plugged_dev->hotplugged && bus->devices[PCI_DEVFN(slotnr, 0)] &&
1207         PCI_FUNC(pdev->devfn) != 0) {
1208         error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
1209                    " additional functions can no longer be exposed to guest.",
1210                    slotnr, bus->devices[PCI_DEVFN(slotnr, 0)]->name);
1211         return;
1212     }
1213 
1214     spapr_phb_add_pci_device(drc, phb, pdev, &local_err);
1215     if (local_err) {
1216         error_propagate(errp, local_err);
1217         return;
1218     }
1219 
1220     /* If this is function 0, signal hotplug for all the device functions.
1221      * Otherwise defer sending the hotplug event.
1222      */
1223     if (plugged_dev->hotplugged && PCI_FUNC(pdev->devfn) == 0) {
1224         int i;
1225 
1226         for (i = 0; i < 8; i++) {
1227             sPAPRDRConnector *func_drc;
1228             sPAPRDRConnectorClass *func_drck;
1229             sPAPRDREntitySense state;
1230 
1231             func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1232                                                   PCI_DEVFN(slotnr, i));
1233             func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1234             func_drck->entity_sense(func_drc, &state);
1235 
1236             if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1237                 spapr_hotplug_req_add_by_index(func_drc);
1238             }
1239         }
1240     }
1241 }
1242 
1243 static void spapr_phb_hot_unplug_child(HotplugHandler *plug_handler,
1244                                        DeviceState *plugged_dev, Error **errp)
1245 {
1246     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1247     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1248     sPAPRDRConnectorClass *drck;
1249     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1250     Error *local_err = NULL;
1251 
1252     if (!phb->dr_enabled) {
1253         error_setg(errp, QERR_BUS_NO_HOTPLUG,
1254                    object_get_typename(OBJECT(phb)));
1255         return;
1256     }
1257 
1258     g_assert(drc);
1259 
1260     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1261     if (!drck->release_pending(drc)) {
1262         PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1263         uint32_t slotnr = PCI_SLOT(pdev->devfn);
1264         sPAPRDRConnector *func_drc;
1265         sPAPRDRConnectorClass *func_drck;
1266         sPAPRDREntitySense state;
1267         int i;
1268 
1269         /* ensure any other present functions are pending unplug */
1270         if (PCI_FUNC(pdev->devfn) == 0) {
1271             for (i = 1; i < 8; i++) {
1272                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1273                                                       PCI_DEVFN(slotnr, i));
1274                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1275                 func_drck->entity_sense(func_drc, &state);
1276                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT
1277                     && !func_drck->release_pending(func_drc)) {
1278                     error_setg(errp,
1279                                "PCI: slot %d, function %d still present. "
1280                                "Must unplug all non-0 functions first.",
1281                                slotnr, i);
1282                     return;
1283                 }
1284             }
1285         }
1286 
1287         spapr_phb_remove_pci_device(drc, phb, pdev, &local_err);
1288         if (local_err) {
1289             error_propagate(errp, local_err);
1290             return;
1291         }
1292 
1293         /* if this isn't func 0, defer unplug event. otherwise signal removal
1294          * for all present functions
1295          */
1296         if (PCI_FUNC(pdev->devfn) == 0) {
1297             for (i = 7; i >= 0; i--) {
1298                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1299                                                       PCI_DEVFN(slotnr, i));
1300                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1301                 func_drck->entity_sense(func_drc, &state);
1302                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1303                     spapr_hotplug_req_remove_by_index(func_drc);
1304                 }
1305             }
1306         }
1307     }
1308 }
1309 
1310 static void spapr_phb_realize(DeviceState *dev, Error **errp)
1311 {
1312     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1313     SysBusDevice *s = SYS_BUS_DEVICE(dev);
1314     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
1315     PCIHostState *phb = PCI_HOST_BRIDGE(s);
1316     sPAPRPHBClass *info = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(s);
1317     char *namebuf;
1318     int i;
1319     PCIBus *bus;
1320     uint64_t msi_window_size = 4096;
1321 
1322     if (sphb->index != (uint32_t)-1) {
1323         hwaddr windows_base;
1324 
1325         if ((sphb->buid != (uint64_t)-1) || (sphb->dma_liobn != (uint32_t)-1)
1326             || (sphb->mem_win_addr != (hwaddr)-1)
1327             || (sphb->io_win_addr != (hwaddr)-1)) {
1328             error_setg(errp, "Either \"index\" or other parameters must"
1329                        " be specified for PAPR PHB, not both");
1330             return;
1331         }
1332 
1333         if (sphb->index > SPAPR_PCI_MAX_INDEX) {
1334             error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",
1335                        SPAPR_PCI_MAX_INDEX);
1336             return;
1337         }
1338 
1339         sphb->buid = SPAPR_PCI_BASE_BUID + sphb->index;
1340         sphb->dma_liobn = SPAPR_PCI_LIOBN(sphb->index, 0);
1341 
1342         windows_base = SPAPR_PCI_WINDOW_BASE
1343             + sphb->index * SPAPR_PCI_WINDOW_SPACING;
1344         sphb->mem_win_addr = windows_base + SPAPR_PCI_MMIO_WIN_OFF;
1345         sphb->io_win_addr = windows_base + SPAPR_PCI_IO_WIN_OFF;
1346     }
1347 
1348     if (sphb->buid == (uint64_t)-1) {
1349         error_setg(errp, "BUID not specified for PHB");
1350         return;
1351     }
1352 
1353     if (sphb->dma_liobn == (uint32_t)-1) {
1354         error_setg(errp, "LIOBN not specified for PHB");
1355         return;
1356     }
1357 
1358     if (sphb->mem_win_addr == (hwaddr)-1) {
1359         error_setg(errp, "Memory window address not specified for PHB");
1360         return;
1361     }
1362 
1363     if (sphb->io_win_addr == (hwaddr)-1) {
1364         error_setg(errp, "IO window address not specified for PHB");
1365         return;
1366     }
1367 
1368     if (spapr_pci_find_phb(spapr, sphb->buid)) {
1369         error_setg(errp, "PCI host bridges must have unique BUIDs");
1370         return;
1371     }
1372 
1373     sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);
1374 
1375     namebuf = alloca(strlen(sphb->dtbusname) + 32);
1376 
1377     /* Initialize memory regions */
1378     sprintf(namebuf, "%s.mmio", sphb->dtbusname);
1379     memory_region_init(&sphb->memspace, OBJECT(sphb), namebuf, UINT64_MAX);
1380 
1381     sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);
1382     memory_region_init_alias(&sphb->memwindow, OBJECT(sphb),
1383                              namebuf, &sphb->memspace,
1384                              SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);
1385     memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,
1386                                 &sphb->memwindow);
1387 
1388     /* Initialize IO regions */
1389     sprintf(namebuf, "%s.io", sphb->dtbusname);
1390     memory_region_init(&sphb->iospace, OBJECT(sphb),
1391                        namebuf, SPAPR_PCI_IO_WIN_SIZE);
1392 
1393     sprintf(namebuf, "%s.io-alias", sphb->dtbusname);
1394     memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf,
1395                              &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE);
1396     memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,
1397                                 &sphb->iowindow);
1398 
1399     bus = pci_register_bus(dev, NULL,
1400                            pci_spapr_set_irq, pci_spapr_map_irq, sphb,
1401                            &sphb->memspace, &sphb->iospace,
1402                            PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS);
1403     phb->bus = bus;
1404     qbus_set_hotplug_handler(BUS(phb->bus), DEVICE(sphb), NULL);
1405 
1406     /*
1407      * Initialize PHB address space.
1408      * By default there will be at least one subregion for default
1409      * 32bit DMA window.
1410      * Later the guest might want to create another DMA window
1411      * which will become another memory subregion.
1412      */
1413     sprintf(namebuf, "%s.iommu-root", sphb->dtbusname);
1414 
1415     memory_region_init(&sphb->iommu_root, OBJECT(sphb),
1416                        namebuf, UINT64_MAX);
1417     address_space_init(&sphb->iommu_as, &sphb->iommu_root,
1418                        sphb->dtbusname);
1419 
1420     /*
1421      * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,
1422      * we need to allocate some memory to catch those writes coming
1423      * from msi_notify()/msix_notify().
1424      * As MSIMessage:addr is going to be the same and MSIMessage:data
1425      * is going to be a VIRQ number, 4 bytes of the MSI MR will only
1426      * be used.
1427      *
1428      * For KVM we want to ensure that this memory is a full page so that
1429      * our memory slot is of page size granularity.
1430      */
1431 #ifdef CONFIG_KVM
1432     if (kvm_enabled()) {
1433         msi_window_size = getpagesize();
1434     }
1435 #endif
1436 
1437     memory_region_init_io(&sphb->msiwindow, NULL, &spapr_msi_ops, spapr,
1438                           "msi", msi_window_size);
1439     memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW,
1440                                 &sphb->msiwindow);
1441 
1442     pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb);
1443 
1444     pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq);
1445 
1446     QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);
1447 
1448     /* Initialize the LSI table */
1449     for (i = 0; i < PCI_NUM_PINS; i++) {
1450         uint32_t irq;
1451         Error *local_err = NULL;
1452 
1453         irq = xics_alloc_block(spapr->icp, 0, 1, true, false, &local_err);
1454         if (local_err) {
1455             error_propagate(errp, local_err);
1456             error_prepend(errp, "can't allocate LSIs: ");
1457             return;
1458         }
1459 
1460         sphb->lsi_table[i].irq = irq;
1461     }
1462 
1463     /* allocate connectors for child PCI devices */
1464     if (sphb->dr_enabled) {
1465         for (i = 0; i < PCI_SLOT_MAX * 8; i++) {
1466             spapr_dr_connector_new(OBJECT(phb),
1467                                    SPAPR_DR_CONNECTOR_TYPE_PCI,
1468                                    (sphb->index << 16) | i);
1469         }
1470     }
1471 
1472     if (!info->finish_realize) {
1473         error_setg(errp, "finish_realize not defined");
1474         return;
1475     }
1476 
1477     info->finish_realize(sphb, errp);
1478 
1479     sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);
1480 }
1481 
1482 static void spapr_phb_finish_realize(sPAPRPHBState *sphb, Error **errp)
1483 {
1484     sPAPRTCETable *tcet;
1485     uint32_t nb_table;
1486 
1487     nb_table = sphb->dma_win_size >> SPAPR_TCE_PAGE_SHIFT;
1488     tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn,
1489                                0, SPAPR_TCE_PAGE_SHIFT, nb_table, false);
1490     if (!tcet) {
1491         error_setg(errp, "Unable to create TCE table for %s",
1492                    sphb->dtbusname);
1493         return ;
1494     }
1495 
1496     /* Register default 32bit DMA window */
1497     memory_region_add_subregion(&sphb->iommu_root, sphb->dma_win_addr,
1498                                 spapr_tce_get_iommu(tcet));
1499 }
1500 
1501 static int spapr_phb_children_reset(Object *child, void *opaque)
1502 {
1503     DeviceState *dev = (DeviceState *) object_dynamic_cast(child, TYPE_DEVICE);
1504 
1505     if (dev) {
1506         device_reset(dev);
1507     }
1508 
1509     return 0;
1510 }
1511 
1512 static void spapr_phb_reset(DeviceState *qdev)
1513 {
1514     /* Reset the IOMMU state */
1515     object_child_foreach(OBJECT(qdev), spapr_phb_children_reset, NULL);
1516 }
1517 
1518 static Property spapr_phb_properties[] = {
1519     DEFINE_PROP_UINT32("index", sPAPRPHBState, index, -1),
1520     DEFINE_PROP_UINT64("buid", sPAPRPHBState, buid, -1),
1521     DEFINE_PROP_UINT32("liobn", sPAPRPHBState, dma_liobn, -1),
1522     DEFINE_PROP_UINT64("mem_win_addr", sPAPRPHBState, mem_win_addr, -1),
1523     DEFINE_PROP_UINT64("mem_win_size", sPAPRPHBState, mem_win_size,
1524                        SPAPR_PCI_MMIO_WIN_SIZE),
1525     DEFINE_PROP_UINT64("io_win_addr", sPAPRPHBState, io_win_addr, -1),
1526     DEFINE_PROP_UINT64("io_win_size", sPAPRPHBState, io_win_size,
1527                        SPAPR_PCI_IO_WIN_SIZE),
1528     DEFINE_PROP_BOOL("dynamic-reconfiguration", sPAPRPHBState, dr_enabled,
1529                      true),
1530     /* Default DMA window is 0..1GB */
1531     DEFINE_PROP_UINT64("dma_win_addr", sPAPRPHBState, dma_win_addr, 0),
1532     DEFINE_PROP_UINT64("dma_win_size", sPAPRPHBState, dma_win_size, 0x40000000),
1533     DEFINE_PROP_END_OF_LIST(),
1534 };
1535 
1536 static const VMStateDescription vmstate_spapr_pci_lsi = {
1537     .name = "spapr_pci/lsi",
1538     .version_id = 1,
1539     .minimum_version_id = 1,
1540     .fields = (VMStateField[]) {
1541         VMSTATE_UINT32_EQUAL(irq, struct spapr_pci_lsi),
1542 
1543         VMSTATE_END_OF_LIST()
1544     },
1545 };
1546 
1547 static const VMStateDescription vmstate_spapr_pci_msi = {
1548     .name = "spapr_pci/msi",
1549     .version_id = 1,
1550     .minimum_version_id = 1,
1551     .fields = (VMStateField []) {
1552         VMSTATE_UINT32(key, spapr_pci_msi_mig),
1553         VMSTATE_UINT32(value.first_irq, spapr_pci_msi_mig),
1554         VMSTATE_UINT32(value.num, spapr_pci_msi_mig),
1555         VMSTATE_END_OF_LIST()
1556     },
1557 };
1558 
1559 static void spapr_pci_pre_save(void *opaque)
1560 {
1561     sPAPRPHBState *sphb = opaque;
1562     GHashTableIter iter;
1563     gpointer key, value;
1564     int i;
1565 
1566     g_free(sphb->msi_devs);
1567     sphb->msi_devs = NULL;
1568     sphb->msi_devs_num = g_hash_table_size(sphb->msi);
1569     if (!sphb->msi_devs_num) {
1570         return;
1571     }
1572     sphb->msi_devs = g_malloc(sphb->msi_devs_num * sizeof(spapr_pci_msi_mig));
1573 
1574     g_hash_table_iter_init(&iter, sphb->msi);
1575     for (i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
1576         sphb->msi_devs[i].key = *(uint32_t *) key;
1577         sphb->msi_devs[i].value = *(spapr_pci_msi *) value;
1578     }
1579 }
1580 
1581 static int spapr_pci_post_load(void *opaque, int version_id)
1582 {
1583     sPAPRPHBState *sphb = opaque;
1584     gpointer key, value;
1585     int i;
1586 
1587     for (i = 0; i < sphb->msi_devs_num; ++i) {
1588         key = g_memdup(&sphb->msi_devs[i].key,
1589                        sizeof(sphb->msi_devs[i].key));
1590         value = g_memdup(&sphb->msi_devs[i].value,
1591                          sizeof(sphb->msi_devs[i].value));
1592         g_hash_table_insert(sphb->msi, key, value);
1593     }
1594     g_free(sphb->msi_devs);
1595     sphb->msi_devs = NULL;
1596     sphb->msi_devs_num = 0;
1597 
1598     return 0;
1599 }
1600 
1601 static const VMStateDescription vmstate_spapr_pci = {
1602     .name = "spapr_pci",
1603     .version_id = 2,
1604     .minimum_version_id = 2,
1605     .pre_save = spapr_pci_pre_save,
1606     .post_load = spapr_pci_post_load,
1607     .fields = (VMStateField[]) {
1608         VMSTATE_UINT64_EQUAL(buid, sPAPRPHBState),
1609         VMSTATE_UINT32_EQUAL(dma_liobn, sPAPRPHBState),
1610         VMSTATE_UINT64_EQUAL(mem_win_addr, sPAPRPHBState),
1611         VMSTATE_UINT64_EQUAL(mem_win_size, sPAPRPHBState),
1612         VMSTATE_UINT64_EQUAL(io_win_addr, sPAPRPHBState),
1613         VMSTATE_UINT64_EQUAL(io_win_size, sPAPRPHBState),
1614         VMSTATE_STRUCT_ARRAY(lsi_table, sPAPRPHBState, PCI_NUM_PINS, 0,
1615                              vmstate_spapr_pci_lsi, struct spapr_pci_lsi),
1616         VMSTATE_INT32(msi_devs_num, sPAPRPHBState),
1617         VMSTATE_STRUCT_VARRAY_ALLOC(msi_devs, sPAPRPHBState, msi_devs_num, 0,
1618                                     vmstate_spapr_pci_msi, spapr_pci_msi_mig),
1619         VMSTATE_END_OF_LIST()
1620     },
1621 };
1622 
1623 static const char *spapr_phb_root_bus_path(PCIHostState *host_bridge,
1624                                            PCIBus *rootbus)
1625 {
1626     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(host_bridge);
1627 
1628     return sphb->dtbusname;
1629 }
1630 
1631 static void spapr_phb_class_init(ObjectClass *klass, void *data)
1632 {
1633     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);
1634     DeviceClass *dc = DEVICE_CLASS(klass);
1635     sPAPRPHBClass *spc = SPAPR_PCI_HOST_BRIDGE_CLASS(klass);
1636     HotplugHandlerClass *hp = HOTPLUG_HANDLER_CLASS(klass);
1637 
1638     hc->root_bus_path = spapr_phb_root_bus_path;
1639     dc->realize = spapr_phb_realize;
1640     dc->props = spapr_phb_properties;
1641     dc->reset = spapr_phb_reset;
1642     dc->vmsd = &vmstate_spapr_pci;
1643     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1644     dc->cannot_instantiate_with_device_add_yet = false;
1645     spc->finish_realize = spapr_phb_finish_realize;
1646     hp->plug = spapr_phb_hot_plug_child;
1647     hp->unplug = spapr_phb_hot_unplug_child;
1648 }
1649 
1650 static const TypeInfo spapr_phb_info = {
1651     .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
1652     .parent        = TYPE_PCI_HOST_BRIDGE,
1653     .instance_size = sizeof(sPAPRPHBState),
1654     .class_init    = spapr_phb_class_init,
1655     .class_size    = sizeof(sPAPRPHBClass),
1656     .interfaces    = (InterfaceInfo[]) {
1657         { TYPE_HOTPLUG_HANDLER },
1658         { }
1659     }
1660 };
1661 
1662 PCIHostState *spapr_create_phb(sPAPRMachineState *spapr, int index)
1663 {
1664     DeviceState *dev;
1665 
1666     dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
1667     qdev_prop_set_uint32(dev, "index", index);
1668     qdev_init_nofail(dev);
1669 
1670     return PCI_HOST_BRIDGE(dev);
1671 }
1672 
1673 typedef struct sPAPRFDT {
1674     void *fdt;
1675     int node_off;
1676     sPAPRPHBState *sphb;
1677 } sPAPRFDT;
1678 
1679 static void spapr_populate_pci_devices_dt(PCIBus *bus, PCIDevice *pdev,
1680                                           void *opaque)
1681 {
1682     PCIBus *sec_bus;
1683     sPAPRFDT *p = opaque;
1684     int offset;
1685     sPAPRFDT s_fdt;
1686 
1687     offset = spapr_create_pci_child_dt(p->sphb, pdev, p->fdt, p->node_off);
1688     if (!offset) {
1689         error_report("Failed to create pci child device tree node");
1690         return;
1691     }
1692 
1693     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1694          PCI_HEADER_TYPE_BRIDGE)) {
1695         return;
1696     }
1697 
1698     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1699     if (!sec_bus) {
1700         return;
1701     }
1702 
1703     s_fdt.fdt = p->fdt;
1704     s_fdt.node_off = offset;
1705     s_fdt.sphb = p->sphb;
1706     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1707                         spapr_populate_pci_devices_dt,
1708                         &s_fdt);
1709 }
1710 
1711 static void spapr_phb_pci_enumerate_bridge(PCIBus *bus, PCIDevice *pdev,
1712                                            void *opaque)
1713 {
1714     unsigned int *bus_no = opaque;
1715     unsigned int primary = *bus_no;
1716     unsigned int subordinate = 0xff;
1717     PCIBus *sec_bus = NULL;
1718 
1719     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1720          PCI_HEADER_TYPE_BRIDGE)) {
1721         return;
1722     }
1723 
1724     (*bus_no)++;
1725     pci_default_write_config(pdev, PCI_PRIMARY_BUS, primary, 1);
1726     pci_default_write_config(pdev, PCI_SECONDARY_BUS, *bus_no, 1);
1727     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1728 
1729     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1730     if (!sec_bus) {
1731         return;
1732     }
1733 
1734     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, subordinate, 1);
1735     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1736                         spapr_phb_pci_enumerate_bridge, bus_no);
1737     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1738 }
1739 
1740 static void spapr_phb_pci_enumerate(sPAPRPHBState *phb)
1741 {
1742     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1743     unsigned int bus_no = 0;
1744 
1745     pci_for_each_device(bus, pci_bus_num(bus),
1746                         spapr_phb_pci_enumerate_bridge,
1747                         &bus_no);
1748 
1749 }
1750 
1751 int spapr_populate_pci_dt(sPAPRPHBState *phb,
1752                           uint32_t xics_phandle,
1753                           void *fdt)
1754 {
1755     int bus_off, i, j, ret;
1756     char nodename[FDT_NAME_MAX];
1757     uint32_t bus_range[] = { cpu_to_be32(0), cpu_to_be32(0xff) };
1758     const uint64_t mmiosize = memory_region_size(&phb->memwindow);
1759     const uint64_t w32max = (1ULL << 32) - SPAPR_PCI_MEM_WIN_BUS_OFFSET;
1760     const uint64_t w32size = MIN(w32max, mmiosize);
1761     const uint64_t w64size = (mmiosize > w32size) ? (mmiosize - w32size) : 0;
1762     struct {
1763         uint32_t hi;
1764         uint64_t child;
1765         uint64_t parent;
1766         uint64_t size;
1767     } QEMU_PACKED ranges[] = {
1768         {
1769             cpu_to_be32(b_ss(1)), cpu_to_be64(0),
1770             cpu_to_be64(phb->io_win_addr),
1771             cpu_to_be64(memory_region_size(&phb->iospace)),
1772         },
1773         {
1774             cpu_to_be32(b_ss(2)), cpu_to_be64(SPAPR_PCI_MEM_WIN_BUS_OFFSET),
1775             cpu_to_be64(phb->mem_win_addr),
1776             cpu_to_be64(w32size),
1777         },
1778         {
1779             cpu_to_be32(b_ss(3)), cpu_to_be64(1ULL << 32),
1780             cpu_to_be64(phb->mem_win_addr + w32size),
1781             cpu_to_be64(w64size)
1782         },
1783     };
1784     const unsigned sizeof_ranges = (w64size ? 3 : 2) * sizeof(ranges[0]);
1785     uint64_t bus_reg[] = { cpu_to_be64(phb->buid), 0 };
1786     uint32_t interrupt_map_mask[] = {
1787         cpu_to_be32(b_ddddd(-1)|b_fff(0)), 0x0, 0x0, cpu_to_be32(-1)};
1788     uint32_t interrupt_map[PCI_SLOT_MAX * PCI_NUM_PINS][7];
1789     sPAPRTCETable *tcet;
1790     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1791     sPAPRFDT s_fdt;
1792 
1793     /* Start populating the FDT */
1794     snprintf(nodename, FDT_NAME_MAX, "pci@%" PRIx64, phb->buid);
1795     bus_off = fdt_add_subnode(fdt, 0, nodename);
1796     if (bus_off < 0) {
1797         return bus_off;
1798     }
1799 
1800     /* Write PHB properties */
1801     _FDT(fdt_setprop_string(fdt, bus_off, "device_type", "pci"));
1802     _FDT(fdt_setprop_string(fdt, bus_off, "compatible", "IBM,Logical_PHB"));
1803     _FDT(fdt_setprop_cell(fdt, bus_off, "#address-cells", 0x3));
1804     _FDT(fdt_setprop_cell(fdt, bus_off, "#size-cells", 0x2));
1805     _FDT(fdt_setprop_cell(fdt, bus_off, "#interrupt-cells", 0x1));
1806     _FDT(fdt_setprop(fdt, bus_off, "used-by-rtas", NULL, 0));
1807     _FDT(fdt_setprop(fdt, bus_off, "bus-range", &bus_range, sizeof(bus_range)));
1808     _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof_ranges));
1809     _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg)));
1810     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1));
1811     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS));
1812 
1813     /* Build the interrupt-map, this must matches what is done
1814      * in pci_spapr_map_irq
1815      */
1816     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map-mask",
1817                      &interrupt_map_mask, sizeof(interrupt_map_mask)));
1818     for (i = 0; i < PCI_SLOT_MAX; i++) {
1819         for (j = 0; j < PCI_NUM_PINS; j++) {
1820             uint32_t *irqmap = interrupt_map[i*PCI_NUM_PINS + j];
1821             int lsi_num = pci_spapr_swizzle(i, j);
1822 
1823             irqmap[0] = cpu_to_be32(b_ddddd(i)|b_fff(0));
1824             irqmap[1] = 0;
1825             irqmap[2] = 0;
1826             irqmap[3] = cpu_to_be32(j+1);
1827             irqmap[4] = cpu_to_be32(xics_phandle);
1828             irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);
1829             irqmap[6] = cpu_to_be32(0x8);
1830         }
1831     }
1832     /* Write interrupt map */
1833     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
1834                      sizeof(interrupt_map)));
1835 
1836     tcet = spapr_tce_find_by_liobn(SPAPR_PCI_LIOBN(phb->index, 0));
1837     spapr_dma_dt(fdt, bus_off, "ibm,dma-window",
1838                  tcet->liobn, tcet->bus_offset,
1839                  tcet->nb_table << tcet->page_shift);
1840 
1841     /* Walk the bridges and program the bus numbers*/
1842     spapr_phb_pci_enumerate(phb);
1843     _FDT(fdt_setprop_cell(fdt, bus_off, "qemu,phb-enumerated", 0x1));
1844 
1845     /* Populate tree nodes with PCI devices attached */
1846     s_fdt.fdt = fdt;
1847     s_fdt.node_off = bus_off;
1848     s_fdt.sphb = phb;
1849     pci_for_each_device(bus, pci_bus_num(bus),
1850                         spapr_populate_pci_devices_dt,
1851                         &s_fdt);
1852 
1853     ret = spapr_drc_populate_dt(fdt, bus_off, OBJECT(phb),
1854                                 SPAPR_DR_CONNECTOR_TYPE_PCI);
1855     if (ret) {
1856         return ret;
1857     }
1858 
1859     return 0;
1860 }
1861 
1862 void spapr_pci_rtas_init(void)
1863 {
1864     spapr_rtas_register(RTAS_READ_PCI_CONFIG, "read-pci-config",
1865                         rtas_read_pci_config);
1866     spapr_rtas_register(RTAS_WRITE_PCI_CONFIG, "write-pci-config",
1867                         rtas_write_pci_config);
1868     spapr_rtas_register(RTAS_IBM_READ_PCI_CONFIG, "ibm,read-pci-config",
1869                         rtas_ibm_read_pci_config);
1870     spapr_rtas_register(RTAS_IBM_WRITE_PCI_CONFIG, "ibm,write-pci-config",
1871                         rtas_ibm_write_pci_config);
1872     if (msi_nonbroken) {
1873         spapr_rtas_register(RTAS_IBM_QUERY_INTERRUPT_SOURCE_NUMBER,
1874                             "ibm,query-interrupt-source-number",
1875                             rtas_ibm_query_interrupt_source_number);
1876         spapr_rtas_register(RTAS_IBM_CHANGE_MSI, "ibm,change-msi",
1877                             rtas_ibm_change_msi);
1878     }
1879 
1880     spapr_rtas_register(RTAS_IBM_SET_EEH_OPTION,
1881                         "ibm,set-eeh-option",
1882                         rtas_ibm_set_eeh_option);
1883     spapr_rtas_register(RTAS_IBM_GET_CONFIG_ADDR_INFO2,
1884                         "ibm,get-config-addr-info2",
1885                         rtas_ibm_get_config_addr_info2);
1886     spapr_rtas_register(RTAS_IBM_READ_SLOT_RESET_STATE2,
1887                         "ibm,read-slot-reset-state2",
1888                         rtas_ibm_read_slot_reset_state2);
1889     spapr_rtas_register(RTAS_IBM_SET_SLOT_RESET,
1890                         "ibm,set-slot-reset",
1891                         rtas_ibm_set_slot_reset);
1892     spapr_rtas_register(RTAS_IBM_CONFIGURE_PE,
1893                         "ibm,configure-pe",
1894                         rtas_ibm_configure_pe);
1895     spapr_rtas_register(RTAS_IBM_SLOT_ERROR_DETAIL,
1896                         "ibm,slot-error-detail",
1897                         rtas_ibm_slot_error_detail);
1898 }
1899 
1900 static void spapr_pci_register_types(void)
1901 {
1902     type_register_static(&spapr_phb_info);
1903 }
1904 
1905 type_init(spapr_pci_register_types)
1906 
1907 static int spapr_switch_one_vga(DeviceState *dev, void *opaque)
1908 {
1909     bool be = *(bool *)opaque;
1910 
1911     if (object_dynamic_cast(OBJECT(dev), "VGA")
1912         || object_dynamic_cast(OBJECT(dev), "secondary-vga")) {
1913         object_property_set_bool(OBJECT(dev), be, "big-endian-framebuffer",
1914                                  &error_abort);
1915     }
1916     return 0;
1917 }
1918 
1919 void spapr_pci_switch_vga(bool big_endian)
1920 {
1921     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1922     sPAPRPHBState *sphb;
1923 
1924     /*
1925      * For backward compatibility with existing guests, we switch
1926      * the endianness of the VGA controller when changing the guest
1927      * interrupt mode
1928      */
1929     QLIST_FOREACH(sphb, &spapr->phbs, list) {
1930         BusState *bus = &PCI_HOST_BRIDGE(sphb)->bus->qbus;
1931         qbus_walk_children(bus, spapr_switch_one_vga, NULL, NULL, NULL,
1932                            &big_endian);
1933     }
1934 }
1935