xref: /openbmc/qemu/hw/ppc/spapr_pci.c (revision b23197f9)
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_drc(sPAPRPHBState *phb,
1146                                                PCIDevice *pdev)
1147 {
1148     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
1149     return spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_PCI,
1150                                     (phb->index << 16) |
1151                                     (busnr << 8) |
1152                                     pdev->devfn);
1153 }
1154 
1155 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
1156                                             PCIDevice *pdev)
1157 {
1158     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1159     sPAPRDRConnectorClass *drck;
1160 
1161     if (!drc) {
1162         return 0;
1163     }
1164 
1165     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1166     return drck->get_index(drc);
1167 }
1168 
1169 static void spapr_phb_hot_plug_child(HotplugHandler *plug_handler,
1170                                      DeviceState *plugged_dev, Error **errp)
1171 {
1172     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1173     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1174     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1175     Error *local_err = NULL;
1176 
1177     /* if DR is disabled we don't need to do anything in the case of
1178      * hotplug or coldplug callbacks
1179      */
1180     if (!phb->dr_enabled) {
1181         /* if this is a hotplug operation initiated by the user
1182          * we need to let them know it's not enabled
1183          */
1184         if (plugged_dev->hotplugged) {
1185             error_setg(errp, QERR_BUS_NO_HOTPLUG,
1186                        object_get_typename(OBJECT(phb)));
1187         }
1188         return;
1189     }
1190 
1191     g_assert(drc);
1192 
1193     spapr_phb_add_pci_device(drc, phb, pdev, &local_err);
1194     if (local_err) {
1195         error_propagate(errp, local_err);
1196         return;
1197     }
1198     if (plugged_dev->hotplugged) {
1199         spapr_hotplug_req_add_by_index(drc);
1200     }
1201 }
1202 
1203 static void spapr_phb_hot_unplug_child(HotplugHandler *plug_handler,
1204                                        DeviceState *plugged_dev, Error **errp)
1205 {
1206     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1207     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1208     sPAPRDRConnectorClass *drck;
1209     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1210     Error *local_err = NULL;
1211 
1212     if (!phb->dr_enabled) {
1213         error_setg(errp, QERR_BUS_NO_HOTPLUG,
1214                    object_get_typename(OBJECT(phb)));
1215         return;
1216     }
1217 
1218     g_assert(drc);
1219 
1220     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1221     if (!drck->release_pending(drc)) {
1222         spapr_phb_remove_pci_device(drc, phb, pdev, &local_err);
1223         if (local_err) {
1224             error_propagate(errp, local_err);
1225             return;
1226         }
1227         spapr_hotplug_req_remove_by_index(drc);
1228     }
1229 }
1230 
1231 static void spapr_phb_realize(DeviceState *dev, Error **errp)
1232 {
1233     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1234     SysBusDevice *s = SYS_BUS_DEVICE(dev);
1235     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
1236     PCIHostState *phb = PCI_HOST_BRIDGE(s);
1237     sPAPRPHBClass *info = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(s);
1238     char *namebuf;
1239     int i;
1240     PCIBus *bus;
1241     uint64_t msi_window_size = 4096;
1242 
1243     if (sphb->index != (uint32_t)-1) {
1244         hwaddr windows_base;
1245 
1246         if ((sphb->buid != (uint64_t)-1) || (sphb->dma_liobn != (uint32_t)-1)
1247             || (sphb->mem_win_addr != (hwaddr)-1)
1248             || (sphb->io_win_addr != (hwaddr)-1)) {
1249             error_setg(errp, "Either \"index\" or other parameters must"
1250                        " be specified for PAPR PHB, not both");
1251             return;
1252         }
1253 
1254         if (sphb->index > SPAPR_PCI_MAX_INDEX) {
1255             error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",
1256                        SPAPR_PCI_MAX_INDEX);
1257             return;
1258         }
1259 
1260         sphb->buid = SPAPR_PCI_BASE_BUID + sphb->index;
1261         sphb->dma_liobn = SPAPR_PCI_LIOBN(sphb->index, 0);
1262 
1263         windows_base = SPAPR_PCI_WINDOW_BASE
1264             + sphb->index * SPAPR_PCI_WINDOW_SPACING;
1265         sphb->mem_win_addr = windows_base + SPAPR_PCI_MMIO_WIN_OFF;
1266         sphb->io_win_addr = windows_base + SPAPR_PCI_IO_WIN_OFF;
1267     }
1268 
1269     if (sphb->buid == (uint64_t)-1) {
1270         error_setg(errp, "BUID not specified for PHB");
1271         return;
1272     }
1273 
1274     if (sphb->dma_liobn == (uint32_t)-1) {
1275         error_setg(errp, "LIOBN not specified for PHB");
1276         return;
1277     }
1278 
1279     if (sphb->mem_win_addr == (hwaddr)-1) {
1280         error_setg(errp, "Memory window address not specified for PHB");
1281         return;
1282     }
1283 
1284     if (sphb->io_win_addr == (hwaddr)-1) {
1285         error_setg(errp, "IO window address not specified for PHB");
1286         return;
1287     }
1288 
1289     if (spapr_pci_find_phb(spapr, sphb->buid)) {
1290         error_setg(errp, "PCI host bridges must have unique BUIDs");
1291         return;
1292     }
1293 
1294     sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);
1295 
1296     namebuf = alloca(strlen(sphb->dtbusname) + 32);
1297 
1298     /* Initialize memory regions */
1299     sprintf(namebuf, "%s.mmio", sphb->dtbusname);
1300     memory_region_init(&sphb->memspace, OBJECT(sphb), namebuf, UINT64_MAX);
1301 
1302     sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);
1303     memory_region_init_alias(&sphb->memwindow, OBJECT(sphb),
1304                              namebuf, &sphb->memspace,
1305                              SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);
1306     memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,
1307                                 &sphb->memwindow);
1308 
1309     /* Initialize IO regions */
1310     sprintf(namebuf, "%s.io", sphb->dtbusname);
1311     memory_region_init(&sphb->iospace, OBJECT(sphb),
1312                        namebuf, SPAPR_PCI_IO_WIN_SIZE);
1313 
1314     sprintf(namebuf, "%s.io-alias", sphb->dtbusname);
1315     memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf,
1316                              &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE);
1317     memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,
1318                                 &sphb->iowindow);
1319 
1320     bus = pci_register_bus(dev, NULL,
1321                            pci_spapr_set_irq, pci_spapr_map_irq, sphb,
1322                            &sphb->memspace, &sphb->iospace,
1323                            PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS);
1324     phb->bus = bus;
1325     qbus_set_hotplug_handler(BUS(phb->bus), DEVICE(sphb), NULL);
1326 
1327     /*
1328      * Initialize PHB address space.
1329      * By default there will be at least one subregion for default
1330      * 32bit DMA window.
1331      * Later the guest might want to create another DMA window
1332      * which will become another memory subregion.
1333      */
1334     sprintf(namebuf, "%s.iommu-root", sphb->dtbusname);
1335 
1336     memory_region_init(&sphb->iommu_root, OBJECT(sphb),
1337                        namebuf, UINT64_MAX);
1338     address_space_init(&sphb->iommu_as, &sphb->iommu_root,
1339                        sphb->dtbusname);
1340 
1341     /*
1342      * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,
1343      * we need to allocate some memory to catch those writes coming
1344      * from msi_notify()/msix_notify().
1345      * As MSIMessage:addr is going to be the same and MSIMessage:data
1346      * is going to be a VIRQ number, 4 bytes of the MSI MR will only
1347      * be used.
1348      *
1349      * For KVM we want to ensure that this memory is a full page so that
1350      * our memory slot is of page size granularity.
1351      */
1352 #ifdef CONFIG_KVM
1353     if (kvm_enabled()) {
1354         msi_window_size = getpagesize();
1355     }
1356 #endif
1357 
1358     memory_region_init_io(&sphb->msiwindow, NULL, &spapr_msi_ops, spapr,
1359                           "msi", msi_window_size);
1360     memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW,
1361                                 &sphb->msiwindow);
1362 
1363     pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb);
1364 
1365     pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq);
1366 
1367     QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);
1368 
1369     /* Initialize the LSI table */
1370     for (i = 0; i < PCI_NUM_PINS; i++) {
1371         uint32_t irq;
1372         Error *local_err = NULL;
1373 
1374         irq = xics_alloc_block(spapr->icp, 0, 1, true, false, &local_err);
1375         if (local_err) {
1376             error_propagate(errp, local_err);
1377             error_prepend(errp, "can't allocate LSIs: ");
1378             return;
1379         }
1380 
1381         sphb->lsi_table[i].irq = irq;
1382     }
1383 
1384     /* allocate connectors for child PCI devices */
1385     if (sphb->dr_enabled) {
1386         for (i = 0; i < PCI_SLOT_MAX * 8; i++) {
1387             spapr_dr_connector_new(OBJECT(phb),
1388                                    SPAPR_DR_CONNECTOR_TYPE_PCI,
1389                                    (sphb->index << 16) | i);
1390         }
1391     }
1392 
1393     if (!info->finish_realize) {
1394         error_setg(errp, "finish_realize not defined");
1395         return;
1396     }
1397 
1398     info->finish_realize(sphb, errp);
1399 
1400     sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);
1401 }
1402 
1403 static void spapr_phb_finish_realize(sPAPRPHBState *sphb, Error **errp)
1404 {
1405     sPAPRTCETable *tcet;
1406     uint32_t nb_table;
1407 
1408     nb_table = sphb->dma_win_size >> SPAPR_TCE_PAGE_SHIFT;
1409     tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn,
1410                                0, SPAPR_TCE_PAGE_SHIFT, nb_table, false);
1411     if (!tcet) {
1412         error_setg(errp, "Unable to create TCE table for %s",
1413                    sphb->dtbusname);
1414         return ;
1415     }
1416 
1417     /* Register default 32bit DMA window */
1418     memory_region_add_subregion(&sphb->iommu_root, sphb->dma_win_addr,
1419                                 spapr_tce_get_iommu(tcet));
1420 }
1421 
1422 static int spapr_phb_children_reset(Object *child, void *opaque)
1423 {
1424     DeviceState *dev = (DeviceState *) object_dynamic_cast(child, TYPE_DEVICE);
1425 
1426     if (dev) {
1427         device_reset(dev);
1428     }
1429 
1430     return 0;
1431 }
1432 
1433 static void spapr_phb_reset(DeviceState *qdev)
1434 {
1435     /* Reset the IOMMU state */
1436     object_child_foreach(OBJECT(qdev), spapr_phb_children_reset, NULL);
1437 }
1438 
1439 static Property spapr_phb_properties[] = {
1440     DEFINE_PROP_UINT32("index", sPAPRPHBState, index, -1),
1441     DEFINE_PROP_UINT64("buid", sPAPRPHBState, buid, -1),
1442     DEFINE_PROP_UINT32("liobn", sPAPRPHBState, dma_liobn, -1),
1443     DEFINE_PROP_UINT64("mem_win_addr", sPAPRPHBState, mem_win_addr, -1),
1444     DEFINE_PROP_UINT64("mem_win_size", sPAPRPHBState, mem_win_size,
1445                        SPAPR_PCI_MMIO_WIN_SIZE),
1446     DEFINE_PROP_UINT64("io_win_addr", sPAPRPHBState, io_win_addr, -1),
1447     DEFINE_PROP_UINT64("io_win_size", sPAPRPHBState, io_win_size,
1448                        SPAPR_PCI_IO_WIN_SIZE),
1449     DEFINE_PROP_BOOL("dynamic-reconfiguration", sPAPRPHBState, dr_enabled,
1450                      true),
1451     /* Default DMA window is 0..1GB */
1452     DEFINE_PROP_UINT64("dma_win_addr", sPAPRPHBState, dma_win_addr, 0),
1453     DEFINE_PROP_UINT64("dma_win_size", sPAPRPHBState, dma_win_size, 0x40000000),
1454     DEFINE_PROP_END_OF_LIST(),
1455 };
1456 
1457 static const VMStateDescription vmstate_spapr_pci_lsi = {
1458     .name = "spapr_pci/lsi",
1459     .version_id = 1,
1460     .minimum_version_id = 1,
1461     .fields = (VMStateField[]) {
1462         VMSTATE_UINT32_EQUAL(irq, struct spapr_pci_lsi),
1463 
1464         VMSTATE_END_OF_LIST()
1465     },
1466 };
1467 
1468 static const VMStateDescription vmstate_spapr_pci_msi = {
1469     .name = "spapr_pci/msi",
1470     .version_id = 1,
1471     .minimum_version_id = 1,
1472     .fields = (VMStateField []) {
1473         VMSTATE_UINT32(key, spapr_pci_msi_mig),
1474         VMSTATE_UINT32(value.first_irq, spapr_pci_msi_mig),
1475         VMSTATE_UINT32(value.num, spapr_pci_msi_mig),
1476         VMSTATE_END_OF_LIST()
1477     },
1478 };
1479 
1480 static void spapr_pci_pre_save(void *opaque)
1481 {
1482     sPAPRPHBState *sphb = opaque;
1483     GHashTableIter iter;
1484     gpointer key, value;
1485     int i;
1486 
1487     g_free(sphb->msi_devs);
1488     sphb->msi_devs = NULL;
1489     sphb->msi_devs_num = g_hash_table_size(sphb->msi);
1490     if (!sphb->msi_devs_num) {
1491         return;
1492     }
1493     sphb->msi_devs = g_malloc(sphb->msi_devs_num * sizeof(spapr_pci_msi_mig));
1494 
1495     g_hash_table_iter_init(&iter, sphb->msi);
1496     for (i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
1497         sphb->msi_devs[i].key = *(uint32_t *) key;
1498         sphb->msi_devs[i].value = *(spapr_pci_msi *) value;
1499     }
1500 }
1501 
1502 static int spapr_pci_post_load(void *opaque, int version_id)
1503 {
1504     sPAPRPHBState *sphb = opaque;
1505     gpointer key, value;
1506     int i;
1507 
1508     for (i = 0; i < sphb->msi_devs_num; ++i) {
1509         key = g_memdup(&sphb->msi_devs[i].key,
1510                        sizeof(sphb->msi_devs[i].key));
1511         value = g_memdup(&sphb->msi_devs[i].value,
1512                          sizeof(sphb->msi_devs[i].value));
1513         g_hash_table_insert(sphb->msi, key, value);
1514     }
1515     g_free(sphb->msi_devs);
1516     sphb->msi_devs = NULL;
1517     sphb->msi_devs_num = 0;
1518 
1519     return 0;
1520 }
1521 
1522 static const VMStateDescription vmstate_spapr_pci = {
1523     .name = "spapr_pci",
1524     .version_id = 2,
1525     .minimum_version_id = 2,
1526     .pre_save = spapr_pci_pre_save,
1527     .post_load = spapr_pci_post_load,
1528     .fields = (VMStateField[]) {
1529         VMSTATE_UINT64_EQUAL(buid, sPAPRPHBState),
1530         VMSTATE_UINT32_EQUAL(dma_liobn, sPAPRPHBState),
1531         VMSTATE_UINT64_EQUAL(mem_win_addr, sPAPRPHBState),
1532         VMSTATE_UINT64_EQUAL(mem_win_size, sPAPRPHBState),
1533         VMSTATE_UINT64_EQUAL(io_win_addr, sPAPRPHBState),
1534         VMSTATE_UINT64_EQUAL(io_win_size, sPAPRPHBState),
1535         VMSTATE_STRUCT_ARRAY(lsi_table, sPAPRPHBState, PCI_NUM_PINS, 0,
1536                              vmstate_spapr_pci_lsi, struct spapr_pci_lsi),
1537         VMSTATE_INT32(msi_devs_num, sPAPRPHBState),
1538         VMSTATE_STRUCT_VARRAY_ALLOC(msi_devs, sPAPRPHBState, msi_devs_num, 0,
1539                                     vmstate_spapr_pci_msi, spapr_pci_msi_mig),
1540         VMSTATE_END_OF_LIST()
1541     },
1542 };
1543 
1544 static const char *spapr_phb_root_bus_path(PCIHostState *host_bridge,
1545                                            PCIBus *rootbus)
1546 {
1547     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(host_bridge);
1548 
1549     return sphb->dtbusname;
1550 }
1551 
1552 static void spapr_phb_class_init(ObjectClass *klass, void *data)
1553 {
1554     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);
1555     DeviceClass *dc = DEVICE_CLASS(klass);
1556     sPAPRPHBClass *spc = SPAPR_PCI_HOST_BRIDGE_CLASS(klass);
1557     HotplugHandlerClass *hp = HOTPLUG_HANDLER_CLASS(klass);
1558 
1559     hc->root_bus_path = spapr_phb_root_bus_path;
1560     dc->realize = spapr_phb_realize;
1561     dc->props = spapr_phb_properties;
1562     dc->reset = spapr_phb_reset;
1563     dc->vmsd = &vmstate_spapr_pci;
1564     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1565     dc->cannot_instantiate_with_device_add_yet = false;
1566     spc->finish_realize = spapr_phb_finish_realize;
1567     hp->plug = spapr_phb_hot_plug_child;
1568     hp->unplug = spapr_phb_hot_unplug_child;
1569 }
1570 
1571 static const TypeInfo spapr_phb_info = {
1572     .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
1573     .parent        = TYPE_PCI_HOST_BRIDGE,
1574     .instance_size = sizeof(sPAPRPHBState),
1575     .class_init    = spapr_phb_class_init,
1576     .class_size    = sizeof(sPAPRPHBClass),
1577     .interfaces    = (InterfaceInfo[]) {
1578         { TYPE_HOTPLUG_HANDLER },
1579         { }
1580     }
1581 };
1582 
1583 PCIHostState *spapr_create_phb(sPAPRMachineState *spapr, int index)
1584 {
1585     DeviceState *dev;
1586 
1587     dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
1588     qdev_prop_set_uint32(dev, "index", index);
1589     qdev_init_nofail(dev);
1590 
1591     return PCI_HOST_BRIDGE(dev);
1592 }
1593 
1594 typedef struct sPAPRFDT {
1595     void *fdt;
1596     int node_off;
1597     sPAPRPHBState *sphb;
1598 } sPAPRFDT;
1599 
1600 static void spapr_populate_pci_devices_dt(PCIBus *bus, PCIDevice *pdev,
1601                                           void *opaque)
1602 {
1603     PCIBus *sec_bus;
1604     sPAPRFDT *p = opaque;
1605     int offset;
1606     sPAPRFDT s_fdt;
1607 
1608     offset = spapr_create_pci_child_dt(p->sphb, pdev, p->fdt, p->node_off);
1609     if (!offset) {
1610         error_report("Failed to create pci child device tree node");
1611         return;
1612     }
1613 
1614     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1615          PCI_HEADER_TYPE_BRIDGE)) {
1616         return;
1617     }
1618 
1619     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1620     if (!sec_bus) {
1621         return;
1622     }
1623 
1624     s_fdt.fdt = p->fdt;
1625     s_fdt.node_off = offset;
1626     s_fdt.sphb = p->sphb;
1627     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1628                         spapr_populate_pci_devices_dt,
1629                         &s_fdt);
1630 }
1631 
1632 static void spapr_phb_pci_enumerate_bridge(PCIBus *bus, PCIDevice *pdev,
1633                                            void *opaque)
1634 {
1635     unsigned int *bus_no = opaque;
1636     unsigned int primary = *bus_no;
1637     unsigned int subordinate = 0xff;
1638     PCIBus *sec_bus = NULL;
1639 
1640     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1641          PCI_HEADER_TYPE_BRIDGE)) {
1642         return;
1643     }
1644 
1645     (*bus_no)++;
1646     pci_default_write_config(pdev, PCI_PRIMARY_BUS, primary, 1);
1647     pci_default_write_config(pdev, PCI_SECONDARY_BUS, *bus_no, 1);
1648     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1649 
1650     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1651     if (!sec_bus) {
1652         return;
1653     }
1654 
1655     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, subordinate, 1);
1656     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1657                         spapr_phb_pci_enumerate_bridge, bus_no);
1658     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1659 }
1660 
1661 static void spapr_phb_pci_enumerate(sPAPRPHBState *phb)
1662 {
1663     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1664     unsigned int bus_no = 0;
1665 
1666     pci_for_each_device(bus, pci_bus_num(bus),
1667                         spapr_phb_pci_enumerate_bridge,
1668                         &bus_no);
1669 
1670 }
1671 
1672 int spapr_populate_pci_dt(sPAPRPHBState *phb,
1673                           uint32_t xics_phandle,
1674                           void *fdt)
1675 {
1676     int bus_off, i, j, ret;
1677     char nodename[FDT_NAME_MAX];
1678     uint32_t bus_range[] = { cpu_to_be32(0), cpu_to_be32(0xff) };
1679     const uint64_t mmiosize = memory_region_size(&phb->memwindow);
1680     const uint64_t w32max = (1ULL << 32) - SPAPR_PCI_MEM_WIN_BUS_OFFSET;
1681     const uint64_t w32size = MIN(w32max, mmiosize);
1682     const uint64_t w64size = (mmiosize > w32size) ? (mmiosize - w32size) : 0;
1683     struct {
1684         uint32_t hi;
1685         uint64_t child;
1686         uint64_t parent;
1687         uint64_t size;
1688     } QEMU_PACKED ranges[] = {
1689         {
1690             cpu_to_be32(b_ss(1)), cpu_to_be64(0),
1691             cpu_to_be64(phb->io_win_addr),
1692             cpu_to_be64(memory_region_size(&phb->iospace)),
1693         },
1694         {
1695             cpu_to_be32(b_ss(2)), cpu_to_be64(SPAPR_PCI_MEM_WIN_BUS_OFFSET),
1696             cpu_to_be64(phb->mem_win_addr),
1697             cpu_to_be64(w32size),
1698         },
1699         {
1700             cpu_to_be32(b_ss(3)), cpu_to_be64(1ULL << 32),
1701             cpu_to_be64(phb->mem_win_addr + w32size),
1702             cpu_to_be64(w64size)
1703         },
1704     };
1705     const unsigned sizeof_ranges = (w64size ? 3 : 2) * sizeof(ranges[0]);
1706     uint64_t bus_reg[] = { cpu_to_be64(phb->buid), 0 };
1707     uint32_t interrupt_map_mask[] = {
1708         cpu_to_be32(b_ddddd(-1)|b_fff(0)), 0x0, 0x0, cpu_to_be32(-1)};
1709     uint32_t interrupt_map[PCI_SLOT_MAX * PCI_NUM_PINS][7];
1710     sPAPRTCETable *tcet;
1711     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1712     sPAPRFDT s_fdt;
1713 
1714     /* Start populating the FDT */
1715     snprintf(nodename, FDT_NAME_MAX, "pci@%" PRIx64, phb->buid);
1716     bus_off = fdt_add_subnode(fdt, 0, nodename);
1717     if (bus_off < 0) {
1718         return bus_off;
1719     }
1720 
1721     /* Write PHB properties */
1722     _FDT(fdt_setprop_string(fdt, bus_off, "device_type", "pci"));
1723     _FDT(fdt_setprop_string(fdt, bus_off, "compatible", "IBM,Logical_PHB"));
1724     _FDT(fdt_setprop_cell(fdt, bus_off, "#address-cells", 0x3));
1725     _FDT(fdt_setprop_cell(fdt, bus_off, "#size-cells", 0x2));
1726     _FDT(fdt_setprop_cell(fdt, bus_off, "#interrupt-cells", 0x1));
1727     _FDT(fdt_setprop(fdt, bus_off, "used-by-rtas", NULL, 0));
1728     _FDT(fdt_setprop(fdt, bus_off, "bus-range", &bus_range, sizeof(bus_range)));
1729     _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof_ranges));
1730     _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg)));
1731     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1));
1732     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS));
1733 
1734     /* Build the interrupt-map, this must matches what is done
1735      * in pci_spapr_map_irq
1736      */
1737     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map-mask",
1738                      &interrupt_map_mask, sizeof(interrupt_map_mask)));
1739     for (i = 0; i < PCI_SLOT_MAX; i++) {
1740         for (j = 0; j < PCI_NUM_PINS; j++) {
1741             uint32_t *irqmap = interrupt_map[i*PCI_NUM_PINS + j];
1742             int lsi_num = pci_spapr_swizzle(i, j);
1743 
1744             irqmap[0] = cpu_to_be32(b_ddddd(i)|b_fff(0));
1745             irqmap[1] = 0;
1746             irqmap[2] = 0;
1747             irqmap[3] = cpu_to_be32(j+1);
1748             irqmap[4] = cpu_to_be32(xics_phandle);
1749             irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);
1750             irqmap[6] = cpu_to_be32(0x8);
1751         }
1752     }
1753     /* Write interrupt map */
1754     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
1755                      sizeof(interrupt_map)));
1756 
1757     tcet = spapr_tce_find_by_liobn(SPAPR_PCI_LIOBN(phb->index, 0));
1758     spapr_dma_dt(fdt, bus_off, "ibm,dma-window",
1759                  tcet->liobn, tcet->bus_offset,
1760                  tcet->nb_table << tcet->page_shift);
1761 
1762     /* Walk the bridges and program the bus numbers*/
1763     spapr_phb_pci_enumerate(phb);
1764     _FDT(fdt_setprop_cell(fdt, bus_off, "qemu,phb-enumerated", 0x1));
1765 
1766     /* Populate tree nodes with PCI devices attached */
1767     s_fdt.fdt = fdt;
1768     s_fdt.node_off = bus_off;
1769     s_fdt.sphb = phb;
1770     pci_for_each_device(bus, pci_bus_num(bus),
1771                         spapr_populate_pci_devices_dt,
1772                         &s_fdt);
1773 
1774     ret = spapr_drc_populate_dt(fdt, bus_off, OBJECT(phb),
1775                                 SPAPR_DR_CONNECTOR_TYPE_PCI);
1776     if (ret) {
1777         return ret;
1778     }
1779 
1780     return 0;
1781 }
1782 
1783 void spapr_pci_rtas_init(void)
1784 {
1785     spapr_rtas_register(RTAS_READ_PCI_CONFIG, "read-pci-config",
1786                         rtas_read_pci_config);
1787     spapr_rtas_register(RTAS_WRITE_PCI_CONFIG, "write-pci-config",
1788                         rtas_write_pci_config);
1789     spapr_rtas_register(RTAS_IBM_READ_PCI_CONFIG, "ibm,read-pci-config",
1790                         rtas_ibm_read_pci_config);
1791     spapr_rtas_register(RTAS_IBM_WRITE_PCI_CONFIG, "ibm,write-pci-config",
1792                         rtas_ibm_write_pci_config);
1793     if (msi_supported) {
1794         spapr_rtas_register(RTAS_IBM_QUERY_INTERRUPT_SOURCE_NUMBER,
1795                             "ibm,query-interrupt-source-number",
1796                             rtas_ibm_query_interrupt_source_number);
1797         spapr_rtas_register(RTAS_IBM_CHANGE_MSI, "ibm,change-msi",
1798                             rtas_ibm_change_msi);
1799     }
1800 
1801     spapr_rtas_register(RTAS_IBM_SET_EEH_OPTION,
1802                         "ibm,set-eeh-option",
1803                         rtas_ibm_set_eeh_option);
1804     spapr_rtas_register(RTAS_IBM_GET_CONFIG_ADDR_INFO2,
1805                         "ibm,get-config-addr-info2",
1806                         rtas_ibm_get_config_addr_info2);
1807     spapr_rtas_register(RTAS_IBM_READ_SLOT_RESET_STATE2,
1808                         "ibm,read-slot-reset-state2",
1809                         rtas_ibm_read_slot_reset_state2);
1810     spapr_rtas_register(RTAS_IBM_SET_SLOT_RESET,
1811                         "ibm,set-slot-reset",
1812                         rtas_ibm_set_slot_reset);
1813     spapr_rtas_register(RTAS_IBM_CONFIGURE_PE,
1814                         "ibm,configure-pe",
1815                         rtas_ibm_configure_pe);
1816     spapr_rtas_register(RTAS_IBM_SLOT_ERROR_DETAIL,
1817                         "ibm,slot-error-detail",
1818                         rtas_ibm_slot_error_detail);
1819 }
1820 
1821 static void spapr_pci_register_types(void)
1822 {
1823     type_register_static(&spapr_phb_info);
1824 }
1825 
1826 type_init(spapr_pci_register_types)
1827 
1828 static int spapr_switch_one_vga(DeviceState *dev, void *opaque)
1829 {
1830     bool be = *(bool *)opaque;
1831 
1832     if (object_dynamic_cast(OBJECT(dev), "VGA")
1833         || object_dynamic_cast(OBJECT(dev), "secondary-vga")) {
1834         object_property_set_bool(OBJECT(dev), be, "big-endian-framebuffer",
1835                                  &error_abort);
1836     }
1837     return 0;
1838 }
1839 
1840 void spapr_pci_switch_vga(bool big_endian)
1841 {
1842     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1843     sPAPRPHBState *sphb;
1844 
1845     /*
1846      * For backward compatibility with existing guests, we switch
1847      * the endianness of the VGA controller when changing the guest
1848      * interrupt mode
1849      */
1850     QLIST_FOREACH(sphb, &spapr->phbs, list) {
1851         BusState *bus = &PCI_HOST_BRIDGE(sphb)->bus->qbus;
1852         qbus_walk_children(bus, spapr_switch_one_vga, NULL, NULL, NULL,
1853                            &big_endian);
1854     }
1855 }
1856