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