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